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