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