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