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