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