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