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