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