Verteilen der Rechte für Finanzbuchhaltung auf Dialogbuchung,Kreditoren-/Debitorenrec...
[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('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 update {
499   $main::lxdebug->enter_sub();
500
501   my $form     = $main::form;
502   my %myconfig = %main::myconfig;
503
504   $main::auth->assert('ap_transactions');
505
506   my $display = shift;
507
508   $form->{invtotal} = 0;
509
510   delete @{ $form }{ grep { m/^tax_\d+$/ } keys %{ $form } };
511
512   map { $form->{$_} = $form->parse_amount(\%myconfig, $form->{$_}) }
513     qw(exchangerate creditlimit creditremaining);
514
515   my @flds  = qw(amount AP_amount projectnumber oldprojectnumber project_id taxchart);
516   my $count = 0;
517   my (@a, $j, $totaltax);
518   for my $i (1 .. $form->{rowcount}) {
519     $form->{"amount_$i"} = $form->parse_amount(\%myconfig, $form->{"amount_$i"});
520     if ($form->{"amount_$i"}) {
521       push @a, {};
522       $j = $#a;
523       my ($taxkey, $rate) = split(/--/, $form->{"taxchart_$i"});
524
525       # calculate tax exactly the same way as AP in post_transaction via form->calculate_tax
526       my $tmpnetamount;
527       ($tmpnetamount,$form->{"tax_$i"}) = $form->calculate_tax($form->{"amount_$i"},$rate,$form->{taxincluded},2);
528
529       $totaltax += $form->{"tax_$i"};
530       map { $a[$j]->{$_} = $form->{"${_}_$i"} } @flds;
531       $count++;
532     }
533   }
534   $form->redo_rows(\@flds, \@a, $count, $form->{rowcount});
535
536   map { $form->{invtotal} += $form->{"amount_$_"} } (1 .. $form->{rowcount});
537
538   $form->{forex}        = $form->check_exchangerate( \%myconfig, $form->{currency}, $form->{transdate}, 'sell');
539   $form->{exchangerate} = $form->{forex} if $form->{forex};
540
541   $form->{invdate} = $form->{transdate};
542   my %saved_variables = map +( $_ => $form->{$_} ), qw(AP AP_amount_1 taxchart_1 notes);
543
544   my $vendor_changed = &check_name("vendor");
545
546   $form->{AP} = $saved_variables{AP};
547   if ($saved_variables{AP_amount_1} =~ m/.--./) {
548     map { $form->{$_} = $saved_variables{$_} } qw(AP_amount_1 taxchart_1);
549   } else {
550     delete $form->{taxchart_1};
551   }
552
553   $form->{rowcount} = $count + 1;
554
555   $form->{invtotal} =
556     ($form->{taxincluded}) ? $form->{invtotal} : $form->{invtotal} + $totaltax;
557
558   my $totalpaid;
559   for my $i (1 .. $form->{paidaccounts}) {
560     if ($form->parse_amount(\%myconfig, $form->{"paid_$i"})) {
561       map {
562         $form->{"${_}_$i"} =
563           $form->parse_amount(\%myconfig, $form->{"${_}_$i"})
564       } qw(paid exchangerate);
565
566       $totalpaid += $form->{"paid_$i"};
567
568       $form->{"forex_$i"}        = $form->check_exchangerate( \%myconfig, $form->{currency}, $form->{"datepaid_$i"}, 'sell');
569       $form->{"exchangerate_$i"} = $form->{"forex_$i"} if $form->{"forex_$i"};
570     }
571   }
572
573   $form->{creditremaining} -=
574     ($form->{invtotal} - $totalpaid + $form->{oldtotalpaid} -
575      $form->{oldinvtotal});
576   $form->{oldinvtotal}  = $form->{invtotal};
577   $form->{oldtotalpaid} = $totalpaid;
578
579   &display_form;
580
581   $main::lxdebug->leave_sub();
582 }
583
584
585 sub post_payment {
586   $main::lxdebug->enter_sub();
587
588   my $form     = $main::form;
589   my %myconfig = %main::myconfig;
590   my $locale   = $main::locale;
591
592   $main::auth->assert('ap_transactions');
593   $form->mtime_ischanged('ap');
594
595   $form->{defaultcurrency} = $form->get_default_currency(\%myconfig);
596
597   my $invdate = $form->datetonum($form->{transdate}, \%myconfig);
598
599   for my $i (1 .. $form->{paidaccounts}) {
600     if ($form->parse_amount(\%myconfig, $form->{"paid_$i"})) {
601       my $datepaid = $form->datetonum($form->{"datepaid_$i"}, \%myconfig);
602
603       $form->isblank("datepaid_$i", $locale->text('Payment date missing!'));
604
605       $form->error($locale->text('Cannot post transaction above the maximum future booking date!'))
606         if ($form->date_max_future($form->{"datepaid_$i"}, \%myconfig));
607
608       #Zusätzlich noch das Buchungsdatum in die Bücherkontrolle einbeziehen
609       # (Dient zur Prüfung ob ZE oder ZA geprüft werden soll)
610       $form->error($locale->text('Cannot post payment for a closed period!'))
611         if ($form->date_closed($form->{"datepaid_$i"})  && !$form->date_closed($form->{"gldate_$i"}, \%myconfig));
612
613       if ($form->{defaultcurrency} && ($form->{currency} ne $form->{defaultcurrency})) {
614         $form->{"exchangerate_$i"} = $form->{exchangerate}
615           if ($invdate == $datepaid);
616         $form->isblank("exchangerate_$i",
617                        $locale->text('Exchangerate for payment missing!'));
618       }
619     }
620   }
621
622   ($form->{AP})      = split /--/, $form->{AP};
623   ($form->{AP_paid}) = split /--/, $form->{AP_paid};
624   if (AP->post_payment(\%myconfig, \%$form)) {
625     $form->{snumbers}  = qq|invnumber_| . $form->{invnumber};
626     $form->{what_done} = 'invoice';
627     $form->{addition}  = "PAYMENT POSTED";
628     $form->save_history;
629     $form->redirect($locale->text('Payment posted!'))
630   } else {
631     $form->error($locale->text('Cannot post payment!'));
632   };
633
634
635   $main::lxdebug->leave_sub();
636 }
637
638
639 sub post {
640   $main::lxdebug->enter_sub();
641
642   my $form     = $main::form;
643   my %myconfig = %main::myconfig;
644   my $locale   = $main::locale;
645
646   $main::auth->assert('ap_transactions');
647   $form->mtime_ischanged('ap');
648
649   my ($inline) = @_;
650
651   # check if there is a vendor, invoice, due date and invnumber
652   $form->isblank("transdate", $locale->text("Invoice Date missing!"));
653   $form->isblank("duedate",   $locale->text("Due Date missing!"));
654   $form->isblank("vendor",    $locale->text('Vendor missing!'));
655   $form->isblank("invnumber", $locale->text('Invoice Number missing!'));
656
657   if ($myconfig{mandatory_departments} && !$form->{department}) {
658     $form->{saved_message} = $::locale->text('You have to specify a department.');
659     update();
660     exit;
661   }
662
663   my $closedto  = $form->datetonum($form->{closedto},  \%myconfig);
664   my $transdate = $form->datetonum($form->{transdate}, \%myconfig);
665
666   $form->error($locale->text('Cannot post transaction above the maximum future booking date!'))
667     if ($form->date_max_future($form->{"transdate"}, \%myconfig));
668   $form->error($locale->text('Cannot post transaction for a closed period!')) if ($form->date_closed($form->{"transdate"}, \%myconfig));
669
670   my $zero_amount_posting = 1;
671   for my $i (1 .. $form->{rowcount}) {
672     if ($form->parse_amount(\%myconfig, $form->{"amount_$i"})) {
673       $zero_amount_posting = 0;
674       last;
675     }
676   }
677
678   $form->error($locale->text('Zero amount posting!')) if $zero_amount_posting;
679
680   $form->isblank("exchangerate", $locale->text('Exchangerate missing!'))
681     if ($form->{defaultcurrency} && ($form->{currency} ne $form->{defaultcurrency}));
682   delete($form->{AP});
683
684   for my $i (1 .. $form->{paidaccounts}) {
685     if ($form->parse_amount(\%myconfig, $form->{"paid_$i"})) {
686       my $datepaid = $form->datetonum($form->{"datepaid_$i"}, \%myconfig);
687
688       $form->isblank("datepaid_$i", $locale->text('Payment date missing!'));
689
690       $form->error($locale->text('Cannot post transaction above the maximum future booking date!'))
691       if ($form->date_max_future($form->{"datepaid_$i"}, \%myconfig));
692
693       #Zusätzlich noch das Buchungsdatum in die Bücherkontrolle einbeziehen
694       # (Dient zur Prüfung ob ZE oder ZA geprüft werden soll)
695       $form->error($locale->text('Cannot post payment for a closed period!'))
696         if ($form->date_closed($form->{"datepaid_$i"})  && !$form->date_closed($form->{"gldate_$i"}, \%myconfig));
697
698       if ($form->{defaultcurrency} && ($form->{currency} ne $form->{defaultcurrency})) {
699         $form->{"exchangerate_$i"} = $form->{exchangerate}
700           if ($transdate == $datepaid);
701         $form->isblank("exchangerate_$i",
702                        $locale->text('Exchangerate for payment missing!'));
703       }
704
705     }
706   }
707
708   # if old vendor ne vendor redo form
709   my ($vendor) = split /--/, $form->{vendor};
710   if ($form->{oldvendor} ne "$vendor--$form->{vendor_id}") {
711     &update;
712     $::dispatcher->end_request;
713   }
714   my ($debitaccno,    $debittaxkey)    = split /--/, $form->{AP_amountselected};
715   my ($taxkey,        $NULL)           = split /--/, $form->{taxchartselected};
716   my ($payablesaccno, $payablestaxkey) = split /--/, $form->{APselected};
717 #  $form->{AP_amount_1}  = $debitaccno;
718   $form->{AP_payables}  = $payablesaccno;
719   $form->{taxkey}       = $taxkey;
720   $form->{storno}       = 0;
721
722   $form->{id} = 0 if $form->{postasnew};
723
724   if (AP->post_transaction(\%myconfig, \%$form)) {
725     # saving the history
726     if(!exists $form->{addition} && $form->{id} ne "") {
727       $form->{snumbers}  = qq|invnumber_| . $form->{invnumber};
728       $form->{addition}  = "POSTED";
729       $form->{what_done} = "invoice";
730       $form->save_history;
731     }
732     # /saving the history
733     # Dieser Text wird niemals ausgegeben: Probleme beim redirect?
734     $form->redirect($locale->text('Transaction posted!')) unless $inline;
735   } else {
736     $form->error($locale->text('Cannot post transaction!'));
737   }
738
739   $main::lxdebug->leave_sub();
740 }
741
742 sub post_as_new {
743   $main::lxdebug->enter_sub();
744
745   my $form     = $main::form;
746   my %myconfig = %main::myconfig;
747
748   $main::auth->assert('ap_transactions');
749
750   $form->{postasnew} = 1;
751   # saving the history
752   if(!exists $form->{addition} && $form->{id} ne "") {
753     # does this work? post_as_new for ap doesn't immediately save the
754     # invoice, because the invnumber has to be entered by hand.
755     # And the value of $form->{postasnew} isn't checked when calling post
756     $form->{snumbers}  = qq|invnumber_| . $form->{invnumber};
757     $form->{addition}  = "POSTED AS NEW";
758     $form->{what_done} = "invoice";
759     $form->save_history;
760   }
761   # /saving the history
762   &post;
763
764   $main::lxdebug->leave_sub();
765 }
766
767 sub use_as_new {
768   $main::lxdebug->enter_sub();
769
770   my $form     = $main::form;
771   my %myconfig = %main::myconfig;
772
773   $main::auth->assert('ap_transactions');
774
775   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);
776   $form->{paidaccounts} = 1;
777   $form->{rowcount}--;
778   $form->{invdate} = $form->current_date(\%myconfig);
779   &update;
780
781   $main::lxdebug->leave_sub();
782 }
783
784 sub delete {
785   $main::lxdebug->enter_sub();
786
787   my $form     = $main::form;
788   my $locale   = $main::locale;
789
790   $main::auth->assert('ap_transactions');
791
792   $form->{title} = $locale->text('Confirm!');
793
794   $form->header;
795
796   delete $form->{header};
797
798   print qq|
799 <form method=post action=$form->{script}>
800 |;
801
802   foreach my $key (keys %$form) {
803     next if (($key eq 'login') || ($key eq 'password') || ('' ne ref $form->{$key}));
804     $form->{$key} =~ s/\"/&quot;/g;
805     print qq|<input type=hidden name=$key value="$form->{$key}">\n|;
806   }
807
808   print qq|
809 <h2 class=confirm>$form->{title}</h2>
810
811 <h4>|
812     . $locale->text('Are you sure you want to delete Transaction')
813     . qq| $form->{invnumber}</h4>
814
815 <input name=action class=submit type=submit value="|
816     . $locale->text('Yes') . qq|">
817 </form>
818 |;
819
820   $main::lxdebug->leave_sub();
821 }
822
823 sub yes {
824   $main::lxdebug->enter_sub();
825
826   my $form     = $main::form;
827   my %myconfig = %main::myconfig;
828   my $locale   = $main::locale;
829
830   $main::auth->assert('ap_transactions');
831
832   if (AP->delete_transaction(\%myconfig, \%$form)) {
833     # saving the history
834     if(!exists $form->{addition}) {
835       $form->{snumbers}  = qq|invnumber_| . $form->{invnumber};
836       $form->{addition}  = "DELETED";
837       $form->{what_done} = "invoice";
838       $form->save_history;
839     }
840     # /saving the history
841     $form->redirect($locale->text('Transaction deleted!'));
842   }
843   $form->error($locale->text('Cannot delete transaction!'));
844
845   $main::lxdebug->leave_sub();
846 }
847
848 sub search {
849   $main::lxdebug->enter_sub();
850
851   $main::auth->assert('vendor_invoice_edit');
852
853   my $form     = $main::form;
854   my %myconfig = %main::myconfig;
855   my $locale   = $main::locale;
856
857   # setup customer selection
858   $form->all_vc(\%myconfig, "vendor", "AP");
859
860   $form->{title}    = $locale->text('AP Transactions');
861
862   $form->get_lists("projects"     => { "key" => "ALL_PROJECTS", "all" => 1 },
863                    "departments"  => "ALL_DEPARTMENTS",
864                    "vendors"      => "ALL_VC");
865
866   # constants and subs for template
867   $form->{vc_keys}   = sub { "$_[0]->{name}--$_[0]->{id}" };
868
869   $form->header;
870   print $form->parse_html_template('ap/search', { %myconfig });
871
872   $main::lxdebug->leave_sub();
873 }
874
875 sub create_subtotal_row {
876   $main::lxdebug->enter_sub();
877
878   my ($totals, $columns, $column_alignment, $subtotal_columns, $class) = @_;
879
880   my $form     = $main::form;
881   my %myconfig = %main::myconfig;
882
883   my $row = { map { $_ => { 'data' => '', 'class' => $class, 'align' => $column_alignment->{$_}, } } @{ $columns } };
884
885   map { $row->{$_}->{data} = $form->format_amount(\%myconfig, $totals->{$_}, 2) } @{ $subtotal_columns };
886
887   $row->{tax}->{data} = $form->format_amount(\%myconfig, $totals->{amount} - $totals->{netamount}, 2);
888
889   map { $totals->{$_} = 0 } @{ $subtotal_columns };
890
891   $main::lxdebug->leave_sub();
892
893   return $row;
894 }
895
896 sub ap_transactions {
897   $main::lxdebug->enter_sub();
898
899   my $form     = $main::form;
900   my %myconfig = %main::myconfig;
901   my $locale   = $main::locale;
902
903   $main::auth->assert('vendor_invoice_edit');
904
905   ($form->{vendor}, $form->{vendor_id}) = split(/--/, $form->{vendor});
906
907   report_generator_set_default_sort('transdate', 1);
908
909   AP->ap_transactions(\%myconfig, \%$form);
910
911   $form->{title} = $locale->text('AP Transactions');
912
913   my $report = SL::ReportGenerator->new(\%myconfig, $form);
914
915   my @columns =
916     qw(transdate id type invnumber ordnumber name netamount tax amount paid datepaid
917        due duedate transaction_description notes employee globalprojectnumber
918        vendornumber country ustid taxzone payment_terms charts direct_debit);
919
920   my @hidden_variables = map { "l_${_}" } @columns;
921   push @hidden_variables, "l_subtotal", qw(open closed vendor invnumber ordnumber transaction_description notes project_id transdatefrom transdateto department
922                                            parts_partnumber parts_description);
923
924   my $href = build_std_url('action=ap_transactions', grep { $form->{$_} } @hidden_variables);
925
926   my %column_defs = (
927     'transdate'               => { 'text' => $locale->text('Date'), },
928     'id'                      => { 'text' => $locale->text('ID'), },
929     'type'                    => { 'text' => $locale->text('Type'), },
930     'invnumber'               => { 'text' => $locale->text('Invoice'), },
931     'ordnumber'               => { 'text' => $locale->text('Order'), },
932     'name'                    => { 'text' => $locale->text('Vendor'), },
933     'netamount'               => { 'text' => $locale->text('Amount'), },
934     'tax'                     => { 'text' => $locale->text('Tax'), },
935     'amount'                  => { 'text' => $locale->text('Total'), },
936     'paid'                    => { 'text' => $locale->text('Paid'), },
937     'datepaid'                => { 'text' => $locale->text('Date Paid'), },
938     'due'                     => { 'text' => $locale->text('Amount Due'), },
939     'duedate'                 => { 'text' => $locale->text('Due Date'), },
940     'transaction_description' => { 'text' => $locale->text('Transaction description'), },
941     'notes'                   => { 'text' => $locale->text('Notes'), },
942     'employee'                => { 'text' => $locale->text('Employee'), },
943     'globalprojectnumber'     => { 'text' => $locale->text('Document Project Number'), },
944     'vendornumber'            => { 'text' => $locale->text('Vendor Number'), },
945     'country'                 => { 'text' => $locale->text('Country'), },
946     'ustid'                   => { 'text' => $locale->text('USt-IdNr.'), },
947     'taxzone'                 => { 'text' => $locale->text('Tax rate'), },
948     'payment_terms'           => { 'text' => $locale->text('Payment Terms'), },
949     'charts'                  => { 'text' => $locale->text('Buchungskonto'), },
950     'direct_debit'            => { 'text' => $locale->text('direct debit'), },
951   );
952
953   foreach my $name (qw(id transdate duedate invnumber ordnumber name datepaid employee shippingpoint shipvia transaction_description direct_debit)) {
954     my $sortdir                 = $form->{sort} eq $name ? 1 - $form->{sortdir} : $form->{sortdir};
955     $column_defs{$name}->{link} = $href . "&sort=$name&sortdir=$sortdir";
956   }
957
958   my %column_alignment = map { $_ => 'right' } qw(netamount tax amount paid due);
959
960   $form->{"l_type"} = "Y";
961   map { $column_defs{$_}->{visible} = $form->{"l_${_}"} ? 1 : 0 } @columns;
962
963   $report->set_columns(%column_defs);
964   $report->set_column_order(@columns);
965
966   $report->set_export_options('ap_transactions', @hidden_variables, qw(sort sortdir));
967
968   $report->set_sort_indicator($form->{sort}, $form->{sortdir});
969
970   my @options;
971   push @options, $locale->text('Vendor')                  . " : $form->{vendor}"                         if ($form->{vendor});
972   push @options, $locale->text('Contact Person')          . " : $form->{cp_name}"                        if ($form->{cp_name});
973   push @options, $locale->text('Department')              . " : " . (split /--/, $form->{department})[0] if ($form->{department});
974   push @options, $locale->text('Invoice Number')          . " : $form->{invnumber}"                      if ($form->{invnumber});
975   push @options, $locale->text('Order Number')            . " : $form->{ordnumber}"                      if ($form->{ordnumber});
976   push @options, $locale->text('Notes')                   . " : $form->{notes}"                          if ($form->{notes});
977   push @options, $locale->text('Transaction description') . " : $form->{transaction_description}"        if ($form->{transaction_description});
978   push @options, $locale->text('Part Description')        . " : $form->{parts_description}"              if $form->{parts_description};
979   push @options, $locale->text('Part Number')             . " : $form->{parts_partnumber}"               if $form->{parts_partnumber};
980   push @options, $locale->text('From') . " " . $locale->date(\%myconfig, $form->{transdatefrom}, 1)      if ($form->{transdatefrom});
981   push @options, $locale->text('Bis')  . " " . $locale->date(\%myconfig, $form->{transdateto},   1)      if ($form->{transdateto});
982   push @options, $locale->text('Open')                                                                   if ($form->{open});
983   push @options, $locale->text('Closed')                                                                 if ($form->{closed});
984
985   $report->set_options('top_info_text'        => join("\n", @options),
986                        'raw_bottom_info_text' => $form->parse_html_template('ap/ap_transactions_bottom'),
987                        'output_format'        => 'HTML',
988                        'title'                => $form->{title},
989                        'attachment_basename'  => $locale->text('vendor_invoice_list') . strftime('_%Y%m%d', localtime time),
990     );
991   $report->set_options_from_form();
992   $locale->set_numberformat_wo_thousands_separator(\%myconfig) if lc($report->{options}->{output_format}) eq 'csv';
993
994   # add sort and escape callback, this one we use for the add sub
995   $form->{callback} = $href .= "&sort=$form->{sort}";
996
997   # escape callback for href
998   my $callback = $form->escape($href);
999
1000   my @subtotal_columns = qw(netamount amount paid due);
1001
1002   my %totals    = map { $_ => 0 } @subtotal_columns;
1003   my %subtotals = map { $_ => 0 } @subtotal_columns;
1004
1005   my $idx = 0;
1006
1007   foreach my $ap (@{ $form->{AP} }) {
1008     $ap->{tax} = $ap->{amount} - $ap->{netamount};
1009     $ap->{due} = $ap->{amount} - $ap->{paid};
1010
1011     map { $subtotals{$_} += $ap->{$_};
1012           $totals{$_}    += $ap->{$_} } @subtotal_columns;
1013
1014     map { $ap->{$_} = $form->format_amount(\%myconfig, $ap->{$_}, 2) } qw(netamount tax amount paid due);
1015
1016     my $is_storno  = $ap->{storno} &&  $ap->{storno_id};
1017     my $has_storno = $ap->{storno} && !$ap->{storno_id};
1018
1019     if ($ap->{invoice}) {
1020       $ap->{type} =
1021           $has_storno       ? $locale->text("Invoice with Storno (abbreviation)")
1022         : $is_storno        ? $locale->text("Storno (one letter abbreviation)")
1023         :                     $locale->text("Invoice (one letter abbreviation)");
1024     } else {
1025       $ap->{type} =
1026           $has_storno       ? $locale->text("AP Transaction with Storno (abbreviation)")
1027         : $is_storno        ? $locale->text("AP Transaction Storno (one letter abbreviation)")
1028         :                     $locale->text("AP Transaction (abbreviation)");
1029     }
1030
1031     $ap->{direct_debit} = $ap->{direct_debit} ? $::locale->text('yes') : $::locale->text('no');
1032
1033     my $row = { };
1034
1035     foreach my $column (@columns) {
1036       $row->{$column} = {
1037         'data'  => $ap->{$column},
1038         'align' => $column_alignment{$column},
1039       };
1040     }
1041
1042     $row->{invnumber}->{link} = build_std_url("script=" . ($ap->{invoice} ? 'ir.pl' : 'ap.pl'), 'action=edit')
1043       . "&id=" . E($ap->{id}) . "&callback=${callback}";
1044
1045     my $row_set = [ $row ];
1046
1047     if (($form->{l_subtotal} eq 'Y')
1048         && (($idx == (scalar @{ $form->{AP} } - 1))
1049             || ($ap->{ $form->{sort} } ne $form->{AP}->[$idx + 1]->{ $form->{sort} }))) {
1050       push @{ $row_set }, create_subtotal_row(\%subtotals, \@columns, \%column_alignment, \@subtotal_columns, 'listsubtotal');
1051     }
1052
1053     $report->add_data($row_set);
1054
1055     $idx++;
1056   }
1057
1058   $report->add_separator();
1059   $report->add_data(create_subtotal_row(\%totals, \@columns, \%column_alignment, \@subtotal_columns, 'listtotal'));
1060
1061   $report->generate_with_headers();
1062
1063   $main::lxdebug->leave_sub();
1064 }
1065
1066 sub storno {
1067   $main::lxdebug->enter_sub();
1068
1069   my $form     = $main::form;
1070   my %myconfig = %main::myconfig;
1071   my $locale   = $main::locale;
1072
1073   $main::auth->assert('ap_transactions');
1074
1075   if (IS->has_storno(\%myconfig, $form, 'ap')) {
1076     $form->{title} = $locale->text("Cancel Accounts Payables Transaction");
1077     $form->error($locale->text("Transaction has already been cancelled!"));
1078   }
1079
1080   $form->error($locale->text('Cannot post storno for a closed period!'))
1081     if ( $form->date_closed($form->{transdate}, \%myconfig));
1082
1083   AP->storno($form, \%myconfig, $form->{id});
1084
1085   # saving the history
1086   if(!exists $form->{addition} && $form->{id} ne "") {
1087     $form->{snumbers}  = qq|invnumber_| . $form->{invnumber};
1088     $form->{addition}  = "STORNO";
1089     $form->{what_done} = "invoice";
1090     $form->save_history;
1091   }
1092   # /saving the history
1093
1094   $form->redirect(sprintf $locale->text("Transaction %d cancelled."), $form->{storno_id});
1095
1096   $main::lxdebug->leave_sub();
1097 }