Merge branch 'master' of github.com:kivitendo/kivitendo-erp
[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 use SL::DB::Default;
44
45 require "bin/mozilla/arap.pl";
46 require "bin/mozilla/common.pl";
47 require "bin/mozilla/drafts.pl";
48 require "bin/mozilla/reportgenerator.pl";
49
50 use strict;
51
52 1;
53
54 # end of main
55
56 # this is for our long dates
57 # $locale->text('January')
58 # $locale->text('February')
59 # $locale->text('March')
60 # $locale->text('April')
61 # $locale->text('May ')
62 # $locale->text('June')
63 # $locale->text('July')
64 # $locale->text('August')
65 # $locale->text('September')
66 # $locale->text('October')
67 # $locale->text('November')
68 # $locale->text('December')
69
70 # this is for our short month
71 # $locale->text('Jan')
72 # $locale->text('Feb')
73 # $locale->text('Mar')
74 # $locale->text('Apr')
75 # $locale->text('May')
76 # $locale->text('Jun')
77 # $locale->text('Jul')
78 # $locale->text('Aug')
79 # $locale->text('Sep')
80 # $locale->text('Oct')
81 # $locale->text('Nov')
82 # $locale->text('Dec')
83
84 sub add {
85   $main::lxdebug->enter_sub();
86
87   my $form     = $main::form;
88   my %myconfig = %main::myconfig;
89
90   $main::auth->assert('general_ledger');
91
92   return $main::lxdebug->leave_sub() if (load_draft_maybe());
93
94   $form->{title} = "Add";
95
96   $form->{callback} = "ap.pl?action=add&DONT_LOAD_DRAFT=1" unless $form->{callback};
97
98   AP->get_transdate(\%myconfig, $form);
99   $form->{initial_transdate} = $form->{transdate};
100   create_links(dont_save => 1);
101   $form->{transdate} = $form->{initial_transdate};
102   &display_form;
103
104   $main::lxdebug->leave_sub();
105 }
106
107 sub edit {
108   $main::lxdebug->enter_sub();
109
110   my $form     = $main::form;
111
112   $main::auth->assert('general_ledger');
113
114   $form->{title} = "Edit";
115
116   create_links();
117   &display_form;
118
119   $main::lxdebug->leave_sub();
120 }
121
122 sub display_form {
123   $main::lxdebug->enter_sub();
124
125   my $form     = $main::form;
126
127   $main::auth->assert('general_ledger');
128
129   &form_header;
130   &form_footer;
131
132   $main::lxdebug->leave_sub();
133 }
134
135 sub create_links {
136   $main::lxdebug->enter_sub();
137
138   my %params   = @_;
139
140   my $form     = $main::form;
141   my %myconfig = %main::myconfig;
142
143   $main::auth->assert('general_ledger');
144
145   $form->create_links("AP", \%myconfig, "vendor");
146   my %saved;
147   if (!$params{dont_save}) {
148     %saved = map { ($_ => $form->{$_}) } qw(direct_debit taxincluded);
149     $saved{duedate} = $form->{duedate} if $form->{duedate};
150   }
151
152   IR->get_vendor(\%myconfig, \%$form);
153
154   $form->{$_}        = $saved{$_} for keys %saved;
155   $form->{oldvendor} = "$form->{vendor}--$form->{vendor_id}";
156   $form->{rowcount}  = 1;
157
158   # build the popup menus
159   $form->{taxincluded} = ($form->{id}) ? $form->{taxincluded} : "checked";
160
161   # currencies
162   $form->{defaultcurrency} = $form->get_default_currency(\%myconfig);
163
164   map { my $quoted = H($_); $form->{selectcurrency} .= "<option value=\"${quoted}\">${quoted}\n" } $form->get_all_currencies(\%myconfig);
165
166   # vendors
167   if (@{ $form->{all_vendor} || [] }) {
168     $form->{vendor} = qq|$form->{vendor}--$form->{vendor_id}|;
169     map { my $quoted = H($_->{name} . "--" . $_->{id}); $form->{selectvendor} .= "<option value=\"${quoted}\">${quoted}\n" }
170       (@{ $form->{all_vendor} });
171   }
172
173   # departments
174   if (@{ $form->{all_departments} || [] }) {
175     $form->{department}       = "$form->{department}--$form->{department_id}";
176     $form->{selectdepartment} = "<option>\n" . join('', map { my $quoted = H("$_->{description}--$_->{id}"); "<option value=\"${quoted}\">${quoted}\n"} @{ $form->{all_departments} || [] });
177   }
178
179   $form->{employee} = "$form->{employee}--$form->{employee_id}";
180
181   AP->setup_form($form);
182
183   $form->{locked} =
184     ($form->datetonum($form->{transdate}, \%myconfig) <=
185      $form->datetonum($form->{closedto}, \%myconfig));
186
187   $main::lxdebug->leave_sub();
188 }
189
190 sub form_header {
191   $main::lxdebug->enter_sub();
192
193   my $form     = $main::form;
194   my %myconfig = %main::myconfig;
195   my $locale   = $main::locale;
196   my $cgi      = $::request->{cgi};
197
198   $main::auth->assert('general_ledger');
199
200   $form->{title_} = $form->{title};
201   $form->{title} = $form->{title} eq 'Add' ? $locale->text('Add Accounts Payables Transaction') : $locale->text('Edit Accounts Payables Transaction');
202
203   # type=submit $locale->text('Add Accounts Payables Transaction')
204   # type=submit $locale->text('Edit Accounts Payables Transaction')
205
206   # set option selected
207   foreach my $item (qw(vendor currency department)) {
208     my $to_replace         =  H($form->{$item});
209     $form->{"select$item"} =~ s/ selected//;
210     $form->{"select$item"} =~ s/>\Q${to_replace}\E/ selected>${to_replace}/;
211   }
212   my $readonly = $form->{id} ? "readonly" : "";
213
214   $form->{radier} = ($::instance_conf->get_ap_changeable == 2)
215                       ? ($form->current_date(\%myconfig) eq $form->{gldate})
216                       : ($::instance_conf->get_ap_changeable == 1);
217   $readonly       = $form->{radier} ? "" : $readonly;
218
219   $form->{readonly} = $readonly;
220
221   $form->{forex} = $form->check_exchangerate( \%myconfig, $form->{currency}, $form->{transdate}, 'sell');
222   if ( $form->{forex} ) {
223     $form->{exchangerate} = $form->{forex};
224   }
225
226   # format amounts
227   $form->{exchangerate}    = $form->{exchangerate} ? $form->format_amount(\%myconfig, $form->{exchangerate}) : '';
228   $form->{creditlimit}     = $form->format_amount(\%myconfig, $form->{creditlimit}, 0, "0");
229   $form->{creditremaining} = $form->format_amount(\%myconfig, $form->{creditremaining}, 0, "0");
230
231   my $rows;
232   if (($rows = $form->numtextrows($form->{notes}, 50)) < 2) {
233     $rows = 2;
234   }
235   $form->{textarea_rows} = $rows;
236
237   $form->{creditremaining_plus} = ($form->{creditremaining} =~ /-/) ? "0" : "1";
238
239   my @old_project_ids = ();
240   map(
241     {
242       if ($form->{"project_id_$_"}) {
243         push(@old_project_ids, $form->{"project_id_$_"});
244       }
245     }
246     (1..$form->{"rowcount"})
247   );
248
249   $form->get_lists("projects"  => { "key"       => "ALL_PROJECTS",
250                                     "all"       => 0,
251                                     "old_id"    => \@old_project_ids },
252                    "charts"    => { "key"       => "ALL_CHARTS",
253                                     "transdate" => $form->{transdate} },
254                    "taxcharts" => { "key"       => "ALL_TAXCHARTS",
255                                     "module"    => "AP" },);
256
257   map(
258     { $_->{link_split} = [ split(/:/, $_->{link}) ]; }
259     @{ $form->{ALL_CHARTS} }
260   );
261
262   my %project_labels = ();
263   foreach my $item (@{ $form->{"ALL_PROJECTS"} }) {
264     $project_labels{$item->{id}} = $item->{projectnumber};
265   }
266
267   my %charts;
268   my $taxchart_init;
269
270   foreach my $item (@{ $form->{ALL_CHARTS} }) {
271     if ( grep({ $_ eq 'AP_amount' } @{ $item->{link_split} }) ) {
272       if ( $taxchart_init eq '' ) {
273         $taxchart_init = $item->{tax_id};
274       }
275
276       push(@{ $form->{ALL_CHARTS_AP_amount} }, $item);
277     }
278     elsif ( grep({ $_ eq 'AP' } @{ $item->{link_split} }) ) {
279       push(@{ $form->{ALL_CHARTS_AP} }, $item);
280     }
281     elsif ( grep({ $_ eq 'AP_paid' } @{ $item->{link_split} }) ) {
282       push(@{ $form->{ALL_CHARTS_AP_paid} }, $item);
283     }
284
285     $charts{$item->{accno}} = $item;
286   }
287
288   my %taxcharts = ();
289   foreach my $item (@{ $form->{ALL_TAXCHARTS} }) {
290     my $key = $item->{id} .'--'. $item->{rate};
291
292     if ( $taxchart_init eq $item->{id} ) {
293       $taxchart_init = $key;
294     }
295
296     $taxcharts{$item->{id}} = $item;
297   }
298
299   my $follow_up_vc         =  $form->{vendor};
300   $follow_up_vc            =~ s/--.*?//;
301   my $follow_up_trans_info =  "$form->{invnumber} ($follow_up_vc)";
302
303   $form->{javascript} .= qq|<script type="text/javascript" src="js/common.js"></script>|;
304   $form->{javascript} .= qq|<script type="text/javascript" src="js/show_vc_details.js"></script>|;
305   $form->{javascript} .= qq|<script type="text/javascript" src="js/follow_up.js"></script>|;
306
307   $form->header();
308
309   for my $i (1 .. $form->{rowcount}) {
310
311     # format amounts
312     $form->{"amount_$i"} = $form->format_amount(\%myconfig, $form->{"amount_$i"}, 2);
313     $form->{"tax_$i"} = $form->format_amount(\%myconfig, $form->{"tax_$i"}, 2);
314
315     my $selected_accno_full;
316     my ($accno_row) = split(/--/, $form->{"AP_amount_$i"});
317     my $item = $charts{$accno_row};
318     $selected_accno_full = "$item->{accno}--$item->{tax_id}";
319
320     my $selected_taxchart = $form->{"taxchart_$i"};
321     my ($selected_accno, $selected_tax_id) = split(/--/, $selected_accno_full);
322     my ($previous_accno, $previous_tax_id) = split(/--/, $form->{"previous_AP_amount_$i"});
323
324     if ($previous_accno &&
325         ($previous_accno eq $selected_accno) &&
326         ($previous_tax_id ne $selected_tax_id)) {
327       my $item = $taxcharts{$selected_tax_id};
328       $selected_taxchart = "$item->{id}--$item->{rate}";
329     }
330
331     $selected_taxchart = $taxchart_init unless ($form->{"taxchart_$i"});
332
333     $form->{'selected_accno_full_'. $i} = $selected_accno_full;
334
335     $form->{'selected_taxchart_'. $i} = $selected_taxchart;
336   }
337
338   $form->{AP_amount_value_title_sub} = sub {
339     my $item = shift;
340     return [
341       $item->{accno} .'--'. $item->{tax_id},
342       $item->{accno} .'--'. $item->{description},
343     ];
344   };
345
346   $form->{taxchart_value_title_sub} = sub {
347     my $item = shift;
348     return [
349       $item->{id} .'--'. $item->{rate},
350       $item->{taxdescription} .' '. ($item->{rate} * 100) .' %',
351     ];
352   };
353
354   $form->{AP_paid_value_title_sub} = sub {
355     my $item = shift;
356     return [
357       $item->{accno},
358       $item->{accno} .'--'. $item->{description}
359     ];
360   };
361
362   $form->{APselected_value_title_sub} = sub {
363     my $item = shift;
364     return [
365       $item->{accno},
366       $item->{accno} .'--'. $item->{description}
367     ];
368   };
369
370   $form->{invtotal_unformatted} = $form->{invtotal};
371   $form->{invtotal} = $form->format_amount(\%myconfig, $form->{invtotal}, 2);
372
373   $form->{totalpaid} = 0;
374
375   if ( $form->{'paid_'. $form->{paidaccounts}} ) {
376     $form->{paidaccounts}++;
377   }
378
379   # default account for current assets (i.e. 1801 - SKR04)
380   $form->{accno_arap} = IS->get_standard_accno_current_assets(\%myconfig, \%$form);
381
382   for my $i (1 .. $form->{paidaccounts}) {
383     $form->{totalpaid} += $form->{"paid_$i"};
384
385     # format amounts
386     if ($form->{"paid_$i"}) {
387       $form->{"paid_$i"} = $form->format_amount(\%myconfig, $form->{"paid_$i"}, 2);
388     }
389     if ($form->{"exchangerate_$i"} == 0) {
390       $form->{"exchangerate_$i"} = "";
391     } else {
392       $form->{"exchangerate_$i"} =
393         $form->format_amount(\%myconfig, $form->{"exchangerate_$i"});
394     }
395
396     my $changeable = 1;
397     if (SL::DB::Default->get->payments_changeable == 0) {
398       # never
399       $changeable = ($form->{"acc_trans_id_$i"})? 0 : 1;
400     }
401     if (SL::DB::Default->get->payments_changeable == 2) {
402       # on the same day
403       $changeable = (($form->{"gldate_$i"} eq '') || $form->current_date(\%myconfig) eq $form->{"gldate_$i"});
404     }
405
406     $form->{'paidaccount_changeable_'. $i} = $changeable;
407
408     $form->{'labelpaid_project_id_'. $i} = $project_labels{$form->{'paid_project_id_'. $i}};
409   }
410
411   $form->{paid_missing} = $form->{invtotal_unformatted} - $form->{totalpaid};
412
413   print $form->parse_html_template('ap/form_header');
414
415   $main::lxdebug->leave_sub();
416 }
417
418 sub form_footer {
419   $::lxdebug->enter_sub;
420   $::auth->assert('general_ledger');
421
422   my $num_due;
423   my $num_follow_ups;
424   if ($::form->{id}) {
425     my $follow_ups = FU->follow_ups('trans_id' => $::form->{id});
426
427     if (@{ $follow_ups }) {
428       $num_due        = sum map { $_->{due} * 1 } @{ $follow_ups };
429       $num_follow_ups = scalar @{ $follow_ups }
430     }
431   }
432
433   my $transdate = $::form->datetonum($::form->{transdate}, \%::myconfig);
434   my $closedto  = $::form->datetonum($::form->{closedto},  \%::myconfig);
435
436   my $storno = $::form->{id}
437             && !IS->has_storno(\%::myconfig, $::form, 'ap')
438             && !IS->is_storno( \%::myconfig, $::form, 'ap', $::form->{id})
439             && ($::form->{totalpaid} == 0 || $::form->{totalpaid} eq '');
440
441   $::form->header;
442   print $::form->parse_html_template('ap/form_footer', {
443     num_due           => $num_due,
444     num_follow_ups    => $num_follow_ups,
445     show_post_draft   => ($transdate > $closedto) && !$::form->{id},
446     show_storno       => $storno,
447   });
448
449   $::lxdebug->leave_sub;
450 }
451
452 sub mark_as_paid {
453   $main::lxdebug->enter_sub();
454
455   my $form     = $main::form;
456   my %myconfig = %main::myconfig;
457
458   $main::auth->assert('general_ledger');
459
460   &mark_as_paid_common(\%myconfig,"ap");
461
462   $main::lxdebug->leave_sub();
463 }
464
465 sub update {
466   $main::lxdebug->enter_sub();
467
468   my $form     = $main::form;
469   my %myconfig = %main::myconfig;
470
471   $main::auth->assert('general_ledger');
472
473   my $display = shift;
474
475   $form->{invtotal} = 0;
476
477   delete @{ $form }{ grep { m/^tax_\d+$/ } keys %{ $form } };
478
479   map { $form->{$_} = $form->parse_amount(\%myconfig, $form->{$_}) }
480     qw(exchangerate creditlimit creditremaining);
481
482   my @flds  = qw(amount AP_amount projectnumber oldprojectnumber project_id taxchart);
483   my $count = 0;
484   my (@a, $j, $totaltax);
485   for my $i (1 .. $form->{rowcount}) {
486     $form->{"amount_$i"} = $form->parse_amount(\%myconfig, $form->{"amount_$i"});
487     if ($form->{"amount_$i"}) {
488       push @a, {};
489       $j = $#a;
490       my ($taxkey, $rate) = split(/--/, $form->{"taxchart_$i"});
491
492       # calculate tax exactly the same way as AP in post_transaction via form->calculate_tax
493       my $tmpnetamount;
494       ($tmpnetamount,$form->{"tax_$i"}) = $form->calculate_tax($form->{"amount_$i"},$rate,$form->{taxincluded},2);
495
496       $totaltax += $form->{"tax_$i"};
497       map { $a[$j]->{$_} = $form->{"${_}_$i"} } @flds;
498       $count++;
499     }
500   }
501   $form->redo_rows(\@flds, \@a, $count, $form->{rowcount});
502
503   map { $form->{invtotal} += $form->{"amount_$_"} } (1 .. $form->{rowcount});
504
505   $form->{forex}        = $form->check_exchangerate( \%myconfig, $form->{currency}, $form->{transdate}, 'sell');
506   $form->{exchangerate} = $form->{forex} if $form->{forex};
507
508   $form->{invdate} = $form->{transdate};
509   my %saved_variables = map +( $_ => $form->{$_} ), qw(AP AP_amount_1 taxchart_1 notes);
510
511   my $vendor_changed = &check_name("vendor");
512
513   $form->{AP} = $saved_variables{AP};
514   if ($saved_variables{AP_amount_1} =~ m/.--./) {
515     map { $form->{$_} = $saved_variables{$_} } qw(AP_amount_1 taxchart_1);
516   } else {
517     delete $form->{taxchart_1};
518   }
519
520   $form->{rowcount} = $count + 1;
521
522   $form->{invtotal} =
523     ($form->{taxincluded}) ? $form->{invtotal} : $form->{invtotal} + $totaltax;
524
525   my $totalpaid;
526   for my $i (1 .. $form->{paidaccounts}) {
527     if ($form->parse_amount(\%myconfig, $form->{"paid_$i"})) {
528       map {
529         $form->{"${_}_$i"} =
530           $form->parse_amount(\%myconfig, $form->{"${_}_$i"})
531       } qw(paid exchangerate);
532
533       $totalpaid += $form->{"paid_$i"};
534
535       $form->{"forex_$i"}        = $form->check_exchangerate( \%myconfig, $form->{currency}, $form->{"datepaid_$i"}, 'sell');
536       $form->{"exchangerate_$i"} = $form->{"forex_$i"} if $form->{"forex_$i"};
537     }
538   }
539
540   $form->{creditremaining} -=
541     ($form->{invtotal} - $totalpaid + $form->{oldtotalpaid} -
542      $form->{oldinvtotal});
543   $form->{oldinvtotal}  = $form->{invtotal};
544   $form->{oldtotalpaid} = $totalpaid;
545
546   &display_form;
547
548   $main::lxdebug->leave_sub();
549 }
550
551
552 sub post_payment {
553   $main::lxdebug->enter_sub();
554
555   my $form     = $main::form;
556   my %myconfig = %main::myconfig;
557   my $locale   = $main::locale;
558
559   $main::auth->assert('general_ledger');
560
561   $form->{defaultcurrency} = $form->get_default_currency(\%myconfig);
562
563   my $invdate = $form->datetonum($form->{transdate}, \%myconfig);
564
565   for my $i (1 .. $form->{paidaccounts}) {
566     if ($form->parse_amount(\%myconfig, $form->{"paid_$i"})) {
567       my $datepaid = $form->datetonum($form->{"datepaid_$i"}, \%myconfig);
568
569       $form->isblank("datepaid_$i", $locale->text('Payment date missing!'));
570
571       $form->error($locale->text('Cannot post payment for a closed period!'))
572         if ($form->date_closed($form->{"datepaid_$i"}, \%myconfig));
573
574       if ($form->{defaultcurrency} && ($form->{currency} ne $form->{defaultcurrency})) {
575         $form->{"exchangerate_$i"} = $form->{exchangerate}
576           if ($invdate == $datepaid);
577         $form->isblank("exchangerate_$i",
578                        $locale->text('Exchangerate for payment missing!'));
579       }
580     }
581   }
582
583   ($form->{AP})      = split /--/, $form->{AP};
584   ($form->{AP_paid}) = split /--/, $form->{AP_paid};
585   if (AP->post_payment(\%myconfig, \%$form)) {
586     $form->{snumbers}  = qq|invnumber_| . $form->{invnumber};
587     $form->{what_done} = 'invoice';
588     $form->{addition}  = "PAYMENT POSTED";
589     $form->save_history;
590     $form->redirect($locale->text('Payment posted!'))
591   } else {
592     $form->error($locale->text('Cannot post payment!'));
593   };
594
595
596   $main::lxdebug->leave_sub();
597 }
598
599
600 sub post {
601   $main::lxdebug->enter_sub();
602
603   my $form     = $main::form;
604   my %myconfig = %main::myconfig;
605   my $locale   = $main::locale;
606
607   $main::auth->assert('general_ledger');
608
609   my ($inline) = @_;
610
611   # check if there is a vendor, invoice, due date and invnumber
612   $form->isblank("transdate", $locale->text("Invoice Date missing!"));
613   $form->isblank("duedate",   $locale->text("Due Date missing!"));
614   $form->isblank("vendor",    $locale->text('Vendor missing!'));
615   $form->isblank("invnumber", $locale->text('Invoice Number missing!'));
616
617   if ($myconfig{mandatory_departments} && !$form->{department}) {
618     $form->{saved_message} = $::locale->text('You have to specify a department.');
619     update();
620     exit;
621   }
622
623   my $closedto  = $form->datetonum($form->{closedto},  \%myconfig);
624   my $transdate = $form->datetonum($form->{transdate}, \%myconfig);
625
626   $form->error($locale->text('Cannot post transaction above the maximum future booking date!'))
627     if ($form->date_max_future($form->{"transdate"}, \%myconfig));
628   $form->error($locale->text('Cannot post transaction for a closed period!')) if ($form->date_closed($form->{"transdate"}, \%myconfig));
629
630   my $zero_amount_posting = 1;
631   for my $i (1 .. $form->{rowcount}) {
632     if ($form->parse_amount(\%myconfig, $form->{"amount_$i"})) {
633       $zero_amount_posting = 0;
634       last;
635     }
636   }
637
638   $form->error($locale->text('Zero amount posting!')) if $zero_amount_posting;
639
640   $form->isblank("exchangerate", $locale->text('Exchangerate missing!'))
641     if ($form->{defaultcurrency} && ($form->{currency} ne $form->{defaultcurrency}));
642   delete($form->{AP});
643
644   for my $i (1 .. $form->{paidaccounts}) {
645     if ($form->parse_amount(\%myconfig, $form->{"paid_$i"})) {
646       my $datepaid = $form->datetonum($form->{"datepaid_$i"}, \%myconfig);
647
648       $form->isblank("datepaid_$i", $locale->text('Payment date missing!'));
649
650       $form->error($locale->text('Cannot post payment for a closed period!'))
651         if ($form->date_closed($form->{"datepaid_$i"}, \%myconfig));
652
653       if ($form->{defaultcurrency} && ($form->{currency} ne $form->{defaultcurrency})) {
654         $form->{"exchangerate_$i"} = $form->{exchangerate}
655           if ($transdate == $datepaid);
656         $form->isblank("exchangerate_$i",
657                        $locale->text('Exchangerate for payment missing!'));
658       }
659
660     }
661   }
662
663   # if old vendor ne vendor redo form
664   my ($vendor) = split /--/, $form->{vendor};
665   if ($form->{oldvendor} ne "$vendor--$form->{vendor_id}") {
666     &update;
667     ::end_of_request();
668   }
669   my ($debitaccno,    $debittaxkey)    = split /--/, $form->{AP_amountselected};
670   my ($taxkey,        $NULL)           = split /--/, $form->{taxchartselected};
671   my ($payablesaccno, $payablestaxkey) = split /--/, $form->{APselected};
672 #  $form->{AP_amount_1}  = $debitaccno;
673   $form->{AP_payables}  = $payablesaccno;
674   $form->{taxkey}       = $taxkey;
675   $form->{storno}       = 0;
676
677   $form->{id} = 0 if $form->{postasnew};
678
679   if (AP->post_transaction(\%myconfig, \%$form)) {
680     # saving the history
681     if(!exists $form->{addition} && $form->{id} ne "") {
682       $form->{snumbers}  = qq|invnumber_| . $form->{invnumber};
683       $form->{addition}  = "POSTED";
684       $form->{what_done} = "invoice";
685       $form->save_history;
686     }
687     # /saving the history
688     remove_draft() if $form->{remove_draft};
689     # Dieser Text wird niemals ausgegeben: Probleme beim redirect?
690     $form->redirect($locale->text('Transaction posted!')) unless $inline;
691   } else {
692     $form->error($locale->text('Cannot post transaction!'));
693   }
694
695   $main::lxdebug->leave_sub();
696 }
697
698 sub post_as_new {
699   $main::lxdebug->enter_sub();
700
701   my $form     = $main::form;
702   my %myconfig = %main::myconfig;
703
704   $main::auth->assert('general_ledger');
705
706   $form->{postasnew} = 1;
707   # saving the history
708   if(!exists $form->{addition} && $form->{id} ne "") {
709     # does this work? post_as_new for ap doesn't immediately save the
710     # invoice, because the invnumber has to be entered by hand.
711     # And the value of $form->{postasnew} isn't checked when calling post
712     $form->{snumbers}  = qq|invnumber_| . $form->{invnumber};
713     $form->{addition}  = "POSTED AS NEW";
714     $form->{what_done} = "invoice";
715     $form->save_history;
716   }
717   # /saving the history
718   &post;
719
720   $main::lxdebug->leave_sub();
721 }
722
723 sub use_as_new {
724   $main::lxdebug->enter_sub();
725
726   my $form     = $main::form;
727   my %myconfig = %main::myconfig;
728
729   $main::auth->assert('general_ledger');
730
731   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);
732   $form->{paidaccounts} = 1;
733   $form->{rowcount}--;
734   $form->{invdate} = $form->current_date(\%myconfig);
735   &update;
736
737   $main::lxdebug->leave_sub();
738 }
739
740 sub delete {
741   $main::lxdebug->enter_sub();
742
743   my $form     = $main::form;
744   my $locale   = $main::locale;
745
746   $main::auth->assert('general_ledger');
747
748   $form->{title} = $locale->text('Confirm!');
749
750   $form->header;
751
752   delete $form->{header};
753
754   print qq|
755 <form method=post action=$form->{script}>
756 |;
757
758   foreach my $key (keys %$form) {
759     next if (($key eq 'login') || ($key eq 'password') || ('' ne ref $form->{$key}));
760     $form->{$key} =~ s/\"/&quot;/g;
761     print qq|<input type=hidden name=$key value="$form->{$key}">\n|;
762   }
763
764   print qq|
765 <h2 class=confirm>$form->{title}</h2>
766
767 <h4>|
768     . $locale->text('Are you sure you want to delete Transaction')
769     . qq| $form->{invnumber}</h4>
770
771 <input name=action class=submit type=submit value="|
772     . $locale->text('Yes') . qq|">
773 </form>
774 |;
775
776   $main::lxdebug->leave_sub();
777 }
778
779 sub yes {
780   $main::lxdebug->enter_sub();
781
782   my $form     = $main::form;
783   my %myconfig = %main::myconfig;
784   my $locale   = $main::locale;
785
786   $main::auth->assert('general_ledger');
787
788   if (AP->delete_transaction(\%myconfig, \%$form)) {
789     # saving the history
790     if(!exists $form->{addition}) {
791       $form->{snumbers}  = qq|invnumber_| . $form->{invnumber};
792       $form->{addition}  = "DELETED";
793       $form->{what_done} = "invoice";
794       $form->save_history;
795     }
796     # /saving the history
797     $form->redirect($locale->text('Transaction deleted!'));
798   }
799   $form->error($locale->text('Cannot delete transaction!'));
800
801   $main::lxdebug->leave_sub();
802 }
803
804 sub search {
805   $main::lxdebug->enter_sub();
806
807   $main::auth->assert('vendor_invoice_edit');
808
809   my $form     = $main::form;
810   my %myconfig = %main::myconfig;
811   my $locale   = $main::locale;
812
813   # setup customer selection
814   $form->all_vc(\%myconfig, "vendor", "AP");
815
816   $form->{title}    = $locale->text('AP Transactions');
817
818   $form->get_lists("projects"     => { "key" => "ALL_PROJECTS", "all" => 1 },
819                    "departments"  => "ALL_DEPARTMENTS",
820                    "vendors"      => "ALL_VC");
821
822   # constants and subs for template
823   $form->{vc_keys}   = sub { "$_[0]->{name}--$_[0]->{id}" };
824
825   $form->header;
826   print $form->parse_html_template('ap/search', { %myconfig });
827
828   $main::lxdebug->leave_sub();
829 }
830
831 sub create_subtotal_row {
832   $main::lxdebug->enter_sub();
833
834   my ($totals, $columns, $column_alignment, $subtotal_columns, $class) = @_;
835
836   my $form     = $main::form;
837   my %myconfig = %main::myconfig;
838
839   my $row = { map { $_ => { 'data' => '', 'class' => $class, 'align' => $column_alignment->{$_}, } } @{ $columns } };
840
841   map { $row->{$_}->{data} = $form->format_amount(\%myconfig, $totals->{$_}, 2) } @{ $subtotal_columns };
842
843   $row->{tax}->{data} = $form->format_amount(\%myconfig, $totals->{amount} - $totals->{netamount}, 2);
844
845   map { $totals->{$_} = 0 } @{ $subtotal_columns };
846
847   $main::lxdebug->leave_sub();
848
849   return $row;
850 }
851
852 sub ap_transactions {
853   $main::lxdebug->enter_sub();
854
855   my $form     = $main::form;
856   my %myconfig = %main::myconfig;
857   my $locale   = $main::locale;
858
859   $main::auth->assert('vendor_invoice_edit');
860
861   ($form->{vendor}, $form->{vendor_id}) = split(/--/, $form->{vendor});
862
863   report_generator_set_default_sort('transdate', 1);
864
865   AP->ap_transactions(\%myconfig, \%$form);
866
867   $form->{title} = $locale->text('AP Transactions');
868
869   my $report = SL::ReportGenerator->new(\%myconfig, $form);
870
871   my @columns =
872     qw(transdate id type invnumber ordnumber name netamount tax amount paid datepaid
873        due duedate transaction_description notes employee globalprojectnumber
874        vendornumber country ustid taxzone payment_terms charts);
875
876   my @hidden_variables = map { "l_${_}" } @columns;
877   push @hidden_variables, "l_subtotal", qw(open closed vendor invnumber ordnumber transaction_description notes project_id transdatefrom transdateto department);
878
879   my $href = build_std_url('action=ap_transactions', grep { $form->{$_} } @hidden_variables);
880
881   my %column_defs = (
882     'transdate'               => { 'text' => $locale->text('Date'), },
883     'id'                      => { 'text' => $locale->text('ID'), },
884     'type'                    => { 'text' => $locale->text('Type'), },
885     'invnumber'               => { 'text' => $locale->text('Invoice'), },
886     'ordnumber'               => { 'text' => $locale->text('Order'), },
887     'name'                    => { 'text' => $locale->text('Vendor'), },
888     'netamount'               => { 'text' => $locale->text('Amount'), },
889     'tax'                     => { 'text' => $locale->text('Tax'), },
890     'amount'                  => { 'text' => $locale->text('Total'), },
891     'paid'                    => { 'text' => $locale->text('Paid'), },
892     'datepaid'                => { 'text' => $locale->text('Date Paid'), },
893     'due'                     => { 'text' => $locale->text('Amount Due'), },
894     'duedate'                 => { 'text' => $locale->text('Due Date'), },
895     'transaction_description' => { 'text' => $locale->text('Transaction description'), },
896     'notes'                   => { 'text' => $locale->text('Notes'), },
897     'employee'                => { 'text' => $locale->text('Employee'), },
898     'globalprojectnumber'     => { 'text' => $locale->text('Document Project Number'), },
899     'vendornumber'            => { 'text' => $locale->text('Vendor Number'), },
900     'country'                 => { 'text' => $locale->text('Country'), },
901     'ustid'                   => { 'text' => $locale->text('USt-IdNr.'), },
902     'taxzone'                 => { 'text' => $locale->text('Steuersatz'), },
903     'payment_terms'           => { 'text' => $locale->text('Payment Terms'), },
904     'charts'                  => { 'text' => $locale->text('Buchungskonto'), },
905   );
906
907   foreach my $name (qw(id transdate duedate invnumber ordnumber name datepaid employee shippingpoint shipvia transaction_description)) {
908     my $sortdir                 = $form->{sort} eq $name ? 1 - $form->{sortdir} : $form->{sortdir};
909     $column_defs{$name}->{link} = $href . "&sort=$name&sortdir=$sortdir";
910   }
911
912   my %column_alignment = map { $_ => 'right' } qw(netamount tax amount paid due);
913
914   $form->{"l_type"} = "Y";
915   map { $column_defs{$_}->{visible} = $form->{"l_${_}"} ? 1 : 0 } @columns;
916
917   $report->set_columns(%column_defs);
918   $report->set_column_order(@columns);
919
920   $report->set_export_options('ap_transactions', @hidden_variables, qw(sort sortdir));
921
922   $report->set_sort_indicator($form->{sort}, $form->{sortdir});
923
924   my @options;
925   push @options, $locale->text('Vendor')                  . " : $form->{vendor}"                         if ($form->{vendor});
926   push @options, $locale->text('Contact Person')          . " : $form->{cp_name}"                        if ($form->{cp_name});
927   push @options, $locale->text('Department')              . " : " . (split /--/, $form->{department})[0] if ($form->{department});
928   push @options, $locale->text('Invoice Number')          . " : $form->{invnumber}"                      if ($form->{invnumber});
929   push @options, $locale->text('Order Number')            . " : $form->{ordnumber}"                      if ($form->{ordnumber});
930   push @options, $locale->text('Notes')                   . " : $form->{notes}"                          if ($form->{notes});
931   push @options, $locale->text('Transaction description') . " : $form->{transaction_description}"        if ($form->{transaction_description});
932   push @options, $locale->text('From') . " " . $locale->date(\%myconfig, $form->{transdatefrom}, 1)      if ($form->{transdatefrom});
933   push @options, $locale->text('Bis')  . " " . $locale->date(\%myconfig, $form->{transdateto},   1)      if ($form->{transdateto});
934   push @options, $locale->text('Open')                                                                   if ($form->{open});
935   push @options, $locale->text('Closed')                                                                 if ($form->{closed});
936
937   $report->set_options('top_info_text'        => join("\n", @options),
938                        'raw_bottom_info_text' => $form->parse_html_template('ap/ap_transactions_bottom'),
939                        'output_format'        => 'HTML',
940                        'title'                => $form->{title},
941                        'attachment_basename'  => $locale->text('vendor_invoice_list') . strftime('_%Y%m%d', localtime time),
942     );
943   $report->set_options_from_form();
944   $locale->set_numberformat_wo_thousands_separator(\%myconfig) if lc($report->{options}->{output_format}) eq 'csv';
945
946   # add sort and escape callback, this one we use for the add sub
947   $form->{callback} = $href .= "&sort=$form->{sort}";
948
949   # escape callback for href
950   my $callback = $form->escape($href);
951
952   my @subtotal_columns = qw(netamount amount paid due);
953
954   my %totals    = map { $_ => 0 } @subtotal_columns;
955   my %subtotals = map { $_ => 0 } @subtotal_columns;
956
957   my $idx = 0;
958
959   foreach my $ap (@{ $form->{AP} }) {
960     $ap->{tax} = $ap->{amount} - $ap->{netamount};
961     $ap->{due} = $ap->{amount} - $ap->{paid};
962
963     map { $subtotals{$_} += $ap->{$_};
964           $totals{$_}    += $ap->{$_} } @subtotal_columns;
965
966     map { $ap->{$_} = $form->format_amount(\%myconfig, $ap->{$_}, 2) } qw(netamount tax amount paid due);
967
968     my $is_storno  = $ap->{storno} &&  $ap->{storno_id};
969     my $has_storno = $ap->{storno} && !$ap->{storno_id};
970
971     if ($ap->{invoice}) {
972       $ap->{type} =
973           $has_storno       ? $locale->text("Invoice with Storno (abbreviation)")
974         : $is_storno        ? $locale->text("Storno (one letter abbreviation)")
975         :                     $locale->text("Invoice (one letter abbreviation)");
976     } else {
977       $ap->{type} =
978           $has_storno       ? $locale->text("AP Transaction with Storno (abbreviation)")
979         : $is_storno        ? $locale->text("AP Transaction Storno (one letter abbreviation)")
980         :                     $locale->text("AP Transaction (abbreviation)");
981     }
982
983     my $row = { };
984
985     foreach my $column (@columns) {
986       $row->{$column} = {
987         'data'  => $ap->{$column},
988         'align' => $column_alignment{$column},
989       };
990     }
991
992     $row->{invnumber}->{link} = build_std_url("script=" . ($ap->{invoice} ? 'ir.pl' : 'ap.pl'), 'action=edit')
993       . "&id=" . E($ap->{id}) . "&callback=${callback}";
994
995     my $row_set = [ $row ];
996
997     if (($form->{l_subtotal} eq 'Y')
998         && (($idx == (scalar @{ $form->{AP} } - 1))
999             || ($ap->{ $form->{sort} } ne $form->{AP}->[$idx + 1]->{ $form->{sort} }))) {
1000       push @{ $row_set }, create_subtotal_row(\%subtotals, \@columns, \%column_alignment, \@subtotal_columns, 'listsubtotal');
1001     }
1002
1003     $report->add_data($row_set);
1004
1005     $idx++;
1006   }
1007
1008   $report->add_separator();
1009   $report->add_data(create_subtotal_row(\%totals, \@columns, \%column_alignment, \@subtotal_columns, 'listtotal'));
1010
1011   $report->generate_with_headers();
1012
1013   $main::lxdebug->leave_sub();
1014 }
1015
1016 sub storno {
1017   $main::lxdebug->enter_sub();
1018
1019   my $form     = $main::form;
1020   my %myconfig = %main::myconfig;
1021   my $locale   = $main::locale;
1022
1023   $main::auth->assert('general_ledger');
1024
1025   if (IS->has_storno(\%myconfig, $form, 'ap')) {
1026     $form->{title} = $locale->text("Cancel Accounts Payables Transaction");
1027     $form->error($locale->text("Transaction has already been cancelled!"));
1028   }
1029
1030   $form->error($locale->text('Cannot post storno for a closed period!'))
1031     if ( $form->date_closed($form->{transdate}, \%myconfig));
1032
1033   AP->storno($form, \%myconfig, $form->{id});
1034
1035   # saving the history
1036   if(!exists $form->{addition} && $form->{id} ne "") {
1037     $form->{snumbers}  = qq|invnumber_| . $form->{invnumber};
1038     $form->{addition}  = "STORNO";
1039     $form->{what_done} = "invoice";
1040     $form->save_history;
1041   }
1042   # /saving the history
1043
1044   $form->redirect(sprintf $locale->text("Transaction %d cancelled."), $form->{storno_id});
1045
1046   $main::lxdebug->leave_sub();
1047 }