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