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