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