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