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