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