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