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