Korrekturen und Vereinheitlichung der Nomenklatur bzgl. Buchungs- und Erfassungsdatum...
[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 @taxcharts       = GL->get_active_taxes_for_chart($amount_chart_id, $transdate);
456
457     foreach my $item (@taxcharts) {
458       my $key             = $item->id . "--" . $item->rate;
459       $first_taxchart   //= $item;
460       $default_taxchart   = $item if $item->{is_default};
461       $taxchart_to_use    = $item if $key eq $form->{"taxchart_$i"};
462     }
463
464     $taxchart_to_use               //= $default_taxchart // $first_taxchart;
465     my $selected_taxchart            = $taxchart_to_use->id . '--' . $taxchart_to_use->rate;
466     $form->{"selected_taxchart_$i"}  = $selected_taxchart;
467     $form->{"AP_amount_chart_id_$i"} = $amount_chart_id;
468     $form->{"taxcharts_$i"}          = \@taxcharts;
469   }
470
471   $form->{taxchart_value_title_sub} = sub {
472     my $item = shift;
473     return [
474       $item->{id} .'--'. $item->{rate},
475       $item->{taxdescription} .' '. ($item->{rate} * 100) .' %',
476     ];
477   };
478
479   $form->{AP_paid_value_title_sub} = sub {
480     my $item = shift;
481     return [
482       $item->{accno},
483       $item->{accno} .'--'. $item->{description}
484     ];
485   };
486
487   $form->{invtotal_unformatted} = $form->{invtotal};
488   $form->{invtotal} = $form->format_amount(\%myconfig, $form->{invtotal}, 2);
489
490   _sort_payments();
491
492   if ( $form->{'paid_'. $form->{paidaccounts}} ) {
493     $form->{paidaccounts}++;
494   }
495
496   # default account for current assets (i.e. 1801 - SKR04)
497   $form->{accno_arap} = IS->get_standard_accno_current_assets(\%myconfig, \%$form);
498
499   for my $i (1 .. $form->{paidaccounts}) {
500     # format amounts
501     if ($form->{"paid_$i"}) {
502       $form->{"paid_$i"} = $form->format_amount(\%myconfig, $form->{"paid_$i"}, 2);
503     }
504     if ($form->{"exchangerate_$i"} == 0) {
505       $form->{"exchangerate_$i"} = "";
506     } else {
507       $form->{"exchangerate_$i"} =
508         $form->format_amount(\%myconfig, $form->{"exchangerate_$i"});
509     }
510
511     my $changeable = 1;
512     if (SL::DB::Default->get->payments_changeable == 0) {
513       # never
514       $changeable = ($form->{"acc_trans_id_$i"})? 0 : 1;
515     }
516     if (SL::DB::Default->get->payments_changeable == 2) {
517       # on the same day
518       $changeable = (($form->{"gldate_$i"} eq '') || $form->current_date(\%myconfig) eq $form->{"gldate_$i"});
519     }
520
521     #deaktivieren von gebuchten Zahlungen ausserhalb der Bücherkontrolle, vorher prüfen ob heute eingegeben
522     if ($form->date_closed($form->{"gldate_$i"})) {
523        $changeable = 0;
524     }
525
526     $form->{'paidaccount_changeable_'. $i} = $changeable;
527
528     $form->{'labelpaid_project_id_'. $i} = $project_labels{$form->{'paid_project_id_'. $i}};
529   }
530
531   $form->{paid_missing} = $form->{invtotal_unformatted} - $form->{totalpaid};
532
533   print $form->parse_html_template('ap/form_header', {
534     today => DateTime->today,
535     currencies => SL::DB::Manager::Currency->get_all_sorted,
536   });
537
538   $main::lxdebug->leave_sub();
539 }
540
541 sub form_footer {
542   $::lxdebug->enter_sub;
543   $::auth->assert('ap_transactions');
544
545   my $num_due;
546   my $num_follow_ups;
547   if ($::form->{id}) {
548     my $follow_ups = FU->follow_ups('trans_id' => $::form->{id}, 'not_done' => 1);
549
550     if (@{ $follow_ups }) {
551       $num_due        = sum map { $_->{due} * 1 } @{ $follow_ups };
552       $num_follow_ups = scalar @{ $follow_ups }
553     }
554   }
555
556   my $transdate = $::form->datetonum($::form->{transdate}, \%::myconfig);
557   my $closedto  = $::form->datetonum($::form->{closedto},  \%::myconfig);
558
559   my $storno = $::form->{id}
560             && !IS->has_storno(\%::myconfig, $::form, 'ap')
561             && !IS->is_storno( \%::myconfig, $::form, 'ap', $::form->{id})
562             && ($::form->{totalpaid} == 0 || $::form->{totalpaid} eq '');
563
564   $::form->header;
565   print $::form->parse_html_template('ap/form_footer', {
566     num_due           => $num_due,
567     num_follow_ups    => $num_follow_ups,
568   });
569
570   $::lxdebug->leave_sub;
571 }
572
573 sub mark_as_paid {
574   $::auth->assert('ap_transactions');
575
576   SL::DB::PurchaseInvoice->new(id => $::form->{id})->load->mark_as_paid;
577
578   $::form->redirect($::locale->text("Marked as paid"));
579 }
580
581 sub show_draft {
582   $::form->{transdate} = DateTime->today_local->to_kivitendo if !$::form->{transdate};
583   $::form->{gldate}    = $::form->{transdate} if !$::form->{gldate};
584   update();
585 }
586
587 sub update {
588   my %params = @_;
589
590   $main::lxdebug->enter_sub();
591
592   my $form     = $main::form;
593   my %myconfig = %main::myconfig;
594
595   $main::auth->assert('ap_transactions');
596
597   my $display = shift;
598
599   $form->{invtotal} = 0;
600
601   delete @{ $form }{ grep { m/^tax_\d+$/ } keys %{ $form } };
602
603   map { $form->{$_} = $form->parse_amount(\%myconfig, $form->{$_}) }
604     qw(exchangerate creditlimit creditremaining);
605
606   my @flds  = qw(amount AP_amount projectnumber oldprojectnumber project_id taxchart);
607   my $count = 0;
608   my (@a, $j, $totaltax);
609   for my $i (1 .. $form->{rowcount}) {
610     $form->{"amount_$i"} = $form->parse_amount(\%myconfig, $form->{"amount_$i"});
611     if ($form->{"amount_$i"} || $params{keep_rows_without_amount}) {
612       push @a, {};
613       $j = $#a;
614       my ($taxkey, $rate) = split(/--/, $form->{"taxchart_$i"});
615
616       # calculate tax exactly the same way as AP in post_transaction via form->calculate_tax
617       my $tmpnetamount;
618       ($tmpnetamount,$form->{"tax_$i"}) = $form->calculate_tax($form->{"amount_$i"},$rate,$form->{taxincluded},2);
619
620       $totaltax += $form->{"tax_$i"};
621       map { $a[$j]->{$_} = $form->{"${_}_$i"} } @flds;
622       $count++;
623     }
624   }
625   $form->redo_rows(\@flds, \@a, $count, $form->{rowcount});
626
627   map { $form->{invtotal} += $form->{"amount_$_"} } (1 .. $form->{rowcount});
628
629   $form->{forex}        = $form->check_exchangerate( \%myconfig, $form->{currency}, $form->{transdate}, 'sell');
630   $form->{exchangerate} = $form->{forex} if $form->{forex};
631
632   $form->{invdate} = $form->{transdate};
633
634   if (($form->{previous_vendor_id} || $form->{vendor_id}) != $form->{vendor_id}) {
635     IR->get_vendor(\%::myconfig, $form);
636     if (($form->{rowcount} == 1) && ($form->{amount_1} == 0)) {
637       my $last_used_ap_chart = SL::DB::Vendor->load_cached($form->{vendor_id})->last_used_ap_chart;
638       $form->{"AP_amount_chart_id_1"} = $last_used_ap_chart->id if $last_used_ap_chart;
639     }
640   }
641
642   $form->{rowcount} = $count + ($params{dont_add_new_row} ? 0 : 1);
643
644   $form->{invtotal} =
645     ($form->{taxincluded}) ? $form->{invtotal} : $form->{invtotal} + $totaltax;
646
647   my $totalpaid;
648   for my $i (1 .. $form->{paidaccounts}) {
649     if ($form->parse_amount(\%myconfig, $form->{"paid_$i"})) {
650       map {
651         $form->{"${_}_$i"} =
652           $form->parse_amount(\%myconfig, $form->{"${_}_$i"})
653       } qw(paid exchangerate);
654
655       $totalpaid += $form->{"paid_$i"};
656
657       $form->{"forex_$i"}        = $form->check_exchangerate( \%myconfig, $form->{currency}, $form->{"datepaid_$i"}, 'sell');
658       $form->{"exchangerate_$i"} = $form->{"forex_$i"} if $form->{"forex_$i"};
659     }
660   }
661
662   $form->{creditremaining} -=
663     ($form->{invtotal} - $totalpaid + $form->{oldtotalpaid} -
664      $form->{oldinvtotal});
665   $form->{oldinvtotal}  = $form->{invtotal};
666   $form->{oldtotalpaid} = $totalpaid;
667
668   display_form();
669
670   $main::lxdebug->leave_sub();
671 }
672
673
674 sub post_payment {
675   $main::lxdebug->enter_sub();
676
677   my $form     = $main::form;
678   my %myconfig = %main::myconfig;
679   my $locale   = $main::locale;
680
681   $main::auth->assert('ap_transactions');
682   $form->mtime_ischanged('ap');
683
684   $form->{defaultcurrency} = $form->get_default_currency(\%myconfig);
685
686   my $invdate = $form->datetonum($form->{transdate}, \%myconfig);
687
688   for my $i (1 .. $form->{paidaccounts}) {
689     if ($form->parse_amount(\%myconfig, $form->{"paid_$i"})) {
690       my $datepaid = $form->datetonum($form->{"datepaid_$i"}, \%myconfig);
691
692       $form->isblank("datepaid_$i", $locale->text('Payment date missing!'));
693
694       $form->error($locale->text('Cannot post transaction above the maximum future booking date!'))
695         if ($form->date_max_future($form->{"datepaid_$i"}, \%myconfig));
696
697       #Zusätzlich noch das Buchungsdatum in die Bücherkontrolle einbeziehen
698       # (Dient zur Prüfung ob ZE oder ZA geprüft werden soll)
699       $form->error($locale->text('Cannot post payment for a closed period!'))
700         if ($form->date_closed($form->{"datepaid_$i"})  && !$form->date_closed($form->{"gldate_$i"}, \%myconfig));
701
702       if ($form->{defaultcurrency} && ($form->{currency} ne $form->{defaultcurrency})) {
703         $form->{"exchangerate_$i"} = $form->{exchangerate}
704           if ($invdate == $datepaid);
705         $form->isblank("exchangerate_$i",
706                        $locale->text('Exchangerate for payment missing!'));
707       }
708     }
709   }
710
711   ($form->{AP})      = split /--/, $form->{AP};
712   ($form->{AP_paid}) = split /--/, $form->{AP_paid};
713   if (AP->post_payment(\%myconfig, \%$form)) {
714     $form->{snumbers}  = qq|invnumber_| . $form->{invnumber};
715     $form->{what_done} = 'invoice';
716     $form->{addition}  = "PAYMENT POSTED";
717     $form->save_history;
718     $form->redirect($locale->text('Payment posted!'))
719   } else {
720     $form->error($locale->text('Cannot post payment!'));
721   };
722
723
724   $main::lxdebug->leave_sub();
725 }
726
727
728 sub post {
729   $main::lxdebug->enter_sub();
730
731   my $form     = $main::form;
732   my %myconfig = %main::myconfig;
733   my $locale   = $main::locale;
734
735   $main::auth->assert('ap_transactions');
736   $form->mtime_ischanged('ap');
737
738   my ($inline) = @_;
739
740   # check if there is a vendor, invoice, due date and invnumber
741   $form->isblank("transdate", $locale->text("Invoice Date missing!"));
742   $form->isblank("duedate",   $locale->text("Due Date missing!"));
743   $form->isblank("vendor_id", $locale->text('Vendor missing!'));
744   $form->isblank("invnumber", $locale->text('Invoice Number missing!'));
745
746   if ($myconfig{mandatory_departments} && !$form->{department_id}) {
747     $form->{saved_message} = $::locale->text('You have to specify a department.');
748     update();
749     exit;
750   }
751
752   my $closedto  = $form->datetonum($form->{closedto},  \%myconfig);
753   my $transdate = $form->datetonum($form->{transdate}, \%myconfig);
754
755   $form->error($locale->text('Cannot post transaction above the maximum future booking date!'))
756     if ($form->date_max_future($form->{"transdate"}, \%myconfig));
757   $form->error($locale->text('Cannot post transaction for a closed period!')) if ($form->date_closed($form->{"transdate"}, \%myconfig));
758
759   my $zero_amount_posting = 1;
760   for my $i (1 .. $form->{rowcount}) {
761     if ($form->parse_amount(\%myconfig, $form->{"amount_$i"})) {
762       $zero_amount_posting = 0;
763       last;
764     }
765   }
766
767   $form->error($locale->text('Zero amount posting!')) if $zero_amount_posting;
768
769   $form->isblank("exchangerate", $locale->text('Exchangerate missing!'))
770     if ($form->{defaultcurrency} && ($form->{currency} ne $form->{defaultcurrency}));
771   delete($form->{AP});
772
773   for my $i (1 .. $form->{paidaccounts}) {
774     if ($form->parse_amount(\%myconfig, $form->{"paid_$i"})) {
775       my $datepaid = $form->datetonum($form->{"datepaid_$i"}, \%myconfig);
776
777       $form->isblank("datepaid_$i", $locale->text('Payment date missing!'));
778
779       $form->error($locale->text('Cannot post transaction above the maximum future booking date!'))
780       if ($form->date_max_future($form->{"datepaid_$i"}, \%myconfig));
781
782       #Zusätzlich noch das Buchungsdatum in die Bücherkontrolle einbeziehen
783       # (Dient zur Prüfung ob ZE oder ZA geprüft werden soll)
784       $form->error($locale->text('Cannot post payment for a closed period!'))
785         if ($form->date_closed($form->{"datepaid_$i"})  && !$form->date_closed($form->{"gldate_$i"}, \%myconfig));
786
787       if ($form->{defaultcurrency} && ($form->{currency} ne $form->{defaultcurrency})) {
788         $form->{"exchangerate_$i"} = $form->{exchangerate}
789           if ($transdate == $datepaid);
790         $form->isblank("exchangerate_$i",
791                        $locale->text('Exchangerate for payment missing!'));
792       }
793
794     }
795   }
796
797   # if old vendor ne vendor redo form
798   if (($form->{previous_customer_id} || $form->{customer_id}) != $form->{customer_id}) {
799     &update;
800     $::dispatcher->end_request;
801   }
802   $form->{storno}       = 0;
803
804   $form->{id} = 0 if $form->{postasnew};
805
806   if (AP->post_transaction(\%myconfig, \%$form)) {
807     # create webdav folder
808     if ($::instance_conf->get_webdav) {
809       SL::Webdav->new(type     => 'accounts_payable',
810                       number   => $form->{invnumber},
811                      )->webdav_path;
812     }
813     # saving the history
814     if(!exists $form->{addition} && $form->{id} ne "") {
815       $form->{snumbers}  = qq|invnumber_| . $form->{invnumber};
816       $form->{addition}  = "POSTED";
817       $form->{what_done} = "invoice";
818       $form->save_history;
819     }
820     # /saving the history
821     # Dieser Text wird niemals ausgegeben: Probleme beim redirect?
822     $form->redirect($locale->text('AP transaction posted.')) unless $inline;
823   } else {
824     $form->error($locale->text('Cannot post transaction!'));
825   }
826
827   $main::lxdebug->leave_sub();
828 }
829
830 sub post_as_new {
831   $main::lxdebug->enter_sub();
832
833   my $form     = $main::form;
834   my %myconfig = %main::myconfig;
835
836   $main::auth->assert('ap_transactions');
837
838   $form->{postasnew} = 1;
839   # saving the history
840   if(!exists $form->{addition} && $form->{id} ne "") {
841     # does this work? post_as_new for ap doesn't immediately save the
842     # invoice, because the invnumber has to be entered by hand.
843     # And the value of $form->{postasnew} isn't checked when calling post
844     $form->{snumbers}  = qq|invnumber_| . $form->{invnumber};
845     $form->{addition}  = "POSTED AS NEW";
846     $form->{what_done} = "invoice";
847     $form->save_history;
848   }
849   # /saving the history
850   &post;
851
852   $main::lxdebug->leave_sub();
853 }
854
855 sub use_as_new {
856   $main::lxdebug->enter_sub();
857
858   my $form     = $main::form;
859   my %myconfig = %main::myconfig;
860
861   $main::auth->assert('ap_transactions');
862
863   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);
864   $form->{paidaccounts} = 1;
865   $form->{rowcount}--;
866
867   my $today          = DateTime->today_local;
868   $form->{transdate} = $today->to_kivitendo;
869   $form->{duedate}   = $form->{transdate};
870
871   if ($form->{vendor_id}) {
872     my $payment_terms = SL::DB::Vendor->load_cached($form->{vendor_id})->payment;
873     $form->{duedate}  = $payment_terms->calc_date(reference_date => $today)->to_kivitendo if $payment_terms;
874   }
875
876   &update;
877
878   $main::lxdebug->leave_sub();
879 }
880
881 sub delete {
882   my $form     = $main::form;
883   my %myconfig = %main::myconfig;
884   my $locale   = $main::locale;
885
886   $main::auth->assert('ap_transactions');
887
888   if (AP->delete_transaction(\%myconfig, \%$form)) {
889     # saving the history
890     if(!exists $form->{addition}) {
891       $form->{snumbers}  = qq|invnumber_| . $form->{invnumber};
892       $form->{addition}  = "DELETED";
893       $form->{what_done} = "invoice";
894       $form->save_history;
895     }
896     # /saving the history
897     $form->redirect($locale->text('Transaction deleted!'));
898   }
899   $form->error($locale->text('Cannot delete transaction!'));
900 }
901
902 sub search {
903   $main::lxdebug->enter_sub();
904
905   $main::auth->assert('vendor_invoice_edit');
906
907   my $form     = $main::form;
908   my %myconfig = %main::myconfig;
909   my $locale   = $main::locale;
910
911   $form->{title} = $locale->text('Vendor Invoices & AP Transactions');
912
913   $form->get_lists(projects => { "key" => "ALL_PROJECTS", "all" => 1 });
914
915   $::form->{ALL_DEPARTMENTS} = SL::DB::Manager::Department->get_all_sorted;
916   # constants and subs for template
917   $form->{vc_keys}   = sub { "$_[0]->{name}--$_[0]->{id}" };
918
919   $::request->layout->add_javascripts("autocomplete_project.js");
920
921   setup_ap_search_action_bar();
922
923   $form->header;
924   print $form->parse_html_template('ap/search', { %myconfig });
925
926   $main::lxdebug->leave_sub();
927 }
928
929 sub create_subtotal_row {
930   $main::lxdebug->enter_sub();
931
932   my ($totals, $columns, $column_alignment, $subtotal_columns, $class) = @_;
933
934   my $form     = $main::form;
935   my %myconfig = %main::myconfig;
936
937   my $row = { map { $_ => { 'data' => '', 'class' => $class, 'align' => $column_alignment->{$_}, } } @{ $columns } };
938
939   map { $row->{$_}->{data} = $form->format_amount(\%myconfig, $totals->{$_}, 2) } @{ $subtotal_columns };
940
941   $row->{tax}->{data} = $form->format_amount(\%myconfig, $totals->{amount} - $totals->{netamount}, 2);
942
943   map { $totals->{$_} = 0 } @{ $subtotal_columns };
944
945   $main::lxdebug->leave_sub();
946
947   return $row;
948 }
949
950 sub ap_transactions {
951   $main::lxdebug->enter_sub();
952
953   my $form     = $main::form;
954   my %myconfig = %main::myconfig;
955   my $locale   = $main::locale;
956
957   $main::auth->assert('vendor_invoice_edit');
958
959   report_generator_set_default_sort('transdate', 1);
960
961   AP->ap_transactions(\%myconfig, \%$form);
962
963   $form->{title} = $locale->text('Vendor Invoices & AP Transactions');
964
965   my $report = SL::ReportGenerator->new(\%myconfig, $form);
966
967   my @columns =
968     qw(transdate id type invnumber ordnumber name netamount tax amount paid datepaid
969        due duedate transaction_description notes employee globalprojectnumber
970        vendornumber country ustid taxzone payment_terms charts direct_debit);
971
972   my @hidden_variables = map { "l_${_}" } @columns;
973   push @hidden_variables, "l_subtotal", qw(open closed vendor invnumber ordnumber transaction_description notes project_id transdatefrom transdateto
974                                            parts_partnumber parts_description);
975
976   my $href = build_std_url('action=ap_transactions', grep { $form->{$_} } @hidden_variables);
977
978   my %column_defs = (
979     'transdate'               => { 'text' => $locale->text('Date'), },
980     'id'                      => { 'text' => $locale->text('ID'), },
981     'type'                    => { 'text' => $locale->text('Type'), },
982     'invnumber'               => { 'text' => $locale->text('Invoice'), },
983     'ordnumber'               => { 'text' => $locale->text('Order'), },
984     'name'                    => { 'text' => $locale->text('Vendor'), },
985     'netamount'               => { 'text' => $locale->text('Amount'), },
986     'tax'                     => { 'text' => $locale->text('Tax'), },
987     'amount'                  => { 'text' => $locale->text('Total'), },
988     'paid'                    => { 'text' => $locale->text('Paid'), },
989     'datepaid'                => { 'text' => $locale->text('Date Paid'), },
990     'due'                     => { 'text' => $locale->text('Amount Due'), },
991     'duedate'                 => { 'text' => $locale->text('Due Date'), },
992     'transaction_description' => { 'text' => $locale->text('Transaction description'), },
993     'notes'                   => { 'text' => $locale->text('Notes'), },
994     'employee'                => { 'text' => $locale->text('Employee'), },
995     'globalprojectnumber'     => { 'text' => $locale->text('Document Project Number'), },
996     'vendornumber'            => { 'text' => $locale->text('Vendor Number'), },
997     'country'                 => { 'text' => $locale->text('Country'), },
998     'ustid'                   => { 'text' => $locale->text('USt-IdNr.'), },
999     'taxzone'                 => { 'text' => $locale->text('Tax rate'), },
1000     'payment_terms'           => { 'text' => $locale->text('Payment Terms'), },
1001     'charts'                  => { 'text' => $locale->text('Chart'), },
1002     'direct_debit'            => { 'text' => $locale->text('direct debit'), },
1003   );
1004
1005   foreach my $name (qw(id transdate duedate invnumber ordnumber name datepaid employee shippingpoint shipvia transaction_description direct_debit)) {
1006     my $sortdir                 = $form->{sort} eq $name ? 1 - $form->{sortdir} : $form->{sortdir};
1007     $column_defs{$name}->{link} = $href . "&sort=$name&sortdir=$sortdir";
1008   }
1009
1010   my %column_alignment = map { $_ => 'right' } qw(netamount tax amount paid due);
1011
1012   $form->{"l_type"} = "Y";
1013   map { $column_defs{$_}->{visible} = $form->{"l_${_}"} ? 1 : 0 } @columns;
1014
1015   $report->set_columns(%column_defs);
1016   $report->set_column_order(@columns);
1017
1018   $report->set_export_options('ap_transactions', @hidden_variables, qw(sort sortdir));
1019
1020   $report->set_sort_indicator($form->{sort}, $form->{sortdir});
1021
1022   my @options;
1023   push @options, $locale->text('Vendor')                  . " : $form->{vendor}"                         if ($form->{vendor});
1024   push @options, $locale->text('Contact Person')          . " : $form->{cp_name}"                        if ($form->{cp_name});
1025   push @options, $locale->text('Department')              . " : $form->{department}"                     if ($form->{department});
1026   push @options, $locale->text('Invoice Number')          . " : $form->{invnumber}"                      if ($form->{invnumber});
1027   push @options, $locale->text('Order Number')            . " : $form->{ordnumber}"                      if ($form->{ordnumber});
1028   push @options, $locale->text('Notes')                   . " : $form->{notes}"                          if ($form->{notes});
1029   push @options, $locale->text('Transaction description') . " : $form->{transaction_description}"        if ($form->{transaction_description});
1030   push @options, $locale->text('Part Description')        . " : $form->{parts_description}"              if $form->{parts_description};
1031   push @options, $locale->text('Part Number')             . " : $form->{parts_partnumber}"               if $form->{parts_partnumber};
1032   push @options, $locale->text('From') . " " . $locale->date(\%myconfig, $form->{transdatefrom}, 1)      if ($form->{transdatefrom});
1033   push @options, $locale->text('Bis')  . " " . $locale->date(\%myconfig, $form->{transdateto},   1)      if ($form->{transdateto});
1034   push @options, $locale->text('Open')                                                                   if ($form->{open});
1035   push @options, $locale->text('Closed')                                                                 if ($form->{closed});
1036
1037   $report->set_options('top_info_text'        => join("\n", @options),
1038                        'output_format'        => 'HTML',
1039                        'title'                => $form->{title},
1040                        'attachment_basename'  => $locale->text('vendor_invoice_list') . strftime('_%Y%m%d', localtime time),
1041     );
1042   $report->set_options_from_form();
1043   $locale->set_numberformat_wo_thousands_separator(\%myconfig) if lc($report->{options}->{output_format}) eq 'csv';
1044
1045   # add sort and escape callback, this one we use for the add sub
1046   $form->{callback} = $href .= "&sort=$form->{sort}";
1047
1048   # escape callback for href
1049   my $callback = $form->escape($href);
1050
1051   my @subtotal_columns = qw(netamount amount paid due);
1052
1053   my %totals    = map { $_ => 0 } @subtotal_columns;
1054   my %subtotals = map { $_ => 0 } @subtotal_columns;
1055
1056   my $idx = 0;
1057
1058   foreach my $ap (@{ $form->{AP} }) {
1059     $ap->{tax} = $ap->{amount} - $ap->{netamount};
1060     $ap->{due} = $ap->{amount} - $ap->{paid};
1061
1062     map { $subtotals{$_} += $ap->{$_};
1063           $totals{$_}    += $ap->{$_} } @subtotal_columns;
1064
1065     map { $ap->{$_} = $form->format_amount(\%myconfig, $ap->{$_}, 2) } qw(netamount tax amount paid due);
1066
1067     my $is_storno  = $ap->{storno} &&  $ap->{storno_id};
1068     my $has_storno = $ap->{storno} && !$ap->{storno_id};
1069
1070     if ($ap->{invoice}) {
1071       $ap->{type} =
1072           $has_storno       ? $locale->text("Invoice with Storno (abbreviation)")
1073         : $is_storno        ? $locale->text("Storno (one letter abbreviation)")
1074         :                     $locale->text("Invoice (one letter abbreviation)");
1075     } else {
1076       $ap->{type} =
1077           $has_storno       ? $locale->text("AP Transaction with Storno (abbreviation)")
1078         : $is_storno        ? $locale->text("AP Transaction Storno (one letter abbreviation)")
1079         :                     $locale->text("AP Transaction (abbreviation)");
1080     }
1081
1082     $ap->{direct_debit} = $ap->{direct_debit} ? $::locale->text('yes') : $::locale->text('no');
1083
1084     my $row = { };
1085
1086     foreach my $column (@columns) {
1087       $row->{$column} = {
1088         'data'  => $ap->{$column},
1089         'align' => $column_alignment{$column},
1090       };
1091     }
1092
1093     $row->{invnumber}->{link} = build_std_url("script=" . ($ap->{invoice} ? 'ir.pl' : 'ap.pl'), 'action=edit')
1094       . "&id=" . E($ap->{id}) . "&callback=${callback}";
1095
1096     my $row_set = [ $row ];
1097
1098     if (($form->{l_subtotal} eq 'Y')
1099         && (($idx == (scalar @{ $form->{AP} } - 1))
1100             || ($ap->{ $form->{sort} } ne $form->{AP}->[$idx + 1]->{ $form->{sort} }))) {
1101       push @{ $row_set }, create_subtotal_row(\%subtotals, \@columns, \%column_alignment, \@subtotal_columns, 'listsubtotal');
1102     }
1103
1104     $report->add_data($row_set);
1105
1106     $idx++;
1107   }
1108
1109   $report->add_separator();
1110   $report->add_data(create_subtotal_row(\%totals, \@columns, \%column_alignment, \@subtotal_columns, 'listtotal'));
1111
1112   setup_ap_transactions_action_bar();
1113   $report->generate_with_headers();
1114
1115   $main::lxdebug->leave_sub();
1116 }
1117
1118 sub storno {
1119   $main::lxdebug->enter_sub();
1120
1121   my $form     = $main::form;
1122   my %myconfig = %main::myconfig;
1123   my $locale   = $main::locale;
1124
1125   $main::auth->assert('ap_transactions');
1126
1127   if (IS->has_storno(\%myconfig, $form, 'ap')) {
1128     $form->{title} = $locale->text("Cancel Accounts Payables Transaction");
1129     $form->error($locale->text("Transaction has already been cancelled!"));
1130   }
1131
1132   $form->error($locale->text('Cannot post storno for a closed period!'))
1133     if ( $form->date_closed($form->{transdate}, \%myconfig));
1134
1135   AP->storno($form, \%myconfig, $form->{id});
1136
1137   # saving the history
1138   if(!exists $form->{addition} && $form->{id} ne "") {
1139     $form->{snumbers}  = qq|invnumber_| . $form->{invnumber};
1140     $form->{addition}  = "STORNO";
1141     $form->{what_done} = "invoice";
1142     $form->save_history;
1143   }
1144   # /saving the history
1145
1146   $form->redirect(sprintf $locale->text("Transaction %d cancelled."), $form->{storno_id});
1147
1148   $main::lxdebug->leave_sub();
1149 }
1150
1151 sub setup_ap_search_action_bar {
1152   my %params = @_;
1153
1154   for my $bar ($::request->layout->get('actionbar')) {
1155     $bar->add(
1156       action => [
1157         $::locale->text('Search'),
1158         submit    => [ '#form', { action => "ap_transactions" } ],
1159         accesskey => 'enter',
1160       ],
1161     );
1162   }
1163 }
1164
1165 sub setup_ap_transactions_action_bar {
1166   my %params = @_;
1167
1168   for my $bar ($::request->layout->get('actionbar')) {
1169     $bar->add(
1170       combobox => [
1171         action => [ t8('Add') ],
1172         link => [
1173           t8('Purchase Invoice'),
1174           link => [ 'ir.pl?action=add' ],
1175         ],
1176         link => [
1177           t8('AP Transaction'),
1178           link => [ 'ap.pl?action=add' ],
1179         ],
1180       ], # end of combobox "Add"
1181     );
1182   }
1183 }
1184
1185 sub setup_ap_display_form_action_bar {
1186   my $transdate               = $::form->datetonum($::form->{transdate}, \%::myconfig);
1187   my $closedto                = $::form->datetonum($::form->{closedto},  \%::myconfig);
1188   my $is_closed               = $transdate <= $closedto;
1189
1190   my $change_never            = $::instance_conf->get_ar_changeable == 0;
1191   my $change_on_same_day_only = $::instance_conf->get_ar_changeable == 2 && ($::form->current_date(\%::myconfig) ne $::form->{gldate});
1192
1193   my $is_storno               = IS->is_storno(\%::myconfig, $::form, 'ap', $::form->{id});
1194   my $has_storno              = IS->has_storno(\%::myconfig, $::form, 'ap');
1195
1196   for my $bar ($::request->layout->get('actionbar')) {
1197     $bar->add(
1198       action => [
1199         t8('Update'),
1200         submit    => [ '#form', { action => "update" } ],
1201         id        => 'update_button',
1202         accesskey => 'enter',
1203       ],
1204
1205       combobox => [
1206         action => [
1207           t8('Post'),
1208           submit   => [ '#form', { action => "post" } ],
1209           checks   => [ 'kivi.AP.check_fields_before_posting' ],
1210           disabled => $is_closed                                  ? t8('The billing period has already been locked.')
1211                     : $is_storno                                  ? t8('A canceled invoice cannot be posted.')
1212                     : ($::form->{id} && $change_never)            ? t8('Changing invoices has been disabled in the configuration.')
1213                     : ($::form->{id} && $change_on_same_day_only) ? t8('Invoices can only be changed on the day they are posted.')
1214                     :                                               undef,
1215         ],
1216         action => [
1217           t8('Post Payment'),
1218           submit   => [ '#form', { action => "post_payment" } ],
1219           disabled => !$::form->{id} ? t8('This invoice has not been posted yet.') : undef,
1220         ],
1221         action => [ t8('Mark as paid'),
1222           submit   => [ '#form', { action => "mark_as_paid" } ],
1223           confirm  => t8('This will remove the invoice from showing as unpaid even if the unpaid amount does not match the amount. Proceed?'),
1224           disabled => !$::form->{id} ? t8('This invoice has not been posted yet.') : undef,
1225           only_if  => $::instance_conf->get_is_show_mark_as_paid,
1226         ],
1227       ], # end of combobox "Post"
1228
1229       combobox => [
1230         action => [ t8('Storno'),
1231           submit   => [ '#form', { action => "storno" } ],
1232           checks   => [ 'kivi.AP.check_fields_before_posting' ],
1233           confirm  => t8('Do you really want to cancel this invoice?'),
1234           disabled => !$::form->{id}         ? t8('This invoice has not been posted yet.')
1235                       : $has_storno          ? t8('This invoice has been canceled already.')
1236                       : $is_storno           ? t8('Reversal invoices cannot be canceled.')
1237                       : $::form->{totalpaid} ? t8('Invoices with payments cannot be canceled.')
1238                       :                        undef,
1239         ],
1240         action => [ t8('Delete'),
1241           submit   => [ '#form', { action => "delete" } ],
1242           confirm  => t8('Do you really want to delete this object?'),
1243           disabled => !$::form->{id}           ? t8('This invoice has not been posted yet.')
1244                     : $change_never            ? t8('Changing invoices has been disabled in the configuration.')
1245                     : $change_on_same_day_only ? t8('Invoices can only be changed on the day they are posted.')
1246                     : $has_storno              ? t8('This invoice has been canceled already.')
1247                     : $is_closed               ? t8('The billing period has already been locked.')
1248                     :                            undef,
1249         ],
1250       ], # end of combobox "Storno"
1251
1252       'separator',
1253
1254       combobox => [
1255         action => [ t8('Workflow') ],
1256         action => [
1257           t8('Use As New'),
1258           submit   => [ '#form', { action => "use_as_new" } ],
1259           disabled => !$::form->{id} ? t8('This invoice has not been posted yet.') : undef,
1260         ],
1261       ], # end of combobox "Workflow"
1262
1263       combobox => [
1264         action => [ t8('more') ],
1265         action => [
1266           t8('History'),
1267           call     => [ 'set_history_window', $::form->{id} * 1, 'glid' ],
1268           disabled => !$::form->{id} ? t8('This invoice has not been posted yet.') : undef,
1269         ],
1270         action => [
1271           t8('Follow-Up'),
1272           call     => [ 'follow_up_window' ],
1273           disabled => !$::form->{id} ? t8('This invoice has not been posted yet.') : undef,
1274         ],
1275         action => [
1276           t8('Record templates'),
1277           call => [ 'kivi.RecordTemplate.popup', 'ap_transaction' ],
1278         ],
1279         action => [
1280           t8('Drafts'),
1281           call     => [ 'kivi.Draft.popup', 'ap', 'invoice', $::form->{draft_id}, $::form->{draft_description} ],
1282           disabled => $::form->{id} ? t8('This invoice has already been posted.')
1283                     : $is_closed    ? t8('The billing period has already been locked.')
1284                     :                 undef,
1285         ],
1286       ], # end of combobox "more"
1287     );
1288   }
1289 }