BUG-Fix: Kreditorenbuchungen: Steuer inklusive wird nicht übernommen
[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     $saved{currency} = $form->{currency} if $form->{currency};
150     $saved{taxincluded} = $form->{taxincluded} if $form->{taxincluded};
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 AP_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->{invoice_obj} = SL::DB::PurchaseInvoice->new(id => $::form->{id})->load if $::form->{id};
221
222   $form->{title_} = $form->{title};
223   $form->{title} = $form->{title} eq 'Add' ? $locale->text('Add Accounts Payables Transaction') : $locale->text('Edit Accounts Payables Transaction');
224
225   # type=submit $locale->text('Add Accounts Payables Transaction')
226   # type=submit $locale->text('Edit Accounts Payables Transaction')
227
228   # set option selected
229   foreach my $item (qw(vendor currency department)) {
230     my $to_replace         =  H($form->{$item});
231     $form->{"select$item"} =~ s/ selected//;
232     $form->{"select$item"} =~ s/>\Q${to_replace}\E/ selected>${to_replace}/;
233   }
234   my $readonly = $form->{id} ? "readonly" : "";
235
236   $form->{radier} = ($::instance_conf->get_ap_changeable == 2)
237                       ? ($form->current_date(\%myconfig) eq $form->{gldate})
238                       : ($::instance_conf->get_ap_changeable == 1);
239   $readonly       = $form->{radier} ? "" : $readonly;
240
241   $form->{readonly} = $readonly;
242
243   $form->{forex} = $form->check_exchangerate( \%myconfig, $form->{currency}, $form->{transdate}, 'sell');
244   if ( $form->{forex} ) {
245     $form->{exchangerate} = $form->{forex};
246   }
247
248   # format amounts
249   $form->{exchangerate}    = $form->{exchangerate} ? $form->format_amount(\%myconfig, $form->{exchangerate}) : '';
250   $form->{creditlimit}     = $form->format_amount(\%myconfig, $form->{creditlimit}, 0, "0");
251   $form->{creditremaining} = $form->format_amount(\%myconfig, $form->{creditremaining}, 0, "0");
252
253   my $rows;
254   if (($rows = $form->numtextrows($form->{notes}, 50)) < 2) {
255     $rows = 2;
256   }
257   $form->{textarea_rows} = $rows;
258
259   $form->{creditremaining_plus} = ($form->{creditremaining} =~ /-/) ? "0" : "1";
260
261   my @old_project_ids = ();
262   map(
263     {
264       if ($form->{"project_id_$_"}) {
265         push(@old_project_ids, $form->{"project_id_$_"});
266       }
267     }
268     (1..$form->{"rowcount"})
269   );
270
271   $form->get_lists("projects"  => { "key"       => "ALL_PROJECTS",
272                                     "all"       => 0,
273                                     "old_id"    => \@old_project_ids },
274                    "charts"    => { "key"       => "ALL_CHARTS",
275                                     "transdate" => $form->{transdate} },
276                    "taxcharts" => { "key"       => "ALL_TAXCHARTS",
277                                     "module"    => "AP" },);
278
279   map(
280     { $_->{link_split} = [ split(/:/, $_->{link}) ]; }
281     @{ $form->{ALL_CHARTS} }
282   );
283
284   my %project_labels = ();
285   foreach my $item (@{ $form->{"ALL_PROJECTS"} }) {
286     $project_labels{$item->{id}} = $item->{projectnumber};
287   }
288
289   my %charts;
290   my $taxchart_init;
291
292   foreach my $item (@{ $form->{ALL_CHARTS} }) {
293     if ( grep({ $_ eq 'AP_amount' } @{ $item->{link_split} }) ) {
294       if ( $taxchart_init eq '' ) {
295         $taxchart_init = $item->{tax_id};
296       }
297
298       push(@{ $form->{ALL_CHARTS_AP_amount} }, $item);
299     }
300     elsif ( grep({ $_ eq 'AP' } @{ $item->{link_split} }) ) {
301       push(@{ $form->{ALL_CHARTS_AP} }, $item);
302     }
303     elsif ( grep({ $_ eq 'AP_paid' } @{ $item->{link_split} }) ) {
304       push(@{ $form->{ALL_CHARTS_AP_paid} }, $item);
305     }
306
307     $charts{$item->{accno}} = $item;
308   }
309
310   my %taxcharts = ();
311   foreach my $item (@{ $form->{ALL_TAXCHARTS} }) {
312     my $key = $item->{id} .'--'. $item->{rate};
313
314     if ( $taxchart_init eq $item->{id} ) {
315       $taxchart_init = $key;
316     }
317
318     $taxcharts{$item->{id}} = $item;
319   }
320
321   my $follow_up_vc         =  $form->{vendor};
322   $follow_up_vc            =~ s/--.*?//;
323   my $follow_up_trans_info =  "$form->{invnumber} ($follow_up_vc)";
324
325   $form->{javascript} .= qq|<script type="text/javascript" src="js/common.js"></script>|;
326   $form->{javascript} .= qq|<script type="text/javascript" src="js/show_vc_details.js"></script>|;
327   $form->{javascript} .= qq|<script type="text/javascript" src="js/follow_up.js"></script>|;
328   $form->{javascript} .= qq|<script type="text/javascript" src="js/kivi.Draft.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     #deaktivieren von gebuchten Zahlungen ausserhalb der Bücherkontrolle, vorher prüfen ob heute eingegeben
432     if ($form->date_closed($form->{"gldate_$i"})) {
433        $changeable = 0;
434     }
435
436     $form->{'paidaccount_changeable_'. $i} = $changeable;
437
438     $form->{'labelpaid_project_id_'. $i} = $project_labels{$form->{'paid_project_id_'. $i}};
439   }
440
441   $form->{paid_missing} = $form->{invtotal_unformatted} - $form->{totalpaid};
442
443   print $form->parse_html_template('ap/form_header', {
444     today => DateTime->today,
445   });
446
447   $main::lxdebug->leave_sub();
448 }
449
450 sub form_footer {
451   $::lxdebug->enter_sub;
452   $::auth->assert('general_ledger');
453
454   my $num_due;
455   my $num_follow_ups;
456   if ($::form->{id}) {
457     my $follow_ups = FU->follow_ups('trans_id' => $::form->{id});
458
459     if (@{ $follow_ups }) {
460       $num_due        = sum map { $_->{due} * 1 } @{ $follow_ups };
461       $num_follow_ups = scalar @{ $follow_ups }
462     }
463   }
464
465   my $transdate = $::form->datetonum($::form->{transdate}, \%::myconfig);
466   my $closedto  = $::form->datetonum($::form->{closedto},  \%::myconfig);
467
468   my $storno = $::form->{id}
469             && !IS->has_storno(\%::myconfig, $::form, 'ap')
470             && !IS->is_storno( \%::myconfig, $::form, 'ap', $::form->{id})
471             && ($::form->{totalpaid} == 0 || $::form->{totalpaid} eq '');
472
473   $::form->header;
474   print $::form->parse_html_template('ap/form_footer', {
475     num_due           => $num_due,
476     num_follow_ups    => $num_follow_ups,
477     show_post_draft   => ($transdate > $closedto) && !$::form->{id},
478     show_storno       => $storno,
479   });
480
481   $::lxdebug->leave_sub;
482 }
483
484 sub mark_as_paid {
485   $main::lxdebug->enter_sub();
486
487   my $form     = $main::form;
488   my %myconfig = %main::myconfig;
489
490   $main::auth->assert('general_ledger');
491
492   &mark_as_paid_common(\%myconfig,"ap");
493
494   $main::lxdebug->leave_sub();
495 }
496
497 sub update {
498   $main::lxdebug->enter_sub();
499
500   my $form     = $main::form;
501   my %myconfig = %main::myconfig;
502
503   $main::auth->assert('general_ledger');
504
505   my $display = shift;
506
507   $form->{invtotal} = 0;
508
509   delete @{ $form }{ grep { m/^tax_\d+$/ } keys %{ $form } };
510
511   map { $form->{$_} = $form->parse_amount(\%myconfig, $form->{$_}) }
512     qw(exchangerate creditlimit creditremaining);
513
514   my @flds  = qw(amount AP_amount projectnumber oldprojectnumber project_id taxchart);
515   my $count = 0;
516   my (@a, $j, $totaltax);
517   for my $i (1 .. $form->{rowcount}) {
518     $form->{"amount_$i"} = $form->parse_amount(\%myconfig, $form->{"amount_$i"});
519     if ($form->{"amount_$i"}) {
520       push @a, {};
521       $j = $#a;
522       my ($taxkey, $rate) = split(/--/, $form->{"taxchart_$i"});
523
524       # calculate tax exactly the same way as AP in post_transaction via form->calculate_tax
525       my $tmpnetamount;
526       ($tmpnetamount,$form->{"tax_$i"}) = $form->calculate_tax($form->{"amount_$i"},$rate,$form->{taxincluded},2);
527
528       $totaltax += $form->{"tax_$i"};
529       map { $a[$j]->{$_} = $form->{"${_}_$i"} } @flds;
530       $count++;
531     }
532   }
533   $form->redo_rows(\@flds, \@a, $count, $form->{rowcount});
534
535   map { $form->{invtotal} += $form->{"amount_$_"} } (1 .. $form->{rowcount});
536
537   $form->{forex}        = $form->check_exchangerate( \%myconfig, $form->{currency}, $form->{transdate}, 'sell');
538   $form->{exchangerate} = $form->{forex} if $form->{forex};
539
540   $form->{invdate} = $form->{transdate};
541   my %saved_variables = map +( $_ => $form->{$_} ), qw(AP AP_amount_1 taxchart_1 notes);
542
543   my $vendor_changed = &check_name("vendor");
544
545   $form->{AP} = $saved_variables{AP};
546   if ($saved_variables{AP_amount_1} =~ m/.--./) {
547     map { $form->{$_} = $saved_variables{$_} } qw(AP_amount_1 taxchart_1);
548   } else {
549     delete $form->{taxchart_1};
550   }
551
552   $form->{rowcount} = $count + 1;
553
554   $form->{invtotal} =
555     ($form->{taxincluded}) ? $form->{invtotal} : $form->{invtotal} + $totaltax;
556
557   my $totalpaid;
558   for my $i (1 .. $form->{paidaccounts}) {
559     if ($form->parse_amount(\%myconfig, $form->{"paid_$i"})) {
560       map {
561         $form->{"${_}_$i"} =
562           $form->parse_amount(\%myconfig, $form->{"${_}_$i"})
563       } qw(paid exchangerate);
564
565       $totalpaid += $form->{"paid_$i"};
566
567       $form->{"forex_$i"}        = $form->check_exchangerate( \%myconfig, $form->{currency}, $form->{"datepaid_$i"}, 'sell');
568       $form->{"exchangerate_$i"} = $form->{"forex_$i"} if $form->{"forex_$i"};
569     }
570   }
571
572   $form->{creditremaining} -=
573     ($form->{invtotal} - $totalpaid + $form->{oldtotalpaid} -
574      $form->{oldinvtotal});
575   $form->{oldinvtotal}  = $form->{invtotal};
576   $form->{oldtotalpaid} = $totalpaid;
577
578   &display_form;
579
580   $main::lxdebug->leave_sub();
581 }
582
583
584 sub post_payment {
585   $main::lxdebug->enter_sub();
586
587   my $form     = $main::form;
588   my %myconfig = %main::myconfig;
589   my $locale   = $main::locale;
590
591   $main::auth->assert('general_ledger');
592   $form->mtime_ischanged('ap');
593
594   $form->{defaultcurrency} = $form->get_default_currency(\%myconfig);
595
596   my $invdate = $form->datetonum($form->{transdate}, \%myconfig);
597
598   for my $i (1 .. $form->{paidaccounts}) {
599     if ($form->parse_amount(\%myconfig, $form->{"paid_$i"})) {
600       my $datepaid = $form->datetonum($form->{"datepaid_$i"}, \%myconfig);
601
602       $form->isblank("datepaid_$i", $locale->text('Payment date missing!'));
603
604       $form->error($locale->text('Cannot post transaction above the maximum future booking date!'))
605         if ($form->date_max_future($form->{"datepaid_$i"}, \%myconfig));
606
607       #Zusätzlich noch das Buchungsdatum in die Bücherkontrolle einbeziehen
608       # (Dient zur Prüfung ob ZE oder ZA geprüft werden soll)
609       $form->error($locale->text('Cannot post payment for a closed period!'))
610         if ($form->date_closed($form->{"datepaid_$i"})  && !$form->date_closed($form->{"gldate_$i"}, \%myconfig));
611
612       if ($form->{defaultcurrency} && ($form->{currency} ne $form->{defaultcurrency})) {
613         $form->{"exchangerate_$i"} = $form->{exchangerate}
614           if ($invdate == $datepaid);
615         $form->isblank("exchangerate_$i",
616                        $locale->text('Exchangerate for payment missing!'));
617       }
618     }
619   }
620
621   ($form->{AP})      = split /--/, $form->{AP};
622   ($form->{AP_paid}) = split /--/, $form->{AP_paid};
623   if (AP->post_payment(\%myconfig, \%$form)) {
624     $form->{snumbers}  = qq|invnumber_| . $form->{invnumber};
625     $form->{what_done} = 'invoice';
626     $form->{addition}  = "PAYMENT POSTED";
627     $form->save_history;
628     $form->redirect($locale->text('Payment posted!'))
629   } else {
630     $form->error($locale->text('Cannot post payment!'));
631   };
632
633
634   $main::lxdebug->leave_sub();
635 }
636
637
638 sub post {
639   $main::lxdebug->enter_sub();
640
641   my $form     = $main::form;
642   my %myconfig = %main::myconfig;
643   my $locale   = $main::locale;
644
645   $main::auth->assert('general_ledger');
646   $form->mtime_ischanged('ap');
647
648   my ($inline) = @_;
649
650   # check if there is a vendor, invoice, due date and invnumber
651   $form->isblank("transdate", $locale->text("Invoice Date missing!"));
652   $form->isblank("duedate",   $locale->text("Due Date missing!"));
653   $form->isblank("vendor",    $locale->text('Vendor missing!'));
654   $form->isblank("invnumber", $locale->text('Invoice Number missing!'));
655
656   if ($myconfig{mandatory_departments} && !$form->{department}) {
657     $form->{saved_message} = $::locale->text('You have to specify a department.');
658     update();
659     exit;
660   }
661
662   my $closedto  = $form->datetonum($form->{closedto},  \%myconfig);
663   my $transdate = $form->datetonum($form->{transdate}, \%myconfig);
664
665   $form->error($locale->text('Cannot post transaction above the maximum future booking date!'))
666     if ($form->date_max_future($form->{"transdate"}, \%myconfig));
667   $form->error($locale->text('Cannot post transaction for a closed period!')) if ($form->date_closed($form->{"transdate"}, \%myconfig));
668
669   my $zero_amount_posting = 1;
670   for my $i (1 .. $form->{rowcount}) {
671     if ($form->parse_amount(\%myconfig, $form->{"amount_$i"})) {
672       $zero_amount_posting = 0;
673       last;
674     }
675   }
676
677   $form->error($locale->text('Zero amount posting!')) if $zero_amount_posting;
678
679   $form->isblank("exchangerate", $locale->text('Exchangerate missing!'))
680     if ($form->{defaultcurrency} && ($form->{currency} ne $form->{defaultcurrency}));
681   delete($form->{AP});
682
683   for my $i (1 .. $form->{paidaccounts}) {
684     if ($form->parse_amount(\%myconfig, $form->{"paid_$i"})) {
685       my $datepaid = $form->datetonum($form->{"datepaid_$i"}, \%myconfig);
686
687       $form->isblank("datepaid_$i", $locale->text('Payment date missing!'));
688
689       $form->error($locale->text('Cannot post transaction above the maximum future booking date!'))
690       if ($form->date_max_future($form->{"datepaid_$i"}, \%myconfig));
691
692       #Zusätzlich noch das Buchungsdatum in die Bücherkontrolle einbeziehen
693       # (Dient zur Prüfung ob ZE oder ZA geprüft werden soll)
694       $form->error($locale->text('Cannot post payment for a closed period!'))
695         if ($form->date_closed($form->{"datepaid_$i"})  && !$form->date_closed($form->{"gldate_$i"}, \%myconfig));
696
697       if ($form->{defaultcurrency} && ($form->{currency} ne $form->{defaultcurrency})) {
698         $form->{"exchangerate_$i"} = $form->{exchangerate}
699           if ($transdate == $datepaid);
700         $form->isblank("exchangerate_$i",
701                        $locale->text('Exchangerate for payment missing!'));
702       }
703
704     }
705   }
706
707   # if old vendor ne vendor redo form
708   my ($vendor) = split /--/, $form->{vendor};
709   if ($form->{oldvendor} ne "$vendor--$form->{vendor_id}") {
710     &update;
711     $::dispatcher->end_request;
712   }
713   my ($debitaccno,    $debittaxkey)    = split /--/, $form->{AP_amountselected};
714   my ($taxkey,        $NULL)           = split /--/, $form->{taxchartselected};
715   my ($payablesaccno, $payablestaxkey) = split /--/, $form->{APselected};
716 #  $form->{AP_amount_1}  = $debitaccno;
717   $form->{AP_payables}  = $payablesaccno;
718   $form->{taxkey}       = $taxkey;
719   $form->{storno}       = 0;
720
721   $form->{id} = 0 if $form->{postasnew};
722
723   if (AP->post_transaction(\%myconfig, \%$form)) {
724     # saving the history
725     if(!exists $form->{addition} && $form->{id} ne "") {
726       $form->{snumbers}  = qq|invnumber_| . $form->{invnumber};
727       $form->{addition}  = "POSTED";
728       $form->{what_done} = "invoice";
729       $form->save_history;
730     }
731     # /saving the history
732     # Dieser Text wird niemals ausgegeben: Probleme beim redirect?
733     $form->redirect($locale->text('Transaction posted!')) unless $inline;
734   } else {
735     $form->error($locale->text('Cannot post transaction!'));
736   }
737
738   $main::lxdebug->leave_sub();
739 }
740
741 sub post_as_new {
742   $main::lxdebug->enter_sub();
743
744   my $form     = $main::form;
745   my %myconfig = %main::myconfig;
746
747   $main::auth->assert('general_ledger');
748
749   $form->{postasnew} = 1;
750   # saving the history
751   if(!exists $form->{addition} && $form->{id} ne "") {
752     # does this work? post_as_new for ap doesn't immediately save the
753     # invoice, because the invnumber has to be entered by hand.
754     # And the value of $form->{postasnew} isn't checked when calling post
755     $form->{snumbers}  = qq|invnumber_| . $form->{invnumber};
756     $form->{addition}  = "POSTED AS NEW";
757     $form->{what_done} = "invoice";
758     $form->save_history;
759   }
760   # /saving the history
761   &post;
762
763   $main::lxdebug->leave_sub();
764 }
765
766 sub use_as_new {
767   $main::lxdebug->enter_sub();
768
769   my $form     = $main::form;
770   my %myconfig = %main::myconfig;
771
772   $main::auth->assert('general_ledger');
773
774   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);
775   $form->{paidaccounts} = 1;
776   $form->{rowcount}--;
777   $form->{invdate} = $form->current_date(\%myconfig);
778   &update;
779
780   $main::lxdebug->leave_sub();
781 }
782
783 sub delete {
784   $main::lxdebug->enter_sub();
785
786   my $form     = $main::form;
787   my $locale   = $main::locale;
788
789   $main::auth->assert('general_ledger');
790
791   $form->{title} = $locale->text('Confirm!');
792
793   $form->header;
794
795   delete $form->{header};
796
797   print qq|
798 <form method=post action=$form->{script}>
799 |;
800
801   foreach my $key (keys %$form) {
802     next if (($key eq 'login') || ($key eq 'password') || ('' ne ref $form->{$key}));
803     $form->{$key} =~ s/\"/&quot;/g;
804     print qq|<input type=hidden name=$key value="$form->{$key}">\n|;
805   }
806
807   print qq|
808 <h2 class=confirm>$form->{title}</h2>
809
810 <h4>|
811     . $locale->text('Are you sure you want to delete Transaction')
812     . qq| $form->{invnumber}</h4>
813
814 <input name=action class=submit type=submit value="|
815     . $locale->text('Yes') . qq|">
816 </form>
817 |;
818
819   $main::lxdebug->leave_sub();
820 }
821
822 sub yes {
823   $main::lxdebug->enter_sub();
824
825   my $form     = $main::form;
826   my %myconfig = %main::myconfig;
827   my $locale   = $main::locale;
828
829   $main::auth->assert('general_ledger');
830
831   if (AP->delete_transaction(\%myconfig, \%$form)) {
832     # saving the history
833     if(!exists $form->{addition}) {
834       $form->{snumbers}  = qq|invnumber_| . $form->{invnumber};
835       $form->{addition}  = "DELETED";
836       $form->{what_done} = "invoice";
837       $form->save_history;
838     }
839     # /saving the history
840     $form->redirect($locale->text('Transaction deleted!'));
841   }
842   $form->error($locale->text('Cannot delete transaction!'));
843
844   $main::lxdebug->leave_sub();
845 }
846
847 sub search {
848   $main::lxdebug->enter_sub();
849
850   $main::auth->assert('vendor_invoice_edit');
851
852   my $form     = $main::form;
853   my %myconfig = %main::myconfig;
854   my $locale   = $main::locale;
855
856   # setup customer selection
857   $form->all_vc(\%myconfig, "vendor", "AP");
858
859   $form->{title}    = $locale->text('AP Transactions');
860
861   $form->get_lists("projects"     => { "key" => "ALL_PROJECTS", "all" => 1 },
862                    "departments"  => "ALL_DEPARTMENTS",
863                    "vendors"      => "ALL_VC");
864
865   # constants and subs for template
866   $form->{vc_keys}   = sub { "$_[0]->{name}--$_[0]->{id}" };
867
868   $form->header;
869   print $form->parse_html_template('ap/search', { %myconfig });
870
871   $main::lxdebug->leave_sub();
872 }
873
874 sub create_subtotal_row {
875   $main::lxdebug->enter_sub();
876
877   my ($totals, $columns, $column_alignment, $subtotal_columns, $class) = @_;
878
879   my $form     = $main::form;
880   my %myconfig = %main::myconfig;
881
882   my $row = { map { $_ => { 'data' => '', 'class' => $class, 'align' => $column_alignment->{$_}, } } @{ $columns } };
883
884   map { $row->{$_}->{data} = $form->format_amount(\%myconfig, $totals->{$_}, 2) } @{ $subtotal_columns };
885
886   $row->{tax}->{data} = $form->format_amount(\%myconfig, $totals->{amount} - $totals->{netamount}, 2);
887
888   map { $totals->{$_} = 0 } @{ $subtotal_columns };
889
890   $main::lxdebug->leave_sub();
891
892   return $row;
893 }
894
895 sub ap_transactions {
896   $main::lxdebug->enter_sub();
897
898   my $form     = $main::form;
899   my %myconfig = %main::myconfig;
900   my $locale   = $main::locale;
901
902   $main::auth->assert('vendor_invoice_edit');
903
904   ($form->{vendor}, $form->{vendor_id}) = split(/--/, $form->{vendor});
905
906   report_generator_set_default_sort('transdate', 1);
907
908   AP->ap_transactions(\%myconfig, \%$form);
909
910   $form->{title} = $locale->text('AP Transactions');
911
912   my $report = SL::ReportGenerator->new(\%myconfig, $form);
913
914   my @columns =
915     qw(transdate id type invnumber ordnumber name netamount tax amount paid datepaid
916        due duedate transaction_description notes employee globalprojectnumber
917        vendornumber country ustid taxzone payment_terms charts direct_debit);
918
919   my @hidden_variables = map { "l_${_}" } @columns;
920   push @hidden_variables, "l_subtotal", qw(open closed vendor invnumber ordnumber transaction_description notes project_id transdatefrom transdateto department
921                                            parts_partnumber parts_description);
922
923   my $href = build_std_url('action=ap_transactions', grep { $form->{$_} } @hidden_variables);
924
925   my %column_defs = (
926     'transdate'               => { 'text' => $locale->text('Date'), },
927     'id'                      => { 'text' => $locale->text('ID'), },
928     'type'                    => { 'text' => $locale->text('Type'), },
929     'invnumber'               => { 'text' => $locale->text('Invoice'), },
930     'ordnumber'               => { 'text' => $locale->text('Order'), },
931     'name'                    => { 'text' => $locale->text('Vendor'), },
932     'netamount'               => { 'text' => $locale->text('Amount'), },
933     'tax'                     => { 'text' => $locale->text('Tax'), },
934     'amount'                  => { 'text' => $locale->text('Total'), },
935     'paid'                    => { 'text' => $locale->text('Paid'), },
936     'datepaid'                => { 'text' => $locale->text('Date Paid'), },
937     'due'                     => { 'text' => $locale->text('Amount Due'), },
938     'duedate'                 => { 'text' => $locale->text('Due Date'), },
939     'transaction_description' => { 'text' => $locale->text('Transaction description'), },
940     'notes'                   => { 'text' => $locale->text('Notes'), },
941     'employee'                => { 'text' => $locale->text('Employee'), },
942     'globalprojectnumber'     => { 'text' => $locale->text('Document Project Number'), },
943     'vendornumber'            => { 'text' => $locale->text('Vendor Number'), },
944     'country'                 => { 'text' => $locale->text('Country'), },
945     'ustid'                   => { 'text' => $locale->text('USt-IdNr.'), },
946     'taxzone'                 => { 'text' => $locale->text('Tax rate'), },
947     'payment_terms'           => { 'text' => $locale->text('Payment Terms'), },
948     'charts'                  => { 'text' => $locale->text('Buchungskonto'), },
949     'direct_debit'            => { 'text' => $locale->text('direct debit'), },
950   );
951
952   foreach my $name (qw(id transdate duedate invnumber ordnumber name datepaid employee shippingpoint shipvia transaction_description direct_debit)) {
953     my $sortdir                 = $form->{sort} eq $name ? 1 - $form->{sortdir} : $form->{sortdir};
954     $column_defs{$name}->{link} = $href . "&sort=$name&sortdir=$sortdir";
955   }
956
957   my %column_alignment = map { $_ => 'right' } qw(netamount tax amount paid due);
958
959   $form->{"l_type"} = "Y";
960   map { $column_defs{$_}->{visible} = $form->{"l_${_}"} ? 1 : 0 } @columns;
961
962   $report->set_columns(%column_defs);
963   $report->set_column_order(@columns);
964
965   $report->set_export_options('ap_transactions', @hidden_variables, qw(sort sortdir));
966
967   $report->set_sort_indicator($form->{sort}, $form->{sortdir});
968
969   my @options;
970   push @options, $locale->text('Vendor')                  . " : $form->{vendor}"                         if ($form->{vendor});
971   push @options, $locale->text('Contact Person')          . " : $form->{cp_name}"                        if ($form->{cp_name});
972   push @options, $locale->text('Department')              . " : " . (split /--/, $form->{department})[0] if ($form->{department});
973   push @options, $locale->text('Invoice Number')          . " : $form->{invnumber}"                      if ($form->{invnumber});
974   push @options, $locale->text('Order Number')            . " : $form->{ordnumber}"                      if ($form->{ordnumber});
975   push @options, $locale->text('Notes')                   . " : $form->{notes}"                          if ($form->{notes});
976   push @options, $locale->text('Transaction description') . " : $form->{transaction_description}"        if ($form->{transaction_description});
977   push @options, $locale->text('Part Description')        . " : $form->{parts_description}"              if $form->{parts_description};
978   push @options, $locale->text('Part Number')             . " : $form->{parts_partnumber}"               if $form->{parts_partnumber};
979   push @options, $locale->text('From') . " " . $locale->date(\%myconfig, $form->{transdatefrom}, 1)      if ($form->{transdatefrom});
980   push @options, $locale->text('Bis')  . " " . $locale->date(\%myconfig, $form->{transdateto},   1)      if ($form->{transdateto});
981   push @options, $locale->text('Open')                                                                   if ($form->{open});
982   push @options, $locale->text('Closed')                                                                 if ($form->{closed});
983
984   $report->set_options('top_info_text'        => join("\n", @options),
985                        'raw_bottom_info_text' => $form->parse_html_template('ap/ap_transactions_bottom'),
986                        'output_format'        => 'HTML',
987                        'title'                => $form->{title},
988                        'attachment_basename'  => $locale->text('vendor_invoice_list') . strftime('_%Y%m%d', localtime time),
989     );
990   $report->set_options_from_form();
991   $locale->set_numberformat_wo_thousands_separator(\%myconfig) if lc($report->{options}->{output_format}) eq 'csv';
992
993   # add sort and escape callback, this one we use for the add sub
994   $form->{callback} = $href .= "&sort=$form->{sort}";
995
996   # escape callback for href
997   my $callback = $form->escape($href);
998
999   my @subtotal_columns = qw(netamount amount paid due);
1000
1001   my %totals    = map { $_ => 0 } @subtotal_columns;
1002   my %subtotals = map { $_ => 0 } @subtotal_columns;
1003
1004   my $idx = 0;
1005
1006   foreach my $ap (@{ $form->{AP} }) {
1007     $ap->{tax} = $ap->{amount} - $ap->{netamount};
1008     $ap->{due} = $ap->{amount} - $ap->{paid};
1009
1010     map { $subtotals{$_} += $ap->{$_};
1011           $totals{$_}    += $ap->{$_} } @subtotal_columns;
1012
1013     map { $ap->{$_} = $form->format_amount(\%myconfig, $ap->{$_}, 2) } qw(netamount tax amount paid due);
1014
1015     my $is_storno  = $ap->{storno} &&  $ap->{storno_id};
1016     my $has_storno = $ap->{storno} && !$ap->{storno_id};
1017
1018     if ($ap->{invoice}) {
1019       $ap->{type} =
1020           $has_storno       ? $locale->text("Invoice with Storno (abbreviation)")
1021         : $is_storno        ? $locale->text("Storno (one letter abbreviation)")
1022         :                     $locale->text("Invoice (one letter abbreviation)");
1023     } else {
1024       $ap->{type} =
1025           $has_storno       ? $locale->text("AP Transaction with Storno (abbreviation)")
1026         : $is_storno        ? $locale->text("AP Transaction Storno (one letter abbreviation)")
1027         :                     $locale->text("AP Transaction (abbreviation)");
1028     }
1029
1030     $ap->{direct_debit} = $ap->{direct_debit} ? $::locale->text('yes') : $::locale->text('no');
1031
1032     my $row = { };
1033
1034     foreach my $column (@columns) {
1035       $row->{$column} = {
1036         'data'  => $ap->{$column},
1037         'align' => $column_alignment{$column},
1038       };
1039     }
1040
1041     $row->{invnumber}->{link} = build_std_url("script=" . ($ap->{invoice} ? 'ir.pl' : 'ap.pl'), 'action=edit')
1042       . "&id=" . E($ap->{id}) . "&callback=${callback}";
1043
1044     my $row_set = [ $row ];
1045
1046     if (($form->{l_subtotal} eq 'Y')
1047         && (($idx == (scalar @{ $form->{AP} } - 1))
1048             || ($ap->{ $form->{sort} } ne $form->{AP}->[$idx + 1]->{ $form->{sort} }))) {
1049       push @{ $row_set }, create_subtotal_row(\%subtotals, \@columns, \%column_alignment, \@subtotal_columns, 'listsubtotal');
1050     }
1051
1052     $report->add_data($row_set);
1053
1054     $idx++;
1055   }
1056
1057   $report->add_separator();
1058   $report->add_data(create_subtotal_row(\%totals, \@columns, \%column_alignment, \@subtotal_columns, 'listtotal'));
1059
1060   $report->generate_with_headers();
1061
1062   $main::lxdebug->leave_sub();
1063 }
1064
1065 sub storno {
1066   $main::lxdebug->enter_sub();
1067
1068   my $form     = $main::form;
1069   my %myconfig = %main::myconfig;
1070   my $locale   = $main::locale;
1071
1072   $main::auth->assert('general_ledger');
1073
1074   if (IS->has_storno(\%myconfig, $form, 'ap')) {
1075     $form->{title} = $locale->text("Cancel Accounts Payables Transaction");
1076     $form->error($locale->text("Transaction has already been cancelled!"));
1077   }
1078
1079   $form->error($locale->text('Cannot post storno for a closed period!'))
1080     if ( $form->date_closed($form->{transdate}, \%myconfig));
1081
1082   AP->storno($form, \%myconfig, $form->{id});
1083
1084   # saving the history
1085   if(!exists $form->{addition} && $form->{id} ne "") {
1086     $form->{snumbers}  = qq|invnumber_| . $form->{invnumber};
1087     $form->{addition}  = "STORNO";
1088     $form->{what_done} = "invoice";
1089     $form->save_history;
1090   }
1091   # /saving the history
1092
1093   $form->redirect(sprintf $locale->text("Transaction %d cancelled."), $form->{storno_id});
1094
1095   $main::lxdebug->leave_sub();
1096 }