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