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