1 #=====================================================================
4 # Based on SQL-Ledger Version 2.1.9
5 # Web http://www.lx-office.org
7 #=====================================================================
8 # SQL-Ledger Accounting
11 # Author: Dieter Simader
12 # Email: dsimader@sql-ledger.org
13 # Web: http://www.sql-ledger.org
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.
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,
29 #======================================================================
33 #======================================================================
35 use POSIX qw(strftime);
36 use List::Util qw(first max sum);
37 use List::UtilsBy qw(sort_by);
42 use SL::Helper::Flash qw(flash flash_later);
45 use SL::ReportGenerator;
46 use SL::DB::BankTransactionAccTrans;
50 use SL::DB::InvoiceItem;
52 use SL::DB::PaymentTerm;
53 use SL::DB::PurchaseInvoice;
54 use SL::DB::RecordTemplate;
56 use SL::DB::EmailJournal;
57 use SL::DB::ValidityToken;
58 use SL::Presenter::ItemsList;
61 use SL::Locale::String qw(t8);
63 require "bin/mozilla/common.pl";
64 require "bin/mozilla/reportgenerator.pl";
72 # this is for our long dates
73 # $locale->text('January')
74 # $locale->text('February')
75 # $locale->text('March')
76 # $locale->text('April')
77 # $locale->text('May ')
78 # $locale->text('June')
79 # $locale->text('July')
80 # $locale->text('August')
81 # $locale->text('September')
82 # $locale->text('October')
83 # $locale->text('November')
84 # $locale->text('December')
86 # this is for our short month
87 # $locale->text('Jan')
88 # $locale->text('Feb')
89 # $locale->text('Mar')
90 # $locale->text('Apr')
91 # $locale->text('May')
92 # $locale->text('Jun')
93 # $locale->text('Jul')
94 # $locale->text('Aug')
95 # $locale->text('Sep')
96 # $locale->text('Oct')
97 # $locale->text('Nov')
98 # $locale->text('Dec')
100 sub _may_view_or_edit_this_invoice {
101 return 1 if $::auth->assert('ap_transactions', 1); # may edit all invoices
102 return 0 if !$::form->{id}; # creating new invoices isn't allowed without invoice_edit
103 return 0 if !$::form->{globalproject_id}; # existing records without a project ID are not allowed
104 return SL::DB::Project->new(id => $::form->{globalproject_id})->load->may_employee_view_project_invoices(SL::DB::Manager::Employee->current);
108 my $cache = $::request->cache('ap.pl::_assert_access');
110 $cache->{_may_view_or_edit_this_invoice} = _may_view_or_edit_this_invoice() if !exists $cache->{_may_view_or_edit_this_invoice};
111 $::form->show_generic_error($::locale->text("You do not have the permissions to access this function.")) if ! $cache->{_may_view_or_edit_this_invoice};
115 $::auth->assert('ap_transactions');
117 my $file_name = $::form->{form_defaults}->{zugferd_session_file};
119 flash('info', $::locale->text(
120 "The ZUGFeRD/Factur-X invoice '#1' has been loaded.", $file_name));
124 $template_ap ||= SL::DB::RecordTemplate->new(id => $::form->{record_template_id})->load()
125 if $::form->{record_template_id};
126 $template_ap ||= SL::DB::Manager::RecordTemplate->get_first(where => [vendor_id => $::form->{form_defaults}->{vendor_id}])
127 if $::form->{form_defaults}->{vendor_id};
129 $::form->{id} = $template_ap->id;
130 # set default values for items
131 my $template_item = $template_ap->items->[0];
132 my $chart = SL::DB::Chart->new(id => $template_item->chart_id)->load();
133 my $tax = SL::DB::Tax->new(id => $template_item->tax_id)->load();
134 foreach my $pos (1 .. $::form->{form_defaults}->{rowcount}) {
135 $::form->{form_defaults}->{"AP_amount_chart_id_$pos"} = $chart->id;
136 $::form->{form_defaults}->{"previous_AP_amount_chart_id_$pos"} = $chart->id;
137 $::form->{form_defaults}->{"taxchart_$pos"} = $tax->id . '--' . $tax->rate;
138 $::form->{form_defaults}->{"project_id_$pos"} = $template_item->project_id;
141 $::form->{form_defaults}->{FLASH} = $::form->{FLASH}; # store flash, form gets cleared
142 return load_record_template();
144 flash('warning', $::locale->text(
145 "No AP Record Template for vendor '#1' found.", $::form->{form_defaults}->{vendor}));
148 my $form_defaults = delete $::form->{form_defaults};
149 $::form->{$_} = $form_defaults->{$_} for keys %{ $form_defaults // {} };
150 $::form->{title} ||= "Add";
151 $::form->{form_validity_token} = SL::DB::ValidityToken->create(scope => SL::DB::ValidityToken::SCOPE_PURCHASE_INVOICE_POST())->token;
153 keep_rows_without_amount => 1,
154 dont_add_new_row => 1,
158 sub load_record_template {
159 $::auth->assert('ap_transactions');
161 # Load existing template and verify that its one for this module.
162 my $template = SL::DB::RecordTemplate
163 ->new(id => $::form->{id})
165 with_object => [ qw(customer payment currency record_items record_items.chart) ],
168 die "invalid template type" unless $template->template_type eq 'ap_transaction';
170 $template->substitute_variables;
172 # Clean the current $::form before rebuilding it from the template.
173 my $form_defaults = delete $::form->{form_defaults};
174 delete @{ $::form }{ grep { !m{^(?:script|login)$}i } keys %{ $::form } };
176 # Fill $::form from the template.
177 my $today = DateTime->today_local;
178 $::form->{title} = "Add";
179 $::form->{currency} = $template->currency->name;
180 $::form->{direct_debit} = $template->direct_debit;
181 $::form->{globalproject_id} = $template->project_id;
182 $::form->{payment_id} = $template->payment_id;
183 $::form->{AP_chart_id} = $template->ar_ap_chart_id;
184 $::form->{transdate} = $today->to_kivitendo;
185 $::form->{duedate} = $today->to_kivitendo;
186 $::form->{rowcount} = @{ $template->items };
187 $::form->{paidaccounts} = 1;
188 $::form->{$_} = $template->$_ for qw(department_id ordnumber taxincluded notes transaction_description);
190 if ($template->vendor) {
191 $::form->{vendor_id} = $template->vendor_id;
192 $::form->{vendor} = $template->vendor->name;
193 $::form->{duedate} = $template->vendor->payment->calc_date(reference_date => $today)->to_kivitendo if $template->vendor->payment;
197 foreach my $item (@{ $template->items }) {
200 my $active_taxkey = $item->chart->get_active_taxkey;
201 my $taxes = SL::DB::Manager::Tax->get_all(
202 where => [ chart_categories => { like => '%' . $item->chart->category . '%' }],
203 sort_by => 'taxkey, rate',
206 my $tax = first { $item->tax_id == $_->id } @{ $taxes };
207 $tax //= first { $active_taxkey->tax_id == $_->id } @{ $taxes };
208 $tax //= $taxes->[0];
215 $::form->{"AP_amount_chart_id_${row}"} = $item->chart_id;
216 $::form->{"previous_AP_amount_chart_id_${row}"} = $item->chart_id;
217 $::form->{"amount_${row}"} = $::form->format_amount(\%::myconfig, $item->amount1, 2);
218 $::form->{"taxchart_${row}"} = $item->tax_id . '--' . $tax->rate;
219 $::form->{"project_id_${row}"} = $item->project_id;
222 $::form->{$_} = $form_defaults->{$_} for keys %{ $form_defaults // {} };
224 flash('info', $::locale->text("The record template '#1' has been loaded.", $template->template_name));
225 flash('info', $::locale->text("Payment bookings disallowed. After the booking this record may be " .
226 "suggested with the amount of '#1' or otherwise has to be choosen manually." .
227 " No automatic payment booking will be done to chart '#2'.",
228 $form_defaults->{paid_1_suggestion},
229 $form_defaults->{AP_paid_1_suggestion},
230 )) if $::form->{no_payment_bookings};
232 $::form->{form_validity_token} = SL::DB::ValidityToken->create(scope => SL::DB::ValidityToken::SCOPE_PURCHASE_INVOICE_POST())->token;
235 keep_rows_without_amount => 1,
236 dont_add_new_row => 1,
240 sub save_record_template {
241 $::auth->assert('ap_transactions');
243 my $template = $::form->{record_template_id} ? SL::DB::RecordTemplate->new(id => $::form->{record_template_id})->load : SL::DB::RecordTemplate->new;
244 my $js = SL::ClientJS->new(controller => SL::Controller::Base->new);
245 my $new_name = $template->template_name_to_use($::form->{record_template_new_template_name});
247 $js->dialog->close('#record_template_dialog');
250 $_->{chart_id} && (($_->{tax_id} // '') ne '')
252 +{ chart_id => $::form->{"AP_amount_chart_id_${_}"},
253 amount1 => $::form->parse_amount(\%::myconfig, $::form->{"amount_${_}"}),
254 tax_id => (split m{--}, $::form->{"taxchart_${_}"})[0],
255 project_id => $::form->{"project_id_${_}"} || undef,
257 } (1..($::form->{rowcount} || 1));
259 $template->assign_attributes(
260 template_type => 'ap_transaction',
261 template_name => $new_name,
263 currency_id => SL::DB::Manager::Currency->find_by(name => $::form->{currency})->id,
264 ar_ap_chart_id => $::form->{AP_chart_id} || undef,
265 vendor_id => $::form->{vendor_id} || undef,
266 department_id => $::form->{department_id} || undef,
267 project_id => $::form->{globalproject_id} || undef,
268 payment_id => $::form->{payment_id} || undef,
269 taxincluded => $::form->{taxincluded} ? 1 : 0,
270 direct_debit => $::form->{direct_debit} ? 1 : 0,
271 ordnumber => $::form->{ordnumber},
272 notes => $::form->{notes},
273 transaction_description => $::form->{transaction_description},
283 ->flash('error', $::locale->text("Saving the record template '#1' failed.", $new_name))
288 ->flash('info', $::locale->text("The record template '#1' has been saved.", $new_name))
293 $main::lxdebug->enter_sub();
295 my $form = $main::form;
296 my %myconfig = %main::myconfig;
298 $main::auth->assert('ap_transactions');
300 $form->{title} = "Add";
302 $form->{callback} = "ap.pl?action=add" unless $form->{callback};
304 AP->get_transdate(\%myconfig, $form);
305 $form->{initial_transdate} = $form->{transdate};
306 $form->{initial_vendor_id} = $form->{vendor_id};
307 create_links(dont_save => 1);
308 $form->{transdate} = $form->{initial_transdate};
309 $form->{vendor_id} = $form->{initial_vendor_id} if $form->{initial_vendor_id};
311 if ($form->{vendor_id}) {
312 my $vendor = SL::DB::Vendor->load_cached($form->{vendor_id});
314 # set initial payment terms
315 $form->{payment_id} = $vendor->payment_id;
317 my $last_used_ap_chart = $vendor->last_used_ap_chart;
318 $form->{"AP_amount_chart_id_1"} = $last_used_ap_chart->id if $last_used_ap_chart;
321 if (!$form->{form_validity_token}) {
322 $form->{form_validity_token} = SL::DB::ValidityToken->create(scope => SL::DB::ValidityToken::SCOPE_PURCHASE_INVOICE_POST())->token;
327 $main::lxdebug->leave_sub();
331 $main::lxdebug->enter_sub();
333 # Delay access check to after the invoice's been loaded in
334 # "create_links" so that project-specific invoice rights can be
337 my $form = $main::form;
339 $form->{title} = "Edit";
344 $main::lxdebug->leave_sub();
348 $main::lxdebug->enter_sub();
352 my $form = $main::form;
354 # get all files stored in the webdav folder
355 if ($form->{invnumber} && $::instance_conf->get_webdav) {
356 my $webdav = SL::Webdav->new(
357 type => 'accounts_payable',
358 number => $form->{invnumber},
360 my @all_objects = $webdav->get_all_objects;
361 @{ $form->{WEBDAV} } = map { { name => $_->filename,
363 link => File::Spec->catfile($_->full_filedescriptor),
369 $main::lxdebug->leave_sub();
373 $main::lxdebug->enter_sub();
375 # Delay access check to after the invoice's been loaded so that
376 # project-specific invoice rights can be evaluated.
380 my $form = $main::form;
381 my %myconfig = %main::myconfig;
383 $form->create_links("AP", \%myconfig, "vendor");
388 if (!$params{dont_save}) {
389 %saved = map { ($_ => $form->{$_}) } qw(direct_debit taxincluded);
390 $saved{duedate} = $form->{duedate} if $form->{duedate};
391 $saved{currency} = $form->{currency} if $form->{currency};
392 $saved{taxincluded} = $form->{taxincluded} if $form->{taxincluded};
393 $saved{intnotes} = $form->{intnotes} if $form->{intnotes};
396 IR->get_vendor(\%myconfig, \%$form);
398 $form->{$_} = $saved{$_} for keys %saved;
399 $form->{rowcount} = 1;
400 $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};
402 # build the popup menus
403 $form->{taxincluded} = ($form->{id}) ? $form->{taxincluded} : "checked";
405 $::form->{ALL_DEPARTMENTS} = SL::DB::Manager::Department->get_all_sorted;
407 $form->{employee} = "$form->{employee}--$form->{employee_id}";
409 AP->setup_form($form);
411 $main::lxdebug->leave_sub();
415 my @fields = qw(acc_trans_id gldate datepaid source memo paid AP_paid paid_project_id);
417 grep { $_->{paid} != 0 }
420 +{ map { ($_ => delete($::form->{"${_}_${idx}"})) } @fields }
421 } (1..$::form->{paidaccounts});
423 @payments = sort_by { DateTime->from_kivitendo($_->{datepaid}) } @payments;
425 $::form->{paidaccounts} = max scalar(@payments), 1;
427 foreach my $idx (1 .. scalar(@payments)) {
428 my $payment = $payments[$idx - 1];
429 $::form->{"${_}_${idx}"} = $payment->{$_} for @fields;
434 $main::lxdebug->enter_sub();
438 my $form = $main::form;
439 my %myconfig = %main::myconfig;
440 my $locale = $main::locale;
441 my $cgi = $::request->{cgi};
443 $::form->{invoice_obj} = SL::DB::PurchaseInvoice->new(id => $::form->{id})->load if $::form->{id};
445 $form->{initial_focus} = !($form->{amount_1} * 1) ? 'vendor_id' : 'row_' . $form->{rowcount};
447 $form->{title_} = $form->{title};
448 $form->{title} = $form->{title} eq 'Add' ? $locale->text('Add Accounts Payables Transaction') : $locale->text('Edit Accounts Payables Transaction');
450 # type=submit $locale->text('Add Accounts Payables Transaction')
451 # type=submit $locale->text('Edit Accounts Payables Transaction')
454 $form->{defaultcurrency} = $form->get_default_currency(\%myconfig);
455 if ($form->{currency} ne $form->{defaultcurrency} && !$form->{exchangerate}) {
456 my $transdate = $form->{transdate} ? DateTime->from_kivitendo($form->{transdate}) : DateTime->today_local;
457 ($form->{exchangerate}, $form->{record_forex}) = $form->{id}
458 ? $form->check_exchangerate(\%myconfig, $form->{currency}, $form->{transdate}, "sell", $form->{id}, 'ap')
459 : $form->check_exchangerate(\%myconfig, $form->{currency}, $transdate, "sell");
463 $form->{creditlimit} = $form->format_amount(\%myconfig, $form->{creditlimit}, 0, "0");
464 $form->{creditremaining} = $form->format_amount(\%myconfig, $form->{creditremaining}, 0, "0");
467 if (($rows = $form->numtextrows($form->{notes}, 50)) < 2) {
470 $form->{textarea_rows} = $rows;
472 $form->{creditremaining_plus} = ($form->{creditremaining} =~ /-/) ? "0" : "1";
474 $form->get_lists("charts" => { "key" => "ALL_CHARTS",
475 "transdate" => $form->{transdate} },
479 { $_->{link_split} = [ split(/:/, $_->{link}) ]; }
480 @{ $form->{ALL_CHARTS} }
483 $form->{ALL_DEPARTMENTS} = SL::DB::Manager::Department->get_all_sorted;
485 my %project_labels = map { $_->id => $_->projectnumber } @{ SL::DB::Manager::Project->get_all };
487 my (%charts, %bank_accounts);
488 my $default_ap_amount_chart_id;
489 # don't add manual bookings for charts which are assigned to real bank accounts
490 # and are flagged for use with bank import
491 my $bank_accounts = SL::DB::Manager::BankAccount->get_all();
492 foreach my $bank (@{ $bank_accounts }) {
493 if ($bank->use_with_bank_import) {
494 my $accno_paid_bank = $bank->chart->accno;
495 $bank_accounts{$accno_paid_bank} = 1;
499 foreach my $item (@{ $form->{ALL_CHARTS} }) {
500 if ( grep({ $_ eq 'AP_amount' } @{ $item->{link_split} }) ) {
501 $default_ap_amount_chart_id //= $item->{id};
503 } elsif ( grep({ $_ eq 'AP_paid' } @{ $item->{link_split} }) ) {
504 next if $bank_accounts{$item->{accno}};
505 push(@{ $form->{ALL_CHARTS_AP_paid} }, $item);
508 $charts{$item->{accno}} = $item;
511 my $follow_up_vc = $form->{vendor_id} ? SL::DB::Vendor->load_cached($form->{vendor_id})->name : '';
512 my $follow_up_trans_info = "$form->{invnumber} ($follow_up_vc)";
514 $::request->layout->add_javascripts("autocomplete_chart.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");
515 # $form->{totalpaid} is used by the action bar setup to determine
516 # whether or not canceling is allowed. Therefore it must be
517 # calculated prior to the action bar setup.
518 $form->{totalpaid} = sum map { $form->{"paid_${_}"} } (1..$form->{paidaccounts});
520 setup_ap_display_form_action_bar();
523 # get the correct date for tax
524 my $transdate = $::form->{transdate} ? DateTime->from_kivitendo($::form->{transdate}) : DateTime->today_local;
525 my $deliverydate = $::form->{deliverydate} ? DateTime->from_kivitendo($::form->{deliverydate}) : undef;
526 my $taxdate = $deliverydate ? $deliverydate : $transdate;
530 for my $i (1 .. $form->{rowcount}) {
533 $form->{"amount_$i"} = $form->format_amount(\%myconfig, $form->{"amount_$i"}, 2);
534 $form->{"tax_$i"} = $form->format_amount(\%myconfig, $form->{"tax_$i"}, 2);
536 my ($default_taxchart, $taxchart_to_use);
538 if ( $form->{"taxchart_$i"} ) {
539 ($used_tax_id) = split(/--/, $form->{"taxchart_$i"});
541 my $amount_chart_id = $form->{"AP_amount_chart_id_$i"} || $default_ap_amount_chart_id;
543 my @taxcharts = GL->get_active_taxes_for_chart($amount_chart_id, $taxdate, $used_tax_id);
544 foreach my $item (@taxcharts) {
545 my $key = $item->id . "--" . $item->rate;
546 $first_taxchart //= $item;
547 $default_taxchart = $item if $item->{is_default};
548 $taxchart_to_use = $item if $key eq $form->{"taxchart_$i"};
551 $taxchart_to_use //= $default_taxchart // $first_taxchart;
552 my $selected_taxchart = $taxchart_to_use->id . '--' . $taxchart_to_use->rate;
553 $form->{"selected_taxchart_$i"} = $selected_taxchart;
554 $form->{"AP_amount_chart_id_$i"} = $amount_chart_id;
555 $form->{"taxcharts_$i"} = \@taxcharts;
557 # reverse charge hack for template, display two taxes
558 if ($taxchart_to_use->reverse_charge_chart_id) {
560 ($tmpnetamount, $form->{"tax_reverse_$i"}) = $form->calculate_tax($form->parse_amount(\%myconfig, $form->{"amount_$i"}),
561 $taxchart_to_use->rate, $form->{taxincluded}, 2 );
563 $form->{"tax_charge_$i"} = $form->{"tax_reverse_$i"} * -1;
564 $form->{"tax_reverse_$i"} = $form->format_amount(\%myconfig, $form->{"tax_reverse_$i"}, 2);
565 $form->{"tax_charge_$i"} = $form->format_amount(\%myconfig, $form->{"tax_charge_$i"}, 2);
569 $form->{taxchart_value_title_sub} = sub {
572 $item->{id} .'--'. $item->{rate},
573 $item->{taxkey} . ' - ' . $item->{taxdescription} .' '. ($item->{rate} * 100) .' %',
577 $form->{AP_paid_value_title_sub} = sub {
581 $item->{accno} .'--'. $item->{description}
585 $form->{invtotal_unformatted} = $form->{invtotal};
586 $form->{invtotal} = $form->format_amount(\%myconfig, $form->{invtotal}, 2);
590 if ( $form->{'paid_'. $form->{paidaccounts}} ) {
591 $form->{paidaccounts}++;
594 # default account for current assets (i.e. 1801 - SKR04)
595 $form->{accno_arap} = IS->get_standard_accno_current_assets(\%myconfig, \%$form);
597 # reset form value of defaultcurrency_totalpaid, as it is currently a hidden and otherwise it gets accumulated after each update
598 # is only used if there are exchange rates
599 $form->{"defaultcurrency_totalpaid"} = 0;
601 for my $i (1 .. $form->{paidaccounts}) {
602 # hook for calc of of defaultcurrency_paid and check if banktransaction has a record exchangerate
603 if ($form->{"exchangerate_$i"} && $form->{"acc_trans_id_$i"}) {
604 my $bt_acc_trans = SL::DB::Manager::BankTransactionAccTrans->find_by(acc_trans_id => $form->{"acc_trans_id_$i"});
606 if ($bt_acc_trans->bank_transaction->exchangerate > 0) {
607 $form->{"exchangerate_$i"} = $bt_acc_trans->bank_transaction->exchangerate;
608 $form->{"forex_$i"} = $form->{"exchangerate_$i"};
609 $form->{"record_forex_$i"} = 1;
612 if (!$form->{"fx_transaction_$i"}) {
613 # this is a banktransaction that was paid in internal currency. revert paid/defaultcurrency_paid
614 $form->{"defaultcurrency_paid_$i"} = $form->{"paid_$i"};
615 $form->{"paid_$i"} /= $form->{"exchangerate_$i"};
617 $form->{"defaultcurrency_paid_$i"} //= $form->{"paid_$i"} * $form->{"exchangerate_$i"};
618 $form->{"defaultcurrency_totalpaid"} += $form->{"defaultcurrency_paid_$i"};
619 } # end hook defaultcurrency_paid
621 if ($form->{"paid_$i"}) {
622 $form->{"paid_$i"} = $form->format_amount(\%myconfig, $form->{"paid_$i"}, 2);
624 if ($form->{"exchangerate_$i"} == 0) {
625 $form->{"exchangerate_$i"} = "";
627 $form->{"exchangerate_$i"} =
628 $form->format_amount(\%myconfig, $form->{"exchangerate_$i"});
632 if (SL::DB::Default->get->payments_changeable == 0) {
634 $changeable = ($form->{"acc_trans_id_$i"})? 0 : 1;
636 if (SL::DB::Default->get->payments_changeable == 2) {
638 $changeable = (($form->{"gldate_$i"} eq '') || $form->current_date(\%myconfig) eq $form->{"gldate_$i"});
641 #deaktivieren von gebuchten Zahlungen ausserhalb der Bücherkontrolle, vorher prüfen ob heute eingegeben
642 if ($form->date_closed($form->{"gldate_$i"})) {
646 $form->{'paidaccount_changeable_'. $i} = $changeable;
648 $form->{'labelpaid_project_id_'. $i} = $project_labels{$form->{'paid_project_id_'. $i}};
649 # accno and description as info text
650 $form->{'AP_paid_readonly_desc_' . $i} = $form->{'AP_paid_' . $i} ?
651 $form->{'AP_paid_' . $i} . " " . SL::DB::Manager::Chart->find_by(accno => $form->{'AP_paid_' . $i})->description
654 $form->{paid_missing} = $::form->{is_linked_bank_transaction} && $form->{invoice_obj}->forex ?
655 $form->{invoice_obj}->open_amount
656 : $form->{invtotal_unformatted} - $form->{totalpaid};
658 $form->{payment_id} = $form->{invoice_obj}->{payment_id} // $form->{payment_id};
659 print $form->parse_html_template('ap/form_header', {
660 today => DateTime->today,
661 currencies => SL::DB::Manager::Currency->get_all_sorted,
662 payment_terms => SL::DB::Manager::PaymentTerm->get_all_sorted(query => [ or => [ obsolete => 0, id => $form->{payment_id}*1 ]]),
665 $main::lxdebug->leave_sub();
669 $::lxdebug->enter_sub;
676 my $follow_ups = FU->follow_ups('trans_id' => $::form->{id}, 'not_done' => 1);
678 if (@{ $follow_ups }) {
679 $num_due = sum map { $_->{due} * 1 } @{ $follow_ups };
680 $num_follow_ups = scalar @{ $follow_ups }
684 my $transdate = $::form->datetonum($::form->{transdate}, \%::myconfig);
685 my $closedto = $::form->datetonum($::form->{closedto}, \%::myconfig);
687 my $storno = $::form->{id}
688 && !IS->has_storno(\%::myconfig, $::form, 'ap')
689 && !IS->is_storno( \%::myconfig, $::form, 'ap', $::form->{id})
690 && ($::form->{totalpaid} == 0 || $::form->{totalpaid} eq '');
693 print $::form->parse_html_template('ap/form_footer', {
695 num_follow_ups => $num_follow_ups,
698 $::lxdebug->leave_sub;
702 $::auth->assert('ap_transactions');
704 SL::DB::PurchaseInvoice->new(id => $::form->{id})->load->mark_as_paid;
706 $::form->redirect($::locale->text("Marked as paid"));
709 sub block_or_unblock_sepa_transfer {
710 $::auth->assert('ap_transactions');
712 my $invoice = SL::DB::PurchaseInvoice->new(id => $::form->{id})->load;
713 $invoice->update_attributes(is_sepa_blocked => 0) if $::form->{unblock_sepa} && $invoice->is_sepa_blocked;
714 $invoice->update_attributes(is_sepa_blocked => 1) if !$::form->{unblock_sepa} && !$invoice->is_sepa_blocked;
716 $::form->redirect($::form->{unblock_sepa} ? t8('Bank transfer via SEPA is unblocked') : t8('Bank transfer via SEPA is blocked'));
720 $::form->{transdate} = DateTime->today_local->to_kivitendo if !$::form->{transdate};
721 $::form->{gldate} = $::form->{transdate} if !$::form->{gldate};
722 $::form->{form_validity_token} = SL::DB::ValidityToken->create(scope => SL::DB::ValidityToken::SCOPE_PURCHASE_INVOICE_POST())->token;
729 $main::lxdebug->enter_sub();
731 my $form = $main::form;
732 my %myconfig = %main::myconfig;
734 $main::auth->assert('ap_transactions');
738 $form->{invtotal} = 0;
740 delete @{ $form }{ grep { m/^tax_\d+$/ } keys %{ $form } };
742 map { $form->{$_} = $form->parse_amount(\%myconfig, $form->{$_}) }
743 qw(exchangerate creditlimit creditremaining);
745 my @flds = qw(amount AP_amount_chart_id projectnumber oldprojectnumber project_id taxchart tax);
747 my (@a, $j, $totaltax);
748 for my $i (1 .. $form->{rowcount}) {
749 $form->{"amount_$i"} = $form->parse_amount(\%myconfig, $form->{"amount_$i"});
750 if ($form->{"amount_$i"} || $params{keep_rows_without_amount}) {
753 my ($taxkey, $rate) = split(/--/, $form->{"taxchart_$i"});
755 # calculate tax exactly the same way as AP in post_transaction via form->calculate_tax
757 ($tmpnetamount,$form->{"tax_$i"}) = $form->calculate_tax($form->{"amount_$i"},$rate,$form->{taxincluded},2);
759 my $tax = SL::DB::Manager::Tax->find_by(id => $taxkey);
760 $totaltax += ($tax->reverse_charge_chart_id) ? 0 : $form->{"tax_$i"};
762 map { $a[$j]->{$_} = $form->{"${_}_$i"} } @flds;
766 $form->redo_rows(\@flds, \@a, $count, $form->{rowcount});
768 map { $form->{invtotal} += $form->{"amount_$_"} } (1 .. $form->{rowcount});
770 $form->{invdate} = $form->{transdate};
772 if (($form->{previous_vendor_id} || $form->{vendor_id}) != $form->{vendor_id}) {
773 IR->get_vendor(\%::myconfig, $form);
775 my $vendor = SL::DB::Vendor->load_cached($form->{vendor_id});
777 # reset payment to new vendor
778 $form->{payment_id} = $vendor->payment_id;
780 if (($form->{rowcount} == 1) && ($form->{amount_1} == 0)) {
781 my $last_used_ap_chart = $vendor->last_used_ap_chart;
782 $form->{"AP_amount_chart_id_1"} = $last_used_ap_chart->id if $last_used_ap_chart;
786 $form->{rowcount} = $count + ($params{dont_add_new_row} ? 0 : 1);
789 ($form->{taxincluded}) ? $form->{invtotal} : $form->{invtotal} + $totaltax;
792 for my $i (1 .. $form->{paidaccounts}) {
793 if ($form->parse_amount(\%myconfig, $form->{"paid_$i"})) {
796 $form->parse_amount(\%myconfig, $form->{"${_}_$i"})
797 } qw(paid exchangerate);
799 $totalpaid += $form->{"paid_$i"};
801 $form->{"forex_$i"} = $form->check_exchangerate( \%myconfig, $form->{currency}, $form->{"datepaid_$i"}, 'sell');
802 $form->{"exchangerate_$i"} = $form->{"forex_$i"} if $form->{"forex_$i"};
806 $form->{creditremaining} -=
807 ($form->{invtotal} - $totalpaid + $form->{oldtotalpaid} -
808 $form->{oldinvtotal});
809 $form->{oldinvtotal} = $form->{invtotal};
810 $form->{oldtotalpaid} = $totalpaid;
814 $main::lxdebug->leave_sub();
819 $main::lxdebug->enter_sub();
821 my $form = $main::form;
822 my %myconfig = %main::myconfig;
823 my $locale = $main::locale;
825 $main::auth->assert('ap_transactions');
826 $form->mtime_ischanged('ap');
828 $form->{defaultcurrency} = $form->get_default_currency(\%myconfig);
830 my $invdate = $form->datetonum($form->{transdate}, \%myconfig);
832 for my $i (1 .. $form->{paidaccounts}) {
833 if ($form->parse_amount(\%myconfig, $form->{"paid_$i"})) {
834 my $datepaid = $form->datetonum($form->{"datepaid_$i"}, \%myconfig);
836 $form->isblank("datepaid_$i", $locale->text('Payment date missing!'));
838 $form->error($locale->text('Cannot post transaction above the maximum future booking date!'))
839 if ($form->date_max_future($form->{"datepaid_$i"}, \%myconfig));
841 #Zusätzlich noch das Buchungsdatum in die Bücherkontrolle einbeziehen
842 # (Dient zur Prüfung ob ZE oder ZA geprüft werden soll)
843 $form->error($locale->text('Cannot post payment for a closed period!'))
844 if ($form->date_closed($form->{"datepaid_$i"}) && !$form->date_closed($form->{"gldate_$i"}, \%myconfig));
846 if ($form->{defaultcurrency} && ($form->{currency} ne $form->{defaultcurrency})) {
847 $form->{"exchangerate_$i"} = $form->{exchangerate}
848 if ($invdate == $datepaid);
849 $form->isblank("exchangerate_$i",
850 $locale->text('Exchangerate for payment missing!'));
855 ($form->{AP}) = split /--/, $form->{AP};
856 ($form->{AP_paid}) = split /--/, $form->{AP_paid};
857 if (AP->post_payment(\%myconfig, \%$form)) {
858 $form->{snumbers} = qq|invnumber_| . $form->{invnumber};
859 $form->{what_done} = 'invoice';
860 $form->{addition} = "PAYMENT POSTED";
862 $form->redirect($locale->text('Payment posted!'))
864 $form->error($locale->text('Cannot post payment!'));
868 $main::lxdebug->leave_sub();
873 $main::lxdebug->enter_sub();
875 my $form = $main::form;
876 my %myconfig = %main::myconfig;
877 my $locale = $main::locale;
879 $main::auth->assert('ap_transactions');
880 $form->mtime_ischanged('ap');
884 # check if there is a vendor, invoice, due date and invnumber
885 $form->isblank("transdate", $locale->text("Invoice Date missing!"));
886 $form->isblank("duedate", $locale->text("Due Date missing!"));
887 $form->isblank("vendor_id", $locale->text('Vendor missing!'));
888 $form->isblank("invnumber", $locale->text('Invoice Number missing!'));
889 $form->isblank("AP_chart_id", $locale->text('No contra account selected!'));
891 if ($myconfig{mandatory_departments} && !$form->{department_id}) {
892 $form->{saved_message} = $::locale->text('You have to specify a department.');
897 my $closedto = $form->datetonum($form->{closedto}, \%myconfig);
898 my $transdate = $form->datetonum($form->{transdate}, \%myconfig);
900 $form->error($locale->text('Cannot post transaction above the maximum future booking date!'))
901 if ($form->date_max_future($form->{"transdate"}, \%myconfig));
902 $form->error($locale->text('Cannot post transaction for a closed period!')) if ($form->date_closed($form->{"transdate"}, \%myconfig));
904 my $zero_amount_posting = 1;
905 for my $i (1 .. $form->{rowcount}) {
907 # no taxincluded for reverse charge
908 my ($used_tax_id) = split(/--/, $form->{"taxchart_$i"});
909 my $tax = SL::DB::Manager::Tax->find_by(id => $used_tax_id);
911 if ($tax->reverse_charge_chart_id) {
912 $form->error($locale->text('Cannot Post AP transaction with tax included!')) if $form->{taxincluded};
913 $form->{"reverse_charge_$i"} = 1;
916 if ($form->parse_amount(\%myconfig, $form->{"amount_$i"})) {
917 $zero_amount_posting = 0;
921 $form->error($locale->text('Zero amount posting!')) if $zero_amount_posting;
923 if ($form->{defaultcurrency} && ($form->{currency} ne $form->{defaultcurrency})) {
924 $form->isblank("exchangerate", $locale->text('Exchangerate missing!'));
925 $form->error($locale->text('Cannot post invoice with negative exchange rate'))
926 unless ($form->parse_amount(\%myconfig, $form->{"exchangerate"}) > 0);
931 for my $i (1 .. $form->{paidaccounts}) {
932 if ($form->parse_amount(\%myconfig, $form->{"paid_$i"})) {
933 my $datepaid = $form->datetonum($form->{"datepaid_$i"}, \%myconfig);
935 $form->isblank("datepaid_$i", $locale->text('Payment date missing!'));
937 $form->error($locale->text('Cannot post transaction above the maximum future booking date!'))
938 if ($form->date_max_future($form->{"datepaid_$i"}, \%myconfig));
940 #Zusätzlich noch das Buchungsdatum in die Bücherkontrolle einbeziehen
941 # (Dient zur Prüfung ob ZE oder ZA geprüft werden soll)
942 $form->error($locale->text('Cannot post payment for a closed period!'))
943 if ($form->date_closed($form->{"datepaid_$i"}) && !$form->date_closed($form->{"gldate_$i"}, \%myconfig));
945 if ($form->{defaultcurrency} && ($form->{currency} ne $form->{defaultcurrency})) {
946 $form->{"exchangerate_$i"} = $form->{exchangerate}
947 if ($transdate == $datepaid);
948 $form->isblank("exchangerate_$i",
949 $locale->text('Exchangerate for payment missing!'));
955 # if old vendor ne vendor redo form
956 if (($form->{previous_customer_id} || $form->{customer_id}) != $form->{customer_id}) {
958 $::dispatcher->end_request;
962 if (AP->post_transaction(\%myconfig, \%$form)) {
963 # create webdav folder
964 if ($::instance_conf->get_webdav) {
965 SL::Webdav->new(type => 'accounts_payable',
966 number => $form->{invnumber},
970 if(!exists $form->{addition} && $form->{id} ne "") {
971 $form->{snumbers} = qq|invnumber_| . $form->{invnumber};
972 $form->{addition} = "POSTED";
973 $form->{what_done} = "invoice";
977 my $file_name = delete $form->{zugferd_session_file};
979 my $file = SL::SessionFile->new($file_name, mode => '<');
981 SL::Helper::Flash::flash_later('error',
982 t8('Could not open ZUGFeRD file for reading: #1', $@));
985 # copy file to webdav folder
986 if ($form->{invnumber} && $::instance_conf->get_webdav_documents) {
987 my $webdav = SL::Webdav->new(
988 type => 'accounts_payable',
989 number => $form->{invnumber},
991 my $webdav_file = SL::Webdav::File->new(
993 filename => $file_name,
996 $webdav_file->store(file => $file->file_name());
999 $form->{zugferd_session_file} = $file_name;
1000 SL::Helper::Flash::flash_later('error',
1001 t8('Storing the ZUGFeRD file to the WebDAV folder failed: #1', $@));
1004 if ($form->{id} && $::instance_conf->get_doc_storage) {
1007 object_id => $form->{id},
1008 object_type => 'purchase_invoice',
1009 mime_type => 'application/pdf',
1010 source => 'uploaded',
1011 file_type => 'document',
1012 file_name => $file_name,
1013 file_path => $file->file_name(),
1017 $form->{zugferd_session_file} = $file_name;
1018 SL::Helper::Flash::flash_later('error',
1019 t8('Storing the ZUGFeRD file in the storage backend failed: #1', $@));
1025 if ($form->{email_journal_id}) {
1026 my $ap_transaction = SL::DB::PurchaseInvoice->new(id => $form->{id})->load;
1027 my $email_journal = SL::DB::EmailJournal->new(
1028 id => delete $form->{email_journal_id}
1030 $email_journal->link_to_record_with_attachment($ap_transaction, delete $::form->{email_attachment_id});
1034 my $msg = $locale->text("AP transaction '#1' posted (ID: #2)", $form->{invnumber}, $form->{id});
1035 if ($form->{callback} =~ /BankTransaction/) {
1036 # no restore_from_session_id needed. we like to have a newly generated
1037 # list of invoices for bank transactions
1038 SL::Helper::Flash::flash_later('info', $msg);
1039 print $form->redirect_header($form->{callback});
1040 $::dispatcher->end_request;
1041 } elsif ($form->{callback} =~ /ScanQRCode/) {
1042 # callback/redirect when coming from mobile view (swiss qr bill scan)
1043 print $form->redirect_header(build_std_url(
1044 "script=controller.pl",
1045 'action=ScanQRBill/scan_view',
1046 'transaction_success=1',
1047 'invnumber=' . E($form->{invnumber})
1049 $::dispatcher->end_request;
1050 } elsif ('doc-tab' eq $form->{after_action}) {
1051 # Redirect with callback containing a fragment does not work (by now)
1052 # because the callback info is stored in the session an parsing the
1053 # callback parameters does not support fragments (see SL::Form::redirect).
1054 # So use flash_later for the message and redirect_headers for redirecting.
1055 my $add_doc_url = build_std_url("script=ap.pl", 'action=edit', 'id=' . E($form->{id}), 'fragment=ui-tabs-docs');
1056 SL::Helper::Flash::flash_later('info', $msg);
1057 print $form->redirect_header($add_doc_url);
1058 $::dispatcher->end_request;
1059 } elsif ('callback' eq $form->{after_action}) {
1060 my $callback = $form->{callback}
1061 || "controller.pl?action=LoginScreen/user_login";
1062 SL::Helper::Flash::flash_later('info', $msg);
1063 print $form->redirect_header($callback);
1064 $::dispatcher->end_request;
1066 $form->redirect($msg);
1071 $form->error($locale->text('Cannot post transaction!'));
1074 $main::lxdebug->leave_sub();
1078 $main::lxdebug->enter_sub();
1080 my $form = $main::form;
1081 my %myconfig = %main::myconfig;
1083 $main::auth->assert('ap_transactions');
1085 $form->{email_journal_id} = delete $form->{workflow_email_journal_id};
1086 $form->{email_attachment_id} = delete $form->{workflow_email_attachment_id};
1087 $form->{callback} = delete $form->{workflow_email_callback};
1089 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);
1090 $form->{paidaccounts} = 1;
1091 $form->{rowcount}--;
1093 my $today = DateTime->today_local;
1094 $form->{transdate} = $today->to_kivitendo;
1095 $form->{duedate} = $form->{transdate};
1097 if ($form->{vendor_id}) {
1098 my $payment_terms = SL::DB::Vendor->load_cached($form->{vendor_id})->payment;
1099 $form->{duedate} = $payment_terms->calc_date(reference_date => $today)->to_kivitendo if $payment_terms;
1102 $form->{form_validity_token} = SL::DB::ValidityToken->create(scope => SL::DB::ValidityToken::SCOPE_PURCHASE_INVOICE_POST())->token;
1106 $main::lxdebug->leave_sub();
1110 my $form = $main::form;
1111 my %myconfig = %main::myconfig;
1112 my $locale = $main::locale;
1114 $main::auth->assert('ap_transactions');
1116 if (AP->delete_transaction(\%myconfig, \%$form)) {
1117 # saving the history
1118 if(!exists $form->{addition}) {
1119 $form->{snumbers} = qq|invnumber_| . $form->{invnumber};
1120 $form->{addition} = "DELETED";
1121 $form->{what_done} = "invoice";
1122 $form->save_history;
1124 # /saving the history
1125 $form->redirect($locale->text('Transaction deleted!'));
1127 $form->error($locale->text('Cannot delete transaction!'));
1131 $main::lxdebug->enter_sub();
1133 my $form = $main::form;
1134 my %myconfig = %main::myconfig;
1135 my $locale = $main::locale;
1137 $form->{title} = $locale->text('Vendor Invoices & AP Transactions');
1139 $::form->{ALL_DEPARTMENTS} = SL::DB::Manager::Department ->get_all_sorted;
1140 $::form->{ALL_TAXZONES} = SL::DB::Manager::TaxZone ->get_all_sorted;
1141 $::form->{ALL_PAYMENT_TERMS} = SL::DB::Manager::PaymentTerm->get_all_sorted;
1143 # constants and subs for template
1144 $form->{vc_keys} = sub { "$_[0]->{name}--$_[0]->{id}" };
1146 $::request->layout->add_javascripts("autocomplete_project.js");
1148 setup_ap_search_action_bar();
1151 print $form->parse_html_template('ap/search', { %myconfig });
1153 $main::lxdebug->leave_sub();
1156 sub create_subtotal_row {
1157 $main::lxdebug->enter_sub();
1159 my ($totals, $columns, $column_alignment, $subtotal_columns, $class) = @_;
1161 my $form = $main::form;
1162 my %myconfig = %main::myconfig;
1164 my $row = { map { $_ => { 'data' => '', 'class' => $class, 'align' => $column_alignment->{$_}, } } @{ $columns } };
1166 map { $row->{$_}->{data} = $form->format_amount(\%myconfig, $totals->{$_}, 2) } @{ $subtotal_columns };
1168 $row->{tax}->{data} = $form->format_amount(\%myconfig, $totals->{amount} - $totals->{netamount}, 2);
1170 map { $totals->{$_} = 0 } @{ $subtotal_columns };
1172 $main::lxdebug->leave_sub();
1177 sub ap_transactions {
1178 $main::lxdebug->enter_sub();
1180 my $form = $main::form;
1181 my %myconfig = %main::myconfig;
1182 my $locale = $main::locale;
1184 report_generator_set_default_sort('transdate', 1);
1186 AP->ap_transactions(\%myconfig, \%$form);
1188 $form->{title} = $locale->text('Vendor Invoices & AP Transactions');
1190 my $report = SL::ReportGenerator->new(\%myconfig, $form);
1193 qw(transdate id type invnumber ordnumber name netamount tax amount paid datepaid
1194 due duedate transaction_description notes intnotes employee globalprojectnumber department
1195 vendornumber country ustid taxzone payment_terms charts debit_chart direct_debit
1198 my @hidden_variables = map { "l_${_}" } @columns;
1199 push @hidden_variables, "l_subtotal", qw(open closed vendor invnumber ordnumber transaction_description notes intnotes project_id
1200 transdatefrom transdateto duedatefrom duedateto datepaidfrom datepaidto
1201 parts_partnumber parts_description department_id taxzone_id payment_id
1202 fulltext insertdatefrom insertdateto);
1204 my $href = build_std_url('action=ap_transactions', grep { $form->{$_} } @hidden_variables);
1207 'transdate' => { 'text' => $locale->text('Date'), },
1208 'id' => { 'text' => $locale->text('ID'), },
1209 'type' => { 'text' => $locale->text('Type'), },
1210 'invnumber' => { 'text' => $locale->text('Invoice'), },
1211 'ordnumber' => { 'text' => $locale->text('Order'), },
1212 'name' => { 'text' => $locale->text('Vendor'), },
1213 'netamount' => { 'text' => $locale->text('Amount'), },
1214 'tax' => { 'text' => $locale->text('Tax'), },
1215 'amount' => { 'text' => $locale->text('Total'), },
1216 'paid' => { 'text' => $locale->text('Paid'), },
1217 'datepaid' => { 'text' => $locale->text('Date Paid'), },
1218 'due' => { 'text' => $locale->text('Amount Due'), },
1219 'duedate' => { 'text' => $locale->text('Due Date'), },
1220 'transaction_description' => { 'text' => $locale->text('Transaction description'), },
1221 'notes' => { 'text' => $locale->text('Notes'), },
1222 'intnotes' => { 'text' => $locale->text('Internal Notes'), },
1223 'employee' => { 'text' => $locale->text('Employee'), },
1224 'globalprojectnumber' => { 'text' => $locale->text('Document Project Number'), },
1225 'department' => { 'text' => $locale->text('Department'), },
1226 'vendornumber' => { 'text' => $locale->text('Vendor Number'), },
1227 'country' => { 'text' => $locale->text('Country'), },
1228 'ustid' => { 'text' => $locale->text('USt-IdNr.'), },
1229 'taxzone' => { 'text' => $locale->text('Tax rate'), },
1230 'payment_terms' => { 'text' => $locale->text('Payment Terms'), },
1231 'charts' => { 'text' => $locale->text('Chart'), },
1232 'debit_chart' => { 'text' => $locale->text('Debit Account'), },
1233 'direct_debit' => { 'text' => $locale->text('direct debit'), },
1234 'insertdate' => { 'text' => $locale->text('Insert Date'), },
1235 'items' => { 'text' => $locale->text('Positions'), },
1238 foreach my $name (qw(id transdate duedate invnumber ordnumber name datepaid employee shipvia transaction_description direct_debit department taxzone insertdate intnotes)) {
1239 my $sortdir = $form->{sort} eq $name ? 1 - $form->{sortdir} : $form->{sortdir};
1240 $column_defs{$name}->{link} = $href . "&sort=$name&sortdir=$sortdir";
1243 my %column_alignment = map { $_ => 'right' } qw(netamount tax amount paid due);
1245 $form->{"l_type"} = "Y";
1246 map { $column_defs{$_}->{visible} = $form->{"l_${_}"} ? 1 : 0 } @columns;
1248 $report->set_columns(%column_defs);
1249 $report->set_column_order(@columns);
1251 $report->set_export_options('ap_transactions', @hidden_variables, qw(sort sortdir));
1253 $report->set_sort_indicator($form->{sort}, $form->{sortdir});
1255 my $department_description;
1256 $department_description = SL::DB::Manager::Department->find_by(id => $form->{department_id})->description if $form->{department_id};
1257 my $project_description;
1258 $project_description = SL::DB::Manager::Project->find_by(id => $form->{project_id})->description if $form->{project_id};
1261 push @options, $locale->text('Vendor') . " : $form->{vendor}" if ($form->{vendor});
1262 push @options, $locale->text('Contact Person') . " : $form->{cp_name}" if ($form->{cp_name});
1263 push @options, $locale->text('Department') . " : $department_description" if ($form->{department_id});
1264 push @options, $locale->text('Project') . " : $project_description" if ($project_description);
1265 push @options, $locale->text('Invoice Number') . " : $form->{invnumber}" if ($form->{invnumber});
1266 push @options, $locale->text('Order Number') . " : $form->{ordnumber}" if ($form->{ordnumber});
1267 push @options, $locale->text('Notes') . " : $form->{notes}" if ($form->{notes});
1268 push @options, $locale->text('Internal Notes') . " : $form->{intnotes}" if $form->{intnotes};
1269 push @options, $locale->text('Transaction description') . " : $form->{transaction_description}" if ($form->{transaction_description});
1270 push @options, $locale->text('Part Description') . " : $form->{parts_description}" if $form->{parts_description};
1271 push @options, $locale->text('Part Number') . " : $form->{parts_partnumber}" if $form->{parts_partnumber};
1272 push @options, $locale->text('Full Text') . " : $form->{fulltext}" if ($form->{fulltext});
1273 push @options, $locale->text('From') . " " . $locale->date(\%myconfig, $form->{transdatefrom}, 1) if ($form->{transdatefrom});
1274 push @options, $locale->text('Bis') . " " . $locale->date(\%myconfig, $form->{transdateto}, 1) if ($form->{transdateto});
1275 push @options, $locale->text('Due Date') . " " . $locale->text('from') . " " . $locale->date(\%myconfig, $form->{duedatefrom}, 1) if ($form->{duedatefrom});
1276 push @options, $locale->text('Due Date') . " " . $locale->text('to') . " " . $locale->date(\%myconfig, $form->{duedateto}, 1) if ($form->{duedateto});
1277 push @options, $locale->text('Date Paid') . " " . $locale->text('from') . " " . $locale->date(\%myconfig, $form->{datepaidfrom}, 1) if ($form->{datepaidfrom});
1278 push @options, $locale->text('Date Paid') . " " . $locale->text('to') . " " . $locale->date(\%myconfig, $form->{datepaidto}, 1) if ($form->{datepaidto});
1279 push @options, $locale->text('Insert Date') . " " . $locale->text('from') . " " . $locale->date(\%myconfig, $form->{insertdatefrom}, 1) if ($form->{insertdatefrom});
1280 push @options, $locale->text('Insert Date') . " " . $locale->text('to') . " " . $locale->date(\%myconfig, $form->{insertdateto}, 1) if ($form->{insertdateto});
1281 push @options, $locale->text('Open') if ($form->{open});
1282 push @options, $locale->text('Closed') if ($form->{closed});
1283 if ($form->{payment_id}) {
1284 my $payment_term = SL::DB::Manager::PaymentTerm->find_by( id => $form->{payment_id} );
1285 push @options, $locale->text('Payment Term') . " : " . $payment_term->description;
1288 $report->set_options('top_info_text' => join("\n", @options),
1289 'output_format' => 'HTML',
1290 'title' => $form->{title},
1291 'attachment_basename' => $locale->text('vendor_invoice_list') . strftime('_%Y%m%d', localtime time),
1293 $report->set_options_from_form();
1294 $locale->set_numberformat_wo_thousands_separator(\%myconfig) if lc($report->{options}->{output_format}) eq 'csv';
1296 # add sort and escape callback, this one we use for the add sub
1297 $form->{callback} = $href .= "&sort=$form->{sort}";
1299 # escape callback for href
1300 my $callback = $form->escape($href);
1302 my @subtotal_columns = qw(netamount amount paid due);
1304 my %totals = map { $_ => 0 } @subtotal_columns;
1305 my %subtotals = map { $_ => 0 } @subtotal_columns;
1309 foreach my $ap (@{ $form->{AP} }) {
1310 $ap->{tax} = $ap->{amount} - $ap->{netamount};
1311 $ap->{due} = $ap->{amount} - $ap->{paid};
1313 map { $subtotals{$_} += $ap->{$_};
1314 $totals{$_} += $ap->{$_} } @subtotal_columns;
1316 map { $ap->{$_} = $form->format_amount(\%myconfig, $ap->{$_}, 2) } qw(netamount tax amount paid due);
1318 my $is_storno = $ap->{storno} && $ap->{storno_id};
1319 my $has_storno = $ap->{storno} && !$ap->{storno_id};
1321 if ($ap->{invoice}) {
1323 $has_storno ? $locale->text("Invoice with Storno (abbreviation)")
1324 : $is_storno ? $locale->text("Storno (one letter abbreviation)")
1325 : $locale->text("Invoice (one letter abbreviation)");
1328 $has_storno ? $locale->text("AP Transaction with Storno (abbreviation)")
1329 : $is_storno ? $locale->text("AP Transaction Storno (one letter abbreviation)")
1330 : $locale->text("AP Transaction (abbreviation)");
1333 $ap->{direct_debit} = $ap->{direct_debit} ? $::locale->text('yes') : $::locale->text('no');
1337 foreach my $column (@columns) {
1338 next if ($column eq 'items');
1341 'data' => $ap->{$column},
1342 'align' => $column_alignment{$column},
1346 $row->{invnumber}->{link} = build_std_url("script=" . ($ap->{invoice} ? 'ir.pl' : 'ap.pl'), 'action=edit')
1347 . "&id=" . E($ap->{id}) . "&callback=${callback}";
1349 if ($form->{l_items}) {
1350 my $items = SL::DB::Manager::InvoiceItem->get_all_sorted(where => [id => $ap->{item_ids}]);
1351 $row->{items}->{raw_data} = SL::Presenter::ItemsList::items_list($items) if lc($report->{options}->{output_format}) eq 'html';
1352 $row->{items}->{data} = SL::Presenter::ItemsList::items_list($items, as_text => 1) if lc($report->{options}->{output_format}) ne 'html';
1355 my $row_set = [ $row ];
1357 if (($form->{l_subtotal} eq 'Y')
1358 && (($idx == (scalar @{ $form->{AP} } - 1))
1359 || ($ap->{ $form->{sort} } ne $form->{AP}->[$idx + 1]->{ $form->{sort} }))) {
1360 push @{ $row_set }, create_subtotal_row(\%subtotals, \@columns, \%column_alignment, \@subtotal_columns, 'listsubtotal');
1363 $report->add_data($row_set);
1368 $report->add_separator();
1369 $report->add_data(create_subtotal_row(\%totals, \@columns, \%column_alignment, \@subtotal_columns, 'listtotal'));
1371 setup_ap_transactions_action_bar();
1372 $report->generate_with_headers();
1374 $main::lxdebug->leave_sub();
1378 $main::lxdebug->enter_sub();
1380 my $form = $main::form;
1381 my %myconfig = %main::myconfig;
1382 my $locale = $main::locale;
1384 $main::auth->assert('ap_transactions');
1386 if (IS->has_storno(\%myconfig, $form, 'ap')) {
1387 $form->{title} = $locale->text("Cancel Accounts Payables Transaction");
1388 $form->error($locale->text("Transaction has already been cancelled!"));
1391 $form->error($locale->text('Cannot post storno for a closed period!'))
1392 if ( $form->date_closed($form->{transdate}, \%myconfig));
1394 AP->storno($form, \%myconfig, $form->{id});
1396 # saving the history
1397 if(!exists $form->{addition} && $form->{id} ne "") {
1398 $form->{snumbers} = qq|invnumber_| . $form->{invnumber};
1399 $form->{addition} = "STORNO";
1400 $form->{what_done} = "invoice";
1401 $form->save_history;
1403 # /saving the history
1405 $form->redirect(sprintf $locale->text("Transaction %d cancelled."), $form->{storno_id});
1407 $main::lxdebug->leave_sub();
1410 sub add_from_purchase_order {
1411 $main::auth->assert('ap_transactions');
1413 return if !$::form->{id};
1415 my $order_id = delete $::form->{id};
1416 my $order = SL::DB::Order->new(id => $order_id)->load(with => [ 'vendor', 'currency', 'payment_terms' ]);
1418 return if $order->type ne 'purchase_order';
1420 my $today = DateTime->today_local;
1421 $::form->{title} = "Add";
1422 $::form->{vc} = 'vendor';
1423 $::form->{vendor_id} = $order->customervendor->id;
1424 $::form->{vendor} = $order->vendor->name;
1425 $::form->{convert_from_oe_id} = $order->id;
1426 $::form->{globalproject_id} = $order->globalproject_id;
1427 $::form->{ordnumber} = $order->number;
1428 $::form->{department_id} = $order->department_id;
1429 $::form->{transaction_description} = $order->transaction_description;
1430 $::form->{currency} = $order->currency->name;
1431 $::form->{taxincluded} = 1; # we use amount below, so tax is included
1432 $::form->{transdate} = $today->to_kivitendo;
1433 $::form->{duedate} = $today->to_kivitendo;
1434 $::form->{duedate} = $order->payment_terms->calc_date(reference_date => $today)->to_kivitendo if $order->payment_terms;
1435 $::form->{deliverydate} = $order->reqdate->to_kivitendo if $order->reqdate;
1438 my $config_po_ap_workflow_chart_id = $::instance_conf->get_workflow_po_ap_chart_id;
1440 my ($first_taxchart, $default_taxchart, $taxchart_to_use);
1442 @taxcharts = GL->get_active_taxes_for_chart($config_po_ap_workflow_chart_id, $::form->{transdate}) if (defined $config_po_ap_workflow_chart_id);
1443 foreach my $item (@taxcharts) {
1444 $first_taxchart //= $item;
1445 $default_taxchart = $item if $item->{is_default};
1447 $taxchart_to_use = $default_taxchart // $first_taxchart;
1449 my %pat = $order->calculate_prices_and_taxes;
1451 foreach my $amount_chart (keys %{$pat{amounts}}) {
1452 my $tax = SL::DB::Manager::Tax->find_by(id => $pat{amounts}->{$amount_chart}->{tax_id});
1453 # If tax chart from order for this amount is active, use it. Use default or first tax chart for selected chart else.
1454 if (defined $config_po_ap_workflow_chart_id) {
1455 $taxchart_to_use = (first {$_->{id} == $tax->id} @taxcharts) // $taxchart_to_use;
1457 $taxchart_to_use = $tax;
1460 $::form->{"AP_amount_chart_id_$row"} = $config_po_ap_workflow_chart_id // $amount_chart;
1461 $::form->{"previous_AP_amount_chart_id_$row"} = $::form->{"AP_amount_chart_id_$row"};
1462 $::form->{"amount_$row"} = $::form->format_amount(\%::myconfig, $pat{amounts}->{$amount_chart}->{amount} * (1 + $tax->rate), 2);
1463 $::form->{"taxchart_$row"} = $taxchart_to_use->id . '--' . $taxchart_to_use->rate;
1464 $::form->{"project_id_$row"} = $order->globalproject_id;
1469 my $last_used_ap_chart = SL::DB::Vendor->load_cached($::form->{vendor_id})->last_used_ap_chart;
1470 $::form->{"AP_amount_chart_id_$row"} = $last_used_ap_chart->id if $last_used_ap_chart;
1471 $::form->{rowcount} = $row;
1473 $::form->{form_validity_token} = SL::DB::ValidityToken->create(scope => SL::DB::ValidityToken::SCOPE_PURCHASE_INVOICE_POST())->token;
1476 keep_rows_without_amount => 1,
1477 dont_add_new_row => 1,
1481 sub add_from_email_journal {
1482 die "No 'email_journal_id' was given." unless ($::form->{email_journal_id});
1486 sub load_record_template_from_email_journal {
1487 die "No 'email_journal_id' was given." unless ($::form->{email_journal_id});
1488 &load_record_template;
1491 sub edit_with_email_journal_workflow {
1493 die "No 'email_journal_id' was given." unless ($::form->{email_journal_id});
1494 $::form->{workflow_email_journal_id} = delete $::form->{email_journal_id};
1495 $::form->{workflow_email_attachment_id} = delete $::form->{email_attachment_id};
1496 $::form->{workflow_email_callback} = delete $::form->{callback};
1501 sub setup_ap_search_action_bar {
1504 for my $bar ($::request->layout->get('actionbar')) {
1507 $::locale->text('Search'),
1508 submit => [ '#form', { action => "ap_transactions" } ],
1509 checks => [ 'kivi.validate_form' ],
1510 accesskey => 'enter',
1514 $::request->layout->add_javascripts('kivi.Validator.js');
1517 sub setup_ap_transactions_action_bar {
1519 my $may_edit_create = $::auth->assert('ap_transactions', 1);
1521 for my $bar ($::request->layout->get('actionbar')) {
1524 action => [ t8('Add') ],
1526 t8('Purchase Invoice'),
1527 link => [ 'ir.pl?action=add' ],
1528 disabled => !$may_edit_create ? t8('You do not have the permissions to access this function.') : undef,
1532 t8('AP Transaction'),
1533 link => [ 'ap.pl?action=add' ],
1534 disabled => !$may_edit_create ? t8('You do not have the permissions to access this function.') : undef,
1536 ], # end of combobox "Add"
1541 sub setup_ap_display_form_action_bar {
1542 my $transdate = $::form->datetonum($::form->{transdate}, \%::myconfig);
1543 my $closedto = $::form->datetonum($::form->{closedto}, \%::myconfig);
1544 my $is_closed = $transdate <= $closedto;
1546 my $change_never = $::instance_conf->get_ap_changeable == 0;
1547 my $change_on_same_day_only = $::instance_conf->get_ap_changeable == 2 && ($::form->current_date(\%::myconfig) ne $::form->{gldate});
1549 my $is_storno = IS->is_storno(\%::myconfig, $::form, 'ap', $::form->{id});
1550 my $has_storno = IS->has_storno(\%::myconfig, $::form, 'ap');
1552 my $may_edit_create = $::auth->assert('ap_transactions', 1);
1554 my $has_sepa_exports;
1555 my $is_sepa_blocked;
1556 if ($::form->{id}) {
1557 my $invoice = SL::DB::Manager::PurchaseInvoice->find_by(id => $::form->{id});
1558 $has_sepa_exports = 1 if ($invoice->find_sepa_export_items()->[0]);
1559 $is_sepa_blocked = !!$invoice->is_sepa_blocked;
1562 my $is_linked_bank_transaction;
1564 && SL::DB::Manager::BankTransactionAccTrans->find_by(ap_id => $::form->{id})) {
1566 $is_linked_bank_transaction = 1;
1568 my $is_linked_gl_transaction;
1569 if ($::form->{id} && SL::DB::Manager::ApGl->find_by(ap_id => $::form->{id})) {
1570 $is_linked_gl_transaction = 1;
1572 # add readonly state in $::form
1573 $::form->{readonly} = !$may_edit_create ? 1
1577 : ($::form->{id} && $change_never) ? 1
1578 : ($::form->{id} && $change_on_same_day_only) ? 1
1579 : $is_linked_bank_transaction ? 1
1580 : $has_sepa_exports ? 1
1582 # and is_linked_bank_transaction
1583 $::form->{is_linked_bank_transaction} = $is_linked_bank_transaction;
1585 my $create_post_action = sub {
1586 # $_[0]: description
1587 # $_[1]: after_action
1591 submit => [ '#form', { action => "post", after_action => $_[1] } ],
1592 checks => [ 'kivi.validate_form', 'kivi.AP.check_fields_before_posting', 'kivi.AP.check_duplicate_invnumber' ],
1593 disabled => !$may_edit_create ? t8('You must not change this AP transaction.')
1594 : $is_closed ? t8('The billing period has already been locked.')
1595 : $is_storno ? t8('A canceled invoice cannot be posted.')
1596 : ($::form->{id} && $change_never) ? t8('Changing invoices has been disabled in the configuration.')
1597 : ($::form->{id} && $change_on_same_day_only) ? t8('Invoices can only be changed on the day they are posted.')
1598 : $is_linked_bank_transaction ? t8('This transaction is linked with a bank transaction. Please undo and redo the bank transaction booking if needed.')
1604 if ($::instance_conf->get_ap_add_doc && $::instance_conf->get_doc_storage) {
1605 @post_entries = ( $create_post_action->(t8('Post'), 'doc-tab'),
1606 $create_post_action->(t8('Post and new booking')) );
1607 } elsif ($::instance_conf->get_doc_storage) {
1608 @post_entries = ( $create_post_action->(t8('Post')),
1609 $create_post_action->(t8('Post and upload document'), 'doc-tab') );
1611 @post_entries = ( $create_post_action->(t8('Post')) );
1613 push @post_entries, $create_post_action->(t8('Post and Close'), 'callback');
1615 for my $bar ($::request->layout->get('actionbar')) {
1619 submit => [ '#form', { action => "update" } ],
1620 id => 'update_button',
1621 checks => [ 'kivi.validate_form' ],
1622 accesskey => 'enter',
1623 disabled => !$may_edit_create ? t8('You must not change this AP transaction.') : undef,
1629 submit => [ '#form', { action => "post_payment" } ],
1630 checks => [ 'kivi.validate_form' ],
1631 disabled => !$may_edit_create ? t8('You must not change this AP transaction.')
1632 : !$::form->{id} ? t8('This invoice has not been posted yet.')
1633 : $is_linked_bank_transaction ? t8('This transaction is linked with a bank transaction. Please undo and redo the bank transaction booking if needed.')
1636 action => [ $is_sepa_blocked ? t8('Unblock Bank transfer via SEPA') : t8('Block Bank transfer via SEPA'),
1637 submit => [ '#form', { action => "block_or_unblock_sepa_transfer", unblock_sepa => !!$is_sepa_blocked } ],
1638 disabled => !$may_edit_create ? t8('You must not change this AP transaction.')
1639 : !$::form->{id} ? t8('This invoice has not been posted yet.')
1642 action => [ t8('Mark as paid'),
1643 submit => [ '#form', { action => "mark_as_paid" } ],
1644 confirm => t8('This will remove the invoice from showing as unpaid even if the unpaid amount does not match the amount. Proceed?'),
1645 disabled => !$may_edit_create ? t8('You must not change this AP transaction.')
1646 : !$::form->{id} ? t8('This invoice has not been posted yet.')
1648 only_if => $::instance_conf->get_is_show_mark_as_paid,
1650 ], # end of combobox "Post"
1653 action => [ t8('Storno'),
1654 submit => [ '#form', { action => "storno" } ],
1655 checks => [ 'kivi.validate_form', 'kivi.AP.check_fields_before_posting' ],
1656 confirm => t8('Do you really want to cancel this invoice?'),
1657 disabled => !$may_edit_create ? t8('You must not change this AP transaction.')
1658 : !$::form->{id} ? t8('This invoice has not been posted yet.')
1659 : $has_storno ? t8('This invoice has been canceled already.')
1660 : $is_storno ? t8('Reversal invoices cannot be canceled.')
1661 : $::form->{totalpaid} ? t8('Invoices with payments cannot be canceled.')
1662 : $has_sepa_exports ? t8('This invoice has been linked with a sepa export, undo this first.')
1663 : $is_linked_gl_transaction ? t8('This transaction is linked with a gl transaction. Please delete the ap transaction booking if needed.')
1664 : $is_linked_bank_transaction ? t8('This transaction is linked with a bank transaction. Please undo and redo the bank transaction booking if needed.')
1667 action => [ t8('Delete'),
1668 submit => [ '#form', { action => "delete" } ],
1669 confirm => t8('Do you really want to delete this object?'),
1670 disabled => !$may_edit_create ? t8('You must not change this AP transaction.')
1671 : !$::form->{id} ? t8('This invoice has not been posted yet.')
1672 : $is_closed ? t8('The billing period has already been locked.')
1673 : $has_sepa_exports ? t8('This invoice has been linked with a sepa export, undo this first.')
1674 : $is_linked_bank_transaction ? t8('This transaction is linked with a bank transaction. Please undo and redo the bank transaction booking if needed.')
1675 # : $is_linked_gl_transaction ? undef # linked transactions can be deleted, if period is not closed
1676 : $change_never ? t8('Changing invoices has been disabled in the configuration.')
1677 : $change_on_same_day_only ? t8('Invoices can only be changed on the day they are posted.')
1678 : $has_storno ? t8('This invoice has been canceled already.')
1681 ], # end of combobox "Storno"
1686 action => [ t8('Workflow') ],
1689 submit => [ '#form', { action => "use_as_new" } ],
1690 checks => [ 'kivi.validate_form' ],
1691 disabled => !$may_edit_create ? t8('You must not change this AP transaction.')
1692 : !$::form->{id} ? t8('This invoice has not been posted yet.')
1695 ], # end of combobox "Workflow"
1698 action => [ t8('more') ],
1701 call => [ 'set_history_window', $::form->{id} * 1, 'glid' ],
1702 disabled => !$::form->{id} ? t8('This invoice has not been posted yet.') : undef,
1706 call => [ 'follow_up_window' ],
1707 disabled => !$::form->{id} ? t8('This invoice has not been posted yet.') : undef,
1710 t8('Record templates'),
1711 call => [ 'kivi.RecordTemplate.popup', 'ap_transaction' ],
1712 disabled => !$may_edit_create ? t8('You must not change this AP transaction.') : undef,
1716 call => [ 'kivi.Draft.popup', 'ap', 'invoice', $::form->{draft_id}, $::form->{draft_description} ],
1717 disabled => !$may_edit_create ? t8('You must not change this AP transaction.')
1718 : $::form->{id} ? t8('This invoice has already been posted.')
1719 : $is_closed ? t8('The billing period has already been locked.')
1722 ], # end of combobox "more"
1725 $::request->layout->add_javascripts('kivi.Validator.js');