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