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