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