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