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