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