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