Merge branch 'frameless_w_fixed_header-div'
[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      = $::request->{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;
289   $department = qq|
290               <tr>
291                 <th align="right" nowrap>| . $locale->text('Department') . qq|</th>
292                 <td colspan=3><select name=department>$form->{selectdepartment}</select>
293                 <input type=hidden name=selectdepartment value="$form->{selectdepartment}">
294                 </td>
295               </tr>
296 | if $form->{selectdepartment};
297
298   my $n = ($form->{creditremaining} =~ /-/) ? "0" : "1";
299
300   my $vendor =
301     ($form->{selectvendor})
302     ? qq|<select name="vendor" onchange="document.getElementById('update_button').click();">$form->{selectvendor} </select>|
303     : qq|<input name=vendor value="$form->{vendor}" size=35>|;
304
305   my @old_project_ids = ();
306   map({ push(@old_project_ids, $form->{"project_id_$_"})
307           if ($form->{"project_id_$_"}); } (1..$form->{"rowcount"}));
308
309   $form->get_lists("projects"  => { "key"       => "ALL_PROJECTS",
310                                     "all"       => 0,
311                                     "old_id"    => \@old_project_ids },
312                    "charts"    => { "key"       => "ALL_CHARTS",
313                                     "transdate" => $form->{transdate} },
314                    "taxcharts" => { "key"       => "ALL_TAXCHARTS",
315                                     "module"    => "AP" },);
316
317   map({ $_->{link_split} = [ split(/:/, $_->{link}) ]; }
318       @{ $form->{ALL_CHARTS} });
319
320   my %project_labels = ();
321   my @project_values = ("");
322   foreach my $item (@{ $form->{"ALL_PROJECTS"} }) {
323     push(@project_values, $item->{"id"});
324     $project_labels{$item->{"id"}} = $item->{"projectnumber"};
325   }
326
327   my (%AP_amount_labels, @AP_amount_values);
328   my (%AP_labels, @AP_values);
329   my (%AP_paid_labels, @AP_paid_values);
330   my %charts;
331   my $taxchart_init;
332
333   foreach my $item (@{ $form->{ALL_CHARTS} }) {
334     if (grep({ $_ eq "AP_amount" } @{ $item->{link_split} })) {
335       $taxchart_init = $item->{tax_id} if ($taxchart_init eq "");
336       my $key = "$item->{accno}--$item->{tax_id}";
337       push(@AP_amount_values, $key);
338       $AP_amount_labels{$key} =
339         "$item->{accno}--$item->{description}";
340
341     } elsif (grep({ $_ eq "AP" } @{ $item->{link_split} })) {
342       push(@AP_values, $item->{accno});
343       $AP_labels{$item->{accno}} = "$item->{accno}--$item->{description}";
344
345     } elsif (grep({ $_ eq "AP_paid" } @{ $item->{link_split} })) {
346       push(@AP_paid_values, $item->{accno});
347       $AP_paid_labels{$item->{accno}} =
348         "$item->{accno}--$item->{description}";
349     }
350
351     $charts{$item->{accno}} = $item;
352   }
353
354   my %taxchart_labels = ();
355   my @taxchart_values = ();
356   my %taxcharts = ();
357   foreach my $item (@{ $form->{ALL_TAXCHARTS} }) {
358     my $key = "$item->{id}--$item->{rate}";
359     $taxchart_init = $key if ($taxchart_init eq $item->{id});
360     push(@taxchart_values, $key);
361     $taxchart_labels{$key} =
362       "$item->{taxdescription} " . ($item->{rate} * 100) . ' %';
363     $taxcharts{$item->{id}} = $item;
364   }
365
366   # use JavaScript Calendar or not
367   $form->{jsscript} = 1;
368   my $jsscript = "";
369   my ($button1, $button2);
370   if ($form->{jsscript}) {
371
372     # with JavaScript Calendar
373     $button1 = qq|
374        <td><input name=transdate onchange="set_duedate()" id=transdate size=11 title="$myconfig{dateformat}" value="$form->{transdate}" onBlur=\"check_right_date_format(this)\" $readonly></td>
375        <td><input type=button name=transdate id="trigger1" value=|
376       . $locale->text('button') . qq|></td>
377        |;
378     $button2 = qq|
379        <td><input name=duedate id=duedate size=11 title="$myconfig{dateformat}" value="$form->{duedate}" onBlur=\"check_right_date_format(this)\" $readonly></td>
380        <td><input type=button name=duedate id="trigger2" value=|
381       . $locale->text('button') . qq|></td></td>
382      |;
383
384     #write Trigger
385     $jsscript =
386       Form->write_trigger(\%myconfig, "2", "transdate", "BL", "trigger1",
387                           "duedate", "BL", "trigger2");
388   } else {
389
390     # without JavaScript Calendar
391     $button1 =
392       qq|<td><input name=transdate onchange="set_duedate()" id=transdate size=11 title="$myconfig{dateformat}" value="$form->{transdate}" onBlur=\"check_right_date_format(this)\" $readonly></td>|;
393     $button2 =
394       qq|<td><input name=duedate id=duedate size=11 title="$myconfig{dateformat}" value="$form->{duedate}" onBlur=\"check_right_date_format(this)\" $readonly></td>|;
395   }
396
397   my $follow_up_vc         =  $form->{vendor};
398   $follow_up_vc            =~ s/--.*?//;
399   my $follow_up_trans_info =  "$form->{invnumber} ($follow_up_vc)";
400
401   $form->{javascript} .= qq|<script type="text/javascript" src="js/common.js"></script>|;
402   $form->{javascript} .= qq|<script type="text/javascript" src="js/show_vc_details.js"></script>|;
403   $form->{javascript} .= qq|<script type="text/javascript" src="js/follow_up.js"></script>|;
404
405   my $globalprojectnumber =
406     NTI($cgi->popup_menu('-name' => "globalproject_id",
407                          '-values' => \@project_values,
408                          '-labels' => \%project_labels,
409                          '-default' => $form->{"globalproject_id"} ));
410
411   $form->header;
412   print qq|
413 <form method=post action=$form->{script}>
414
415 <input type=hidden name=id value=$form->{id}>
416 <input type=hidden name=sort value=$form->{sort}>
417 <input type=hidden name=closedto value=$form->{closedto}>
418 <input type=hidden name=locked value=$form->{locked}>
419 <input type=hidden name=title value="$title">
420
421 <input type="hidden" name="follow_up_trans_id_1" value="| . H($form->{id}) . qq|">
422 <input type="hidden" name="follow_up_trans_type_1" value="ap_transaction">
423 <input type="hidden" name="follow_up_trans_info_1" value="| . H($follow_up_trans_info) . qq|">
424 <input type="hidden" name="follow_up_rowcount" value="1">
425
426 | . ($form->{saved_message} ? qq|<p>$form->{saved_message}</p>| : "") . qq|
427
428 <table width=100%>
429   <tr class=listtop>
430     <th class=listtop>$form->{title}</th>
431   </tr>
432   <tr height="5"></tr>
433   <tr valign=top>
434     <td>
435       <table width=100%>
436         <tr valign=top>
437           <td>
438             <table>
439               <tr>
440                 <th align=right nowrap>| . $locale->text('Vendor') . qq|</th>
441                 <td colspan=3>$vendor <input type="button" value="D" onclick="show_vc_details('vendor')"></td>
442                 <input type=hidden name=selectvendor value="| . H($form->{selectvendor}) . qq|">
443                 <input type=hidden name=oldvendor value="| . H($form->{oldvendor}) . qq|">
444                 <input type=hidden name=vendor_id value="| . H($form->{vendor_id}) . qq|">
445                 <input type=hidden name=terms value="| . H($form->{terms}) . qq|">
446               </tr>
447               <tr>
448                 <td></td>
449                 <td colspan=3>
450                   <table width=100%>
451                     <tr>
452                       <th align=left nowrap>| . $locale->text('Credit Limit') . qq|</th>
453                       <td>$form->{creditlimit}</td>
454                       <th align=left nowrap>| . $locale->text('Remaining') . qq|</th>
455                       <td class="plus$n">$form->{creditremaining}</td>
456                       <input type=hidden name=creditlimit value=$form->{creditlimit}>
457                       <input type=hidden name=creditremaining value=$form->{creditremaining}>
458                     </tr>
459                   </table>
460                 </td>
461               <tr>
462                 <th align=right nowrap>| . $locale->text('Currency') . qq|</th>
463                 <td><select name=currency>$form->{selectcurrency}</select></td>
464                 <input type=hidden name=selectcurrency value="$form->{selectcurrency}">
465                 <input type=hidden name=defaultcurrency value=$form->{defaultcurrency}>
466                 <input type=hidden name=fxgain_accno value=$form->{fxgain_accno}>
467                 <input type=hidden name=fxloss_accno value=$form->{fxloss_accno}>
468                 $exchangerate
469               </tr>
470               $department
471               $taxincluded
472             </table>
473           </td>
474           <td align=right>
475             <table>
476               <tr>
477                 <th align=right nowrap>| . $locale->text('Invoice Number') . qq|</th>
478                 <td><input name=invnumber size=11 value="$form->{invnumber}" $readonly></td>
479               </tr>
480               <tr>
481                 <th align=right nowrap>| . $locale->text('Order Number') . qq|</th>
482                 <td><input name=ordnumber size=11 value="$form->{ordnumber}" $readonly></td>
483               </tr>
484               <tr>
485                 <th align=right nowrap>| . $locale->text('Invoice Date') . qq|</th>
486                 $button1
487               </tr>
488               <tr>
489                 <th align=right nowrap>| . $locale->text('Due Date') . qq|</th>
490                 $button2
491               </tr>
492               <tr>
493                 <th align=right nowrap>| . $locale->text('Project Number') . qq|</th>
494                 <td>$globalprojectnumber</td>
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   $form->{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     $form->{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     if ($form->{"exchangerate_$i"} == 0) {
687       $form->{"exchangerate_$i"} = "";
688     } else {
689       $form->{"exchangerate_$i"} =
690         $form->format_amount(\%myconfig, $form->{"exchangerate_$i"});
691     }
692
693     print qq|<input type=hidden name="acc_trans_id_$i" value=$form->{"acc_trans_id_$i"}>\n|;
694     print qq|<input type=hidden name="gldate_$i" value=$form->{"gldate_$i"}>\n|;
695     my $changeable = 1;
696     if ($::lx_office_conf{features}->{payments_changeable} == 0) {
697       # never
698       $changeable = ($form->{"acc_trans_id_$i"})? 0 : 1;
699     }
700     if ($::lx_office_conf{features}->{payments_changeable} == 2) {
701       # on the same day
702       $changeable = (($form->{"gldate_$i"} eq '') || $form->current_date(\%myconfig) eq $form->{"gldate_$i"});
703     }
704
705     $exchangerate = qq|&nbsp;|;
706     if ($form->{defaultcurrency} && ($form->{currency} ne $form->{defaultcurrency})) {
707       if ($form->{"forex_$i"}) {
708         $exchangerate =
709           qq|<input type=hidden name="exchangerate_$i" value=$form->{"exchangerate_$i"}>$form->{"exchangerate_$i"}|;
710       } else {
711         if ($changeable) {
712           $exchangerate =
713             qq|<input name="exchangerate_$i" size=10 value=$form->{"exchangerate_$i"}>|;
714         } else {
715           $exchangerate =
716             qq|<input type=hidden name="exchangerate_$i" value=$form->{"exchangerate_$i"}>$form->{"exchangerate_$i"}|;
717         }
718       }
719     }
720
721     $exchangerate .= qq|
722 <input type=hidden name="forex_$i" value=$form->{"forex_$i"}>
723 |;
724
725     my $datepaid;
726     if ($changeable) {
727       $datepaid = qq|<td align=center><input name="datepaid_$i" id="datepaid_$i" size=11 title="($myconfig{'dateformat'})" value="$form->{"datepaid_$i"}" onBlur=\"check_right_date_format(this)\">
728          <input type="button" name="datepaid_$i" id="trigger_datepaid_$i" value="| . $locale->text('Details (one letter abbreviation)') . qq|"></td>|;
729     } else {
730       $datepaid = qq|<td align=center>$form->{"datepaid_$i"}</td>|.
731         qq|<input type=hidden name="datepaid_$i" value=$form->{"datepaid_$i"}>|;
732     }
733
734     my $paid;
735     if ($changeable) {
736       $paid = qq|<td align=center><input name="paid_$i" size=11 value="$form->{"paid_$i"}" onBlur=\"check_right_number_format(this)\"></td>|;
737     } else {
738       $paid = qq|<td align=center>$form->{"paid_$i"}</td>|.
739         qq|<input type=hidden name="paid_$i" value=$form->{"paid_$i"}>|;
740     }
741
742     my $source;
743     if ($changeable) {
744       $source = qq|<td align=center><input name="source_$i" size=11 value="$form->{"source_$i"}"></td>|;
745     } else {
746       $source = qq|<td align=center>$form->{"source_$i"}</td>|.
747         qq|<input type=hidden name="source_$i" value=$form->{"source_$i"}>|;
748     }
749
750     my $memo;
751     if ($changeable) {
752       $memo = qq|<td align=center><input name="memo_$i" size=11 value="$form->{"memo_$i"}"></td>|;
753     } else {
754       $memo = qq|<td align=center>$form->{"memo_$i"}</td>|.
755         qq|<input type=hidden name="memo_$i" value=$form->{"memo_$i"}>|;
756     }
757
758     my $AP_paid;
759     if ($changeable) {
760       $AP_paid = qq|<td align=center>${selectAP_paid}</td>|;
761     } else {
762       $AP_paid = qq|<td align=center>$form->{"AP_paid_$i"}</td>|.
763         qq|<input type=hidden name="AP_paid_$i" value=$form->{"AP_paid_$i"}>|;
764     }
765
766     my $paid_project_id;
767     if ($changeable) {
768       $paid_project_id =
769       qq|<td>|
770       . NTI($cgi->popup_menu('-name' => "paid_project_id_$i",
771                              '-values' => \@project_values,
772                              '-labels' => \%project_labels,
773                              '-default' => $form->{"paid_project_id_$i"} ))
774       . qq|</td>|;
775     } else {
776       my $projectnumber = $project_labels{$form->{"paid_project_id_$i"}};
777       $paid_project_id = qq|<td>$projectnumber</td>|.
778         qq|<input type=hidden name="paid_project_id_$i" value=$form->{"paid_project_id_$i"}>|;
779     }
780
781     $column_data{"paid_$i"}            = $paid;
782     $column_data{"AP_paid_$i"}         = $AP_paid;
783     $column_data{"exchangerate_$i"}    = qq|<td align=center>$exchangerate</td>|;
784     $column_data{"datepaid_$i"}        = $datepaid;
785     $column_data{"source_$i"}          = $source;
786     $column_data{"memo_$i"}            = $memo;
787     $column_data{"paid_project_id_$i"} = $paid_project_id;
788
789     map { print qq|$column_data{"${_}_$i"}\n| } @column_index;
790
791     print "
792         </tr>
793 ";
794     if ($changeable) {
795       push(@triggers, "datepaid_$i", "BL", "trigger_datepaid_$i");
796     }
797   }
798
799   my $paid_missing = $form->{invtotal_unformatted} - $form->{totalpaid};
800
801   print qq|
802         <tr>
803           <td></td>
804           <td></td>
805           <td align="center">| . $locale->text('Total') . qq|</td>
806           <td align="center">| . H($form->format_amount(\%myconfig, $form->{totalpaid}, 2)) . qq|</td>
807         </tr>
808         <tr>
809           <td></td>
810           <td></td>
811           <td align="center">| . $locale->text('Missing amount') . qq|</td>
812           <td align="center">| . H($form->format_amount(\%myconfig, $paid_missing, 2)) . qq|</td>
813         </tr>
814 | . $form->write_trigger(\%myconfig, scalar(@triggers) / 3, @triggers) .
815     qq|
816     <input type=hidden name=paidaccounts value=$form->{paidaccounts}>
817
818       </table>
819     </td>
820   </tr>
821   <tr>
822     <td><hr size=3 noshade></td>
823   </tr>
824 </table>
825 |;
826
827   $main::lxdebug->leave_sub();
828 }
829
830 sub form_footer {
831   $::lxdebug->enter_sub;
832   $::auth->assert('general_ledger');
833
834   my $num_due;
835   my $num_follow_ups;
836   if ($::form->{id}) {
837     my $follow_ups = FU->follow_ups('trans_id' => $::form->{id});
838
839     if (@{ $follow_ups }) {
840       $num_due        = sum map { $_->{due} * 1 } @{ $follow_ups };
841       $num_follow_ups = scalar @{ $follow_ups }
842     }
843   }
844
845   my $transdate = $::form->datetonum($::form->{transdate}, \%::myconfig);
846   my $closedto  = $::form->datetonum($::form->{closedto},  \%::myconfig);
847
848   my $storno = $::form->{id}
849             && !IS->has_storno(\%::myconfig, $::form, 'ap')
850             && !IS->is_storno( \%::myconfig, $::form, 'ap', $::form->{id})
851             && ($::form->{totalpaid} == 0 || $::form->{totalpaid} eq '');
852
853   $::form->header;
854   print $::form->parse_html_template('ap/form_footer', {
855     num_due         => $num_due,
856     num_follow_ups  => $num_follow_ups,
857     show_post_draft => ($transdate > $closedto) && !$::form->{id},
858     show_storno     => $storno,
859   });
860
861   $::lxdebug->leave_sub;
862 }
863
864 sub mark_as_paid {
865   $main::lxdebug->enter_sub();
866
867   my $form     = $main::form;
868   my %myconfig = %main::myconfig;
869
870   $main::auth->assert('general_ledger');
871
872   &mark_as_paid_common(\%myconfig,"ap");
873
874   $main::lxdebug->leave_sub();
875 }
876
877 sub update {
878   $main::lxdebug->enter_sub();
879
880   my $form     = $main::form;
881   my %myconfig = %main::myconfig;
882
883   $main::auth->assert('general_ledger');
884
885   my $display = shift;
886
887   $form->{invtotal} = 0;
888
889   delete @{ $form }{ grep { m/^tax_\d+$/ } keys %{ $form } };
890
891   map { $form->{$_} = $form->parse_amount(\%myconfig, $form->{$_}) }
892     qw(exchangerate creditlimit creditremaining);
893
894   my @flds  = qw(amount AP_amount projectnumber oldprojectnumber project_id taxchart);
895   my $count = 0;
896   my (@a, $j, $totaltax);
897   for my $i (1 .. $form->{rowcount}) {
898     $form->{"amount_$i"} =
899       $form->parse_amount(\%myconfig, $form->{"amount_$i"});
900     $form->{"tax_$i"} = $form->parse_amount(\%myconfig, $form->{"tax_$i"});
901     if ($form->{"amount_$i"}) {
902       push @a, {};
903       $j = $#a;
904       my ($taxkey, $rate) = split(/--/, $form->{"taxchart_$i"});
905       if ($taxkey > 1) {
906         if ($form->{taxincluded}) {
907           $form->{"tax_$i"} = $form->{"amount_$i"} / ($rate + 1) * $rate;
908         } else {
909           $form->{"tax_$i"} = $form->{"amount_$i"} * $rate;
910         }
911       } else {
912         $form->{"tax_$i"} = 0;
913       }
914       $form->{"tax_$i"} = $form->round_amount($form->{"tax_$i"}, 2);
915
916       $totaltax += $form->{"tax_$i"};
917       map { $a[$j]->{$_} = $form->{"${_}_$i"} } @flds;
918       $count++;
919     }
920   }
921   $form->redo_rows(\@flds, \@a, $count, $form->{rowcount});
922
923   map { $form->{invtotal} += $form->{"amount_$_"} } (1 .. $form->{rowcount});
924
925   $form->{forex}        = $form->check_exchangerate( \%myconfig, $form->{currency}, $form->{transdate}, 'sell');
926   $form->{exchangerate} = $form->{forex} if $form->{forex};
927
928   $form->{invdate} = $form->{transdate};
929   my %saved_variables = map +( $_ => $form->{$_} ), qw(AP AP_amount_1 taxchart_1);
930
931   my $vendor_changed = &check_name("vendor");
932
933   $form->{AP} = $saved_variables{AP};
934   if ($saved_variables{AP_amount_1} =~ m/.--./) {
935     map { $form->{$_} = $saved_variables{$_} } qw(AP_amount_1 taxchart_1);
936   } else {
937     delete $form->{taxchart_1};
938   }
939
940   $form->{rowcount} = $count + 1;
941
942   $form->{invtotal} =
943     ($form->{taxincluded}) ? $form->{invtotal} : $form->{invtotal} + $totaltax;
944
945   my $totalpaid;
946   for my $i (1 .. $form->{paidaccounts}) {
947     if ($form->parse_amount(\%myconfig, $form->{"paid_$i"})) {
948       map {
949         $form->{"${_}_$i"} =
950           $form->parse_amount(\%myconfig, $form->{"${_}_$i"})
951       } qw(paid exchangerate);
952
953       $totalpaid += $form->{"paid_$i"};
954
955       $form->{"forex_$i"}        = $form->check_exchangerate( \%myconfig, $form->{currency}, $form->{"datepaid_$i"}, 'sell');
956       $form->{"exchangerate_$i"} = $form->{"forex_$i"} if $form->{"forex_$i"};
957     }
958   }
959
960   $form->{creditremaining} -=
961     ($form->{invtotal} - $totalpaid + $form->{oldtotalpaid} -
962      $form->{oldinvtotal});
963   $form->{oldinvtotal}  = $form->{invtotal};
964   $form->{oldtotalpaid} = $totalpaid;
965
966   # notes
967   $form->{notes} = $form->{intnotes} if $vendor_changed;
968
969   &display_form;
970
971   $main::lxdebug->leave_sub();
972 }
973
974
975 sub post_payment {
976   $main::lxdebug->enter_sub();
977
978   my $form     = $main::form;
979   my %myconfig = %main::myconfig;
980   my $locale   = $main::locale;
981
982   $main::auth->assert('general_ledger');
983
984   $form->{defaultcurrency} = $form->get_default_currency(\%myconfig);
985
986   my $invdate = $form->datetonum($form->{transdate}, \%myconfig);
987
988   for my $i (1 .. $form->{paidaccounts}) {
989     if ($form->parse_amount(\%myconfig, $form->{"paid_$i"})) {
990       my $datepaid = $form->datetonum($form->{"datepaid_$i"}, \%myconfig);
991
992       $form->isblank("datepaid_$i", $locale->text('Payment date missing!'));
993
994       $form->error($locale->text('Cannot post payment for a closed period!'))
995         if ($form->date_closed($form->{"datepaid_$i"}, \%myconfig));
996
997       if ($form->{defaultcurrency} && ($form->{currency} ne $form->{defaultcurrency})) {
998         $form->{"exchangerate_$i"} = $form->{exchangerate}
999           if ($invdate == $datepaid);
1000         $form->isblank("exchangerate_$i",
1001                        $locale->text('Exchangerate for payment missing!'));
1002       }
1003     }
1004   }
1005
1006   ($form->{AP})      = split /--/, $form->{AP};
1007   ($form->{AP_paid}) = split /--/, $form->{AP_paid};
1008   $form->redirect($locale->text('Payment posted!'))
1009       if (AP->post_payment(\%myconfig, \%$form));
1010     $form->error($locale->text('Cannot post payment!'));
1011
1012
1013   $main::lxdebug->leave_sub();
1014 }
1015
1016
1017 sub post {
1018   $main::lxdebug->enter_sub();
1019
1020   my $form     = $main::form;
1021   my %myconfig = %main::myconfig;
1022   my $locale   = $main::locale;
1023
1024   $main::auth->assert('general_ledger');
1025
1026   my ($inline) = @_;
1027
1028   # check if there is a vendor, invoice and due date
1029   $form->isblank("transdate", $locale->text("Invoice Date missing!"));
1030   $form->isblank("duedate",   $locale->text("Due Date missing!"));
1031   $form->isblank("vendor",    $locale->text('Vendor missing!'));
1032
1033   if ($myconfig{mandatory_departments} && !$form->{department}) {
1034     $form->{saved_message} = $::locale->text('You have to specify a department.');
1035     update();
1036     exit;
1037   }
1038
1039   my $closedto  = $form->datetonum($form->{closedto},  \%myconfig);
1040   my $transdate = $form->datetonum($form->{transdate}, \%myconfig);
1041   $form->error($locale->text('Cannot post transaction for a closed period!')) if ($form->date_closed($form->{"transdate"}, \%myconfig));
1042
1043   my $zero_amount_posting = 1;
1044   for my $i (1 .. $form->{rowcount}) {
1045     if ($form->parse_amount(\%myconfig, $form->{"amount_$i"})) {
1046       $zero_amount_posting = 0;
1047       last;
1048     }
1049   }
1050
1051   $form->error($locale->text('Zero amount posting!')) if $zero_amount_posting;
1052
1053   $form->isblank("exchangerate", $locale->text('Exchangerate missing!'))
1054     if ($form->{defaultcurrency} && ($form->{currency} ne $form->{defaultcurrency}));
1055   delete($form->{AP});
1056
1057   for my $i (1 .. $form->{paidaccounts}) {
1058     if ($form->parse_amount(\%myconfig, $form->{"paid_$i"})) {
1059       my $datepaid = $form->datetonum($form->{"datepaid_$i"}, \%myconfig);
1060
1061       $form->isblank("datepaid_$i", $locale->text('Payment date missing!'));
1062
1063       $form->error($locale->text('Cannot post payment for a closed period!'))
1064         if ($form->date_closed($form->{"datepaid_$i"}, \%myconfig));
1065
1066       if ($form->{defaultcurrency} && ($form->{currency} ne $form->{defaultcurrency})) {
1067         $form->{"exchangerate_$i"} = $form->{exchangerate}
1068           if ($transdate == $datepaid);
1069         $form->isblank("exchangerate_$i",
1070                        $locale->text('Exchangerate for payment missing!'));
1071       }
1072
1073     }
1074   }
1075
1076   # if old vendor ne vendor redo form
1077   my ($vendor) = split /--/, $form->{vendor};
1078   if ($form->{oldvendor} ne "$vendor--$form->{vendor_id}") {
1079     &update;
1080     ::end_of_request();
1081   }
1082   my ($debitaccno,    $debittaxkey)    = split /--/, $form->{AP_amountselected};
1083   my ($taxkey,        $NULL)           = split /--/, $form->{taxchartselected};
1084   my ($payablesaccno, $payablestaxkey) = split /--/, $form->{APselected};
1085 #  $form->{AP_amount_1}  = $debitaccno;
1086   $form->{AP_payables}  = $payablesaccno;
1087   $form->{taxkey}       = $taxkey;
1088   $form->{storno}       = 0;
1089
1090   $form->{id} = 0 if $form->{postasnew};
1091
1092   if (AP->post_transaction(\%myconfig, \%$form)) {
1093     # saving the history
1094     if(!exists $form->{addition} && $form->{id} ne "") {
1095       $form->{snumbers} = qq|invnumber_| . $form->{invnumber};
1096       $form->{addition} = "POSTED";
1097       $form->save_history;
1098     }
1099     # /saving the history
1100     remove_draft() if $form->{remove_draft};
1101     # Dieser Text wird niemals ausgegeben: Probleme beim redirect?
1102     $form->redirect($locale->text('Transaction posted!')) unless $inline;
1103   } else {
1104     $form->error($locale->text('Cannot post transaction!'));
1105   }
1106
1107   $main::lxdebug->leave_sub();
1108 }
1109
1110 sub post_as_new {
1111   $main::lxdebug->enter_sub();
1112
1113   my $form     = $main::form;
1114   my %myconfig = %main::myconfig;
1115
1116   $main::auth->assert('general_ledger');
1117
1118   $form->{postasnew} = 1;
1119   # saving the history
1120   if(!exists $form->{addition} && $form->{id} ne "") {
1121     $form->{snumbers} = qq|invnumber_| . $form->{invnumber};
1122     $form->{addition} = "POSTED AS NEW";
1123     $form->save_history;
1124   }
1125   # /saving the history
1126   &post;
1127
1128   $main::lxdebug->leave_sub();
1129 }
1130
1131 sub use_as_template {
1132   $main::lxdebug->enter_sub();
1133
1134   my $form     = $main::form;
1135   my %myconfig = %main::myconfig;
1136
1137   $main::auth->assert('general_ledger');
1138
1139   map { delete $form->{$_} } qw(printed emailed queued invnumber invdate deliverydate id datepaid_1 gldate_1 acc_trans_id_1 source_1 memo_1 paid_1 exchangerate_1 AP_paid_1 storno);
1140   $form->{paidaccounts} = 1;
1141   $form->{rowcount}--;
1142   $form->{invdate} = $form->current_date(\%myconfig);
1143   &update;
1144
1145   $main::lxdebug->leave_sub();
1146 }
1147
1148 sub delete {
1149   $main::lxdebug->enter_sub();
1150
1151   my $form     = $main::form;
1152   my $locale   = $main::locale;
1153
1154   $main::auth->assert('general_ledger');
1155
1156   $form->{title} = $locale->text('Confirm!');
1157
1158   $form->header;
1159
1160   delete $form->{header};
1161
1162   print qq|
1163 <form method=post action=$form->{script}>
1164 |;
1165
1166   foreach my $key (keys %$form) {
1167     next if (($key eq 'login') || ($key eq 'password') || ('' ne ref $form->{$key}));
1168     $form->{$key} =~ s/\"/&quot;/g;
1169     print qq|<input type=hidden name=$key value="$form->{$key}">\n|;
1170   }
1171
1172   print qq|
1173 <h2 class=confirm>$form->{title}</h2>
1174
1175 <h4>|
1176     . $locale->text('Are you sure you want to delete Transaction')
1177     . qq| $form->{invnumber}</h4>
1178
1179 <input name=action class=submit type=submit value="|
1180     . $locale->text('Yes') . qq|">
1181 </form>
1182 |;
1183
1184   $main::lxdebug->leave_sub();
1185 }
1186
1187 sub yes {
1188   $main::lxdebug->enter_sub();
1189
1190   my $form     = $main::form;
1191   my %myconfig = %main::myconfig;
1192   my $locale   = $main::locale;
1193
1194   $main::auth->assert('general_ledger');
1195
1196   if (AP->delete_transaction(\%myconfig, \%$form)) {
1197     # saving the history
1198     if(!exists $form->{addition}) {
1199       $form->{snumbers} = qq|invnumber_| . $form->{invnumber};
1200       $form->{addition} = "DELETED";
1201       $form->save_history;
1202     }
1203     # /saving the history
1204     $form->redirect($locale->text('Transaction deleted!'));
1205   }
1206   $form->error($locale->text('Cannot delete transaction!'));
1207
1208   $main::lxdebug->leave_sub();
1209 }
1210
1211 sub search {
1212   $main::lxdebug->enter_sub();
1213
1214   $main::auth->assert('general_ledger | vendor_invoice_edit');
1215
1216   my $form     = $main::form;
1217   my %myconfig = %main::myconfig;
1218   my $locale   = $main::locale;
1219
1220   # setup customer selection
1221   $form->all_vc(\%myconfig, "vendor", "AP");
1222
1223   $form->{title}    = $locale->text('AP Transactions');
1224   $form->{fokus}    = "search.vendor";
1225   $form->{jsscript} = 1;
1226
1227   $form->get_lists("projects"     => { "key" => "ALL_PROJECTS", "all" => 1 },
1228                    "departments"  => "ALL_DEPARTMENTS",
1229                    "vendors"      => "ALL_VC");
1230
1231   # constants and subs for template
1232   $form->{jsscript}  = 1;
1233   $form->{vc_keys}   = sub { "$_[0]->{name}--$_[0]->{id}" };
1234
1235   $form->header;
1236   print $form->parse_html_template('ap/search', { %myconfig });
1237
1238   $main::lxdebug->leave_sub();
1239 }
1240
1241 sub create_subtotal_row {
1242   $main::lxdebug->enter_sub();
1243
1244   my ($totals, $columns, $column_alignment, $subtotal_columns, $class) = @_;
1245
1246   my $form     = $main::form;
1247   my %myconfig = %main::myconfig;
1248
1249   my $row = { map { $_ => { 'data' => '', 'class' => $class, 'align' => $column_alignment->{$_}, } } @{ $columns } };
1250
1251   map { $row->{$_}->{data} = $form->format_amount(\%myconfig, $totals->{$_}, 2) } @{ $subtotal_columns };
1252
1253   $row->{tax}->{data} = $form->format_amount(\%myconfig, $totals->{amount} - $totals->{netamount}, 2);
1254
1255   map { $totals->{$_} = 0 } @{ $subtotal_columns };
1256
1257   $main::lxdebug->leave_sub();
1258
1259   return $row;
1260 }
1261
1262 sub ap_transactions {
1263   $main::lxdebug->enter_sub();
1264
1265   my $form     = $main::form;
1266   my %myconfig = %main::myconfig;
1267   my $locale   = $main::locale;
1268
1269   $main::auth->assert('general_ledger | vendor_invoice_edit');
1270
1271   ($form->{vendor}, $form->{vendor_id}) = split(/--/, $form->{vendor});
1272
1273   report_generator_set_default_sort('transdate', 1);
1274
1275   AP->ap_transactions(\%myconfig, \%$form);
1276
1277   $form->{title} = $locale->text('AP Transactions');
1278
1279   my $report = SL::ReportGenerator->new(\%myconfig, $form);
1280
1281   my @columns =
1282     qw(transdate id type invnumber ordnumber name netamount tax amount paid datepaid
1283        due duedate transaction_description notes employee globalprojectnumber
1284        vendornumber country ustid taxzone payment_terms charts);
1285
1286   my @hidden_variables = map { "l_${_}" } @columns;
1287   push @hidden_variables, "l_subtotal", qw(open closed vendor invnumber ordnumber transaction_description notes project_id transdatefrom transdateto department);
1288
1289   my $href = build_std_url('action=ap_transactions', grep { $form->{$_} } @hidden_variables);
1290
1291   my %column_defs = (
1292     'transdate'               => { 'text' => $locale->text('Date'), },
1293     'id'                      => { 'text' => $locale->text('ID'), },
1294     'type'                    => { 'text' => $locale->text('Type'), },
1295     'invnumber'               => { 'text' => $locale->text('Invoice'), },
1296     'ordnumber'               => { 'text' => $locale->text('Order'), },
1297     'name'                    => { 'text' => $locale->text('Vendor'), },
1298     'netamount'               => { 'text' => $locale->text('Amount'), },
1299     'tax'                     => { 'text' => $locale->text('Tax'), },
1300     'amount'                  => { 'text' => $locale->text('Total'), },
1301     'paid'                    => { 'text' => $locale->text('Paid'), },
1302     'datepaid'                => { 'text' => $locale->text('Date Paid'), },
1303     'due'                     => { 'text' => $locale->text('Amount Due'), },
1304     'duedate'                 => { 'text' => $locale->text('Due Date'), },
1305     'transaction_description' => { 'text' => $locale->text('Transaction description'), },
1306     'notes'                   => { 'text' => $locale->text('Notes'), },
1307     'employee'                => { 'text' => $locale->text('Employee'), },
1308     'globalprojectnumber'     => { 'text' => $locale->text('Document Project Number'), },
1309     'vendornumber'            => { 'text' => $locale->text('Vendor Number'), },
1310     'country'                 => { 'text' => $locale->text('Country'), },
1311     'ustid'                   => { 'text' => $locale->text('USt-IdNr.'), },
1312     'taxzone'                 => { 'text' => $locale->text('Steuersatz'), },
1313     'payment_terms'           => { 'text' => $locale->text('Payment Terms'), },
1314     'charts'                  => { 'text' => $locale->text('Buchungskonto'), },
1315   );
1316
1317   foreach my $name (qw(id transdate duedate invnumber ordnumber name datepaid employee shippingpoint shipvia transaction_description)) {
1318     my $sortdir                 = $form->{sort} eq $name ? 1 - $form->{sortdir} : $form->{sortdir};
1319     $column_defs{$name}->{link} = $href . "&sort=$name&sortdir=$sortdir";
1320   }
1321
1322   my %column_alignment = map { $_ => 'right' } qw(netamount tax amount paid due);
1323
1324   $form->{"l_type"} = "Y";
1325   map { $column_defs{$_}->{visible} = $form->{"l_${_}"} ? 1 : 0 } @columns;
1326
1327   $report->set_columns(%column_defs);
1328   $report->set_column_order(@columns);
1329
1330   $report->set_export_options('ap_transactions', @hidden_variables, qw(sort sortdir));
1331
1332   $report->set_sort_indicator($form->{sort}, $form->{sortdir});
1333
1334   my @options;
1335   push @options, $locale->text('Vendor')                  . " : $form->{vendor}"                         if ($form->{vendor});
1336   push @options, $locale->text('Department')              . " : " . (split /--/, $form->{department})[0] if ($form->{department});
1337   push @options, $locale->text('Invoice Number')          . " : $form->{invnumber}"                      if ($form->{invnumber});
1338   push @options, $locale->text('Order Number')            . " : $form->{ordnumber}"                      if ($form->{ordnumber});
1339   push @options, $locale->text('Notes')                   . " : $form->{notes}"                          if ($form->{notes});
1340   push @options, $locale->text('Transaction description') . " : $form->{transaction_description}"        if ($form->{transaction_description});
1341   push @options, $locale->text('From') . " " . $locale->date(\%myconfig, $form->{transdatefrom}, 1)      if ($form->{transdatefrom});
1342   push @options, $locale->text('Bis')  . " " . $locale->date(\%myconfig, $form->{transdateto},   1)      if ($form->{transdateto});
1343   push @options, $locale->text('Open')                                                                   if ($form->{open});
1344   push @options, $locale->text('Closed')                                                                 if ($form->{closed});
1345
1346   $report->set_options('top_info_text'        => join("\n", @options),
1347                        'raw_bottom_info_text' => $form->parse_html_template('ap/ap_transactions_bottom'),
1348                        'output_format'        => 'HTML',
1349                        'title'                => $form->{title},
1350                        'attachment_basename'  => $locale->text('vendor_invoice_list') . strftime('_%Y%m%d', localtime time),
1351     );
1352   $report->set_options_from_form();
1353   $locale->set_numberformat_wo_thousands_separator(\%myconfig) if lc($report->{options}->{output_format}) eq 'csv';
1354
1355   # add sort and escape callback, this one we use for the add sub
1356   $form->{callback} = $href .= "&sort=$form->{sort}";
1357
1358   # escape callback for href
1359   my $callback = $form->escape($href);
1360
1361   my @subtotal_columns = qw(netamount amount paid due);
1362
1363   my %totals    = map { $_ => 0 } @subtotal_columns;
1364   my %subtotals = map { $_ => 0 } @subtotal_columns;
1365
1366   my $idx = 0;
1367
1368   foreach my $ap (@{ $form->{AP} }) {
1369     $ap->{tax} = $ap->{amount} - $ap->{netamount};
1370     $ap->{due} = $ap->{amount} - $ap->{paid};
1371
1372     map { $subtotals{$_} += $ap->{$_};
1373           $totals{$_}    += $ap->{$_} } @subtotal_columns;
1374
1375     map { $ap->{$_} = $form->format_amount(\%myconfig, $ap->{$_}, 2) } qw(netamount tax amount paid due);
1376
1377     my $is_storno  = $ap->{storno} &&  $ap->{storno_id};
1378     my $has_storno = $ap->{storno} && !$ap->{storno_id};
1379
1380     if ($ap->{invoice}) {
1381       $ap->{type} =
1382           $has_storno       ? $locale->text("Invoice with Storno (abbreviation)")
1383         : $is_storno        ? $locale->text("Storno (one letter abbreviation)")
1384         :                     $locale->text("Invoice (one letter abbreviation)");
1385     } else {
1386       $ap->{type} =
1387           $has_storno       ? $locale->text("AP Transaction with Storno (abbreviation)")
1388         : $is_storno        ? $locale->text("AP Transaction Storno (one letter abbreviation)")
1389         :                     $locale->text("AP Transaction (abbreviation)");
1390     }
1391
1392     my $row = { };
1393
1394     foreach my $column (@columns) {
1395       $row->{$column} = {
1396         'data'  => $ap->{$column},
1397         'align' => $column_alignment{$column},
1398       };
1399     }
1400
1401     $row->{invnumber}->{link} = build_std_url("script=" . ($ap->{invoice} ? 'ir.pl' : 'ap.pl'), 'action=edit')
1402       . "&id=" . E($ap->{id}) . "&callback=${callback}";
1403
1404     my $row_set = [ $row ];
1405
1406     if (($form->{l_subtotal} eq 'Y')
1407         && (($idx == (scalar @{ $form->{AP} } - 1))
1408             || ($ap->{ $form->{sort} } ne $form->{AP}->[$idx + 1]->{ $form->{sort} }))) {
1409       push @{ $row_set }, create_subtotal_row(\%subtotals, \@columns, \%column_alignment, \@subtotal_columns, 'listsubtotal');
1410     }
1411
1412     $report->add_data($row_set);
1413
1414     $idx++;
1415   }
1416
1417   $report->add_separator();
1418   $report->add_data(create_subtotal_row(\%totals, \@columns, \%column_alignment, \@subtotal_columns, 'listtotal'));
1419
1420   $report->generate_with_headers();
1421
1422   $main::lxdebug->leave_sub();
1423 }
1424
1425 sub storno {
1426   $main::lxdebug->enter_sub();
1427
1428   my $form     = $main::form;
1429   my %myconfig = %main::myconfig;
1430   my $locale   = $main::locale;
1431
1432   $main::auth->assert('general_ledger');
1433
1434   if (IS->has_storno(\%myconfig, $form, 'ap')) {
1435     $form->{title} = $locale->text("Cancel Accounts Payables Transaction");
1436     $form->error($locale->text("Transaction has already been cancelled!"));
1437   }
1438
1439   $form->error($locale->text('Cannot post storno for a closed period!'))
1440     if ( $form->date_closed($form->{transdate}, \%myconfig));
1441
1442   AP->storno($form, \%myconfig, $form->{id});
1443
1444   # saving the history
1445   if(!exists $form->{addition} && $form->{id} ne "") {
1446     $form->{snumbers} = "ordnumber_$form->{ordnumber}";
1447     $form->{addition} = "STORNO";
1448     $form->save_history;
1449   }
1450   # /saving the history
1451
1452   $form->redirect(sprintf $locale->text("Transaction %d cancelled."), $form->{storno_id});
1453
1454   $main::lxdebug->leave_sub();
1455 }