ActionBar: Verwendung bei »Einkauf« → »Berichte« → »Einkaufsrechnungen…«
[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   # $form->{totalpaid} is used by the action bar setup to determine
439   # whether or not canceling is allowed. Therefore it must be
440   # calculated prior to the action bar setup.
441   $form->{totalpaid} = sum map { $form->{"paid_${_}"} } (1..$form->{paidaccounts});
442
443   setup_ap_display_form_action_bar();
444
445   $form->header();
446
447   for my $i (1 .. $form->{rowcount}) {
448
449     # format amounts
450     $form->{"amount_$i"} = $form->format_amount(\%myconfig, $form->{"amount_$i"}, 2);
451     $form->{"tax_$i"} = $form->format_amount(\%myconfig, $form->{"tax_$i"}, 2);
452
453     my ($default_taxchart, $taxchart_to_use);
454     my $amount_chart_id   = $form->{"AP_amount_chart_id_$i"} || $default_ap_amount_chart_id;
455     my $chart_has_changed = $::form->{"previous_AP_amount_chart_id_$i"} && ($amount_chart_id != $::form->{"previous_AP_amount_chart_id_$i"});
456     my @taxcharts         = GL->get_active_taxes_for_chart($amount_chart_id, $transdate);
457
458     foreach my $item (@taxcharts) {
459       my $key             = $item->id . "--" . $item->rate;
460       $first_taxchart   //= $item;
461       $default_taxchart   = $item if $item->{is_default};
462       $taxchart_to_use    = $item if $key eq $form->{"taxchart_$i"};
463     }
464
465     $taxchart_to_use                 = $default_taxchart // $first_taxchart if $chart_has_changed || !$taxchart_to_use;
466     my $selected_taxchart            = $taxchart_to_use->id . '--' . $taxchart_to_use->rate;
467     $form->{"selected_taxchart_$i"}  = $selected_taxchart;
468     $form->{"AP_amount_chart_id_$i"} = $amount_chart_id;
469     $form->{"taxcharts_$i"}          = \@taxcharts;
470   }
471
472   $form->{taxchart_value_title_sub} = sub {
473     my $item = shift;
474     return [
475       $item->{id} .'--'. $item->{rate},
476       $item->{taxdescription} .' '. ($item->{rate} * 100) .' %',
477     ];
478   };
479
480   $form->{AP_paid_value_title_sub} = sub {
481     my $item = shift;
482     return [
483       $item->{accno},
484       $item->{accno} .'--'. $item->{description}
485     ];
486   };
487
488   $form->{invtotal_unformatted} = $form->{invtotal};
489   $form->{invtotal} = $form->format_amount(\%myconfig, $form->{invtotal}, 2);
490
491   _sort_payments();
492
493   if ( $form->{'paid_'. $form->{paidaccounts}} ) {
494     $form->{paidaccounts}++;
495   }
496
497   # default account for current assets (i.e. 1801 - SKR04)
498   $form->{accno_arap} = IS->get_standard_accno_current_assets(\%myconfig, \%$form);
499
500   for my $i (1 .. $form->{paidaccounts}) {
501     # 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   setup_ap_search_action_bar();
919
920   $form->header;
921   print $form->parse_html_template('ap/search', { %myconfig });
922
923   $main::lxdebug->leave_sub();
924 }
925
926 sub create_subtotal_row {
927   $main::lxdebug->enter_sub();
928
929   my ($totals, $columns, $column_alignment, $subtotal_columns, $class) = @_;
930
931   my $form     = $main::form;
932   my %myconfig = %main::myconfig;
933
934   my $row = { map { $_ => { 'data' => '', 'class' => $class, 'align' => $column_alignment->{$_}, } } @{ $columns } };
935
936   map { $row->{$_}->{data} = $form->format_amount(\%myconfig, $totals->{$_}, 2) } @{ $subtotal_columns };
937
938   $row->{tax}->{data} = $form->format_amount(\%myconfig, $totals->{amount} - $totals->{netamount}, 2);
939
940   map { $totals->{$_} = 0 } @{ $subtotal_columns };
941
942   $main::lxdebug->leave_sub();
943
944   return $row;
945 }
946
947 sub ap_transactions {
948   $main::lxdebug->enter_sub();
949
950   my $form     = $main::form;
951   my %myconfig = %main::myconfig;
952   my $locale   = $main::locale;
953
954   $main::auth->assert('vendor_invoice_edit');
955
956   report_generator_set_default_sort('transdate', 1);
957
958   AP->ap_transactions(\%myconfig, \%$form);
959
960   $form->{title} = $locale->text('AP Transactions');
961
962   my $report = SL::ReportGenerator->new(\%myconfig, $form);
963
964   my @columns =
965     qw(transdate id type invnumber ordnumber name netamount tax amount paid datepaid
966        due duedate transaction_description notes employee globalprojectnumber
967        vendornumber country ustid taxzone payment_terms charts direct_debit);
968
969   my @hidden_variables = map { "l_${_}" } @columns;
970   push @hidden_variables, "l_subtotal", qw(open closed vendor invnumber ordnumber transaction_description notes project_id transdatefrom transdateto
971                                            parts_partnumber parts_description);
972
973   my $href = build_std_url('action=ap_transactions', grep { $form->{$_} } @hidden_variables);
974
975   my %column_defs = (
976     'transdate'               => { 'text' => $locale->text('Date'), },
977     'id'                      => { 'text' => $locale->text('ID'), },
978     'type'                    => { 'text' => $locale->text('Type'), },
979     'invnumber'               => { 'text' => $locale->text('Invoice'), },
980     'ordnumber'               => { 'text' => $locale->text('Order'), },
981     'name'                    => { 'text' => $locale->text('Vendor'), },
982     'netamount'               => { 'text' => $locale->text('Amount'), },
983     'tax'                     => { 'text' => $locale->text('Tax'), },
984     'amount'                  => { 'text' => $locale->text('Total'), },
985     'paid'                    => { 'text' => $locale->text('Paid'), },
986     'datepaid'                => { 'text' => $locale->text('Date Paid'), },
987     'due'                     => { 'text' => $locale->text('Amount Due'), },
988     'duedate'                 => { 'text' => $locale->text('Due Date'), },
989     'transaction_description' => { 'text' => $locale->text('Transaction description'), },
990     'notes'                   => { 'text' => $locale->text('Notes'), },
991     'employee'                => { 'text' => $locale->text('Employee'), },
992     'globalprojectnumber'     => { 'text' => $locale->text('Document Project Number'), },
993     'vendornumber'            => { 'text' => $locale->text('Vendor Number'), },
994     'country'                 => { 'text' => $locale->text('Country'), },
995     'ustid'                   => { 'text' => $locale->text('USt-IdNr.'), },
996     'taxzone'                 => { 'text' => $locale->text('Tax rate'), },
997     'payment_terms'           => { 'text' => $locale->text('Payment Terms'), },
998     'charts'                  => { 'text' => $locale->text('Buchungskonto'), },
999     'direct_debit'            => { 'text' => $locale->text('direct debit'), },
1000   );
1001
1002   foreach my $name (qw(id transdate duedate invnumber ordnumber name datepaid employee shippingpoint shipvia transaction_description direct_debit)) {
1003     my $sortdir                 = $form->{sort} eq $name ? 1 - $form->{sortdir} : $form->{sortdir};
1004     $column_defs{$name}->{link} = $href . "&sort=$name&sortdir=$sortdir";
1005   }
1006
1007   my %column_alignment = map { $_ => 'right' } qw(netamount tax amount paid due);
1008
1009   $form->{"l_type"} = "Y";
1010   map { $column_defs{$_}->{visible} = $form->{"l_${_}"} ? 1 : 0 } @columns;
1011
1012   $report->set_columns(%column_defs);
1013   $report->set_column_order(@columns);
1014
1015   $report->set_export_options('ap_transactions', @hidden_variables, qw(sort sortdir));
1016
1017   $report->set_sort_indicator($form->{sort}, $form->{sortdir});
1018
1019   my @options;
1020   push @options, $locale->text('Vendor')                  . " : $form->{vendor}"                         if ($form->{vendor});
1021   push @options, $locale->text('Contact Person')          . " : $form->{cp_name}"                        if ($form->{cp_name});
1022   push @options, $locale->text('Department')              . " : $form->{department}"                     if ($form->{department});
1023   push @options, $locale->text('Invoice Number')          . " : $form->{invnumber}"                      if ($form->{invnumber});
1024   push @options, $locale->text('Order Number')            . " : $form->{ordnumber}"                      if ($form->{ordnumber});
1025   push @options, $locale->text('Notes')                   . " : $form->{notes}"                          if ($form->{notes});
1026   push @options, $locale->text('Transaction description') . " : $form->{transaction_description}"        if ($form->{transaction_description});
1027   push @options, $locale->text('Part Description')        . " : $form->{parts_description}"              if $form->{parts_description};
1028   push @options, $locale->text('Part Number')             . " : $form->{parts_partnumber}"               if $form->{parts_partnumber};
1029   push @options, $locale->text('From') . " " . $locale->date(\%myconfig, $form->{transdatefrom}, 1)      if ($form->{transdatefrom});
1030   push @options, $locale->text('Bis')  . " " . $locale->date(\%myconfig, $form->{transdateto},   1)      if ($form->{transdateto});
1031   push @options, $locale->text('Open')                                                                   if ($form->{open});
1032   push @options, $locale->text('Closed')                                                                 if ($form->{closed});
1033
1034   $report->set_options('top_info_text'        => join("\n", @options),
1035                        'output_format'        => 'HTML',
1036                        'title'                => $form->{title},
1037                        'attachment_basename'  => $locale->text('vendor_invoice_list') . strftime('_%Y%m%d', localtime time),
1038     );
1039   $report->set_options_from_form();
1040   $locale->set_numberformat_wo_thousands_separator(\%myconfig) if lc($report->{options}->{output_format}) eq 'csv';
1041
1042   # add sort and escape callback, this one we use for the add sub
1043   $form->{callback} = $href .= "&sort=$form->{sort}";
1044
1045   # escape callback for href
1046   my $callback = $form->escape($href);
1047
1048   my @subtotal_columns = qw(netamount amount paid due);
1049
1050   my %totals    = map { $_ => 0 } @subtotal_columns;
1051   my %subtotals = map { $_ => 0 } @subtotal_columns;
1052
1053   my $idx = 0;
1054
1055   foreach my $ap (@{ $form->{AP} }) {
1056     $ap->{tax} = $ap->{amount} - $ap->{netamount};
1057     $ap->{due} = $ap->{amount} - $ap->{paid};
1058
1059     map { $subtotals{$_} += $ap->{$_};
1060           $totals{$_}    += $ap->{$_} } @subtotal_columns;
1061
1062     map { $ap->{$_} = $form->format_amount(\%myconfig, $ap->{$_}, 2) } qw(netamount tax amount paid due);
1063
1064     my $is_storno  = $ap->{storno} &&  $ap->{storno_id};
1065     my $has_storno = $ap->{storno} && !$ap->{storno_id};
1066
1067     if ($ap->{invoice}) {
1068       $ap->{type} =
1069           $has_storno       ? $locale->text("Invoice with Storno (abbreviation)")
1070         : $is_storno        ? $locale->text("Storno (one letter abbreviation)")
1071         :                     $locale->text("Invoice (one letter abbreviation)");
1072     } else {
1073       $ap->{type} =
1074           $has_storno       ? $locale->text("AP Transaction with Storno (abbreviation)")
1075         : $is_storno        ? $locale->text("AP Transaction Storno (one letter abbreviation)")
1076         :                     $locale->text("AP Transaction (abbreviation)");
1077     }
1078
1079     $ap->{direct_debit} = $ap->{direct_debit} ? $::locale->text('yes') : $::locale->text('no');
1080
1081     my $row = { };
1082
1083     foreach my $column (@columns) {
1084       $row->{$column} = {
1085         'data'  => $ap->{$column},
1086         'align' => $column_alignment{$column},
1087       };
1088     }
1089
1090     $row->{invnumber}->{link} = build_std_url("script=" . ($ap->{invoice} ? 'ir.pl' : 'ap.pl'), 'action=edit')
1091       . "&id=" . E($ap->{id}) . "&callback=${callback}";
1092
1093     my $row_set = [ $row ];
1094
1095     if (($form->{l_subtotal} eq 'Y')
1096         && (($idx == (scalar @{ $form->{AP} } - 1))
1097             || ($ap->{ $form->{sort} } ne $form->{AP}->[$idx + 1]->{ $form->{sort} }))) {
1098       push @{ $row_set }, create_subtotal_row(\%subtotals, \@columns, \%column_alignment, \@subtotal_columns, 'listsubtotal');
1099     }
1100
1101     $report->add_data($row_set);
1102
1103     $idx++;
1104   }
1105
1106   $report->add_separator();
1107   $report->add_data(create_subtotal_row(\%totals, \@columns, \%column_alignment, \@subtotal_columns, 'listtotal'));
1108
1109   setup_ap_transactions_action_bar();
1110   $report->generate_with_headers();
1111
1112   $main::lxdebug->leave_sub();
1113 }
1114
1115 sub storno {
1116   $main::lxdebug->enter_sub();
1117
1118   my $form     = $main::form;
1119   my %myconfig = %main::myconfig;
1120   my $locale   = $main::locale;
1121
1122   $main::auth->assert('ap_transactions');
1123
1124   if (IS->has_storno(\%myconfig, $form, 'ap')) {
1125     $form->{title} = $locale->text("Cancel Accounts Payables Transaction");
1126     $form->error($locale->text("Transaction has already been cancelled!"));
1127   }
1128
1129   $form->error($locale->text('Cannot post storno for a closed period!'))
1130     if ( $form->date_closed($form->{transdate}, \%myconfig));
1131
1132   AP->storno($form, \%myconfig, $form->{id});
1133
1134   # saving the history
1135   if(!exists $form->{addition} && $form->{id} ne "") {
1136     $form->{snumbers}  = qq|invnumber_| . $form->{invnumber};
1137     $form->{addition}  = "STORNO";
1138     $form->{what_done} = "invoice";
1139     $form->save_history;
1140   }
1141   # /saving the history
1142
1143   $form->redirect(sprintf $locale->text("Transaction %d cancelled."), $form->{storno_id});
1144
1145   $main::lxdebug->leave_sub();
1146 }
1147
1148 sub setup_ap_search_action_bar {
1149   my %params = @_;
1150
1151   for my $bar ($::request->layout->get('actionbar')) {
1152     $bar->add(
1153       action => [
1154         $::locale->text('Search'),
1155         submit    => [ '#form', { action => "ap_transactions" } ],
1156         accesskey => 'enter',
1157       ],
1158     );
1159   }
1160 }
1161
1162 sub setup_ap_transactions_action_bar {
1163   my %params = @_;
1164
1165   for my $bar ($::request->layout->get('actionbar')) {
1166     $bar->add(
1167       combobox => [
1168         action => [ t8('Add') ],
1169         link => [
1170           t8('Purchase Invoice'),
1171           link => [ 'ir.pl?action=add' ],
1172         ],
1173         link => [
1174           t8('AP Transaction'),
1175           link => [ 'ap.pl?action=add' ],
1176         ],
1177       ], # end of combobox "Add"
1178     );
1179   }
1180 }
1181
1182 sub setup_ap_display_form_action_bar {
1183   my $transdate               = $::form->datetonum($::form->{transdate}, \%::myconfig);
1184   my $closedto                = $::form->datetonum($::form->{closedto},  \%::myconfig);
1185   my $is_closed               = $transdate <= $closedto;
1186
1187   my $change_never            = $::instance_conf->get_ar_changeable == 0;
1188   my $change_on_same_day_only = $::instance_conf->get_ar_changeable == 2 && ($::form->current_date(\%::myconfig) ne $::form->{gldate});
1189
1190   my $is_storno               = IS->is_storno(\%::myconfig, $::form, 'ap', $::form->{id});
1191   my $has_storno              = IS->has_storno(\%::myconfig, $::form, 'ap');
1192
1193   for my $bar ($::request->layout->get('actionbar')) {
1194     $bar->add(
1195       action => [
1196         t8('Update'),
1197         submit    => [ '#form', { action => "update" } ],
1198         id        => 'update_button',
1199         accesskey => 'enter',
1200       ],
1201
1202       combobox => [
1203         action => [
1204           t8('Post'),
1205           submit   => [ '#form', { action => "post" } ],
1206           checks   => [ 'kivi.AP.check_fields_before_posting' ],
1207           disabled => $is_closed                                  ? t8('The billing period has already been locked.')
1208                     : $is_storno                                  ? t8('A canceled invoice cannot be posted.')
1209                     : ($::form->{id} && $change_never)            ? t8('Changing invoices has been disabled in the configuration.')
1210                     : ($::form->{id} && $change_on_same_day_only) ? t8('Invoices can only be changed on the day they are posted.')
1211                     :                                               undef,
1212         ],
1213         action => [
1214           t8('Post Payment'),
1215           submit   => [ '#form', { action => "post_payment" } ],
1216           disabled => !$::form->{id} ? t8('This invoice has not been posted yet.') : undef,
1217         ],
1218         action => [ t8('Mark as paid'),
1219           submit   => [ '#form', { action => "mark_as_paid" } ],
1220           confirm  => t8('This will remove the invoice from showing as unpaid even if the unpaid amount does not match the amount. Proceed?'),
1221           disabled => !$::form->{id} ? t8('This invoice has not been posted yet.') : undef,
1222           only_if  => $::instance_conf->get_is_show_mark_as_paid,
1223         ],
1224       ], # end of combobox "Post"
1225
1226       combobox => [
1227         action => [ t8('Storno'),
1228           submit   => [ '#form', { action => "storno" } ],
1229           checks   => [ 'kivi.AP.check_fields_before_posting' ],
1230           confirm  => t8('Do you really want to cancel this invoice?'),
1231           disabled => !$::form->{id}         ? t8('This invoice has not been posted yet.')
1232                       : $has_storno          ? t8('This invoice has been canceled already.')
1233                       : $is_storno           ? t8('Reversal invoices cannot be canceled.')
1234                       : $::form->{totalpaid} ? t8('Invoices with payments cannot be canceled.')
1235                       :                        undef,
1236         ],
1237         action => [ t8('Delete'),
1238           submit   => [ '#form', { action => "delete" } ],
1239           confirm  => t8('Do you really want to delete this object?'),
1240           disabled => !$::form->{id}           ? t8('This invoice has not been posted yet.')
1241                     : $change_never            ? t8('Changing invoices has been disabled in the configuration.')
1242                     : $change_on_same_day_only ? t8('Invoices can only be changed on the day they are posted.')
1243                     : $has_storno              ? t8('This invoice has been canceled already.')
1244                     : $is_closed               ? t8('The billing period has already been locked.')
1245                     :                            undef,
1246         ],
1247       ], # end of combobox "Storno"
1248
1249       'separator',
1250
1251       combobox => [
1252         action => [ t8('Workflow') ],
1253         action => [
1254           t8('Use As New'),
1255           submit   => [ '#form', { action => "use_as_new" } ],
1256           disabled => !$::form->{id} ? t8('This invoice has not been posted yet.') : undef,
1257         ],
1258       ], # end of combobox "Workflow"
1259
1260       combobox => [
1261         action => [ t8('more') ],
1262         action => [
1263           t8('History'),
1264           call     => [ 'set_history_window', $::form->{id} * 1, 'glid' ],
1265           disabled => !$::form->{id} ? t8('This invoice has not been posted yet.') : undef,
1266         ],
1267         action => [
1268           t8('Follow-Up'),
1269           call     => [ 'follow_up_window' ],
1270           disabled => !$::form->{id} ? t8('This invoice has not been posted yet.') : undef,
1271         ],
1272         action => [
1273           t8('Record templates'),
1274           call => [ 'kivi.RecordTemplate.popup', 'ap_transaction' ],
1275         ],
1276         action => [
1277           t8('Drafts'),
1278           call     => [ 'kivi.Draft.popup', 'ap', 'invoice', $::form->{draft_id}, $::form->{draft_description} ],
1279           disabled => $::form->{id} ? t8('This invoice has already been posted.')
1280                     : $is_closed    ? t8('The billing period has already been locked.')
1281                     :                 undef,
1282         ],
1283       ], # end of combobox "more"
1284     );
1285   }
1286 }