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