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