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