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