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