7fcfef17d850e4ed8aee62a108a8684dfc480d51
[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 flash_later);
43 use SL::IR;
44 use SL::IS;
45 use SL::ReportGenerator;
46 use SL::DB::BankTransactionAccTrans;
47 use SL::DB::Chart;
48 use SL::DB::Currency;
49 use SL::DB::Default;
50 use SL::DB::Order;
51 use SL::DB::PaymentTerm;
52 use SL::DB::PurchaseInvoice;
53 use SL::DB::RecordTemplate;
54 use SL::DB::Tax;
55 use SL::Webdav;
56 use SL::Locale::String qw(t8);
57
58 require "bin/mozilla/common.pl";
59 require "bin/mozilla/reportgenerator.pl";
60
61 use strict;
62
63 1;
64
65 # end of main
66
67 # this is for our long dates
68 # $locale->text('January')
69 # $locale->text('February')
70 # $locale->text('March')
71 # $locale->text('April')
72 # $locale->text('May ')
73 # $locale->text('June')
74 # $locale->text('July')
75 # $locale->text('August')
76 # $locale->text('September')
77 # $locale->text('October')
78 # $locale->text('November')
79 # $locale->text('December')
80
81 # this is for our short month
82 # $locale->text('Jan')
83 # $locale->text('Feb')
84 # $locale->text('Mar')
85 # $locale->text('Apr')
86 # $locale->text('May')
87 # $locale->text('Jun')
88 # $locale->text('Jul')
89 # $locale->text('Aug')
90 # $locale->text('Sep')
91 # $locale->text('Oct')
92 # $locale->text('Nov')
93 # $locale->text('Dec')
94
95 sub _may_view_or_edit_this_invoice {
96   return 1 if  $::auth->assert('ap_transactions', 1); # may edit all invoices
97   return 0 if !$::form->{id};                         # creating new invoices isn't allowed without invoice_edit
98   return 0 if !$::form->{globalproject_id};           # existing records without a project ID are not allowed
99   return SL::DB::Project->new(id => $::form->{globalproject_id})->load->may_employee_view_project_invoices(SL::DB::Manager::Employee->current);
100 }
101
102 sub _assert_access {
103   my $cache = $::request->cache('ap.pl::_assert_access');
104
105   $cache->{_may_view_or_edit_this_invoice} = _may_view_or_edit_this_invoice()                              if !exists $cache->{_may_view_or_edit_this_invoice};
106   $::form->show_generic_error($::locale->text("You do not have the permissions to access this function.")) if !       $cache->{_may_view_or_edit_this_invoice};
107 }
108
109 sub load_record_template {
110   $::auth->assert('ap_transactions');
111
112   # Load existing template and verify that its one for this module.
113   my $template = SL::DB::RecordTemplate
114     ->new(id => $::form->{id})
115     ->load(
116       with_object => [ qw(customer payment currency record_items record_items.chart) ],
117     );
118
119   die "invalid template type" unless $template->template_type eq 'ap_transaction';
120
121   $template->substitute_variables;
122
123   # Clean the current $::form before rebuilding it from the template.
124   my $form_defaults = delete $::form->{form_defaults};
125   delete @{ $::form }{ grep { !m{^(?:script|login)$}i } keys %{ $::form } };
126
127   # Fill $::form from the template.
128   my $today                   = DateTime->today_local;
129   $::form->{title}            = "Add";
130   $::form->{currency}         = $template->currency->name;
131   $::form->{direct_debit}     = $template->direct_debit;
132   $::form->{globalproject_id} = $template->project_id;
133   $::form->{payment_id}       = $template->payment_id;
134   $::form->{AP_chart_id}      = $template->ar_ap_chart_id;
135   $::form->{transdate}        = $today->to_kivitendo;
136   $::form->{duedate}          = $today->to_kivitendo;
137   $::form->{rowcount}         = @{ $template->items };
138   $::form->{paidaccounts}     = 1;
139   $::form->{$_}               = $template->$_ for qw(department_id ordnumber taxincluded notes);
140
141   if ($template->vendor) {
142     $::form->{vendor_id} = $template->vendor_id;
143     $::form->{vendor}    = $template->vendor->name;
144     $::form->{duedate}     = $template->vendor->payment->calc_date(reference_date => $today)->to_kivitendo if $template->vendor->payment;
145   }
146
147   my $row = 0;
148   foreach my $item (@{ $template->items }) {
149     $row++;
150
151     my $active_taxkey = $item->chart->get_active_taxkey;
152     my $taxes         = SL::DB::Manager::Tax->get_all(
153       where   => [ chart_categories => { like => '%' . $item->chart->category . '%' }],
154       sort_by => 'taxkey, rate',
155     );
156
157     my $tax   = first { $item->tax_id          == $_->id } @{ $taxes };
158     $tax    //= first { $active_taxkey->tax_id == $_->id } @{ $taxes };
159     $tax    //= $taxes->[0];
160
161     if (!$tax) {
162       $row--;
163       next;
164     }
165
166     $::form->{"AP_amount_chart_id_${row}"}          = $item->chart_id;
167     $::form->{"previous_AP_amount_chart_id_${row}"} = $item->chart_id;
168     $::form->{"amount_${row}"}                      = $::form->format_amount(\%::myconfig, $item->amount1, 2);
169     $::form->{"taxchart_${row}"}                    = $item->tax_id . '--' . $tax->rate;
170     $::form->{"project_id_${row}"}                  = $item->project_id;
171   }
172
173   $::form->{$_} = $form_defaults->{$_} for keys %{ $form_defaults // {} };
174
175   flash('info', $::locale->text("The record template '#1' has been loaded.", $template->template_name));
176   flash('info', $::locale->text("Payment bookings disallowed. After the booking this record may be " .
177                                 "suggested with the amount of '#1' or otherwise has to be choosen manually." .
178                                 " No automatic payment booking will be done to chart '#2'.",
179                                   $form_defaults->{paid_1_suggestion},
180                                   $form_defaults->{AP_paid_1_suggestion},
181                                 )) if $::form->{no_payment_bookings};
182
183   update(
184     keep_rows_without_amount => 1,
185     dont_add_new_row         => 1,
186   );
187 }
188
189 sub save_record_template {
190   $::auth->assert('ap_transactions');
191
192   my $template = $::form->{record_template_id} ? SL::DB::RecordTemplate->new(id => $::form->{record_template_id})->load : SL::DB::RecordTemplate->new;
193   my $js       = SL::ClientJS->new(controller => SL::Controller::Base->new);
194   my $new_name = $template->template_name_to_use($::form->{record_template_new_template_name});
195
196   $js->dialog->close('#record_template_dialog');
197
198   my @items = grep {
199     $_->{chart_id} && (($_->{tax_id} // '') ne '')
200   } map {
201     +{ chart_id   => $::form->{"AP_amount_chart_id_${_}"},
202        amount1    => $::form->parse_amount(\%::myconfig, $::form->{"amount_${_}"}),
203        tax_id     => (split m{--}, $::form->{"taxchart_${_}"})[0],
204        project_id => $::form->{"project_id_${_}"} || undef,
205      }
206   } (1..($::form->{rowcount} || 1));
207
208   $template->assign_attributes(
209     template_type  => 'ap_transaction',
210     template_name  => $new_name,
211
212     currency_id    => SL::DB::Manager::Currency->find_by(name => $::form->{currency})->id,
213     ar_ap_chart_id => $::form->{AP_chart_id}      || undef,
214     vendor_id      => $::form->{vendor_id}        || undef,
215     department_id  => $::form->{department_id}    || undef,
216     project_id     => $::form->{globalproject_id} || undef,
217     payment_id     => $::form->{payment_id}       || undef,
218     taxincluded    => $::form->{taxincluded}  ? 1 : 0,
219     direct_debit   => $::form->{direct_debit} ? 1 : 0,
220     ordnumber      => $::form->{ordnumber},
221     notes          => $::form->{notes},
222
223     items          => \@items,
224   );
225
226   eval {
227     $template->save;
228     1;
229   } or do {
230     return $js
231       ->flash('error', $::locale->text("Saving the record template '#1' failed.", $new_name))
232       ->render;
233   };
234
235   return $js
236     ->flash('info', $::locale->text("The record template '#1' has been saved.", $new_name))
237     ->render;
238 }
239
240 sub add {
241   $main::lxdebug->enter_sub();
242
243   my $form     = $main::form;
244   my %myconfig = %main::myconfig;
245
246   $main::auth->assert('ap_transactions');
247
248   $form->{title} = "Add";
249
250   $form->{callback} = "ap.pl?action=add" unless $form->{callback};
251
252   AP->get_transdate(\%myconfig, $form);
253   $form->{initial_transdate} = $form->{transdate};
254   create_links(dont_save => 1);
255   $form->{transdate} = $form->{initial_transdate};
256
257   if ($form->{vendor_id}) {
258     my $vendor = SL::DB::Vendor->load_cached($form->{vendor_id});
259
260     # set initial payment terms
261     $form->{payment_id} = $vendor->payment_id;
262
263     my $last_used_ap_chart = $vendor->last_used_ap_chart;
264     $form->{"AP_amount_chart_id_1"} = $last_used_ap_chart->id if $last_used_ap_chart;
265   }
266
267   &display_form;
268
269   $main::lxdebug->leave_sub();
270 }
271
272 sub edit {
273   $main::lxdebug->enter_sub();
274
275   # Delay access check to after the invoice's been loaded in
276   # "create_links" so that project-specific invoice rights can be
277   # evaluated.
278
279   my $form     = $main::form;
280
281   $form->{title} = "Edit";
282
283   create_links();
284   &display_form;
285
286   $main::lxdebug->leave_sub();
287 }
288
289 sub display_form {
290   $main::lxdebug->enter_sub();
291
292   _assert_access();
293
294   my $form     = $main::form;
295
296   # get all files stored in the webdav folder
297   if ($form->{invnumber} && $::instance_conf->get_webdav) {
298     my $webdav = SL::Webdav->new(
299       type     => 'accounts_payable',
300       number   => $form->{invnumber},
301     );
302     my @all_objects = $webdav->get_all_objects;
303     @{ $form->{WEBDAV} } = map { { name => $_->filename,
304                                    type => t8('File'),
305                                    link => File::Spec->catfile($_->full_filedescriptor),
306                                } } @all_objects;
307   }
308   &form_header;
309   &form_footer;
310
311   $main::lxdebug->leave_sub();
312 }
313
314 sub create_links {
315   $main::lxdebug->enter_sub();
316
317   # Delay access check to after the invoice's been loaded so that
318   # project-specific invoice rights can be evaluated.
319
320   my %params   = @_;
321
322   my $form     = $main::form;
323   my %myconfig = %main::myconfig;
324
325   $form->create_links("AP", \%myconfig, "vendor");
326
327   _assert_access();
328
329   my %saved;
330   if (!$params{dont_save}) {
331     %saved = map { ($_ => $form->{$_}) } qw(direct_debit taxincluded);
332     $saved{duedate} = $form->{duedate} if $form->{duedate};
333     $saved{currency} = $form->{currency} if $form->{currency};
334     $saved{taxincluded} = $form->{taxincluded} if $form->{taxincluded};
335   }
336
337   IR->get_vendor(\%myconfig, \%$form);
338
339   $form->{$_}        = $saved{$_} for keys %saved;
340   $form->{rowcount}  = 1;
341   $form->{AP_chart_id} = $form->{acc_trans} && $form->{acc_trans}->{AP} ? $form->{acc_trans}->{AP}->[0]->{chart_id} : $::instance_conf->get_ap_chart_id || $form->{AP_links}->{AP}->[0]->{chart_id};
342
343   # build the popup menus
344   $form->{taxincluded} = ($form->{id}) ? $form->{taxincluded} : "checked";
345
346   # currencies
347   $form->{defaultcurrency} = $form->get_default_currency(\%myconfig);
348
349   $::form->{ALL_DEPARTMENTS} = SL::DB::Manager::Department->get_all_sorted;
350
351   $form->{employee} = "$form->{employee}--$form->{employee_id}";
352
353   AP->setup_form($form);
354
355   $main::lxdebug->leave_sub();
356 }
357
358 sub _sort_payments {
359   my @fields   = qw(acc_trans_id gldate datepaid source memo paid AP_paid paid_project_id);
360   my @payments =
361     grep { $_->{paid} != 0 }
362     map  {
363       my $idx = $_;
364       +{ map { ($_ => delete($::form->{"${_}_${idx}"})) } @fields }
365     } (1..$::form->{paidaccounts});
366
367   @payments = sort_by { DateTime->from_kivitendo($_->{datepaid}) } @payments;
368
369   $::form->{paidaccounts} = max scalar(@payments), 1;
370
371   foreach my $idx (1 .. scalar(@payments)) {
372     my $payment = $payments[$idx - 1];
373     $::form->{"${_}_${idx}"} = $payment->{$_} for @fields;
374   }
375 }
376
377 sub form_header {
378   $main::lxdebug->enter_sub();
379
380   _assert_access();
381
382   my $form     = $main::form;
383   my %myconfig = %main::myconfig;
384   my $locale   = $main::locale;
385   my $cgi      = $::request->{cgi};
386
387   $::form->{invoice_obj} = SL::DB::PurchaseInvoice->new(id => $::form->{id})->load if $::form->{id};
388
389   $form->{initial_focus} = !($form->{amount_1} * 1) ? 'vendor_id' : 'row_' . $form->{rowcount};
390
391   $form->{title_} = $form->{title};
392   $form->{title} = $form->{title} eq 'Add' ? $locale->text('Add Accounts Payables Transaction') : $locale->text('Edit Accounts Payables Transaction');
393
394   # type=submit $locale->text('Add Accounts Payables Transaction')
395   # type=submit $locale->text('Edit Accounts Payables Transaction')
396
397   my $readonly = $form->{id} ? "readonly" : "";
398
399   $form->{radier} = ($::instance_conf->get_ap_changeable == 2)
400                       ? ($form->current_date(\%myconfig) eq $form->{gldate})
401                       : ($::instance_conf->get_ap_changeable == 1);
402   $readonly       = $form->{radier} ? "" : $readonly;
403
404   $form->{readonly} = $readonly;
405
406   $form->{forex} = $form->check_exchangerate( \%myconfig, $form->{currency}, $form->{transdate}, 'sell');
407   if ( $form->{forex} ) {
408     $form->{exchangerate} = $form->{forex};
409   }
410
411   # format amounts
412   $form->{exchangerate}    = $form->{exchangerate} ? $form->format_amount(\%myconfig, $form->{exchangerate}) : '';
413   $form->{creditlimit}     = $form->format_amount(\%myconfig, $form->{creditlimit}, 0, "0");
414   $form->{creditremaining} = $form->format_amount(\%myconfig, $form->{creditremaining}, 0, "0");
415
416   my $rows;
417   if (($rows = $form->numtextrows($form->{notes}, 50)) < 2) {
418     $rows = 2;
419   }
420   $form->{textarea_rows} = $rows;
421
422   $form->{creditremaining_plus} = ($form->{creditremaining} =~ /-/) ? "0" : "1";
423
424   $form->get_lists("charts"    => { "key"       => "ALL_CHARTS",
425                                     "transdate" => $form->{transdate} },
426                   );
427
428   map(
429     { $_->{link_split} = [ split(/:/, $_->{link}) ]; }
430     @{ $form->{ALL_CHARTS} }
431   );
432
433   $form->{ALL_DEPARTMENTS} = SL::DB::Manager::Department->get_all_sorted;
434
435   my %project_labels = map { $_->id => $_->projectnumber }  @{ SL::DB::Manager::Project->get_all };
436
437   my %charts;
438   my $default_ap_amount_chart_id;
439
440   foreach my $item (@{ $form->{ALL_CHARTS} }) {
441     if ( grep({ $_ eq 'AP_amount' } @{ $item->{link_split} }) ) {
442       $default_ap_amount_chart_id //= $item->{id};
443
444     } elsif ( grep({ $_ eq 'AP_paid' } @{ $item->{link_split} }) ) {
445       push(@{ $form->{ALL_CHARTS_AP_paid} }, $item);
446     }
447
448     $charts{$item->{accno}} = $item;
449   }
450
451   my $follow_up_vc         = $form->{vendor_id} ? SL::DB::Vendor->load_cached($form->{vendor_id})->name : '';
452   my $follow_up_trans_info =  "$form->{invnumber} ($follow_up_vc)";
453
454   $::request->layout->add_javascripts("autocomplete_chart.js", "show_vc_details.js", "show_history.js", "follow_up.js", "kivi.Draft.js", "kivi.SalesPurchase.js", "kivi.GL.js", "kivi.RecordTemplate.js", "kivi.File.js", "kivi.AP.js", "kivi.CustomerVendor.js", "kivi.Validator.js", "autocomplete_project.js");
455   # $form->{totalpaid} is used by the action bar setup to determine
456   # whether or not canceling is allowed. Therefore it must be
457   # calculated prior to the action bar setup.
458   $form->{totalpaid} = sum map { $form->{"paid_${_}"} } (1..$form->{paidaccounts});
459
460   setup_ap_display_form_action_bar();
461
462   $form->header();
463   # get the correct date for tax
464   my $transdate    = $::form->{transdate}    ? DateTime->from_kivitendo($::form->{transdate})    : DateTime->today_local;
465   my $deliverydate = $::form->{deliverydate} ? DateTime->from_kivitendo($::form->{deliverydate}) : undef;
466   my $taxdate      = $deliverydate ? $deliverydate : $transdate;
467   # helper for loop
468   my $first_taxchart;
469
470   for my $i (1 .. $form->{rowcount}) {
471
472     # format amounts
473     $form->{"amount_$i"} = $form->format_amount(\%myconfig, $form->{"amount_$i"}, 2);
474     $form->{"tax_$i"} = $form->format_amount(\%myconfig, $form->{"tax_$i"}, 2);
475
476     my ($default_taxchart, $taxchart_to_use);
477     my $used_tax_id;
478     if ( $form->{"taxchart_$i"} ) {
479       ($used_tax_id) = split(/--/, $form->{"taxchart_$i"});
480     }
481     my $amount_chart_id = $form->{"AP_amount_chart_id_$i"} || $default_ap_amount_chart_id;
482
483     my @taxcharts       = GL->get_active_taxes_for_chart($amount_chart_id, $taxdate, $used_tax_id);
484     foreach my $item (@taxcharts) {
485       my $key             = $item->id . "--" . $item->rate;
486       $first_taxchart   //= $item;
487       $default_taxchart   = $item if $item->{is_default};
488       $taxchart_to_use    = $item if $key eq $form->{"taxchart_$i"};
489     }
490
491     $taxchart_to_use               //= $default_taxchart // $first_taxchart;
492     my $selected_taxchart            = $taxchart_to_use->id . '--' . $taxchart_to_use->rate;
493     $form->{"selected_taxchart_$i"}  = $selected_taxchart;
494     $form->{"AP_amount_chart_id_$i"} = $amount_chart_id;
495     $form->{"taxcharts_$i"}          = \@taxcharts;
496
497     # reverse charge hack for template, display two taxes
498     if ($taxchart_to_use->taxkey == 94) {
499       my $tmpnetamount;
500       ($tmpnetamount, $form->{"tax_reverse_$i"}) = $form->calculate_tax($form->parse_amount(\%myconfig, $form->{"amount_$i"}), 0.19, $form->{taxincluded},2);
501       $form->{"tax_charge_$i"}  = $form->{"tax_reverse_$i"} * -1;
502       $form->{"tax_reverse_$i"} = $form->format_amount(\%myconfig, $form->{"tax_reverse_$i"}, 2);
503       $form->{"tax_charge_$i"}  = $form->format_amount(\%myconfig, $form->{"tax_charge_$i"}, 2);
504     }
505   }
506
507   $form->{taxchart_value_title_sub} = sub {
508     my $item = shift;
509     return [
510       $item->{id} .'--'. $item->{rate},
511       $item->{taxkey} . ' - ' . $item->{taxdescription} .' '. ($item->{rate} * 100) .' %',
512     ];
513   };
514
515   $form->{AP_paid_value_title_sub} = sub {
516     my $item = shift;
517     return [
518       $item->{accno},
519       $item->{accno} .'--'. $item->{description}
520     ];
521   };
522
523   $form->{invtotal_unformatted} = $form->{invtotal};
524   $form->{invtotal} = $form->format_amount(\%myconfig, $form->{invtotal}, 2);
525
526   _sort_payments();
527
528   if ( $form->{'paid_'. $form->{paidaccounts}} ) {
529     $form->{paidaccounts}++;
530   }
531
532   # default account for current assets (i.e. 1801 - SKR04)
533   $form->{accno_arap} = IS->get_standard_accno_current_assets(\%myconfig, \%$form);
534
535   for my $i (1 .. $form->{paidaccounts}) {
536     # format amounts
537     if ($form->{"paid_$i"}) {
538       $form->{"paid_$i"} = $form->format_amount(\%myconfig, $form->{"paid_$i"}, 2);
539     }
540     if ($form->{"exchangerate_$i"} == 0) {
541       $form->{"exchangerate_$i"} = "";
542     } else {
543       $form->{"exchangerate_$i"} =
544         $form->format_amount(\%myconfig, $form->{"exchangerate_$i"});
545     }
546
547     my $changeable = 1;
548     if (SL::DB::Default->get->payments_changeable == 0) {
549       # never
550       $changeable = ($form->{"acc_trans_id_$i"})? 0 : 1;
551     }
552     if (SL::DB::Default->get->payments_changeable == 2) {
553       # on the same day
554       $changeable = (($form->{"gldate_$i"} eq '') || $form->current_date(\%myconfig) eq $form->{"gldate_$i"});
555     }
556
557     #deaktivieren von gebuchten Zahlungen ausserhalb der Bücherkontrolle, vorher prüfen ob heute eingegeben
558     if ($form->date_closed($form->{"gldate_$i"})) {
559        $changeable = 0;
560     }
561
562     $form->{'paidaccount_changeable_'. $i} = $changeable;
563
564     $form->{'labelpaid_project_id_'. $i} = $project_labels{$form->{'paid_project_id_'. $i}};
565     # accno and description as info text
566     $form->{'AP_paid_readonly_desc_' . $i} =  $form->{'AP_paid_' . $i} ?
567        $form->{'AP_paid_' . $i} . " " . SL::DB::Manager::Chart->find_by(accno => $form->{'AP_paid_' . $i})->description
568      : '';
569   }
570
571   $form->{paid_missing} = $form->{invtotal_unformatted} - $form->{totalpaid};
572
573   $form->{payment_id} = $form->{invoice_obj}->{payment_id} // $form->{payment_id};
574   print $form->parse_html_template('ap/form_header', {
575     today => DateTime->today,
576     currencies => SL::DB::Manager::Currency->get_all_sorted,
577     payment_terms => SL::DB::Manager::PaymentTerm->get_all_sorted(query => [ or => [ obsolete => 0, id => $form->{payment_id}*1 ]]),
578   });
579
580   $main::lxdebug->leave_sub();
581 }
582
583 sub form_footer {
584   $::lxdebug->enter_sub;
585
586   _assert_access();
587
588   my $num_due;
589   my $num_follow_ups;
590   if ($::form->{id}) {
591     my $follow_ups = FU->follow_ups('trans_id' => $::form->{id}, 'not_done' => 1);
592
593     if (@{ $follow_ups }) {
594       $num_due        = sum map { $_->{due} * 1 } @{ $follow_ups };
595       $num_follow_ups = scalar @{ $follow_ups }
596     }
597   }
598
599   my $transdate = $::form->datetonum($::form->{transdate}, \%::myconfig);
600   my $closedto  = $::form->datetonum($::form->{closedto},  \%::myconfig);
601
602   my $storno = $::form->{id}
603             && !IS->has_storno(\%::myconfig, $::form, 'ap')
604             && !IS->is_storno( \%::myconfig, $::form, 'ap', $::form->{id})
605             && ($::form->{totalpaid} == 0 || $::form->{totalpaid} eq '');
606
607   $::form->header;
608   print $::form->parse_html_template('ap/form_footer', {
609     num_due           => $num_due,
610     num_follow_ups    => $num_follow_ups,
611   });
612
613   $::lxdebug->leave_sub;
614 }
615
616 sub mark_as_paid {
617   $::auth->assert('ap_transactions');
618
619   SL::DB::PurchaseInvoice->new(id => $::form->{id})->load->mark_as_paid;
620
621   $::form->redirect($::locale->text("Marked as paid"));
622 }
623
624 sub show_draft {
625   $::form->{transdate} = DateTime->today_local->to_kivitendo if !$::form->{transdate};
626   $::form->{gldate}    = $::form->{transdate} if !$::form->{gldate};
627   update();
628 }
629
630 sub update {
631   my %params = @_;
632
633   $main::lxdebug->enter_sub();
634
635   my $form     = $main::form;
636   my %myconfig = %main::myconfig;
637
638   $main::auth->assert('ap_transactions');
639
640   my $display = shift;
641
642   $form->{invtotal} = 0;
643
644   delete @{ $form }{ grep { m/^tax_\d+$/ } keys %{ $form } };
645
646   map { $form->{$_} = $form->parse_amount(\%myconfig, $form->{$_}) }
647     qw(exchangerate creditlimit creditremaining);
648
649   my @flds  = qw(amount AP_amount_chart_id projectnumber oldprojectnumber project_id taxchart tax);
650   my $count = 0;
651   my (@a, $j, $totaltax);
652   for my $i (1 .. $form->{rowcount}) {
653     $form->{"amount_$i"} = $form->parse_amount(\%myconfig, $form->{"amount_$i"});
654     if ($form->{"amount_$i"} || $params{keep_rows_without_amount}) {
655       push @a, {};
656       $j = $#a;
657       my ($taxkey, $rate) = split(/--/, $form->{"taxchart_$i"});
658
659       # calculate tax exactly the same way as AP in post_transaction via form->calculate_tax
660       my $tmpnetamount;
661       ($tmpnetamount,$form->{"tax_$i"}) = $form->calculate_tax($form->{"amount_$i"},$rate,$form->{taxincluded},2);
662       $totaltax += $form->{"tax_$i"};
663       map { $a[$j]->{$_} = $form->{"${_}_$i"} } @flds;
664       $count++;
665     }
666   }
667   $form->redo_rows(\@flds, \@a, $count, $form->{rowcount});
668
669   map { $form->{invtotal} += $form->{"amount_$_"} } (1 .. $form->{rowcount});
670
671   $form->{forex}        = $form->check_exchangerate( \%myconfig, $form->{currency}, $form->{transdate}, 'sell');
672   $form->{exchangerate} = $form->{forex} if $form->{forex};
673
674   $form->{invdate} = $form->{transdate};
675
676   if (($form->{previous_vendor_id} || $form->{vendor_id}) != $form->{vendor_id}) {
677     IR->get_vendor(\%::myconfig, $form);
678
679     my $vendor = SL::DB::Vendor->load_cached($form->{vendor_id});
680
681     # reset payment to new vendor
682     $form->{payment_id} = $vendor->payment_id;
683
684     if (($form->{rowcount} == 1) && ($form->{amount_1} == 0)) {
685       my $last_used_ap_chart = $vendor->last_used_ap_chart;
686       $form->{"AP_amount_chart_id_1"} = $last_used_ap_chart->id if $last_used_ap_chart;
687     }
688   }
689
690   $form->{rowcount} = $count + ($params{dont_add_new_row} ? 0 : 1);
691
692   $form->{invtotal} =
693     ($form->{taxincluded}) ? $form->{invtotal} : $form->{invtotal} + $totaltax;
694
695   my $totalpaid;
696   for my $i (1 .. $form->{paidaccounts}) {
697     if ($form->parse_amount(\%myconfig, $form->{"paid_$i"})) {
698       map {
699         $form->{"${_}_$i"} =
700           $form->parse_amount(\%myconfig, $form->{"${_}_$i"})
701       } qw(paid exchangerate);
702
703       $totalpaid += $form->{"paid_$i"};
704
705       $form->{"forex_$i"}        = $form->check_exchangerate( \%myconfig, $form->{currency}, $form->{"datepaid_$i"}, 'sell');
706       $form->{"exchangerate_$i"} = $form->{"forex_$i"} if $form->{"forex_$i"};
707     }
708   }
709
710   $form->{creditremaining} -=
711     ($form->{invtotal} - $totalpaid + $form->{oldtotalpaid} -
712      $form->{oldinvtotal});
713   $form->{oldinvtotal}  = $form->{invtotal};
714   $form->{oldtotalpaid} = $totalpaid;
715
716   display_form();
717
718   $main::lxdebug->leave_sub();
719 }
720
721
722 sub post_payment {
723   $main::lxdebug->enter_sub();
724
725   my $form     = $main::form;
726   my %myconfig = %main::myconfig;
727   my $locale   = $main::locale;
728
729   $main::auth->assert('ap_transactions');
730   $form->mtime_ischanged('ap');
731
732   $form->{defaultcurrency} = $form->get_default_currency(\%myconfig);
733
734   my $invdate = $form->datetonum($form->{transdate}, \%myconfig);
735
736   for my $i (1 .. $form->{paidaccounts}) {
737     if ($form->parse_amount(\%myconfig, $form->{"paid_$i"})) {
738       my $datepaid = $form->datetonum($form->{"datepaid_$i"}, \%myconfig);
739
740       $form->isblank("datepaid_$i", $locale->text('Payment date missing!'));
741
742       $form->error($locale->text('Cannot post transaction above the maximum future booking date!'))
743         if ($form->date_max_future($form->{"datepaid_$i"}, \%myconfig));
744
745       #Zusätzlich noch das Buchungsdatum in die Bücherkontrolle einbeziehen
746       # (Dient zur Prüfung ob ZE oder ZA geprüft werden soll)
747       $form->error($locale->text('Cannot post payment for a closed period!'))
748         if ($form->date_closed($form->{"datepaid_$i"})  && !$form->date_closed($form->{"gldate_$i"}, \%myconfig));
749
750       if ($form->{defaultcurrency} && ($form->{currency} ne $form->{defaultcurrency})) {
751         $form->{"exchangerate_$i"} = $form->{exchangerate}
752           if ($invdate == $datepaid);
753         $form->isblank("exchangerate_$i",
754                        $locale->text('Exchangerate for payment missing!'));
755       }
756     }
757   }
758
759   ($form->{AP})      = split /--/, $form->{AP};
760   ($form->{AP_paid}) = split /--/, $form->{AP_paid};
761   if (AP->post_payment(\%myconfig, \%$form)) {
762     $form->{snumbers}  = qq|invnumber_| . $form->{invnumber};
763     $form->{what_done} = 'invoice';
764     $form->{addition}  = "PAYMENT POSTED";
765     $form->save_history;
766     $form->redirect($locale->text('Payment posted!'))
767   } else {
768     $form->error($locale->text('Cannot post payment!'));
769   };
770
771
772   $main::lxdebug->leave_sub();
773 }
774
775
776 sub post {
777   $main::lxdebug->enter_sub();
778
779   my $form     = $main::form;
780   my %myconfig = %main::myconfig;
781   my $locale   = $main::locale;
782
783   $main::auth->assert('ap_transactions');
784   $form->mtime_ischanged('ap');
785
786   my ($inline) = @_;
787
788   # check if there is a vendor, invoice, due date and invnumber
789   $form->isblank("transdate",   $locale->text("Invoice Date missing!"));
790   $form->isblank("duedate",     $locale->text("Due Date missing!"));
791   $form->isblank("vendor_id",   $locale->text('Vendor missing!'));
792   $form->isblank("invnumber",   $locale->text('Invoice Number missing!'));
793   $form->isblank("AP_chart_id", $locale->text('No contra account selected!'));
794
795   if ($myconfig{mandatory_departments} && !$form->{department_id}) {
796     $form->{saved_message} = $::locale->text('You have to specify a department.');
797     update();
798     exit;
799   }
800
801   my $closedto  = $form->datetonum($form->{closedto},  \%myconfig);
802   my $transdate = $form->datetonum($form->{transdate}, \%myconfig);
803
804   $form->error($locale->text('Cannot post transaction above the maximum future booking date!'))
805     if ($form->date_max_future($form->{"transdate"}, \%myconfig));
806   $form->error($locale->text('Cannot post transaction for a closed period!')) if ($form->date_closed($form->{"transdate"}, \%myconfig));
807
808   my $zero_amount_posting = 1;
809   # no taxincluded for 94
810   my $tax = SL::DB::Manager::Tax->get_first( where => [taxkey => 94 ]);
811   my $tax_id = ref $tax eq 'SL::DB::Tax' ? $tax->id : undef;
812   for my $i (1 .. $form->{rowcount}) {
813     # no taxincluded for 94
814     if ($tax_id && $form->{"taxchart_$i"} =~ m/^$tax_id--/ && $form->{taxincluded}) {
815       $form->error($locale->text('Cannot Post AP transaction with tax included!'));
816     }
817     if ($form->parse_amount(\%myconfig, $form->{"amount_$i"})) {
818       $zero_amount_posting = 0;
819     }
820   }
821
822   $form->error($locale->text('Zero amount posting!')) if $zero_amount_posting;
823
824   $form->isblank("exchangerate", $locale->text('Exchangerate missing!'))
825     if ($form->{defaultcurrency} && ($form->{currency} ne $form->{defaultcurrency}));
826   delete($form->{AP});
827
828   for my $i (1 .. $form->{paidaccounts}) {
829     if ($form->parse_amount(\%myconfig, $form->{"paid_$i"})) {
830       my $datepaid = $form->datetonum($form->{"datepaid_$i"}, \%myconfig);
831
832       $form->isblank("datepaid_$i", $locale->text('Payment date missing!'));
833
834       $form->error($locale->text('Cannot post transaction above the maximum future booking date!'))
835       if ($form->date_max_future($form->{"datepaid_$i"}, \%myconfig));
836
837       #Zusätzlich noch das Buchungsdatum in die Bücherkontrolle einbeziehen
838       # (Dient zur Prüfung ob ZE oder ZA geprüft werden soll)
839       $form->error($locale->text('Cannot post payment for a closed period!'))
840         if ($form->date_closed($form->{"datepaid_$i"})  && !$form->date_closed($form->{"gldate_$i"}, \%myconfig));
841
842       if ($form->{defaultcurrency} && ($form->{currency} ne $form->{defaultcurrency})) {
843         $form->{"exchangerate_$i"} = $form->{exchangerate}
844           if ($transdate == $datepaid);
845         $form->isblank("exchangerate_$i",
846                        $locale->text('Exchangerate for payment missing!'));
847       }
848
849     }
850   }
851
852   # if old vendor ne vendor redo form
853   if (($form->{previous_customer_id} || $form->{customer_id}) != $form->{customer_id}) {
854     &update;
855     $::dispatcher->end_request;
856   }
857   $form->{storno}       = 0;
858
859   $form->{id} = 0 if $form->{postasnew};
860
861   if (AP->post_transaction(\%myconfig, \%$form)) {
862     # create webdav folder
863     if ($::instance_conf->get_webdav) {
864       SL::Webdav->new(type     => 'accounts_payable',
865                       number   => $form->{invnumber},
866                      )->webdav_path;
867     }
868     # saving the history
869     if(!exists $form->{addition} && $form->{id} ne "") {
870       $form->{snumbers}  = qq|invnumber_| . $form->{invnumber};
871       $form->{addition}  = "POSTED";
872       $form->{what_done} = "invoice";
873       $form->save_history;
874     }
875
876     if (!$inline) {
877       my $msg = $locale->text("AP transaction '#1' posted (ID: #2)", $form->{invnumber}, $form->{id});
878       if ($form->{callback} =~ /BankTransaction/) {
879         # no restore_from_session_id needed. we like to have a newly generated
880         # list of invoices for bank transactions
881         SL::Helper::Flash::flash_later('info', $msg);
882         print $form->redirect_header($form->{callback});
883         $::dispatcher->end_request;
884
885       } elsif ('doc-tab' eq $form->{after_action}) {
886         # Redirect with callback containing a fragment does not work (by now)
887         # because the callback info is stored in the session an parsing the
888         # callback parameters does not support fragments (see SL::Form::redirect).
889         # So use flash_later for the message and redirect_headers for redirecting.
890         my $add_doc_url = build_std_url("script=ap.pl", 'action=edit', 'id=' . E($form->{id}), 'fragment=ui-tabs-docs');
891         SL::Helper::Flash::flash_later('info', $msg);
892         print $form->redirect_header($add_doc_url);
893         $::dispatcher->end_request;
894
895       } else {
896         $form->redirect($msg);
897       }
898     }
899
900   } else {
901     $form->error($locale->text('Cannot post transaction!'));
902   }
903
904   $main::lxdebug->leave_sub();
905 }
906
907 sub post_as_new {
908   $main::lxdebug->enter_sub();
909
910   my $form     = $main::form;
911   my %myconfig = %main::myconfig;
912
913   $main::auth->assert('ap_transactions');
914
915   $form->{postasnew} = 1;
916   # saving the history
917   if(!exists $form->{addition} && $form->{id} ne "") {
918     # does this work? post_as_new for ap doesn't immediately save the
919     # invoice, because the invnumber has to be entered by hand.
920     # And the value of $form->{postasnew} isn't checked when calling post
921     $form->{snumbers}  = qq|invnumber_| . $form->{invnumber};
922     $form->{addition}  = "POSTED AS NEW";
923     $form->{what_done} = "invoice";
924     $form->save_history;
925   }
926   # /saving the history
927   &post;
928
929   $main::lxdebug->leave_sub();
930 }
931
932 sub use_as_new {
933   $main::lxdebug->enter_sub();
934
935   my $form     = $main::form;
936   my %myconfig = %main::myconfig;
937
938   $main::auth->assert('ap_transactions');
939
940   map { delete $form->{$_} } qw(printed emailed queued invnumber deliverydate id datepaid_1 gldate_1 acc_trans_id_1 source_1 memo_1 paid_1 exchangerate_1 AP_paid_1 storno convert_from_oe_id);
941   $form->{paidaccounts} = 1;
942   $form->{rowcount}--;
943
944   my $today          = DateTime->today_local;
945   $form->{transdate} = $today->to_kivitendo;
946   $form->{duedate}   = $form->{transdate};
947
948   if ($form->{vendor_id}) {
949     my $payment_terms = SL::DB::Vendor->load_cached($form->{vendor_id})->payment;
950     $form->{duedate}  = $payment_terms->calc_date(reference_date => $today)->to_kivitendo if $payment_terms;
951   }
952
953   &update;
954
955   $main::lxdebug->leave_sub();
956 }
957
958 sub delete {
959   my $form     = $main::form;
960   my %myconfig = %main::myconfig;
961   my $locale   = $main::locale;
962
963   $main::auth->assert('ap_transactions');
964
965   if (AP->delete_transaction(\%myconfig, \%$form)) {
966     # saving the history
967     if(!exists $form->{addition}) {
968       $form->{snumbers}  = qq|invnumber_| . $form->{invnumber};
969       $form->{addition}  = "DELETED";
970       $form->{what_done} = "invoice";
971       $form->save_history;
972     }
973     # /saving the history
974     $form->redirect($locale->text('Transaction deleted!'));
975   }
976   $form->error($locale->text('Cannot delete transaction!'));
977 }
978
979 sub search {
980   $main::lxdebug->enter_sub();
981
982   my $form     = $main::form;
983   my %myconfig = %main::myconfig;
984   my $locale   = $main::locale;
985
986   $form->{title} = $locale->text('Vendor Invoices & AP Transactions');
987
988   $::form->{ALL_DEPARTMENTS} = SL::DB::Manager::Department->get_all_sorted;
989   # constants and subs for template
990   $form->{vc_keys}   = sub { "$_[0]->{name}--$_[0]->{id}" };
991
992   $::request->layout->add_javascripts("autocomplete_project.js");
993
994   setup_ap_search_action_bar();
995
996   $form->header;
997   print $form->parse_html_template('ap/search', { %myconfig });
998
999   $main::lxdebug->leave_sub();
1000 }
1001
1002 sub create_subtotal_row {
1003   $main::lxdebug->enter_sub();
1004
1005   my ($totals, $columns, $column_alignment, $subtotal_columns, $class) = @_;
1006
1007   my $form     = $main::form;
1008   my %myconfig = %main::myconfig;
1009
1010   my $row = { map { $_ => { 'data' => '', 'class' => $class, 'align' => $column_alignment->{$_}, } } @{ $columns } };
1011
1012   map { $row->{$_}->{data} = $form->format_amount(\%myconfig, $totals->{$_}, 2) } @{ $subtotal_columns };
1013
1014   $row->{tax}->{data} = $form->format_amount(\%myconfig, $totals->{amount} - $totals->{netamount}, 2);
1015
1016   map { $totals->{$_} = 0 } @{ $subtotal_columns };
1017
1018   $main::lxdebug->leave_sub();
1019
1020   return $row;
1021 }
1022
1023 sub ap_transactions {
1024   $main::lxdebug->enter_sub();
1025
1026   my $form     = $main::form;
1027   my %myconfig = %main::myconfig;
1028   my $locale   = $main::locale;
1029
1030   report_generator_set_default_sort('transdate', 1);
1031
1032   AP->ap_transactions(\%myconfig, \%$form);
1033
1034   $form->{title} = $locale->text('Vendor Invoices & AP Transactions');
1035
1036   my $report = SL::ReportGenerator->new(\%myconfig, $form);
1037
1038   my @columns =
1039     qw(transdate id type invnumber ordnumber name netamount tax amount paid datepaid
1040        due duedate transaction_description notes employee globalprojectnumber department
1041        vendornumber country ustid taxzone payment_terms charts debit_chart direct_debit
1042        insertdate);
1043
1044   my @hidden_variables = map { "l_${_}" } @columns;
1045   push @hidden_variables, "l_subtotal", qw(open closed vendor invnumber ordnumber transaction_description notes project_id transdatefrom transdateto
1046                                            parts_partnumber parts_description department_id);
1047
1048   my $href = build_std_url('action=ap_transactions', grep { $form->{$_} } @hidden_variables);
1049
1050   my %column_defs = (
1051     'transdate'               => { 'text' => $locale->text('Date'), },
1052     'id'                      => { 'text' => $locale->text('ID'), },
1053     'type'                    => { 'text' => $locale->text('Type'), },
1054     'invnumber'               => { 'text' => $locale->text('Invoice'), },
1055     'ordnumber'               => { 'text' => $locale->text('Order'), },
1056     'name'                    => { 'text' => $locale->text('Vendor'), },
1057     'netamount'               => { 'text' => $locale->text('Amount'), },
1058     'tax'                     => { 'text' => $locale->text('Tax'), },
1059     'amount'                  => { 'text' => $locale->text('Total'), },
1060     'paid'                    => { 'text' => $locale->text('Paid'), },
1061     'datepaid'                => { 'text' => $locale->text('Date Paid'), },
1062     'due'                     => { 'text' => $locale->text('Amount Due'), },
1063     'duedate'                 => { 'text' => $locale->text('Due Date'), },
1064     'transaction_description' => { 'text' => $locale->text('Transaction description'), },
1065     'notes'                   => { 'text' => $locale->text('Notes'), },
1066     'employee'                => { 'text' => $locale->text('Employee'), },
1067     'globalprojectnumber'     => { 'text' => $locale->text('Document Project Number'), },
1068     'department'              => { 'text' => $locale->text('Department'), },
1069     'vendornumber'            => { 'text' => $locale->text('Vendor Number'), },
1070     'country'                 => { 'text' => $locale->text('Country'), },
1071     'ustid'                   => { 'text' => $locale->text('USt-IdNr.'), },
1072     'taxzone'                 => { 'text' => $locale->text('Tax rate'), },
1073     'payment_terms'           => { 'text' => $locale->text('Payment Terms'), },
1074     'charts'                  => { 'text' => $locale->text('Chart'), },
1075     'debit_chart'             => { 'text' => $locale->text('Debit Account'), },
1076     'direct_debit'            => { 'text' => $locale->text('direct debit'), },
1077     'insertdate'              => { 'text' => $locale->text('Insert Date'), },
1078   );
1079
1080   foreach my $name (qw(id transdate duedate invnumber ordnumber name datepaid employee shippingpoint shipvia transaction_description direct_debit department)) {
1081     my $sortdir                 = $form->{sort} eq $name ? 1 - $form->{sortdir} : $form->{sortdir};
1082     $column_defs{$name}->{link} = $href . "&sort=$name&sortdir=$sortdir";
1083   }
1084
1085   my %column_alignment = map { $_ => 'right' } qw(netamount tax amount paid due);
1086
1087   $form->{"l_type"} = "Y";
1088   map { $column_defs{$_}->{visible} = $form->{"l_${_}"} ? 1 : 0 } @columns;
1089
1090   $report->set_columns(%column_defs);
1091   $report->set_column_order(@columns);
1092
1093   $report->set_export_options('ap_transactions', @hidden_variables, qw(sort sortdir));
1094
1095   $report->set_sort_indicator($form->{sort}, $form->{sortdir});
1096
1097   my $department_description;
1098   $department_description = SL::DB::Manager::Department->find_by(id => $form->{department_id})->description if $form->{department_id};
1099   my $project_description;
1100   $project_description = SL::DB::Manager::Project->find_by(id => $form->{project_id})->description if $form->{project_id};
1101
1102   my @options;
1103   push @options, $locale->text('Vendor')                  . " : $form->{vendor}"                         if ($form->{vendor});
1104   push @options, $locale->text('Contact Person')          . " : $form->{cp_name}"                        if ($form->{cp_name});
1105   push @options, $locale->text('Department')              . " : $department_description"                 if ($form->{department_id});
1106   push @options, $locale->text('Project')                 . " : $project_description"                    if ($project_description);
1107   push @options, $locale->text('Invoice Number')          . " : $form->{invnumber}"                      if ($form->{invnumber});
1108   push @options, $locale->text('Order Number')            . " : $form->{ordnumber}"                      if ($form->{ordnumber});
1109   push @options, $locale->text('Notes')                   . " : $form->{notes}"                          if ($form->{notes});
1110   push @options, $locale->text('Transaction description') . " : $form->{transaction_description}"        if ($form->{transaction_description});
1111   push @options, $locale->text('Part Description')        . " : $form->{parts_description}"              if $form->{parts_description};
1112   push @options, $locale->text('Part Number')             . " : $form->{parts_partnumber}"               if $form->{parts_partnumber};
1113   push @options, $locale->text('From') . " " . $locale->date(\%myconfig, $form->{transdatefrom}, 1)      if ($form->{transdatefrom});
1114   push @options, $locale->text('Bis')  . " " . $locale->date(\%myconfig, $form->{transdateto},   1)      if ($form->{transdateto});
1115   push @options, $locale->text('Open')                                                                   if ($form->{open});
1116   push @options, $locale->text('Closed')                                                                 if ($form->{closed});
1117
1118   $report->set_options('top_info_text'        => join("\n", @options),
1119                        'output_format'        => 'HTML',
1120                        'title'                => $form->{title},
1121                        'attachment_basename'  => $locale->text('vendor_invoice_list') . strftime('_%Y%m%d', localtime time),
1122     );
1123   $report->set_options_from_form();
1124   $locale->set_numberformat_wo_thousands_separator(\%myconfig) if lc($report->{options}->{output_format}) eq 'csv';
1125
1126   # add sort and escape callback, this one we use for the add sub
1127   $form->{callback} = $href .= "&sort=$form->{sort}";
1128
1129   # escape callback for href
1130   my $callback = $form->escape($href);
1131
1132   my @subtotal_columns = qw(netamount amount paid due);
1133
1134   my %totals    = map { $_ => 0 } @subtotal_columns;
1135   my %subtotals = map { $_ => 0 } @subtotal_columns;
1136
1137   my $idx = 0;
1138
1139   foreach my $ap (@{ $form->{AP} }) {
1140     $ap->{tax} = $ap->{amount} - $ap->{netamount};
1141     $ap->{due} = $ap->{amount} - $ap->{paid};
1142
1143     map { $subtotals{$_} += $ap->{$_};
1144           $totals{$_}    += $ap->{$_} } @subtotal_columns;
1145
1146     map { $ap->{$_} = $form->format_amount(\%myconfig, $ap->{$_}, 2) } qw(netamount tax amount paid due);
1147
1148     my $is_storno  = $ap->{storno} &&  $ap->{storno_id};
1149     my $has_storno = $ap->{storno} && !$ap->{storno_id};
1150
1151     if ($ap->{invoice}) {
1152       $ap->{type} =
1153           $has_storno       ? $locale->text("Invoice with Storno (abbreviation)")
1154         : $is_storno        ? $locale->text("Storno (one letter abbreviation)")
1155         :                     $locale->text("Invoice (one letter abbreviation)");
1156     } else {
1157       $ap->{type} =
1158           $has_storno       ? $locale->text("AP Transaction with Storno (abbreviation)")
1159         : $is_storno        ? $locale->text("AP Transaction Storno (one letter abbreviation)")
1160         :                     $locale->text("AP Transaction (abbreviation)");
1161     }
1162
1163     $ap->{direct_debit} = $ap->{direct_debit} ? $::locale->text('yes') : $::locale->text('no');
1164
1165     my $row = { };
1166
1167     foreach my $column (@columns) {
1168       $row->{$column} = {
1169         'data'  => $ap->{$column},
1170         'align' => $column_alignment{$column},
1171       };
1172     }
1173
1174     $row->{invnumber}->{link} = build_std_url("script=" . ($ap->{invoice} ? 'ir.pl' : 'ap.pl'), 'action=edit')
1175       . "&id=" . E($ap->{id}) . "&callback=${callback}";
1176
1177     my $row_set = [ $row ];
1178
1179     if (($form->{l_subtotal} eq 'Y')
1180         && (($idx == (scalar @{ $form->{AP} } - 1))
1181             || ($ap->{ $form->{sort} } ne $form->{AP}->[$idx + 1]->{ $form->{sort} }))) {
1182       push @{ $row_set }, create_subtotal_row(\%subtotals, \@columns, \%column_alignment, \@subtotal_columns, 'listsubtotal');
1183     }
1184
1185     $report->add_data($row_set);
1186
1187     $idx++;
1188   }
1189
1190   $report->add_separator();
1191   $report->add_data(create_subtotal_row(\%totals, \@columns, \%column_alignment, \@subtotal_columns, 'listtotal'));
1192
1193   setup_ap_transactions_action_bar();
1194   $report->generate_with_headers();
1195
1196   $main::lxdebug->leave_sub();
1197 }
1198
1199 sub storno {
1200   $main::lxdebug->enter_sub();
1201
1202   my $form     = $main::form;
1203   my %myconfig = %main::myconfig;
1204   my $locale   = $main::locale;
1205
1206   $main::auth->assert('ap_transactions');
1207
1208   if (IS->has_storno(\%myconfig, $form, 'ap')) {
1209     $form->{title} = $locale->text("Cancel Accounts Payables Transaction");
1210     $form->error($locale->text("Transaction has already been cancelled!"));
1211   }
1212
1213   $form->error($locale->text('Cannot post storno for a closed period!'))
1214     if ( $form->date_closed($form->{transdate}, \%myconfig));
1215
1216   AP->storno($form, \%myconfig, $form->{id});
1217
1218   # saving the history
1219   if(!exists $form->{addition} && $form->{id} ne "") {
1220     $form->{snumbers}  = qq|invnumber_| . $form->{invnumber};
1221     $form->{addition}  = "STORNO";
1222     $form->{what_done} = "invoice";
1223     $form->save_history;
1224   }
1225   # /saving the history
1226
1227   $form->redirect(sprintf $locale->text("Transaction %d cancelled."), $form->{storno_id});
1228
1229   $main::lxdebug->leave_sub();
1230 }
1231
1232 sub add_from_purchase_order {
1233   $main::auth->assert('ap_transactions');
1234
1235   return if !$::form->{id};
1236
1237   my $order_id = delete $::form->{id};
1238   my $order    = SL::DB::Order->new(id => $order_id)->load(with => [ 'vendor', 'currency', 'payment_terms' ]);
1239
1240   return if $order->type ne 'purchase_order';
1241
1242   my $today                     = DateTime->today_local;
1243   $::form->{title}              = "Add";
1244   $::form->{vc}                 = 'vendor';
1245   $::form->{vendor_id}          = $order->customervendor->id;
1246   $::form->{vendor}             = $order->vendor->name;
1247   $::form->{convert_from_oe_id} = $order->id;
1248   $::form->{globalproject_id}   = $order->globalproject_id;
1249   $::form->{ordnumber}          = $order->number;
1250   $::form->{department_id}      = $order->department_id;
1251   $::form->{currency}           = $order->currency->name;
1252   $::form->{taxincluded}        = 1; # we use amount below, so tax is included
1253   $::form->{transdate}          = $today->to_kivitendo;
1254   $::form->{duedate}            = $today->to_kivitendo;
1255   $::form->{duedate}            = $order->payment_terms->calc_date(reference_date => $today)->to_kivitendo if $order->payment_terms;
1256   $::form->{deliverydate}       = $order->reqdate->to_kivitendo                                            if $order->reqdate;
1257   create_links();
1258
1259   my $config_po_ap_workflow_chart_id = $::instance_conf->get_workflow_po_ap_chart_id;
1260
1261   my ($first_taxchart, $default_taxchart, $taxchart_to_use);
1262   my @taxcharts = ();
1263   @taxcharts    = GL->get_active_taxes_for_chart($config_po_ap_workflow_chart_id, $::form->{transdate}) if (defined $config_po_ap_workflow_chart_id);
1264   foreach my $item (@taxcharts) {
1265     $first_taxchart   //= $item;
1266     $default_taxchart   = $item if $item->{is_default};
1267   }
1268   $taxchart_to_use      = $default_taxchart // $first_taxchart;
1269
1270   my %pat = $order->calculate_prices_and_taxes;
1271   my $row = 1;
1272   foreach my $amount_chart (keys %{$pat{amounts}}) {
1273     my $tax = SL::DB::Manager::Tax->find_by(id => $pat{amounts}->{$amount_chart}->{tax_id});
1274     # If tax chart from order for this amount is active, use it. Use default or first tax chart for selected chart else.
1275     if (defined $config_po_ap_workflow_chart_id) {
1276       $taxchart_to_use = (first {$_->{id} == $tax->id} @taxcharts) // $taxchart_to_use;
1277     } else {
1278       $taxchart_to_use = $tax;
1279     }
1280
1281     $::form->{"AP_amount_chart_id_$row"}          = $config_po_ap_workflow_chart_id // $amount_chart;
1282     $::form->{"previous_AP_amount_chart_id_$row"} = $::form->{"AP_amount_chart_id_$row"};
1283     $::form->{"amount_$row"}                      = $::form->format_amount(\%::myconfig, $pat{amounts}->{$amount_chart}->{amount} * (1 + $tax->rate), 2);
1284     $::form->{"taxchart_$row"}                    = $taxchart_to_use->id . '--' . $taxchart_to_use->rate;
1285     $::form->{"project_id_$row"}                  = $order->globalproject_id;
1286
1287     $row++;
1288   }
1289
1290   my $last_used_ap_chart               = SL::DB::Vendor->load_cached($::form->{vendor_id})->last_used_ap_chart;
1291   $::form->{"AP_amount_chart_id_$row"} = $last_used_ap_chart->id if $last_used_ap_chart;
1292   $::form->{rowcount}                  = $row;
1293
1294   update(
1295     keep_rows_without_amount => 1,
1296     dont_add_new_row         => 1,
1297   );
1298 }
1299
1300 sub setup_ap_search_action_bar {
1301   my %params = @_;
1302
1303   for my $bar ($::request->layout->get('actionbar')) {
1304     $bar->add(
1305       action => [
1306         $::locale->text('Search'),
1307         submit    => [ '#form', { action => "ap_transactions" } ],
1308         checks    => [ 'kivi.validate_form' ],
1309         accesskey => 'enter',
1310       ],
1311     );
1312   }
1313   $::request->layout->add_javascripts('kivi.Validator.js');
1314 }
1315
1316 sub setup_ap_transactions_action_bar {
1317   my %params          = @_;
1318   my $may_edit_create = $::auth->assert('ap_transactions', 1);
1319
1320   for my $bar ($::request->layout->get('actionbar')) {
1321     $bar->add(
1322       combobox => [
1323         action => [ t8('Add') ],
1324         link => [
1325           t8('Purchase Invoice'),
1326           link     => [ 'ir.pl?action=add' ],
1327           disabled => !$may_edit_create ? t8('You do not have the permissions to access this function.') : undef,
1328
1329         ],
1330         link => [
1331           t8('AP Transaction'),
1332           link     => [ 'ap.pl?action=add' ],
1333           disabled => !$may_edit_create ? t8('You do not have the permissions to access this function.') : undef,
1334         ],
1335       ], # end of combobox "Add"
1336     );
1337   }
1338 }
1339
1340 sub setup_ap_display_form_action_bar {
1341   my $transdate               = $::form->datetonum($::form->{transdate}, \%::myconfig);
1342   my $closedto                = $::form->datetonum($::form->{closedto},  \%::myconfig);
1343   my $is_closed               = $transdate <= $closedto;
1344
1345   my $change_never            = $::instance_conf->get_ap_changeable == 0;
1346   my $change_on_same_day_only = $::instance_conf->get_ap_changeable == 2 && ($::form->current_date(\%::myconfig) ne $::form->{gldate});
1347
1348   my $is_storno               = IS->is_storno(\%::myconfig, $::form, 'ap', $::form->{id});
1349   my $has_storno              = IS->has_storno(\%::myconfig, $::form, 'ap');
1350
1351   my $may_edit_create         = $::auth->assert('ap_transactions', 1);
1352
1353   my $has_sepa_exports;
1354   if ($::form->{id}) {
1355     my $invoice = SL::DB::Manager::PurchaseInvoice->find_by(id => $::form->{id});
1356     $has_sepa_exports = 1 if ($invoice->find_sepa_export_items()->[0]);
1357   }
1358
1359   my $is_linked_bank_transaction;
1360   if ($::form->{id}
1361       && SL::DB::Default->get->payments_changeable != 0
1362       && SL::DB::Manager::BankTransactionAccTrans->find_by(ap_id => $::form->{id})) {
1363
1364     $is_linked_bank_transaction = 1;
1365   }
1366   my $is_linked_gl_transaction;
1367   if ($::form->{id} && SL::DB::Manager::ApGl->find_by(ap_id => $::form->{id})) {
1368     $is_linked_gl_transaction = 1;
1369   }
1370
1371   my $create_post_action = sub {
1372     # $_[0]: description
1373     # $_[1]: after_action
1374     action => [
1375       $_[0],
1376       submit   => [ '#form', { action => "post", after_action => $_[1] } ],
1377       checks   => [ 'kivi.validate_form', 'kivi.AP.check_fields_before_posting', 'kivi.AP.check_duplicate_invnumber' ],
1378       disabled => !$may_edit_create                           ? t8('You must not change this AP transaction.')
1379                 : $is_closed                                  ? t8('The billing period has already been locked.')
1380                 : $is_storno                                  ? t8('A canceled invoice cannot be posted.')
1381                 : ($::form->{id} && $change_never)            ? t8('Changing invoices has been disabled in the configuration.')
1382                 : ($::form->{id} && $change_on_same_day_only) ? t8('Invoices can only be changed on the day they are posted.')
1383                 : $is_linked_bank_transaction                 ? t8('This transaction is linked with a bank transaction. Please undo and redo the bank transaction booking if needed.')
1384                 :                                               undef,
1385     ],
1386   };
1387
1388   my @post_entries;
1389   if ($::instance_conf->get_ap_add_doc && $::instance_conf->get_doc_storage) {
1390     @post_entries = ( $create_post_action->(t8('Post'), 'doc-tab'),
1391                       $create_post_action->(t8('Post and new booking')) );
1392   } elsif ($::instance_conf->get_doc_storage) {
1393     @post_entries = ( $create_post_action->(t8('Post')),
1394                       $create_post_action->(t8('Post and upload document'), 'doc-tab') );
1395   } else {
1396     @post_entries = ( $create_post_action->(t8('Post')) );
1397   }
1398
1399   for my $bar ($::request->layout->get('actionbar')) {
1400     $bar->add(
1401       action => [
1402         t8('Update'),
1403         submit    => [ '#form', { action => "update" } ],
1404         id        => 'update_button',
1405         checks    => [ 'kivi.validate_form' ],
1406         accesskey => 'enter',
1407         disabled  => !$may_edit_create ? t8('You must not change this AP transaction.') : undef,
1408       ],
1409       combobox => [
1410         @post_entries,
1411         action => [
1412           t8('Post Payment'),
1413           submit   => [ '#form', { action => "post_payment" } ],
1414           checks   => [ 'kivi.validate_form' ],
1415           disabled => !$may_edit_create           ? t8('You must not change this AP transaction.')
1416                     : !$::form->{id}              ? t8('This invoice has not been posted yet.')
1417                     : $is_linked_bank_transaction ? t8('This transaction is linked with a bank transaction. Please undo and redo the bank transaction booking if needed.')
1418                     :                               undef,
1419         ],
1420         action => [ t8('Mark as paid'),
1421           submit   => [ '#form', { action => "mark_as_paid" } ],
1422           confirm  => t8('This will remove the invoice from showing as unpaid even if the unpaid amount does not match the amount. Proceed?'),
1423           disabled => !$may_edit_create ? t8('You must not change this AP transaction.')
1424                     : !$::form->{id}    ? t8('This invoice has not been posted yet.')
1425                     :                     undef,
1426           only_if  => $::instance_conf->get_is_show_mark_as_paid,
1427         ],
1428       ], # end of combobox "Post"
1429
1430       combobox => [
1431         action => [ t8('Storno'),
1432           submit   => [ '#form', { action => "storno" } ],
1433           checks   => [ 'kivi.validate_form', 'kivi.AP.check_fields_before_posting' ],
1434           confirm  => t8('Do you really want to cancel this invoice?'),
1435           disabled => !$may_edit_create    ? t8('You must not change this AP transaction.')
1436                     : !$::form->{id}       ? t8('This invoice has not been posted yet.')
1437                     : $has_storno          ? t8('This invoice has been canceled already.')
1438                     : $is_storno           ? t8('Reversal invoices cannot be canceled.')
1439                     : $::form->{totalpaid} ? t8('Invoices with payments cannot be canceled.')
1440                     : $has_sepa_exports    ? t8('This invoice has been linked with a sepa export, undo this first.')
1441                     : $is_linked_gl_transaction ? t8('This transaction is linked with a gl transaction. Please delete the ap transaction booking if needed.')
1442                     :                        undef,
1443         ],
1444         action => [ t8('Delete'),
1445           submit   => [ '#form', { action => "delete" } ],
1446           confirm  => t8('Do you really want to delete this object?'),
1447           disabled => !$may_edit_create           ? t8('You must not change this AP transaction.')
1448                     : !$::form->{id}              ? t8('This invoice has not been posted yet.')
1449                     : $is_closed                  ? t8('The billing period has already been locked.')
1450                     : $has_sepa_exports           ? t8('This invoice has been linked with a sepa export, undo this first.')
1451                     : $is_linked_bank_transaction ? t8('This transaction is linked with a bank transaction. Please undo and redo the bank transaction booking if needed.')
1452                     : $is_linked_gl_transaction   ? undef # linked transactions can be deleted, if period is not closed
1453                     : $change_never               ? t8('Changing invoices has been disabled in the configuration.')
1454                     : $change_on_same_day_only    ? t8('Invoices can only be changed on the day they are posted.')
1455                     : $has_storno                 ? t8('This invoice has been canceled already.')
1456                     :                               undef,
1457         ],
1458       ], # end of combobox "Storno"
1459
1460       'separator',
1461
1462       combobox => [
1463         action => [ t8('Workflow') ],
1464         action => [
1465           t8('Use As New'),
1466           submit   => [ '#form', { action => "use_as_new" } ],
1467           checks   => [ 'kivi.validate_form' ],
1468           disabled => !$may_edit_create ? t8('You must not change this AP transaction.')
1469                     : !$::form->{id}    ? t8('This invoice has not been posted yet.')
1470                     :                     undef,
1471         ],
1472       ], # end of combobox "Workflow"
1473
1474       combobox => [
1475         action => [ t8('more') ],
1476         action => [
1477           t8('History'),
1478           call     => [ 'set_history_window', $::form->{id} * 1, 'glid' ],
1479           disabled => !$::form->{id} ? t8('This invoice has not been posted yet.') : undef,
1480         ],
1481         action => [
1482           t8('Follow-Up'),
1483           call     => [ 'follow_up_window' ],
1484           disabled => !$::form->{id} ? t8('This invoice has not been posted yet.') : undef,
1485         ],
1486         action => [
1487           t8('Record templates'),
1488           call     => [ 'kivi.RecordTemplate.popup', 'ap_transaction' ],
1489           disabled => !$may_edit_create ? t8('You must not change this AP transaction.') : undef,
1490         ],
1491         action => [
1492           t8('Drafts'),
1493           call     => [ 'kivi.Draft.popup', 'ap', 'invoice', $::form->{draft_id}, $::form->{draft_description} ],
1494           disabled => !$may_edit_create ? t8('You must not change this AP transaction.')
1495                     : $::form->{id}     ? t8('This invoice has already been posted.')
1496                     : $is_closed        ? t8('The billing period has already been locked.')
1497                     :                     undef,
1498         ],
1499       ], # end of combobox "more"
1500     );
1501   }
1502   $::request->layout->add_javascripts('kivi.Validator.js');
1503 }