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