Tabs aus *.pl Dateien entfernt.
[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" 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   my @curr = split(/:/, $form->{currencies});
160   chomp $curr[0];
161   $form->{defaultcurrency} = $curr[0];
162
163   map { $form->{selectcurrency} .= "<option>$_\n" } @curr;
164
165   # vendors
166   if (@{ $form->{all_vendor} || [] }) {
167     $form->{vendor} = qq|$form->{vendor}--$form->{vendor_id}|;
168     map { $form->{selectvendor} .= "<option>$_->{name}--$_->{id}\n" }
169       (@{ $form->{all_vendor} });
170   }
171
172   # departments
173   if (@{ $form->{all_departments} || [] }) {
174     $form->{selectdepartment} = "<option>\n";
175     $form->{department}       = "$form->{department}--$form->{department_id}";
176
177     map {
178       $form->{selectdepartment} .=
179         "<option>$_->{description}--$_->{id}\n"
180     } (@{ $form->{all_departments} || [] });
181   }
182
183   $form->{employee} = "$form->{employee}--$form->{employee_id}";
184
185   AP->setup_form($form);
186
187   $form->{locked} =
188     ($form->datetonum($form->{transdate}, \%myconfig) <=
189      $form->datetonum($form->{closedto}, \%myconfig));
190
191   $main::lxdebug->leave_sub();
192 }
193
194 sub form_header {
195   $main::lxdebug->enter_sub();
196
197   my $form     = $main::form;
198   my %myconfig = %main::myconfig;
199   my $locale   = $main::locale;
200   my $cgi      = $main::cgi;
201
202   $main::auth->assert('general_ledger');
203
204   my $title = $form->{title};
205   $form->{title} = $locale->text("$title Accounts Payables Transaction");
206
207   $form->{taxincluded} = ($form->{taxincluded}) ? "checked" : "";
208
209   # type=submit $locale->text('Add Accounts Payables Transaction')
210   # type=submit $locale->text('Edit Accounts Payables Transaction')
211
212   $form->{javascript} = qq|<script type="text/javascript">
213   <!--
214   function setTaxkey(accno, row) {
215     var taxkey = accno.options[accno.selectedIndex].value;
216     var reg = /--([0-9]*)/;
217     var found = reg.exec(taxkey);
218     var index = found[1];
219     index = parseInt(index);
220     var tax = 'taxchart_' + row;
221     for (var i = 0; i < document.getElementById(tax).options.length; ++i) {
222       var reg2 = new RegExp("^"+ index, "");
223       if (reg2.exec(document.getElementById(tax).options[i].value)) {
224         document.getElementById(tax).options[i].selected = true;
225         break;
226       }
227     }
228   };
229   //-->
230   </script>|;
231   # show history button
232   $form->{javascript} .= qq|<script type="text/javascript" src="js/show_history.js"></script>|;
233   #/show hhistory button
234
235   # set option selected
236   foreach my $item (qw(vendor currency department)) {
237     $form->{"select$item"} =~ s/ selected//;
238     $form->{"select$item"} =~
239       s/option>\Q$form->{$item}\E/option selected>$form->{$item}/;
240   }
241   my $readonly = ($form->{id}) ? "readonly" : "";
242
243   $form->{radier} = ($form->current_date(\%myconfig) eq $form->{gldate}) ? 1 : 0;
244   $readonly       = ($form->{radier}) ? "" : $readonly;
245
246   $form->{forex}        = $form->check_exchangerate( \%myconfig, $form->{currency}, $form->{transdate}, 'sell');
247   $form->{exchangerate} = $form->{forex} if $form->{forex};
248
249
250   # format amounts
251   $form->{exchangerate} =
252     $form->format_amount(\%myconfig, $form->{exchangerate});
253   if ($form->{exchangerate} == 0) {
254     $form->{exchangerate} = "";
255   }
256   $form->{creditlimit} =
257     $form->format_amount(\%myconfig, $form->{creditlimit}, 0, "0");
258   $form->{creditremaining} =
259     $form->format_amount(\%myconfig, $form->{creditremaining}, 0, "0");
260
261   my $exchangerate = qq|
262 <input type=hidden name=forex value=$form->{forex}>
263 |;
264   if ($form->{currency} ne $form->{defaultcurrency}) {
265     if ($form->{forex}) {
266       $exchangerate .= qq|
267             <tr>
268               <th align=right>| . $locale->text('Exchangerate') . qq|</th>
269               <td><input type=hidden name=exchangerate value=$form->{exchangerate}>$form->{exchangerate}</td>
270            </tr>
271 |;
272     } else {
273       $exchangerate .= qq|
274              <th align=right>| . $locale->text('Exchangerate') . qq|</th>
275              <td><input name=exchangerate size=10 value=$form->{exchangerate}></td>
276 |;
277     }
278   }
279
280   my $taxincluded = "";
281
282   $taxincluded = qq|
283             <tr>
284               <td align=right><input name=taxincluded class=checkbox type=checkbox value=1 $form->{taxincluded}></td>
285               <th align=left nowrap>|
286     . $locale->text('Tax Included') . qq|</th>
287             </tr>
288 |;
289
290   my $rows;
291   if (($rows = $form->numtextrows($form->{notes}, 50)) < 2) {
292     $rows = 2;
293   }
294   my $notes =
295     qq|<textarea name=notes rows=$rows cols=50 wrap=soft $readonly>$form->{notes}</textarea>|;
296
297   my $department = qq|
298               <tr>
299                 <th align="right" nowrap>| . $locale->text('Department') . qq|</th>
300                 <td colspan=3><select name=department>$form->{selectdepartment}</select>
301                 <input type=hidden name=selectdepartment value="$form->{selectdepartment}">
302                 </td>
303               </tr>
304 | if $form->{selectdepartment};
305
306   my $n = ($form->{creditremaining} =~ /-/) ? "0" : "1";
307
308   my $vendor =
309     ($form->{selectvendor})
310     ? qq|<select name="vendor" onchange="document.getElementById('update_button').click();">$form->{selectvendor} </select>|
311     : qq|<input name=vendor value="$form->{vendor}" size=35>|;
312
313   my @old_project_ids = ();
314   map({ push(@old_project_ids, $form->{"project_id_$_"})
315           if ($form->{"project_id_$_"}); } (1..$form->{"rowcount"}));
316
317   $form->get_lists("projects"  => { "key"       => "ALL_PROJECTS",
318                                     "all"       => 0,
319                                     "old_id"    => \@old_project_ids },
320                    "charts"    => { "key"       => "ALL_CHARTS",
321                                     "transdate" => $form->{transdate} },
322                    "taxcharts" => { "key"       => "ALL_TAXCHARTS",
323                                     "module"    => "AP" },);
324
325   map({ $_->{link_split} = [ split(/:/, $_->{link}) ]; }
326       @{ $form->{ALL_CHARTS} });
327
328   my %project_labels = ();
329   my @project_values = ("");
330   foreach my $item (@{ $form->{"ALL_PROJECTS"} }) {
331     push(@project_values, $item->{"id"});
332     $project_labels{$item->{"id"}} = $item->{"projectnumber"};
333   }
334
335   my (%AP_amount_labels, @AP_amount_values);
336   my (%AP_labels, @AP_values);
337   my (%AP_paid_labels, @AP_paid_values);
338   my %charts;
339   my $taxchart_init;
340
341   foreach my $item (@{ $form->{ALL_CHARTS} }) {
342     if (grep({ $_ eq "AP_amount" } @{ $item->{link_split} })) {
343       $taxchart_init = $item->{tax_id} if ($taxchart_init eq "");
344       my $key = "$item->{accno}--$item->{tax_id}";
345       push(@AP_amount_values, $key);
346       $AP_amount_labels{$key} =
347         "$item->{accno}--$item->{description}";
348
349     } elsif (grep({ $_ eq "AP" } @{ $item->{link_split} })) {
350       push(@AP_values, $item->{accno});
351       $AP_labels{$item->{accno}} = "$item->{accno}--$item->{description}";
352
353     } elsif (grep({ $_ eq "AP_paid" } @{ $item->{link_split} })) {
354       push(@AP_paid_values, $item->{accno});
355       $AP_paid_labels{$item->{accno}} =
356         "$item->{accno}--$item->{description}";
357     }
358
359     $charts{$item->{accno}} = $item;
360   }
361
362   my %taxchart_labels = ();
363   my @taxchart_values = ();
364   my %taxcharts = ();
365   foreach my $item (@{ $form->{ALL_TAXCHARTS} }) {
366     my $key = "$item->{id}--$item->{rate}";
367     $taxchart_init = $key if ($taxchart_init eq $item->{id});
368     push(@taxchart_values, $key);
369     $taxchart_labels{$key} =
370       "$item->{taxdescription} " . ($item->{rate} * 100) . ' %';
371     $taxcharts{$item->{id}} = $item;
372   }
373
374   # use JavaScript Calendar or not
375   $form->{jsscript} = 1;
376   my $jsscript = "";
377   my ($button1, $button2);
378   if ($form->{jsscript}) {
379
380     # with JavaScript Calendar
381     $button1 = qq|
382        <td><input name=transdate id=transdate size=11 title="$myconfig{dateformat}" value="$form->{transdate}" onBlur=\"check_right_date_format(this)\" $readonly></td>
383        <td><input type=button name=transdate id="trigger1" value=|
384       . $locale->text('button') . qq|></td>
385        |;
386     $button2 = qq|
387        <td><input name=duedate id=duedate size=11 title="$myconfig{dateformat}" value="$form->{duedate}" onBlur=\"check_right_date_format(this)\" $readonly></td>
388        <td><input type=button name=duedate id="trigger2" value=|
389       . $locale->text('button') . qq|></td></td>
390      |;
391
392     #write Trigger
393     $jsscript =
394       Form->write_trigger(\%myconfig, "2", "transdate", "BL", "trigger1",
395                           "duedate", "BL", "trigger2");
396   } else {
397
398     # without JavaScript Calendar
399     $button1 =
400       qq|<td><input name=transdate id=transdate size=11 title="$myconfig{dateformat}" value="$form->{transdate}" onBlur=\"check_right_date_format(this)\" $readonly></td>|;
401     $button2 =
402       qq|<td><input name=duedate id=duedate size=11 title="$myconfig{dateformat}" value="$form->{duedate}" onBlur=\"check_right_date_format(this)\" $readonly></td>|;
403   }
404
405   my $follow_up_vc         =  $form->{vendor};
406   $follow_up_vc            =~ s/--.*?//;
407   my $follow_up_trans_info =  "$form->{invnumber} ($follow_up_vc)";
408
409   $form->{javascript} .= qq|<script type="text/javascript" src="js/common.js"></script>|;
410   $form->{javascript} .= qq|<script type="text/javascript" src="js/show_vc_details.js"></script>|;
411   $form->{javascript} .= qq|<script type="text/javascript" src="js/follow_up.js"></script>|;
412
413   $form->header;
414   my $onload = qq|;setupDateFormat('|. $myconfig{dateformat} .qq|', '|. $locale->text("Falsches Datumsformat!") .qq|')|;
415   $onload .= qq|;setupPoints('|. $myconfig{numberformat} .qq|', '|. $locale->text("wrongformat") .qq|')|;
416   print qq|
417 <body onLoad="$onload">
418
419 <form method=post action=$form->{script}>
420
421 <input type=hidden name=id value=$form->{id}>
422 <input type=hidden name=sort value=$form->{sort}>
423 <input type=hidden name=closedto value=$form->{closedto}>
424 <input type=hidden name=locked value=$form->{locked}>
425 <input type=hidden name=title value="$title">
426
427 <input type="hidden" name="follow_up_trans_id_1" value="| . H($form->{id}) . qq|">
428 <input type="hidden" name="follow_up_trans_type_1" value="ap_transaction">
429 <input type="hidden" name="follow_up_trans_info_1" value="| . H($follow_up_trans_info) . qq|">
430 <input type="hidden" name="follow_up_rowcount" value="1">
431
432 | . ($form->{saved_message} ? qq|<p>$form->{saved_message}</p>| : "") . qq|
433
434 <table width=100%>
435   <tr class=listtop>
436     <th class=listtop>$form->{title}</th>
437   </tr>
438   <tr height="5"></tr>
439   <tr valign=top>
440     <td>
441       <table width=100%>
442         <tr valign=top>
443           <td>
444             <table>
445               <tr>
446                 <th align=right nowrap>| . $locale->text('Vendor') . qq|</th>
447                 <td colspan=3>$vendor <input type="button" value="D" onclick="show_vc_details('vendor')"></td>
448                 <input type=hidden name=selectvendor value="| . H($form->{selectvendor}) . qq|">
449                 <input type=hidden name=oldvendor value="| . H($form->{oldvendor}) . qq|">
450                 <input type=hidden name=vendor_id value="| . H($form->{vendor_id}) . qq|">
451                 <input type=hidden name=terms value="| . H($form->{terms}) . qq|">
452               </tr>
453               <tr>
454                 <td></td>
455                 <td colspan=3>
456                   <table width=100%>
457                     <tr>
458                       <th align=left nowrap>| . $locale->text('Credit Limit') . qq|</th>
459                       <td>$form->{creditlimit}</td>
460                       <th align=left nowrap>| . $locale->text('Remaining') . qq|</th>
461                       <td class="plus$n">$form->{creditremaining}</td>
462                       <input type=hidden name=creditlimit value=$form->{creditlimit}>
463                       <input type=hidden name=creditremaining value=$form->{creditremaining}>
464                     </tr>
465                   </table>
466                 </td>
467               <tr>
468                 <th align=right nowrap>| . $locale->text('Currency') . qq|</th>
469                 <td><select name=currency>$form->{selectcurrency}</select></td>
470                 <input type=hidden name=selectcurrency value="$form->{selectcurrency}">
471                 <input type=hidden name=defaultcurrency value=$form->{defaultcurrency}>
472                 <input type=hidden name=fxgain_accno value=$form->{fxgain_accno}>
473                 <input type=hidden name=fxloss_accno value=$form->{fxloss_accno}>
474                 $exchangerate
475               </tr>
476               $department
477               $taxincluded
478             </table>
479           </td>
480           <td align=right>
481             <table>
482               <tr>
483                 <th align=right nowrap>| . $locale->text('Invoice Number') . qq|</th>
484                 <td><input name=invnumber size=11 value="$form->{invnumber}" $readonly></td>
485               </tr>
486               <tr>
487                 <th align=right nowrap>| . $locale->text('Order Number') . qq|</th>
488                 <td><input name=ordnumber size=11 value="$form->{ordnumber}" $readonly></td>
489               </tr>
490               <tr>
491                 <th align=right nowrap>| . $locale->text('Invoice Date') . qq|</th>
492                 $button1
493               </tr>
494               <tr>
495                 <th align=right nowrap>| . $locale->text('Due Date') . qq|</th>
496                 $button2
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->{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   my $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     $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     $form->{"exchangerate_$i"} =
689       $form->format_amount(\%myconfig, $form->{"exchangerate_$i"});
690     if ($form->{"exchangerate_$i"} == 0) {
691       $form->{"exchangerate_$i"} = "";
692     }
693
694     $exchangerate = qq|&nbsp;|;
695     if ($form->{currency} ne $form->{defaultcurrency}) {
696       if ($form->{"forex_$i"}) {
697         $exchangerate =
698           qq|<input type=hidden name="exchangerate_$i" value=$form->{"exchangerate_$i"}>$form->{"exchangerate_$i"}|;
699       } else {
700         $exchangerate =
701           qq|<input name="exchangerate_$i" size=10 value=$form->{"exchangerate_$i"}>|;
702       }
703     }
704
705     $exchangerate .= qq|
706 <input type=hidden name="forex_$i" value=$form->{"forex_$i"}>
707 |;
708
709     $column_data{"paid_$i"} =
710       qq|<td align=center><input name="paid_$i" size=11 value="$form->{"paid_$i"}" onBlur=\"check_right_number_format(this)\"></td>|;
711     $column_data{"AP_paid_$i"} =
712       qq|<td align=center>${selectAP_paid}</td>|;
713     $column_data{"exchangerate_$i"} = qq|<td align=center>$exchangerate</td>|;
714     $column_data{"datepaid_$i"}     =
715       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)\">
716          <input type="button" name="datepaid_$i" id="trigger_datepaid_$i" value="| . $locale->text('Details (one letter abbreviation)') . qq|"></td>|;
717     $column_data{"source_$i"} =
718       qq|<td align=center><input name="source_$i" size=11 value="$form->{"source_$i"}"></td>|;
719     $column_data{"memo_$i"} =
720       qq|<td align=center><input name="memo_$i" size=11 value="$form->{"memo_$i"}"></td>|;
721     $column_data{"paid_project_id_$i"} =
722       qq|<td>|
723       . NTI($cgi->popup_menu('-name' => "paid_project_id_$i",
724                              '-values' => \@project_values,
725                              '-labels' => \%project_labels,
726                              '-default' => $form->{"paid_project_id_$i"} ))
727       . qq|</td>|;
728
729     map { print qq|$column_data{"${_}_$i"}\n| } @column_index;
730
731     print "
732         </tr>
733 ";
734     push(@triggers, "datepaid_$i", "BL", "trigger_datepaid_$i");
735   }
736
737   my $paid_missing = $form->{invtotal_unformatted} - $totalpaid;
738
739   print qq|
740         <tr>
741           <td></td>
742           <td></td>
743           <td align="center">| . $locale->text('Total') . qq|</td>
744           <td align="center">| . H($form->format_amount(\%myconfig, $totalpaid, 2)) . qq|</td>
745         </tr>
746         <tr>
747           <td></td>
748           <td></td>
749           <td align="center">| . $locale->text('Missing amount') . qq|</td>
750           <td align="center">| . H($form->format_amount(\%myconfig, $paid_missing, 2)) . qq|</td>
751         </tr>
752 | . $form->write_trigger(\%myconfig, scalar(@triggers) / 3, @triggers) .
753     qq|
754     <input type=hidden name=paidaccounts value=$form->{paidaccounts}>
755
756       </table>
757     </td>
758   </tr>
759   <tr>
760     <td><hr size=3 noshade></td>
761   </tr>
762 </table>
763 |;
764
765   $main::lxdebug->leave_sub();
766 }
767
768 sub form_footer {
769   $main::lxdebug->enter_sub();
770
771   my $form     = $main::form;
772   my %myconfig = %main::myconfig;
773   my $locale   = $main::locale;
774   my $cgi      = $main::cgi;
775
776   $main::auth->assert('general_ledger');
777
778   my $follow_ups_block;
779   if ($form->{id}) {
780     my $follow_ups = FU->follow_ups('trans_id' => $form->{id});
781
782     if (@{ $follow_ups} ) {
783       my $num_due       = sum map { $_->{due} * 1 } @{ $follow_ups };
784       $follow_ups_block = qq|<p>| . $locale->text("There are #1 unfinished follow-ups of which #2 are due.", scalar @{ $follow_ups }, $num_due) . qq|</p>|;
785     }
786   }
787
788   print qq|
789
790 $follow_ups_block
791
792 <input name=callback type=hidden value="$form->{callback}">
793 <input name="gldate" type="hidden" value="| . Q($form->{gldate}) . qq|">
794 |
795 . $cgi->hidden('-name' => 'draft_id', '-default' => [$form->{draft_id}])
796 . $cgi->hidden('-name' => 'draft_description', '-default' => [$form->{draft_description}])
797 . qq|
798
799 <br>
800 |;
801
802   if (!$form->{id} && $form->{draft_id}) {
803     print(NTI($cgi->checkbox('-name' => 'remove_draft', '-id' => 'remove_draft',
804                              '-value' => 1, '-checked' => $form->{remove_draft},
805                              '-label' => '')) .
806           qq|&nbsp;<label for="remove_draft">| .
807           $locale->text("Remove draft when posting") .
808           qq|</label><br>|);
809   }
810
811   my $transdate = $form->datetonum($form->{transdate}, \%myconfig);
812   my $closedto  = $form->datetonum($form->{closedto},  \%myconfig);
813
814   print qq|<input class="submit" type="submit" name="action" id="update_button" value="| . $locale->text('Update') . qq|">|;
815
816   if ($form->{id}) {
817     if ($form->{radier}) {
818       print qq| <input class=submit type=submit name=action value="| . $locale->text('Post') . qq|">
819                 <input class=submit type=submit name=action value="| . $locale->text('Delete') . qq|">
820 |;
821     }
822     # ToDO: - insert a global check for stornos, so that a storno is only possible a limited time after saving it
823     our $total_paid;
824     print qq| <input class=submit type=submit name=action value="| . $locale->text('Storno') . qq|"> |
825       if ($form->{id} && !IS->has_storno(\%myconfig, $form, 'ap') && !IS->is_storno(\%myconfig, $form, 'ap', $form->{id}) && (($total_paid == 0) || ($total_paid eq "")));
826
827     print qq| <input class=submit type=submit name=action value="| . $locale->text('Post Payment') . qq|">
828               <input class=submit type=submit name=action value="| . $locale->text('Use As Template') . qq|">
829               <input type="button" class="submit" onclick="follow_up_window()" value="| . $locale->text('Follow-Up') . qq|">
830 |;
831   } elsif (($transdate > $closedto) && !$form->{id}) {
832     print qq|
833       <input class=submit type=submit name=action value="| . $locale->text('Post') . qq|"> | .
834       NTI($cgi->submit('-name' => 'action', '-value' => $locale->text('Save draft'), '-class' => 'submit'));
835   }
836   # button for saving history
837   if($form->{id} ne "") {
838     print qq| <input type="button" class="submit" onclick="set_history_window($form->{id});" name="history" id="history" value="| . $locale->text('history') . qq|"> |;
839   }
840   # /button for saving history
841   # mark_as_paid button
842   if($form->{id} ne "") {
843     print qq| <input type="submit" class="submit" name="action" value="| . $locale->text('mark as paid') . qq|"> |;
844   }
845   # /mark_as_paid button
846   print "
847 </form>
848
849 </body>
850 </html>
851 ";
852
853   $main::lxdebug->leave_sub();
854 }
855
856 sub mark_as_paid {
857   $main::lxdebug->enter_sub();
858
859   my $form     = $main::form;
860   my %myconfig = %main::myconfig;
861
862   $main::auth->assert('general_ledger');
863
864   &mark_as_paid_common(\%myconfig,"ap");
865
866   $main::lxdebug->leave_sub();
867 }
868
869 sub update {
870   $main::lxdebug->enter_sub();
871
872   my $form     = $main::form;
873   my %myconfig = %main::myconfig;
874
875   $main::auth->assert('general_ledger');
876
877   my $display = shift;
878
879   $form->{invtotal} = 0;
880
881   delete @{ $form }{ grep { m/^tax_\d+$/ } keys %{ $form } };
882
883   map { $form->{$_} = $form->parse_amount(\%myconfig, $form->{$_}) }
884     qw(exchangerate creditlimit creditremaining);
885
886   my @flds  = qw(amount AP_amount projectnumber oldprojectnumber project_id taxchart);
887   my $count = 0;
888   my (@a, $j, $totaltax);
889   for my $i (1 .. $form->{rowcount}) {
890     $form->{"amount_$i"} =
891       $form->parse_amount(\%myconfig, $form->{"amount_$i"});
892     $form->{"tax_$i"} = $form->parse_amount(\%myconfig, $form->{"tax_$i"});
893     if ($form->{"amount_$i"}) {
894       push @a, {};
895       $j = $#a;
896       my ($taxkey, $rate) = split(/--/, $form->{"taxchart_$i"});
897       if ($taxkey > 1) {
898         if ($form->{taxincluded}) {
899           $form->{"tax_$i"} = $form->{"amount_$i"} / ($rate + 1) * $rate;
900         } else {
901           $form->{"tax_$i"} = $form->{"amount_$i"} * $rate;
902         }
903       } else {
904         $form->{"tax_$i"} = 0;
905       }
906       $form->{"tax_$i"} = $form->round_amount($form->{"tax_$i"}, 2);
907
908       $totaltax += $form->{"tax_$i"};
909       map { $a[$j]->{$_} = $form->{"${_}_$i"} } @flds;
910       $count++;
911     }
912   }
913   $form->redo_rows(\@flds, \@a, $count, $form->{rowcount});
914
915   map { $form->{invtotal} += $form->{"amount_$_"} } (1 .. $form->{rowcount});
916
917   $form->{forex}        = $form->check_exchangerate( \%myconfig, $form->{currency}, $form->{transdate}, 'sell');
918   $form->{exchangerate} = $form->{forex} if $form->{forex};
919
920   $form->{invdate} = $form->{transdate};
921   my %saved_variables = map +( $_ => $form->{$_} ), qw(AP AP_amount_1 taxchart_1);
922
923   my $vendor_changed = &check_name("vendor");
924
925   $form->{AP} = $saved_variables{AP};
926   if ($saved_variables{AP_amount_1} =~ m/.--./) {
927     map { $form->{$_} = $saved_variables{$_} } qw(AP_amount_1 taxchart_1);
928   } else {
929     delete $form->{taxchart_1};
930   }
931
932   $form->{rowcount} = $count + 1;
933
934   $form->{invtotal} =
935     ($form->{taxincluded}) ? $form->{invtotal} : $form->{invtotal} + $totaltax;
936
937   my $totalpaid;
938   for my $i (1 .. $form->{paidaccounts}) {
939     if ($form->parse_amount(\%myconfig, $form->{"paid_$i"})) {
940       map {
941         $form->{"${_}_$i"} =
942           $form->parse_amount(\%myconfig, $form->{"${_}_$i"})
943       } qw(paid exchangerate);
944
945       $totalpaid += $form->{"paid_$i"};
946
947       $form->{"forex_$i"}        = $form->check_exchangerate( \%myconfig, $form->{currency}, $form->{"datepaid_$i"}, 'sell');
948       $form->{"exchangerate_$i"} = $form->{"forex_$i"} if $form->{"forex_$i"};
949     }
950   }
951
952   $form->{creditremaining} -=
953     ($form->{invtotal} - $totalpaid + $form->{oldtotalpaid} -
954      $form->{oldinvtotal});
955   $form->{oldinvtotal}  = $form->{invtotal};
956   $form->{oldtotalpaid} = $totalpaid;
957
958   # notes
959   $form->{notes} = $form->{intnotes} if $vendor_changed;
960
961   &display_form;
962
963   $main::lxdebug->leave_sub();
964 }
965
966
967 sub post_payment {
968   $main::lxdebug->enter_sub();
969
970   my $form     = $main::form;
971   my %myconfig = %main::myconfig;
972   my $locale   = $main::locale;
973
974   $main::auth->assert('general_ledger');
975
976   $form->{defaultcurrency} = $form->get_default_currency(\%myconfig);
977
978   our $invdate;
979   for my $i (1 .. $form->{paidaccounts}) {
980     if ($form->parse_amount(\%myconfig, $form->{"paid_$i"})) {
981       my $datepaid = $form->datetonum($form->{"datepaid_$i"}, \%myconfig);
982
983       $form->isblank("datepaid_$i", $locale->text('Payment date missing!'));
984
985       $form->error($locale->text('Cannot post payment for a closed period!'))
986         if ($form->date_closed($form->{"datepaid_$i"}, \%myconfig));
987
988       if ($form->{currency} ne $form->{defaultcurrency}) {
989         $form->{"exchangerate_$i"} = $form->{exchangerate}
990           if ($invdate == $datepaid);
991         $form->isblank("exchangerate_$i",
992                        $locale->text('Exchangerate for payment missing!'));
993       }
994     }
995   }
996
997   ($form->{AP})      = split /--/, $form->{AP};
998   ($form->{AP_paid}) = split /--/, $form->{AP_paid};
999   $form->redirect($locale->text('Payment posted!'))
1000       if (AP->post_payment(\%myconfig, \%$form));
1001     $form->error($locale->text('Cannot post payment!'));
1002
1003
1004   $main::lxdebug->leave_sub();
1005 }
1006
1007
1008 sub post {
1009   $main::lxdebug->enter_sub();
1010
1011   my $form     = $main::form;
1012   my %myconfig = %main::myconfig;
1013   my $locale   = $main::locale;
1014
1015   $main::auth->assert('general_ledger');
1016
1017   # check if there is a vendor, invoice and due date
1018   $form->isblank("transdate", $locale->text("Invoice Date missing!"));
1019   $form->isblank("duedate",   $locale->text("Due Date missing!"));
1020   $form->isblank("vendor",    $locale->text('Vendor missing!'));
1021
1022   my $closedto  = $form->datetonum($form->{closedto},  \%myconfig);
1023   my $transdate = $form->datetonum($form->{transdate}, \%myconfig);
1024   $form->error($locale->text('Cannot post transaction for a closed period!')) if ($form->date_closed($form->{"transdate"}, \%myconfig));
1025
1026   my $zero_amount_posting = 1;
1027   for my $i (1 .. $form->{rowcount}) {
1028     if ($form->parse_amount(\%myconfig, $form->{"amount_$i"})) {
1029       $zero_amount_posting = 0;
1030       last;
1031     }
1032   }
1033
1034   $form->error($locale->text('Zero amount posting!')) if $zero_amount_posting;
1035
1036   $form->isblank("exchangerate", $locale->text('Exchangerate missing!'))
1037     if ($form->{currency} ne $form->{defaultcurrency});
1038   delete($form->{AP});
1039
1040   for my $i (1 .. $form->{paidaccounts}) {
1041     if ($form->parse_amount(\%myconfig, $form->{"paid_$i"})) {
1042       my $datepaid = $form->datetonum($form->{"datepaid_$i"}, \%myconfig);
1043
1044       $form->isblank("datepaid_$i", $locale->text('Payment date missing!'));
1045
1046       $form->error($locale->text('Cannot post payment for a closed period!'))
1047         if ($form->date_closed($form->{"datepaid_$i"}, \%myconfig));
1048
1049       if ($form->{currency} ne $form->{defaultcurrency}) {
1050         $form->{"exchangerate_$i"} = $form->{exchangerate}
1051           if ($transdate == $datepaid);
1052         $form->isblank("exchangerate_$i",
1053                        $locale->text('Exchangerate for payment missing!'));
1054       }
1055
1056     }
1057   }
1058
1059   # if old vendor ne vendor redo form
1060   my ($vendor) = split /--/, $form->{vendor};
1061   if ($form->{oldvendor} ne "$vendor--$form->{vendor_id}") {
1062     &update;
1063     exit;
1064   }
1065   my ($debitaccno,    $debittaxkey)    = split /--/, $form->{AP_amountselected};
1066   my ($taxkey,        $NULL)           = split /--/, $form->{taxchartselected};
1067   my ($payablesaccno, $payablestaxkey) = split /--/, $form->{APselected};
1068 #  $form->{AP_amount_1}  = $debitaccno;
1069   $form->{AP_payables}  = $payablesaccno;
1070   $form->{taxkey}       = $taxkey;
1071   $form->{storno}       = 0;
1072
1073   $form->{id} = 0 if $form->{postasnew};
1074
1075   if (AP->post_transaction(\%myconfig, \%$form)) {
1076     # saving the history
1077     if(!exists $form->{addition} && $form->{id} ne "") {
1078       $form->{snumbers} = qq|invnumber_| . $form->{invnumber};
1079       $form->{addition} = "POSTED";
1080       $form->save_history($form->dbconnect(\%myconfig));
1081     }
1082     # /saving the history
1083     remove_draft() if $form->{remove_draft};
1084     $form->redirect($locale->text('Transaction posted!'));
1085   }
1086   $form->error($locale->text('Cannot post transaction!'));
1087
1088   $main::lxdebug->leave_sub();
1089 }
1090
1091 sub post_as_new {
1092   $main::lxdebug->enter_sub();
1093
1094   my $form     = $main::form;
1095   my %myconfig = %main::myconfig;
1096
1097   $main::auth->assert('general_ledger');
1098
1099   $form->{postasnew} = 1;
1100   # saving the history
1101   if(!exists $form->{addition} && $form->{id} ne "") {
1102     $form->{snumbers} = qq|invnumber_| . $form->{invnumber};
1103     $form->{addition} = "POSTED AS NEW";
1104     $form->save_history($form->dbconnect(\%myconfig));
1105   }
1106   # /saving the history
1107   &post;
1108
1109   $main::lxdebug->leave_sub();
1110 }
1111
1112 sub use_as_template {
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   map { delete $form->{$_} } qw(printed emailed queued invnumber invdate deliverydate id datepaid_1 source_1 memo_1 paid_1 exchangerate_1 AP_paid_1 storno);
1121   $form->{paidaccounts} = 1;
1122   $form->{rowcount}--;
1123   $form->{invdate} = $form->current_date(\%myconfig);
1124   &update;
1125
1126   $main::lxdebug->leave_sub();
1127 }
1128
1129 sub delete {
1130   $main::lxdebug->enter_sub();
1131
1132   my $form     = $main::form;
1133   my $locale   = $main::locale;
1134
1135   $main::auth->assert('general_ledger');
1136
1137   $form->{title} = $locale->text('Confirm!');
1138
1139   $form->header;
1140
1141   delete $form->{header};
1142
1143   print qq|
1144 <body>
1145
1146 <form method=post action=$form->{script}>
1147 |;
1148
1149   foreach my $key (keys %$form) {
1150     next if (($key eq 'login') || ($key eq 'password') || ('' ne ref $form->{$key}));
1151     $form->{$key} =~ s/\"/&quot;/g;
1152     print qq|<input type=hidden name=$key value="$form->{$key}">\n|;
1153   }
1154
1155   print qq|
1156 <h2 class=confirm>$form->{title}</h2>
1157
1158 <h4>|
1159     . $locale->text('Are you sure you want to delete Transaction')
1160     . qq| $form->{invnumber}</h4>
1161
1162 <input name=action class=submit type=submit value="|
1163     . $locale->text('Yes') . qq|">
1164 </form>
1165
1166 </body>
1167 </html>
1168 |;
1169
1170   $main::lxdebug->leave_sub();
1171 }
1172
1173 sub yes {
1174   $main::lxdebug->enter_sub();
1175
1176   my $form     = $main::form;
1177   my %myconfig = %main::myconfig;
1178   my $locale   = $main::locale;
1179
1180   $main::auth->assert('general_ledger');
1181
1182   if (AP->delete_transaction(\%myconfig, \%$form, $main::spool)) {
1183     # saving the history
1184     if(!exists $form->{addition}) {
1185       $form->{snumbers} = qq|invnumber_| . $form->{invnumber};
1186       $form->{addition} = "DELETED";
1187       $form->save_history($form->dbconnect(\%myconfig));
1188     }
1189     # /saving the history
1190     $form->redirect($locale->text('Transaction deleted!'));
1191   }
1192   $form->error($locale->text('Cannot delete transaction!'));
1193
1194   $main::lxdebug->leave_sub();
1195 }
1196
1197 sub search {
1198   $main::lxdebug->enter_sub();
1199
1200   $main::auth->assert('general_ledger | invoice_edit');
1201
1202   my $form     = $main::form;
1203   my %myconfig = %main::myconfig;
1204   my $locale   = $main::locale;
1205
1206   # setup customer selection
1207   $form->all_vc(\%myconfig, "vendor", "AP");
1208
1209   $form->{title}    = $locale->text('AP Transactions');
1210   $form->{fokus}    = "search.vendor";
1211   $form->{jsscript} = 1;
1212
1213   $form->get_lists("projects"     => { "key" => "ALL_PROJECTS", "all" => 1 },
1214                    "departments"  => "ALL_DEPARTMENTS",
1215                    "vendors"      => "ALL_VC");
1216
1217   # constants and subs for template
1218   $form->{jsscript}  = 1;
1219   $form->{vc_keys}   = sub { "$_[0]->{name}--$_[0]->{id}" };
1220
1221   $form->header;
1222   print $form->parse_html_template('ap/search', { %myconfig });
1223
1224   $main::lxdebug->leave_sub();
1225 }
1226
1227 sub create_subtotal_row {
1228   $main::lxdebug->enter_sub();
1229
1230   my ($totals, $columns, $column_alignment, $subtotal_columns, $class) = @_;
1231
1232   my $form     = $main::form;
1233   my %myconfig = %main::myconfig;
1234
1235   my $row = { map { $_ => { 'data' => '', 'class' => $class, 'align' => $column_alignment->{$_}, } } @{ $columns } };
1236
1237   map { $row->{$_}->{data} = $form->format_amount(\%myconfig, $totals->{$_}, 2) } @{ $subtotal_columns };
1238
1239   $row->{tax}->{data} = $form->format_amount(\%myconfig, $totals->{amount} - $totals->{netamount}, 2);
1240
1241   map { $totals->{$_} = 0 } @{ $subtotal_columns };
1242
1243   $main::lxdebug->leave_sub();
1244
1245   return $row;
1246 }
1247
1248 sub ap_transactions {
1249   $main::lxdebug->enter_sub();
1250
1251   my $form     = $main::form;
1252   my %myconfig = %main::myconfig;
1253   my $locale   = $main::locale;
1254
1255   $main::auth->assert('general_ledger | vendor_invoice_edit');
1256
1257   ($form->{vendor}, $form->{vendor_id}) = split(/--/, $form->{vendor});
1258
1259   report_generator_set_default_sort('transdate', 1);
1260
1261   AP->ap_transactions(\%myconfig, \%$form);
1262
1263   $form->{title} = $locale->text('AP Transactions');
1264
1265   my $report = SL::ReportGenerator->new(\%myconfig, $form);
1266
1267   my @columns =
1268     qw(transdate id type invnumber ordnumber name netamount tax amount paid datepaid
1269        due duedate transaction_description notes employee globalprojectnumber
1270        vendornumber country ustid taxzone payment_terms charts);
1271
1272   my @hidden_variables = map { "l_${_}" } @columns;
1273   push @hidden_variables, "l_subtotal", qw(open closed vendor invnumber ordnumber transaction_description notes project_id transdatefrom transdateto);
1274
1275   my $href = build_std_url('action=ap_transactions', grep { $form->{$_} } @hidden_variables);
1276
1277   my %column_defs = (
1278     'transdate'               => { 'text' => $locale->text('Date'), },
1279     'id'                      => { 'text' => $locale->text('ID'), },
1280     'type'                    => { 'text' => $locale->text('Type'), },
1281     'invnumber'               => { 'text' => $locale->text('Invoice'), },
1282     'ordnumber'               => { 'text' => $locale->text('Order'), },
1283     'name'                    => { 'text' => $locale->text('Vendor'), },
1284     'netamount'               => { 'text' => $locale->text('Amount'), },
1285     'tax'                     => { 'text' => $locale->text('Tax'), },
1286     'amount'                  => { 'text' => $locale->text('Total'), },
1287     'paid'                    => { 'text' => $locale->text('Paid'), },
1288     'datepaid'                => { 'text' => $locale->text('Date Paid'), },
1289     'due'                     => { 'text' => $locale->text('Amount Due'), },
1290     'duedate'                 => { 'text' => $locale->text('Due Date'), },
1291     'transaction_description' => { 'text' => $locale->text('Transaction description'), },
1292     'notes'                   => { 'text' => $locale->text('Notes'), },
1293     'employee'                => { 'text' => $locale->text('Salesperson'), },
1294     'globalprojectnumber'     => { 'text' => $locale->text('Project Number'), },
1295     'vendornumber'            => { 'text' => $locale->text('Vendor Number'), },
1296     'country'                 => { 'text' => $locale->text('Country'), },
1297     'ustid'                   => { 'text' => $locale->text('USt-IdNr.'), },
1298     'taxzone'                 => { 'text' => $locale->text('Steuersatz'), },
1299     'payment_terms'           => { 'text' => $locale->text('Payment Terms'), },
1300     'charts'                  => { 'text' => $locale->text('Buchungskonto'), },
1301   );
1302
1303   foreach my $name (qw(id transdate duedate invnumber ordnumber name datepaid employee shippingpoint shipvia transaction_description)) {
1304     my $sortdir                 = $form->{sort} eq $name ? 1 - $form->{sortdir} : $form->{sortdir};
1305     $column_defs{$name}->{link} = $href . "&sort=$name&sortdir=$sortdir";
1306   }
1307
1308   my %column_alignment = map { $_ => 'right' } qw(netamount tax amount paid due);
1309
1310   $form->{"l_type"} = "Y";
1311   map { $column_defs{$_}->{visible} = $form->{"l_${_}"} ? 1 : 0 } @columns;
1312
1313   $report->set_columns(%column_defs);
1314   $report->set_column_order(@columns);
1315
1316   $report->set_export_options('ap_transactions', @hidden_variables, qw(sort sortdir));
1317
1318   $report->set_sort_indicator($form->{sort}, $form->{sortdir});
1319
1320   my @options;
1321   push @options, $locale->text('Vendor')                  . " : $form->{vendor}"                         if ($form->{vendor});
1322   push @options, $locale->text('Department')              . " : " . (split /--/, $form->{department})[0] if ($form->{department});
1323   push @options, $locale->text('Invoice Number')          . " : $form->{invnumber}"                      if ($form->{invnumber});
1324   push @options, $locale->text('Order Number')            . " : $form->{ordnumber}"                      if ($form->{ordnumber});
1325   push @options, $locale->text('Notes')                   . " : $form->{notes}"                          if ($form->{notes});
1326   push @options, $locale->text('Transaction description') . " : $form->{transaction_description}"        if ($form->{transaction_description});
1327   push @options, $locale->text('From') . " " . $locale->date(\%myconfig, $form->{transdatefrom}, 1)      if ($form->{transdatefrom});
1328   push @options, $locale->text('Bis')  . " " . $locale->date(\%myconfig, $form->{transdateto},   1)      if ($form->{transdateto});
1329   push @options, $locale->text('Open')                                                                   if ($form->{open});
1330   push @options, $locale->text('Closed')                                                                 if ($form->{closed});
1331
1332   $report->set_options('top_info_text'        => join("\n", @options),
1333                        'raw_bottom_info_text' => $form->parse_html_template('ap/ap_transactions_bottom'),
1334                        'output_format'        => 'HTML',
1335                        'title'                => $form->{title},
1336                        'attachment_basename'  => $locale->text('vendor_invoice_list') . strftime('_%Y%m%d', localtime time),
1337     );
1338   $report->set_options_from_form();
1339
1340   # add sort and escape callback, this one we use for the add sub
1341   $form->{callback} = $href .= "&sort=$form->{sort}";
1342
1343   # escape callback for href
1344   my $callback = $form->escape($href);
1345
1346   my @subtotal_columns = qw(netamount amount paid due);
1347
1348   my %totals    = map { $_ => 0 } @subtotal_columns;
1349   my %subtotals = map { $_ => 0 } @subtotal_columns;
1350
1351   my $idx = 0;
1352
1353   foreach my $ap (@{ $form->{AP} }) {
1354     $ap->{tax} = $ap->{amount} - $ap->{netamount};
1355     $ap->{due} = $ap->{amount} - $ap->{paid};
1356
1357     map { $subtotals{$_} += $ap->{$_};
1358           $totals{$_}    += $ap->{$_} } @subtotal_columns;
1359
1360     map { $ap->{$_} = $form->format_amount(\%myconfig, $ap->{$_}, 2) } qw(netamount tax amount paid due);
1361
1362     my $is_storno  = $ap->{storno} &&  $ap->{storno_id};
1363     my $has_storno = $ap->{storno} && !$ap->{storno_id};
1364
1365     if ($ap->{invoice}) {
1366       $ap->{type} =
1367           $has_storno       ? $locale->text("Invoice with Storno (abbreviation)")
1368         : $is_storno        ? $locale->text("Storno (one letter abbreviation)")
1369         :                     $locale->text("Invoice (one letter abbreviation)");
1370     } else {
1371       $ap->{type} =
1372           $has_storno       ? $locale->text("AP Transaction with Storno (abbreviation)")
1373         : $is_storno        ? $locale->text("AP Transaction Storno (one letter abbreviation)")
1374         :                     $locale->text("AP Transaction (abbreviation)");
1375     }
1376
1377     my $row = { };
1378
1379     foreach my $column (@columns) {
1380       $row->{$column} = {
1381         'data'  => $ap->{$column},
1382         'align' => $column_alignment{$column},
1383       };
1384     }
1385
1386     $row->{invnumber}->{link} = build_std_url("script=" . ($ap->{invoice} ? 'ir.pl' : 'ap.pl'), 'action=edit')
1387       . "&id=" . E($ap->{id}) . "&callback=${callback}";
1388
1389     my $row_set = [ $row ];
1390
1391     if (($form->{l_subtotal} eq 'Y')
1392         && (($idx == (scalar @{ $form->{AP} } - 1))
1393             || ($ap->{ $form->{sort} } ne $form->{AP}->[$idx + 1]->{ $form->{sort} }))) {
1394       push @{ $row_set }, create_subtotal_row(\%subtotals, \@columns, \%column_alignment, \@subtotal_columns, 'listsubtotal');
1395     }
1396
1397     $report->add_data($row_set);
1398
1399     $idx++;
1400   }
1401
1402   $report->add_separator();
1403   $report->add_data(create_subtotal_row(\%totals, \@columns, \%column_alignment, \@subtotal_columns, 'listtotal'));
1404
1405   $report->generate_with_headers();
1406
1407   $main::lxdebug->leave_sub();
1408 }
1409
1410 sub storno {
1411   $main::lxdebug->enter_sub();
1412
1413   my $form     = $main::form;
1414   my %myconfig = %main::myconfig;
1415   my $locale   = $main::locale;
1416
1417   $main::auth->assert('general_ledger');
1418
1419   if (IS->has_storno(\%myconfig, $form, 'ap')) {
1420     $form->{title} = $locale->text("Cancel Accounts Payables Transaction");
1421     $form->error($locale->text("Transaction has already been cancelled!"));
1422   }
1423
1424   AP->storno($form, \%myconfig, $form->{id});
1425
1426   # saving the history
1427   if(!exists $form->{addition} && $form->{id} ne "") {
1428     $form->{snumbers} = "ordnumber_$form->{ordnumber}";
1429     $form->{addition} = "STORNO";
1430     $form->save_history($form->dbconnect(\%myconfig));
1431   }
1432   # /saving the history
1433
1434   $form->redirect(sprintf $locale->text("Transaction %d cancelled."), $form->{storno_id});
1435
1436   $main::lxdebug->leave_sub();
1437 }