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