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