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