setupPoints und setupDateFormat in ein partial Layout verschoben
[kivitendo-erp.git] / bin / mozilla / ap.pl
1 #=====================================================================
2 # LX-Office ERP
3 # Copyright (C) 2004
4 # Based on SQL-Ledger Version 2.1.9
5 # Web http://www.lx-office.org
6 #
7 #=====================================================================
8 # SQL-Ledger Accounting
9 # Copyright (c) 2001
10 #
11 #  Author: Dieter Simader
12 #   Email: dsimader@sql-ledger.org
13 #     Web: http://www.sql-ledger.org
14 #
15 #
16 # This program is free software; you can redistribute it and/or modify
17 # it under the terms of the GNU General Public License as published by
18 # the Free Software Foundation; either version 2 of the License, or
19 # (at your option) any later version.
20 #
21 # This program is distributed in the hope that it will be useful,
22 # but WITHOUT ANY WARRANTY; without even the implied warranty of
23 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
24 # GNU General Public License for more details.
25 # You should have received a copy of the GNU General Public License
26 # along with this program; if not, write to the Free Software
27 # Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
28 #======================================================================
29 #
30 # Accounts Payables
31 #
32 #======================================================================
33
34 use POSIX qw(strftime);
35 use List::Util qw(sum);
36
37 use SL::AP;
38 use SL::FU;
39 use SL::IR;
40 use SL::IS;
41 use SL::PE;
42 use SL::ReportGenerator;
43
44 require "bin/mozilla/arap.pl";
45 require "bin/mozilla/common.pl";
46 require "bin/mozilla/drafts.pl";
47 require "bin/mozilla/reportgenerator.pl";
48
49 use strict;
50
51 1;
52
53 # end of main
54
55 # this is for our long dates
56 # $locale->text('January')
57 # $locale->text('February')
58 # $locale->text('March')
59 # $locale->text('April')
60 # $locale->text('May ')
61 # $locale->text('June')
62 # $locale->text('July')
63 # $locale->text('August')
64 # $locale->text('September')
65 # $locale->text('October')
66 # $locale->text('November')
67 # $locale->text('December')
68
69 # this is for our short month
70 # $locale->text('Jan')
71 # $locale->text('Feb')
72 # $locale->text('Mar')
73 # $locale->text('Apr')
74 # $locale->text('May')
75 # $locale->text('Jun')
76 # $locale->text('Jul')
77 # $locale->text('Aug')
78 # $locale->text('Sep')
79 # $locale->text('Oct')
80 # $locale->text('Nov')
81 # $locale->text('Dec')
82
83 sub add {
84   $main::lxdebug->enter_sub();
85
86   my $form     = $main::form;
87   my %myconfig = %main::myconfig;
88
89   $main::auth->assert('general_ledger');
90
91   return $main::lxdebug->leave_sub() if (load_draft_maybe());
92
93   $form->{title} = "Add";
94
95   $form->{callback} = "ap.pl?action=add&DONT_LOAD_DRAFT=1" unless $form->{callback};
96
97   AP->get_transdate(\%myconfig, $form);
98   $form->{initial_transdate} = $form->{transdate};
99   &create_links;
100   $form->{transdate} = $form->{initial_transdate};
101   &display_form;
102
103   $main::lxdebug->leave_sub();
104 }
105
106 sub edit {
107   $main::lxdebug->enter_sub();
108
109   my $form     = $main::form;
110
111   $main::auth->assert('general_ledger');
112
113   $form->{title} = "Edit";
114
115   &create_links;
116   &display_form;
117
118   $main::lxdebug->leave_sub();
119 }
120
121 sub display_form {
122   $main::lxdebug->enter_sub();
123
124   my $form     = $main::form;
125
126   $main::auth->assert('general_ledger');
127
128   &form_header;
129   &form_footer;
130
131   $main::lxdebug->leave_sub();
132 }
133
134 sub create_links {
135   $main::lxdebug->enter_sub();
136
137   my $form     = $main::form;
138   my %myconfig = %main::myconfig;
139
140   $main::auth->assert('general_ledger');
141
142   $form->create_links("AP", \%myconfig, "vendor");
143   my $taxincluded = $form->{taxincluded};
144   my $duedate     = $form->{duedate};
145
146   IR->get_vendor(\%myconfig, \%$form);
147   $form->{taxincluded} = $taxincluded;
148   $form->{duedate}   = $duedate if $duedate;
149   $form->{oldvendor} = "$form->{vendor}--$form->{vendor_id}";
150   $form->{rowcount}  = 1;
151
152   # build the popup menus
153   $form->{taxincluded} = ($form->{id}) ? $form->{taxincluded} : "checked";
154
155   # notes
156   $form->{notes} = $form->{intnotes} unless $form->{notes};
157
158   # currencies
159   $form->{defaultcurrency} = $form->get_default_currency(\%myconfig);
160
161   map { $form->{selectcurrency} .= "<option>$_\n" } $form->get_all_currencies(\%myconfig);
162
163   # vendors
164   if (@{ $form->{all_vendor} || [] }) {
165     $form->{vendor} = qq|$form->{vendor}--$form->{vendor_id}|;
166     map { $form->{selectvendor} .= "<option>$_->{name}--$_->{id}\n" }
167       (@{ $form->{all_vendor} });
168   }
169
170   # departments
171   if (@{ $form->{all_departments} || [] }) {
172     $form->{selectdepartment} = "<option>\n";
173     $form->{department}       = "$form->{department}--$form->{department_id}";
174
175     map {
176       $form->{selectdepartment} .=
177         "<option>$_->{description}--$_->{id}\n"
178     } (@{ $form->{all_departments} || [] });
179   }
180
181   $form->{employee} = "$form->{employee}--$form->{employee_id}";
182
183   AP->setup_form($form);
184
185   $form->{locked} =
186     ($form->datetonum($form->{transdate}, \%myconfig) <=
187      $form->datetonum($form->{closedto}, \%myconfig));
188
189   $main::lxdebug->leave_sub();
190 }
191
192 sub form_header {
193   $main::lxdebug->enter_sub();
194
195   my $form     = $main::form;
196   my %myconfig = %main::myconfig;
197   my $locale   = $main::locale;
198   my $cgi      = $::request->{cgi};
199
200   $main::auth->assert('general_ledger');
201
202   my $title = $form->{title};
203   $form->{title} = $locale->text("$title Accounts Payables Transaction");
204
205   $form->{taxincluded} = ($form->{taxincluded}) ? "checked" : "";
206
207   # type=submit $locale->text('Add Accounts Payables Transaction')
208   # type=submit $locale->text('Edit Accounts Payables Transaction')
209
210   $form->{javascript} = qq|<script type="text/javascript">
211   <!--
212   function setTaxkey(accno, row) {
213     var taxkey = accno.options[accno.selectedIndex].value;
214     var reg = /--([0-9]*)/;
215     var found = reg.exec(taxkey);
216     var index = found[1];
217     index = parseInt(index);
218     var tax = 'taxchart_' + row;
219     for (var i = 0; i < document.getElementById(tax).options.length; ++i) {
220       var reg2 = new RegExp("^"+ index, "");
221       if (reg2.exec(document.getElementById(tax).options[i].value)) {
222         document.getElementById(tax).options[i].selected = true;
223         break;
224       }
225     }
226   };
227   //-->
228   </script>|;
229   # show history button
230   $form->{javascript} .= qq|<script type="text/javascript" src="js/show_history.js"></script>|;
231   #/show hhistory button
232
233   # set option selected
234   foreach my $item (qw(vendor currency department)) {
235     $form->{"select$item"} =~ s/ selected//;
236     $form->{"select$item"} =~
237       s/option>\Q$form->{$item}\E/option selected>$form->{$item}/;
238   }
239   my $readonly = ($form->{id}) ? "readonly" : "";
240
241   $form->{radier} = ($form->current_date(\%myconfig) eq $form->{gldate}) ? 1 : 0;
242   $readonly       = ($form->{radier}) ? "" : $readonly;
243
244   $form->{forex}        = $form->check_exchangerate( \%myconfig, $form->{currency}, $form->{transdate}, 'sell');
245   $form->{exchangerate} = $form->{forex} if $form->{forex};
246
247   # format amounts
248   $form->{exchangerate}    = $form->{exchangerate} ? $form->format_amount(\%myconfig, $form->{exchangerate}) : '';
249   $form->{creditlimit}     = $form->format_amount(\%myconfig, $form->{creditlimit}, 0, "0");
250   $form->{creditremaining} = $form->format_amount(\%myconfig, $form->{creditremaining}, 0, "0");
251
252   my $exchangerate = qq|
253 <input type=hidden name=forex value=$form->{forex}>
254 |;
255   if ($form->{defaultcurrency} && ($form->{currency} ne $form->{defaultcurrency})) {
256     if ($form->{forex}) {
257       $exchangerate .= qq|
258             <tr>
259               <th align=right>| . $locale->text('Exchangerate') . qq|</th>
260               <td><input type=hidden name=exchangerate value=$form->{exchangerate}>$form->{exchangerate}</td>
261            </tr>
262 |;
263     } else {
264       $exchangerate .= qq|
265              <th align=right>| . $locale->text('Exchangerate') . qq|</th>
266              <td><input name=exchangerate size=10 value=$form->{exchangerate}></td>
267 |;
268     }
269   }
270
271   my $taxincluded = "";
272
273   $taxincluded = qq|
274             <tr>
275               <td align=right><input name=taxincluded class=checkbox type=checkbox value=1 $form->{taxincluded}></td>
276               <th align=left nowrap>|
277     . $locale->text('Tax Included') . qq|</th>
278             </tr>
279 |;
280
281   my $rows;
282   if (($rows = $form->numtextrows($form->{notes}, 50)) < 2) {
283     $rows = 2;
284   }
285   my $notes =
286     qq|<textarea name=notes rows=$rows cols=50 wrap=soft $readonly>$form->{notes}</textarea>|;
287
288   my $department;
289   $department = qq|
290               <tr>
291                 <th align="right" nowrap>| . $locale->text('Department') . qq|</th>
292                 <td colspan=3><select name=department>$form->{selectdepartment}</select>
293                 <input type=hidden name=selectdepartment value="$form->{selectdepartment}">
294                 </td>
295               </tr>
296 | if $form->{selectdepartment};
297
298   my $n = ($form->{creditremaining} =~ /-/) ? "0" : "1";
299
300   my $vendor =
301     ($form->{selectvendor})
302     ? qq|<select name="vendor" onchange="document.getElementById('update_button').click();">$form->{selectvendor} </select>|
303     : qq|<input name=vendor value="$form->{vendor}" size=35>|;
304
305   my @old_project_ids = ();
306   map({ push(@old_project_ids, $form->{"project_id_$_"})
307           if ($form->{"project_id_$_"}); } (1..$form->{"rowcount"}));
308
309   $form->get_lists("projects"  => { "key"       => "ALL_PROJECTS",
310                                     "all"       => 0,
311                                     "old_id"    => \@old_project_ids },
312                    "charts"    => { "key"       => "ALL_CHARTS",
313                                     "transdate" => $form->{transdate} },
314                    "taxcharts" => { "key"       => "ALL_TAXCHARTS",
315                                     "module"    => "AP" },);
316
317   map({ $_->{link_split} = [ split(/:/, $_->{link}) ]; }
318       @{ $form->{ALL_CHARTS} });
319
320   my %project_labels = ();
321   my @project_values = ("");
322   foreach my $item (@{ $form->{"ALL_PROJECTS"} }) {
323     push(@project_values, $item->{"id"});
324     $project_labels{$item->{"id"}} = $item->{"projectnumber"};
325   }
326
327   my (%AP_amount_labels, @AP_amount_values);
328   my (%AP_labels, @AP_values);
329   my (%AP_paid_labels, @AP_paid_values);
330   my %charts;
331   my $taxchart_init;
332
333   foreach my $item (@{ $form->{ALL_CHARTS} }) {
334     if (grep({ $_ eq "AP_amount" } @{ $item->{link_split} })) {
335       $taxchart_init = $item->{tax_id} if ($taxchart_init eq "");
336       my $key = "$item->{accno}--$item->{tax_id}";
337       push(@AP_amount_values, $key);
338       $AP_amount_labels{$key} =
339         "$item->{accno}--$item->{description}";
340
341     } elsif (grep({ $_ eq "AP" } @{ $item->{link_split} })) {
342       push(@AP_values, $item->{accno});
343       $AP_labels{$item->{accno}} = "$item->{accno}--$item->{description}";
344
345     } elsif (grep({ $_ eq "AP_paid" } @{ $item->{link_split} })) {
346       push(@AP_paid_values, $item->{accno});
347       $AP_paid_labels{$item->{accno}} =
348         "$item->{accno}--$item->{description}";
349     }
350
351     $charts{$item->{accno}} = $item;
352   }
353
354   my %taxchart_labels = ();
355   my @taxchart_values = ();
356   my %taxcharts = ();
357   foreach my $item (@{ $form->{ALL_TAXCHARTS} }) {
358     my $key = "$item->{id}--$item->{rate}";
359     $taxchart_init = $key if ($taxchart_init eq $item->{id});
360     push(@taxchart_values, $key);
361     $taxchart_labels{$key} =
362       "$item->{taxdescription} " . ($item->{rate} * 100) . ' %';
363     $taxcharts{$item->{id}} = $item;
364   }
365
366   # use JavaScript Calendar or not
367   $form->{jsscript} = 1;
368   my $jsscript = "";
369   my ($button1, $button2);
370   if ($form->{jsscript}) {
371
372     # with JavaScript Calendar
373     $button1 = qq|
374        <td><input name=transdate onchange="set_duedate()" id=transdate size=11 title="$myconfig{dateformat}" value="$form->{transdate}" onBlur=\"check_right_date_format(this)\" $readonly></td>
375        <td><input type=button name=transdate id="trigger1" value=|
376       . $locale->text('button') . qq|></td>
377        |;
378     $button2 = qq|
379        <td><input name=duedate id=duedate size=11 title="$myconfig{dateformat}" value="$form->{duedate}" onBlur=\"check_right_date_format(this)\" $readonly></td>
380        <td><input type=button name=duedate id="trigger2" value=|
381       . $locale->text('button') . qq|></td></td>
382      |;
383
384     #write Trigger
385     $jsscript =
386       Form->write_trigger(\%myconfig, "2", "transdate", "BL", "trigger1",
387                           "duedate", "BL", "trigger2");
388   } else {
389
390     # without JavaScript Calendar
391     $button1 =
392       qq|<td><input name=transdate onchange="set_duedate()" id=transdate size=11 title="$myconfig{dateformat}" value="$form->{transdate}" onBlur=\"check_right_date_format(this)\" $readonly></td>|;
393     $button2 =
394       qq|<td><input name=duedate id=duedate size=11 title="$myconfig{dateformat}" value="$form->{duedate}" onBlur=\"check_right_date_format(this)\" $readonly></td>|;
395   }
396
397   my $follow_up_vc         =  $form->{vendor};
398   $follow_up_vc            =~ s/--.*?//;
399   my $follow_up_trans_info =  "$form->{invnumber} ($follow_up_vc)";
400
401   $form->{javascript} .= qq|<script type="text/javascript" src="js/common.js"></script>|;
402   $form->{javascript} .= qq|<script type="text/javascript" src="js/show_vc_details.js"></script>|;
403   $form->{javascript} .= qq|<script type="text/javascript" src="js/follow_up.js"></script>|;
404
405   my $globalprojectnumber =
406     NTI($cgi->popup_menu('-name' => "globalproject_id",
407                          '-values' => \@project_values,
408                          '-labels' => \%project_labels,
409                          '-default' => $form->{"globalproject_id"} ));
410
411   $form->header;
412   print qq|
413 <body onLoad="$onload">
414
415 <form method=post action=$form->{script}>
416
417 <input type=hidden name=id value=$form->{id}>
418 <input type=hidden name=sort value=$form->{sort}>
419 <input type=hidden name=closedto value=$form->{closedto}>
420 <input type=hidden name=locked value=$form->{locked}>
421 <input type=hidden name=title value="$title">
422
423 <input type="hidden" name="follow_up_trans_id_1" value="| . H($form->{id}) . qq|">
424 <input type="hidden" name="follow_up_trans_type_1" value="ap_transaction">
425 <input type="hidden" name="follow_up_trans_info_1" value="| . H($follow_up_trans_info) . qq|">
426 <input type="hidden" name="follow_up_rowcount" value="1">
427
428 | . ($form->{saved_message} ? qq|<p>$form->{saved_message}</p>| : "") . qq|
429
430 <table width=100%>
431   <tr class=listtop>
432     <th class=listtop>$form->{title}</th>
433   </tr>
434   <tr height="5"></tr>
435   <tr valign=top>
436     <td>
437       <table width=100%>
438         <tr valign=top>
439           <td>
440             <table>
441               <tr>
442                 <th align=right nowrap>| . $locale->text('Vendor') . qq|</th>
443                 <td colspan=3>$vendor <input type="button" value="D" onclick="show_vc_details('vendor')"></td>
444                 <input type=hidden name=selectvendor value="| . H($form->{selectvendor}) . qq|">
445                 <input type=hidden name=oldvendor value="| . H($form->{oldvendor}) . qq|">
446                 <input type=hidden name=vendor_id value="| . H($form->{vendor_id}) . qq|">
447                 <input type=hidden name=terms value="| . H($form->{terms}) . qq|">
448               </tr>
449               <tr>
450                 <td></td>
451                 <td colspan=3>
452                   <table width=100%>
453                     <tr>
454                       <th align=left nowrap>| . $locale->text('Credit Limit') . qq|</th>
455                       <td>$form->{creditlimit}</td>
456                       <th align=left nowrap>| . $locale->text('Remaining') . qq|</th>
457                       <td class="plus$n">$form->{creditremaining}</td>
458                       <input type=hidden name=creditlimit value=$form->{creditlimit}>
459                       <input type=hidden name=creditremaining value=$form->{creditremaining}>
460                     </tr>
461                   </table>
462                 </td>
463               <tr>
464                 <th align=right nowrap>| . $locale->text('Currency') . qq|</th>
465                 <td><select name=currency>$form->{selectcurrency}</select></td>
466                 <input type=hidden name=selectcurrency value="$form->{selectcurrency}">
467                 <input type=hidden name=defaultcurrency value=$form->{defaultcurrency}>
468                 <input type=hidden name=fxgain_accno value=$form->{fxgain_accno}>
469                 <input type=hidden name=fxloss_accno value=$form->{fxloss_accno}>
470                 $exchangerate
471               </tr>
472               $department
473               $taxincluded
474             </table>
475           </td>
476           <td align=right>
477             <table>
478               <tr>
479                 <th align=right nowrap>| . $locale->text('Invoice Number') . qq|</th>
480                 <td><input name=invnumber size=11 value="$form->{invnumber}" $readonly></td>
481               </tr>
482               <tr>
483                 <th align=right nowrap>| . $locale->text('Order Number') . qq|</th>
484                 <td><input name=ordnumber size=11 value="$form->{ordnumber}" $readonly></td>
485               </tr>
486               <tr>
487                 <th align=right nowrap>| . $locale->text('Invoice Date') . qq|</th>
488                 $button1
489               </tr>
490               <tr>
491                 <th align=right nowrap>| . $locale->text('Due Date') . qq|</th>
492                 $button2
493               </tr>
494               <tr>
495                 <th align=right nowrap>| . $locale->text('Project Number') . qq|</th>
496                 <td>$globalprojectnumber</td>
497               </tr>
498             </table>
499           </td>
500         </tr>
501       </table>
502     </td>
503   </tr>
504
505
506
507 $jsscript
508   <input type=hidden name=rowcount value=$form->{rowcount}>
509   <tr>
510     <td>
511       <table width=100%>
512         <tr class=listheading>
513           <th class=listheading style="width:15%">| . $locale->text('Account') . qq|</th>
514           <th class=listheading style="width:10%">| . $locale->text('Amount') . qq|</th>
515           <th class=listheading style="width:10%">| . $locale->text('Tax') . qq|</th>
516           <th class=listheading style="width:10%">| . $locale->text('Taxkey') . qq|</th>
517           <th class=listheading style="width:10%">| . $locale->text('Project') . qq|</th>
518         </tr>
519 |;
520
521   my $amount  = $locale->text('Amount');
522   my $project = $locale->text('Project');
523
524   for my $i (1 .. $form->{rowcount}) {
525
526     # format amounts
527     $form->{"amount_$i"} =
528       $form->format_amount(\%myconfig, $form->{"amount_$i"}, 2);
529     $form->{"tax_$i"} = $form->format_amount(\%myconfig, $form->{"tax_$i"}, 2);
530
531     my $selected_accno_full;
532     my ($accno_row) = split(/--/, $form->{"AP_amount_$i"});
533     my $item = $charts{$accno_row};
534     $selected_accno_full = "$item->{accno}--$item->{tax_id}";
535
536     my $selected_taxchart = $form->{"taxchart_$i"};
537     my ($selected_accno, $selected_tax_id) = split(/--/, $selected_accno_full);
538     my ($previous_accno, $previous_tax_id) = split(/--/, $form->{"previous_AP_amount_$i"});
539
540     if ($previous_accno &&
541         ($previous_accno eq $selected_accno) &&
542         ($previous_tax_id ne $selected_tax_id)) {
543       my $item = $taxcharts{$selected_tax_id};
544       $selected_taxchart = "$item->{id}--$item->{rate}";
545     }
546
547     $selected_taxchart = $taxchart_init unless ($form->{"taxchart_$i"});
548
549     my $selectAP_amount =
550       NTI($cgi->popup_menu('-name' => "AP_amount_$i",
551                            '-id' => "AP_amount_$i",
552                            '-style' => 'width:400px',
553                            '-onChange' => "setTaxkey(this, $i)",
554                            '-values' => \@AP_amount_values,
555                            '-labels' => \%AP_amount_labels,
556                            '-default' => $selected_accno_full))
557       . $cgi->hidden('-name' => "previous_AP_amount_$i",
558                      '-default' => $selected_accno_full);
559
560     my $tax = qq|<td>| .
561       NTI($cgi->popup_menu('-name' => "taxchart_$i",
562                            '-id' => "taxchart_$i",
563                            '-style' => 'width:200px',
564                            '-values' => \@taxchart_values,
565                            '-labels' => \%taxchart_labels,
566                            '-default' => $selected_taxchart))
567       . qq|</td>|;
568
569     my $projectnumber =
570       NTI($cgi->popup_menu('-name' => "project_id_$i",
571                            '-values' => \@project_values,
572                            '-labels' => \%project_labels,
573                            '-default' => $form->{"project_id_$i"} ));
574
575     print qq|
576         <tr>
577           <td>$selectAP_amount</td>
578           <td><input name="amount_$i" size=10 value=$form->{"amount_$i"}></td>
579           <td><input type="hidden" name="tax_$i" value="$form->{"tax_$i"}">$form->{"tax_$i"}</td>
580           $tax
581           <td>$projectnumber</td>
582         </tr>
583 |;
584     $amount  = "";
585     $project = "";
586   }
587
588   my $taxlabel =
589     ($form->{taxincluded})
590     ? $locale->text('Tax Included')
591     : $locale->text('Tax');
592
593   $form->{invtotal_unformatted} = $form->{invtotal};
594   $form->{invtotal} = $form->format_amount(\%myconfig, $form->{invtotal}, 2);
595
596   my $APselected =
597     NTI($cgi->popup_menu('-name' => "APselected", '-id' => "APselected",
598                          '-style' => 'width:400px',
599                          '-values' => \@AP_values, '-labels' => \%AP_labels,
600                          '-default' => $form->{APselected}));
601   print qq|
602         <tr>
603           <td colspan=6>
604             <hr noshade>
605           </td>
606         </tr>
607         <tr>
608           <td>${APselected}</td>
609           <th align=left>$form->{invtotal}</th>
610
611           <input type=hidden name=oldinvtotal value=$form->{oldinvtotal}>
612           <input type=hidden name=oldtotalpaid value=$form->{oldtotalpaid}>
613
614           <input type=hidden name=taxaccounts value="$form->{taxaccounts}">
615
616           <td colspan=4></td>
617
618
619         </tr>
620       </table>
621      </td>
622     </tr>
623     <tr>
624       <td>
625         <table width=100%>
626         <tr>
627           <th align=left width=1%>| . $locale->text('Notes') . qq|</th>
628           <td align=left>$notes</td>
629         </tr>
630       </table>
631     </td>
632   </tr>
633   <tr>
634     <td>
635       <table width=100%>
636         <tr class=listheading>
637           <th class=listheading colspan=7>| . $locale->text('Payments') . qq|</th>
638         </tr>
639 |;
640
641   my @column_index;
642   if ($form->{defaultcurrency} && ($form->{currency} eq $form->{defaultcurrency})) {
643     @column_index = qw(datepaid source memo paid AP_paid paid_project_id);
644   } else {
645     @column_index = qw(datepaid source memo paid exchangerate AP_paid paid_project_id);
646   }
647
648   my %column_data;
649   $column_data{datepaid}     = "<th>" . $locale->text('Date') . "</th>";
650   $column_data{paid}         = "<th>" . $locale->text('Amount') . "</th>";
651   $column_data{exchangerate} = "<th>" . $locale->text('Exch') . "</th>";
652   $column_data{AP_paid}      = "<th>" . $locale->text('Account') . "</th>";
653   $column_data{source}       = "<th>" . $locale->text('Source') . "</th>";
654   $column_data{memo}         = "<th>" . $locale->text('Memo') . "</th>";
655   $column_data{paid_project_id} = "<th>" . $locale->text('Project Number') . "</th>";
656
657   print "
658         <tr>
659 ";
660   map { print "$column_data{$_}\n" } @column_index;
661   print "
662         </tr>
663 ";
664
665   my @triggers  = ();
666   $form->{totalpaid} = 0;
667
668   $form->{paidaccounts}++ if ($form->{"paid_$form->{paidaccounts}"});
669   for my $i (1 .. $form->{paidaccounts}) {
670     print "
671         <tr>
672 ";
673
674     my $selectAP_paid =
675       NTI($cgi->popup_menu('-name' => "AP_paid_$i",
676                            '-id' => "AP_paid_$i",
677                            '-values' => \@AP_paid_values,
678                            '-labels' => \%AP_paid_labels,
679                            '-default' => $form->{"AP_paid_$i"}));
680
681     $form->{totalpaid} += $form->{"paid_$i"};
682
683     # format amounts
684     if ($form->{"paid_$i"}) {
685       $form->{"paid_$i"} =
686         $form->format_amount(\%myconfig, $form->{"paid_$i"}, 2);
687     }
688     if ($form->{"exchangerate_$i"} == 0) {
689       $form->{"exchangerate_$i"} = "";
690     } else {
691       $form->{"exchangerate_$i"} =
692         $form->format_amount(\%myconfig, $form->{"exchangerate_$i"});
693     }
694
695     print qq|<input type=hidden name="acc_trans_id_$i" value=$form->{"acc_trans_id_$i"}>\n|;
696     print qq|<input type=hidden name="gldate_$i" value=$form->{"gldate_$i"}>\n|;
697     my $changeable = 1;
698     if ($::lx_office_conf{features}->{payments_changeable} == 0) {
699       # never
700       $changeable = ($form->{"acc_trans_id_$i"})? 0 : 1;
701     }
702     if ($::lx_office_conf{features}->{payments_changeable} == 2) {
703       # on the same day
704       $changeable = (($form->{"gldate_$i"} eq '') || $form->current_date(\%myconfig) eq $form->{"gldate_$i"});
705     }
706
707     $exchangerate = qq|&nbsp;|;
708     if ($form->{defaultcurrency} && ($form->{currency} ne $form->{defaultcurrency})) {
709       if ($form->{"forex_$i"}) {
710         $exchangerate =
711           qq|<input type=hidden name="exchangerate_$i" value=$form->{"exchangerate_$i"}>$form->{"exchangerate_$i"}|;
712       } else {
713         if ($changeable) {
714           $exchangerate =
715             qq|<input name="exchangerate_$i" size=10 value=$form->{"exchangerate_$i"}>|;
716         } else {
717           $exchangerate =
718             qq|<input type=hidden name="exchangerate_$i" value=$form->{"exchangerate_$i"}>$form->{"exchangerate_$i"}|;
719         }
720       }
721     }
722
723     $exchangerate .= qq|
724 <input type=hidden name="forex_$i" value=$form->{"forex_$i"}>
725 |;
726
727     my $datepaid;
728     if ($changeable) {
729       $datepaid = qq|<td align=center><input name="datepaid_$i" id="datepaid_$i" size=11 title="($myconfig{'dateformat'})" value="$form->{"datepaid_$i"}" onBlur=\"check_right_date_format(this)\">
730          <input type="button" name="datepaid_$i" id="trigger_datepaid_$i" value="| . $locale->text('Details (one letter abbreviation)') . qq|"></td>|;
731     } else {
732       $datepaid = qq|<td align=center>$form->{"datepaid_$i"}</td>|.
733         qq|<input type=hidden name="datepaid_$i" value=$form->{"datepaid_$i"}>|;
734     }
735
736     my $paid;
737     if ($changeable) {
738       $paid = qq|<td align=center><input name="paid_$i" size=11 value="$form->{"paid_$i"}" onBlur=\"check_right_number_format(this)\"></td>|;
739     } else {
740       $paid = qq|<td align=center>$form->{"paid_$i"}</td>|.
741         qq|<input type=hidden name="paid_$i" value=$form->{"paid_$i"}>|;
742     }
743
744     my $source;
745     if ($changeable) {
746       $source = qq|<td align=center><input name="source_$i" size=11 value="$form->{"source_$i"}"></td>|;
747     } else {
748       $source = qq|<td align=center>$form->{"source_$i"}</td>|.
749         qq|<input type=hidden name="source_$i" value=$form->{"source_$i"}>|;
750     }
751
752     my $memo;
753     if ($changeable) {
754       $memo = qq|<td align=center><input name="memo_$i" size=11 value="$form->{"memo_$i"}"></td>|;
755     } else {
756       $memo = qq|<td align=center>$form->{"memo_$i"}</td>|.
757         qq|<input type=hidden name="memo_$i" value=$form->{"memo_$i"}>|;
758     }
759
760     my $AP_paid;
761     if ($changeable) {
762       $AP_paid = qq|<td align=center>${selectAP_paid}</td>|;
763     } else {
764       $AP_paid = qq|<td align=center>$form->{"AP_paid_$i"}</td>|.
765         qq|<input type=hidden name="AP_paid_$i" value=$form->{"AP_paid_$i"}>|;
766     }
767
768     my $paid_project_id;
769     if ($changeable) {
770       $paid_project_id =
771       qq|<td>|
772       . NTI($cgi->popup_menu('-name' => "paid_project_id_$i",
773                              '-values' => \@project_values,
774                              '-labels' => \%project_labels,
775                              '-default' => $form->{"paid_project_id_$i"} ))
776       . qq|</td>|;
777     } else {
778       my $projectnumber = $project_labels{$form->{"paid_project_id_$i"}};
779       $paid_project_id = qq|<td>$projectnumber</td>|.
780         qq|<input type=hidden name="paid_project_id_$i" value=$form->{"paid_project_id_$i"}>|;
781     }
782
783     $column_data{"paid_$i"}            = $paid;
784     $column_data{"AP_paid_$i"}         = $AP_paid;
785     $column_data{"exchangerate_$i"}    = qq|<td align=center>$exchangerate</td>|;
786     $column_data{"datepaid_$i"}        = $datepaid;
787     $column_data{"source_$i"}          = $source;
788     $column_data{"memo_$i"}            = $memo;
789     $column_data{"paid_project_id_$i"} = $paid_project_id;
790
791     map { print qq|$column_data{"${_}_$i"}\n| } @column_index;
792
793     print "
794         </tr>
795 ";
796     if ($changeable) {
797       push(@triggers, "datepaid_$i", "BL", "trigger_datepaid_$i");
798     }
799   }
800
801   my $paid_missing = $form->{invtotal_unformatted} - $form->{totalpaid};
802
803   print qq|
804         <tr>
805           <td></td>
806           <td></td>
807           <td align="center">| . $locale->text('Total') . qq|</td>
808           <td align="center">| . H($form->format_amount(\%myconfig, $form->{totalpaid}, 2)) . qq|</td>
809         </tr>
810         <tr>
811           <td></td>
812           <td></td>
813           <td align="center">| . $locale->text('Missing amount') . qq|</td>
814           <td align="center">| . H($form->format_amount(\%myconfig, $paid_missing, 2)) . qq|</td>
815         </tr>
816 | . $form->write_trigger(\%myconfig, scalar(@triggers) / 3, @triggers) .
817     qq|
818     <input type=hidden name=paidaccounts value=$form->{paidaccounts}>
819
820       </table>
821     </td>
822   </tr>
823   <tr>
824     <td><hr size=3 noshade></td>
825   </tr>
826 </table>
827 |;
828
829   $main::lxdebug->leave_sub();
830 }
831
832 sub form_footer {
833   $::lxdebug->enter_sub;
834   $::auth->assert('general_ledger');
835
836   my $num_due;
837   my $num_follow_ups;
838   if ($::form->{id}) {
839     my $follow_ups = FU->follow_ups('trans_id' => $::form->{id});
840
841     if (@{ $follow_ups }) {
842       $num_due        = sum map { $_->{due} * 1 } @{ $follow_ups };
843       $num_follow_ups = scalar @{ $follow_ups }
844     }
845   }
846
847   my $transdate = $::form->datetonum($::form->{transdate}, \%::myconfig);
848   my $closedto  = $::form->datetonum($::form->{closedto},  \%::myconfig);
849
850   my $storno = $::form->{id}
851             && !IS->has_storno(\%::myconfig, $::form, 'ap')
852             && !IS->is_storno( \%::myconfig, $::form, 'ap', $::form->{id})
853             && ($::form->{totalpaid} == 0 || $::form->{totalpaid} eq '');
854
855   $::form->header;
856   print $::form->parse_html_template('ap/form_footer', {
857     num_due         => $num_due,
858     num_follow_ups  => $num_follow_ups,
859     show_post_draft => ($transdate > $closedto) && !$::form->{id},
860     show_storno     => $storno,
861   });
862
863   $::lxdebug->leave_sub;
864 }
865
866 sub mark_as_paid {
867   $main::lxdebug->enter_sub();
868
869   my $form     = $main::form;
870   my %myconfig = %main::myconfig;
871
872   $main::auth->assert('general_ledger');
873
874   &mark_as_paid_common(\%myconfig,"ap");
875
876   $main::lxdebug->leave_sub();
877 }
878
879 sub update {
880   $main::lxdebug->enter_sub();
881
882   my $form     = $main::form;
883   my %myconfig = %main::myconfig;
884
885   $main::auth->assert('general_ledger');
886
887   my $display = shift;
888
889   $form->{invtotal} = 0;
890
891   delete @{ $form }{ grep { m/^tax_\d+$/ } keys %{ $form } };
892
893   map { $form->{$_} = $form->parse_amount(\%myconfig, $form->{$_}) }
894     qw(exchangerate creditlimit creditremaining);
895
896   my @flds  = qw(amount AP_amount projectnumber oldprojectnumber project_id taxchart);
897   my $count = 0;
898   my (@a, $j, $totaltax);
899   for my $i (1 .. $form->{rowcount}) {
900     $form->{"amount_$i"} =
901       $form->parse_amount(\%myconfig, $form->{"amount_$i"});
902     $form->{"tax_$i"} = $form->parse_amount(\%myconfig, $form->{"tax_$i"});
903     if ($form->{"amount_$i"}) {
904       push @a, {};
905       $j = $#a;
906       my ($taxkey, $rate) = split(/--/, $form->{"taxchart_$i"});
907       if ($taxkey > 1) {
908         if ($form->{taxincluded}) {
909           $form->{"tax_$i"} = $form->{"amount_$i"} / ($rate + 1) * $rate;
910         } else {
911           $form->{"tax_$i"} = $form->{"amount_$i"} * $rate;
912         }
913       } else {
914         $form->{"tax_$i"} = 0;
915       }
916       $form->{"tax_$i"} = $form->round_amount($form->{"tax_$i"}, 2);
917
918       $totaltax += $form->{"tax_$i"};
919       map { $a[$j]->{$_} = $form->{"${_}_$i"} } @flds;
920       $count++;
921     }
922   }
923   $form->redo_rows(\@flds, \@a, $count, $form->{rowcount});
924
925   map { $form->{invtotal} += $form->{"amount_$_"} } (1 .. $form->{rowcount});
926
927   $form->{forex}        = $form->check_exchangerate( \%myconfig, $form->{currency}, $form->{transdate}, 'sell');
928   $form->{exchangerate} = $form->{forex} if $form->{forex};
929
930   $form->{invdate} = $form->{transdate};
931   my %saved_variables = map +( $_ => $form->{$_} ), qw(AP AP_amount_1 taxchart_1);
932
933   my $vendor_changed = &check_name("vendor");
934
935   $form->{AP} = $saved_variables{AP};
936   if ($saved_variables{AP_amount_1} =~ m/.--./) {
937     map { $form->{$_} = $saved_variables{$_} } qw(AP_amount_1 taxchart_1);
938   } else {
939     delete $form->{taxchart_1};
940   }
941
942   $form->{rowcount} = $count + 1;
943
944   $form->{invtotal} =
945     ($form->{taxincluded}) ? $form->{invtotal} : $form->{invtotal} + $totaltax;
946
947   my $totalpaid;
948   for my $i (1 .. $form->{paidaccounts}) {
949     if ($form->parse_amount(\%myconfig, $form->{"paid_$i"})) {
950       map {
951         $form->{"${_}_$i"} =
952           $form->parse_amount(\%myconfig, $form->{"${_}_$i"})
953       } qw(paid exchangerate);
954
955       $totalpaid += $form->{"paid_$i"};
956
957       $form->{"forex_$i"}        = $form->check_exchangerate( \%myconfig, $form->{currency}, $form->{"datepaid_$i"}, 'sell');
958       $form->{"exchangerate_$i"} = $form->{"forex_$i"} if $form->{"forex_$i"};
959     }
960   }
961
962   $form->{creditremaining} -=
963     ($form->{invtotal} - $totalpaid + $form->{oldtotalpaid} -
964      $form->{oldinvtotal});
965   $form->{oldinvtotal}  = $form->{invtotal};
966   $form->{oldtotalpaid} = $totalpaid;
967
968   # notes
969   $form->{notes} = $form->{intnotes} if $vendor_changed;
970
971   &display_form;
972
973   $main::lxdebug->leave_sub();
974 }
975
976
977 sub post_payment {
978   $main::lxdebug->enter_sub();
979
980   my $form     = $main::form;
981   my %myconfig = %main::myconfig;
982   my $locale   = $main::locale;
983
984   $main::auth->assert('general_ledger');
985
986   $form->{defaultcurrency} = $form->get_default_currency(\%myconfig);
987
988   my $invdate = $form->datetonum($form->{transdate}, \%myconfig);
989
990   for my $i (1 .. $form->{paidaccounts}) {
991     if ($form->parse_amount(\%myconfig, $form->{"paid_$i"})) {
992       my $datepaid = $form->datetonum($form->{"datepaid_$i"}, \%myconfig);
993
994       $form->isblank("datepaid_$i", $locale->text('Payment date missing!'));
995
996       $form->error($locale->text('Cannot post payment for a closed period!'))
997         if ($form->date_closed($form->{"datepaid_$i"}, \%myconfig));
998
999       if ($form->{defaultcurrency} && ($form->{currency} ne $form->{defaultcurrency})) {
1000         $form->{"exchangerate_$i"} = $form->{exchangerate}
1001           if ($invdate == $datepaid);
1002         $form->isblank("exchangerate_$i",
1003                        $locale->text('Exchangerate for payment missing!'));
1004       }
1005     }
1006   }
1007
1008   ($form->{AP})      = split /--/, $form->{AP};
1009   ($form->{AP_paid}) = split /--/, $form->{AP_paid};
1010   $form->redirect($locale->text('Payment posted!'))
1011       if (AP->post_payment(\%myconfig, \%$form));
1012     $form->error($locale->text('Cannot post payment!'));
1013
1014
1015   $main::lxdebug->leave_sub();
1016 }
1017
1018
1019 sub post {
1020   $main::lxdebug->enter_sub();
1021
1022   my $form     = $main::form;
1023   my %myconfig = %main::myconfig;
1024   my $locale   = $main::locale;
1025
1026   $main::auth->assert('general_ledger');
1027
1028   my ($inline) = @_;
1029
1030   # check if there is a vendor, invoice and due date
1031   $form->isblank("transdate", $locale->text("Invoice Date missing!"));
1032   $form->isblank("duedate",   $locale->text("Due Date missing!"));
1033   $form->isblank("vendor",    $locale->text('Vendor missing!'));
1034
1035   if ($myconfig{mandatory_departments} && !$form->{department}) {
1036     $form->{saved_message} = $::locale->text('You have to specify a department.');
1037     update();
1038     exit;
1039   }
1040
1041   my $closedto  = $form->datetonum($form->{closedto},  \%myconfig);
1042   my $transdate = $form->datetonum($form->{transdate}, \%myconfig);
1043   $form->error($locale->text('Cannot post transaction for a closed period!')) if ($form->date_closed($form->{"transdate"}, \%myconfig));
1044
1045   my $zero_amount_posting = 1;
1046   for my $i (1 .. $form->{rowcount}) {
1047     if ($form->parse_amount(\%myconfig, $form->{"amount_$i"})) {
1048       $zero_amount_posting = 0;
1049       last;
1050     }
1051   }
1052
1053   $form->error($locale->text('Zero amount posting!')) if $zero_amount_posting;
1054
1055   $form->isblank("exchangerate", $locale->text('Exchangerate missing!'))
1056     if ($form->{defaultcurrency} && ($form->{currency} ne $form->{defaultcurrency}));
1057   delete($form->{AP});
1058
1059   for my $i (1 .. $form->{paidaccounts}) {
1060     if ($form->parse_amount(\%myconfig, $form->{"paid_$i"})) {
1061       my $datepaid = $form->datetonum($form->{"datepaid_$i"}, \%myconfig);
1062
1063       $form->isblank("datepaid_$i", $locale->text('Payment date missing!'));
1064
1065       $form->error($locale->text('Cannot post payment for a closed period!'))
1066         if ($form->date_closed($form->{"datepaid_$i"}, \%myconfig));
1067
1068       if ($form->{defaultcurrency} && ($form->{currency} ne $form->{defaultcurrency})) {
1069         $form->{"exchangerate_$i"} = $form->{exchangerate}
1070           if ($transdate == $datepaid);
1071         $form->isblank("exchangerate_$i",
1072                        $locale->text('Exchangerate for payment missing!'));
1073       }
1074
1075     }
1076   }
1077
1078   # if old vendor ne vendor redo form
1079   my ($vendor) = split /--/, $form->{vendor};
1080   if ($form->{oldvendor} ne "$vendor--$form->{vendor_id}") {
1081     &update;
1082     ::end_of_request();
1083   }
1084   my ($debitaccno,    $debittaxkey)    = split /--/, $form->{AP_amountselected};
1085   my ($taxkey,        $NULL)           = split /--/, $form->{taxchartselected};
1086   my ($payablesaccno, $payablestaxkey) = split /--/, $form->{APselected};
1087 #  $form->{AP_amount_1}  = $debitaccno;
1088   $form->{AP_payables}  = $payablesaccno;
1089   $form->{taxkey}       = $taxkey;
1090   $form->{storno}       = 0;
1091
1092   $form->{id} = 0 if $form->{postasnew};
1093
1094   if (AP->post_transaction(\%myconfig, \%$form)) {
1095     # saving the history
1096     if(!exists $form->{addition} && $form->{id} ne "") {
1097       $form->{snumbers} = qq|invnumber_| . $form->{invnumber};
1098       $form->{addition} = "POSTED";
1099       $form->save_history;
1100     }
1101     # /saving the history
1102     remove_draft() if $form->{remove_draft};
1103     # Dieser Text wird niemals ausgegeben: Probleme beim redirect?
1104     $form->redirect($locale->text('Transaction posted!')) unless $inline;
1105   } else {
1106     $form->error($locale->text('Cannot post transaction!'));
1107   }
1108
1109   $main::lxdebug->leave_sub();
1110 }
1111
1112 sub post_as_new {
1113   $main::lxdebug->enter_sub();
1114
1115   my $form     = $main::form;
1116   my %myconfig = %main::myconfig;
1117
1118   $main::auth->assert('general_ledger');
1119
1120   $form->{postasnew} = 1;
1121   # saving the history
1122   if(!exists $form->{addition} && $form->{id} ne "") {
1123     $form->{snumbers} = qq|invnumber_| . $form->{invnumber};
1124     $form->{addition} = "POSTED AS NEW";
1125     $form->save_history;
1126   }
1127   # /saving the history
1128   &post;
1129
1130   $main::lxdebug->leave_sub();
1131 }
1132
1133 sub use_as_template {
1134   $main::lxdebug->enter_sub();
1135
1136   my $form     = $main::form;
1137   my %myconfig = %main::myconfig;
1138
1139   $main::auth->assert('general_ledger');
1140
1141   map { delete $form->{$_} } qw(printed emailed queued invnumber invdate deliverydate id datepaid_1 gldate_1 acc_trans_id_1 source_1 memo_1 paid_1 exchangerate_1 AP_paid_1 storno);
1142   $form->{paidaccounts} = 1;
1143   $form->{rowcount}--;
1144   $form->{invdate} = $form->current_date(\%myconfig);
1145   &update;
1146
1147   $main::lxdebug->leave_sub();
1148 }
1149
1150 sub delete {
1151   $main::lxdebug->enter_sub();
1152
1153   my $form     = $main::form;
1154   my $locale   = $main::locale;
1155
1156   $main::auth->assert('general_ledger');
1157
1158   $form->{title} = $locale->text('Confirm!');
1159
1160   $form->header;
1161
1162   delete $form->{header};
1163
1164   print qq|
1165 <form method=post action=$form->{script}>
1166 |;
1167
1168   foreach my $key (keys %$form) {
1169     next if (($key eq 'login') || ($key eq 'password') || ('' ne ref $form->{$key}));
1170     $form->{$key} =~ s/\"/&quot;/g;
1171     print qq|<input type=hidden name=$key value="$form->{$key}">\n|;
1172   }
1173
1174   print qq|
1175 <h2 class=confirm>$form->{title}</h2>
1176
1177 <h4>|
1178     . $locale->text('Are you sure you want to delete Transaction')
1179     . qq| $form->{invnumber}</h4>
1180
1181 <input name=action class=submit type=submit value="|
1182     . $locale->text('Yes') . qq|">
1183 </form>
1184 |;
1185
1186   $main::lxdebug->leave_sub();
1187 }
1188
1189 sub yes {
1190   $main::lxdebug->enter_sub();
1191
1192   my $form     = $main::form;
1193   my %myconfig = %main::myconfig;
1194   my $locale   = $main::locale;
1195
1196   $main::auth->assert('general_ledger');
1197
1198   if (AP->delete_transaction(\%myconfig, \%$form)) {
1199     # saving the history
1200     if(!exists $form->{addition}) {
1201       $form->{snumbers} = qq|invnumber_| . $form->{invnumber};
1202       $form->{addition} = "DELETED";
1203       $form->save_history;
1204     }
1205     # /saving the history
1206     $form->redirect($locale->text('Transaction deleted!'));
1207   }
1208   $form->error($locale->text('Cannot delete transaction!'));
1209
1210   $main::lxdebug->leave_sub();
1211 }
1212
1213 sub search {
1214   $main::lxdebug->enter_sub();
1215
1216   $main::auth->assert('general_ledger | vendor_invoice_edit');
1217
1218   my $form     = $main::form;
1219   my %myconfig = %main::myconfig;
1220   my $locale   = $main::locale;
1221
1222   # setup customer selection
1223   $form->all_vc(\%myconfig, "vendor", "AP");
1224
1225   $form->{title}    = $locale->text('AP Transactions');
1226   $form->{fokus}    = "search.vendor";
1227   $form->{jsscript} = 1;
1228
1229   $form->get_lists("projects"     => { "key" => "ALL_PROJECTS", "all" => 1 },
1230                    "departments"  => "ALL_DEPARTMENTS",
1231                    "vendors"      => "ALL_VC");
1232
1233   # constants and subs for template
1234   $form->{jsscript}  = 1;
1235   $form->{vc_keys}   = sub { "$_[0]->{name}--$_[0]->{id}" };
1236
1237   $form->header;
1238   print $form->parse_html_template('ap/search', { %myconfig });
1239
1240   $main::lxdebug->leave_sub();
1241 }
1242
1243 sub create_subtotal_row {
1244   $main::lxdebug->enter_sub();
1245
1246   my ($totals, $columns, $column_alignment, $subtotal_columns, $class) = @_;
1247
1248   my $form     = $main::form;
1249   my %myconfig = %main::myconfig;
1250
1251   my $row = { map { $_ => { 'data' => '', 'class' => $class, 'align' => $column_alignment->{$_}, } } @{ $columns } };
1252
1253   map { $row->{$_}->{data} = $form->format_amount(\%myconfig, $totals->{$_}, 2) } @{ $subtotal_columns };
1254
1255   $row->{tax}->{data} = $form->format_amount(\%myconfig, $totals->{amount} - $totals->{netamount}, 2);
1256
1257   map { $totals->{$_} = 0 } @{ $subtotal_columns };
1258
1259   $main::lxdebug->leave_sub();
1260
1261   return $row;
1262 }
1263
1264 sub ap_transactions {
1265   $main::lxdebug->enter_sub();
1266
1267   my $form     = $main::form;
1268   my %myconfig = %main::myconfig;
1269   my $locale   = $main::locale;
1270
1271   $main::auth->assert('general_ledger | vendor_invoice_edit');
1272
1273   ($form->{vendor}, $form->{vendor_id}) = split(/--/, $form->{vendor});
1274
1275   report_generator_set_default_sort('transdate', 1);
1276
1277   AP->ap_transactions(\%myconfig, \%$form);
1278
1279   $form->{title} = $locale->text('AP Transactions');
1280
1281   my $report = SL::ReportGenerator->new(\%myconfig, $form);
1282
1283   my @columns =
1284     qw(transdate id type invnumber ordnumber name netamount tax amount paid datepaid
1285        due duedate transaction_description notes employee globalprojectnumber
1286        vendornumber country ustid taxzone payment_terms charts);
1287
1288   my @hidden_variables = map { "l_${_}" } @columns;
1289   push @hidden_variables, "l_subtotal", qw(open closed vendor invnumber ordnumber transaction_description notes project_id transdatefrom transdateto department);
1290
1291   my $href = build_std_url('action=ap_transactions', grep { $form->{$_} } @hidden_variables);
1292
1293   my %column_defs = (
1294     'transdate'               => { 'text' => $locale->text('Date'), },
1295     'id'                      => { 'text' => $locale->text('ID'), },
1296     'type'                    => { 'text' => $locale->text('Type'), },
1297     'invnumber'               => { 'text' => $locale->text('Invoice'), },
1298     'ordnumber'               => { 'text' => $locale->text('Order'), },
1299     'name'                    => { 'text' => $locale->text('Vendor'), },
1300     'netamount'               => { 'text' => $locale->text('Amount'), },
1301     'tax'                     => { 'text' => $locale->text('Tax'), },
1302     'amount'                  => { 'text' => $locale->text('Total'), },
1303     'paid'                    => { 'text' => $locale->text('Paid'), },
1304     'datepaid'                => { 'text' => $locale->text('Date Paid'), },
1305     'due'                     => { 'text' => $locale->text('Amount Due'), },
1306     'duedate'                 => { 'text' => $locale->text('Due Date'), },
1307     'transaction_description' => { 'text' => $locale->text('Transaction description'), },
1308     'notes'                   => { 'text' => $locale->text('Notes'), },
1309     'employee'                => { 'text' => $locale->text('Employee'), },
1310     'globalprojectnumber'     => { 'text' => $locale->text('Document Project Number'), },
1311     'vendornumber'            => { 'text' => $locale->text('Vendor Number'), },
1312     'country'                 => { 'text' => $locale->text('Country'), },
1313     'ustid'                   => { 'text' => $locale->text('USt-IdNr.'), },
1314     'taxzone'                 => { 'text' => $locale->text('Steuersatz'), },
1315     'payment_terms'           => { 'text' => $locale->text('Payment Terms'), },
1316     'charts'                  => { 'text' => $locale->text('Buchungskonto'), },
1317   );
1318
1319   foreach my $name (qw(id transdate duedate invnumber ordnumber name datepaid employee shippingpoint shipvia transaction_description)) {
1320     my $sortdir                 = $form->{sort} eq $name ? 1 - $form->{sortdir} : $form->{sortdir};
1321     $column_defs{$name}->{link} = $href . "&sort=$name&sortdir=$sortdir";
1322   }
1323
1324   my %column_alignment = map { $_ => 'right' } qw(netamount tax amount paid due);
1325
1326   $form->{"l_type"} = "Y";
1327   map { $column_defs{$_}->{visible} = $form->{"l_${_}"} ? 1 : 0 } @columns;
1328
1329   $report->set_columns(%column_defs);
1330   $report->set_column_order(@columns);
1331
1332   $report->set_export_options('ap_transactions', @hidden_variables, qw(sort sortdir));
1333
1334   $report->set_sort_indicator($form->{sort}, $form->{sortdir});
1335
1336   my @options;
1337   push @options, $locale->text('Vendor')                  . " : $form->{vendor}"                         if ($form->{vendor});
1338   push @options, $locale->text('Department')              . " : " . (split /--/, $form->{department})[0] if ($form->{department});
1339   push @options, $locale->text('Invoice Number')          . " : $form->{invnumber}"                      if ($form->{invnumber});
1340   push @options, $locale->text('Order Number')            . " : $form->{ordnumber}"                      if ($form->{ordnumber});
1341   push @options, $locale->text('Notes')                   . " : $form->{notes}"                          if ($form->{notes});
1342   push @options, $locale->text('Transaction description') . " : $form->{transaction_description}"        if ($form->{transaction_description});
1343   push @options, $locale->text('From') . " " . $locale->date(\%myconfig, $form->{transdatefrom}, 1)      if ($form->{transdatefrom});
1344   push @options, $locale->text('Bis')  . " " . $locale->date(\%myconfig, $form->{transdateto},   1)      if ($form->{transdateto});
1345   push @options, $locale->text('Open')                                                                   if ($form->{open});
1346   push @options, $locale->text('Closed')                                                                 if ($form->{closed});
1347
1348   $report->set_options('top_info_text'        => join("\n", @options),
1349                        'raw_bottom_info_text' => $form->parse_html_template('ap/ap_transactions_bottom'),
1350                        'output_format'        => 'HTML',
1351                        'title'                => $form->{title},
1352                        'attachment_basename'  => $locale->text('vendor_invoice_list') . strftime('_%Y%m%d', localtime time),
1353     );
1354   $report->set_options_from_form();
1355   $locale->set_numberformat_wo_thousands_separator(\%myconfig) if lc($report->{options}->{output_format}) eq 'csv';
1356
1357   # add sort and escape callback, this one we use for the add sub
1358   $form->{callback} = $href .= "&sort=$form->{sort}";
1359
1360   # escape callback for href
1361   my $callback = $form->escape($href);
1362
1363   my @subtotal_columns = qw(netamount amount paid due);
1364
1365   my %totals    = map { $_ => 0 } @subtotal_columns;
1366   my %subtotals = map { $_ => 0 } @subtotal_columns;
1367
1368   my $idx = 0;
1369
1370   foreach my $ap (@{ $form->{AP} }) {
1371     $ap->{tax} = $ap->{amount} - $ap->{netamount};
1372     $ap->{due} = $ap->{amount} - $ap->{paid};
1373
1374     map { $subtotals{$_} += $ap->{$_};
1375           $totals{$_}    += $ap->{$_} } @subtotal_columns;
1376
1377     map { $ap->{$_} = $form->format_amount(\%myconfig, $ap->{$_}, 2) } qw(netamount tax amount paid due);
1378
1379     my $is_storno  = $ap->{storno} &&  $ap->{storno_id};
1380     my $has_storno = $ap->{storno} && !$ap->{storno_id};
1381
1382     if ($ap->{invoice}) {
1383       $ap->{type} =
1384           $has_storno       ? $locale->text("Invoice with Storno (abbreviation)")
1385         : $is_storno        ? $locale->text("Storno (one letter abbreviation)")
1386         :                     $locale->text("Invoice (one letter abbreviation)");
1387     } else {
1388       $ap->{type} =
1389           $has_storno       ? $locale->text("AP Transaction with Storno (abbreviation)")
1390         : $is_storno        ? $locale->text("AP Transaction Storno (one letter abbreviation)")
1391         :                     $locale->text("AP Transaction (abbreviation)");
1392     }
1393
1394     my $row = { };
1395
1396     foreach my $column (@columns) {
1397       $row->{$column} = {
1398         'data'  => $ap->{$column},
1399         'align' => $column_alignment{$column},
1400       };
1401     }
1402
1403     $row->{invnumber}->{link} = build_std_url("script=" . ($ap->{invoice} ? 'ir.pl' : 'ap.pl'), 'action=edit')
1404       . "&id=" . E($ap->{id}) . "&callback=${callback}";
1405
1406     my $row_set = [ $row ];
1407
1408     if (($form->{l_subtotal} eq 'Y')
1409         && (($idx == (scalar @{ $form->{AP} } - 1))
1410             || ($ap->{ $form->{sort} } ne $form->{AP}->[$idx + 1]->{ $form->{sort} }))) {
1411       push @{ $row_set }, create_subtotal_row(\%subtotals, \@columns, \%column_alignment, \@subtotal_columns, 'listsubtotal');
1412     }
1413
1414     $report->add_data($row_set);
1415
1416     $idx++;
1417   }
1418
1419   $report->add_separator();
1420   $report->add_data(create_subtotal_row(\%totals, \@columns, \%column_alignment, \@subtotal_columns, 'listtotal'));
1421
1422   $report->generate_with_headers();
1423
1424   $main::lxdebug->leave_sub();
1425 }
1426
1427 sub storno {
1428   $main::lxdebug->enter_sub();
1429
1430   my $form     = $main::form;
1431   my %myconfig = %main::myconfig;
1432   my $locale   = $main::locale;
1433
1434   $main::auth->assert('general_ledger');
1435
1436   if (IS->has_storno(\%myconfig, $form, 'ap')) {
1437     $form->{title} = $locale->text("Cancel Accounts Payables Transaction");
1438     $form->error($locale->text("Transaction has already been cancelled!"));
1439   }
1440
1441   $form->error($locale->text('Cannot post storno for a closed period!'))
1442     if ( $form->date_closed($form->{transdate}, \%myconfig));
1443
1444   AP->storno($form, \%myconfig, $form->{id});
1445
1446   # saving the history
1447   if(!exists $form->{addition} && $form->{id} ne "") {
1448     $form->{snumbers} = "ordnumber_$form->{ordnumber}";
1449     $form->{addition} = "STORNO";
1450     $form->save_history;
1451   }
1452   # /saving the history
1453
1454   $form->redirect(sprintf $locale->text("Transaction %d cancelled."), $form->{storno_id});
1455
1456   $main::lxdebug->leave_sub();
1457 }