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