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