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