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