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