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 #======================================================================
31 # Accounts Receivables
33 #======================================================================
35 use POSIX qw(strftime);
36 use List::Util qw(sum first max);
37 use List::UtilsBy qw(sort_by);
40 use SL::Controller::Base;
44 use SL::DB::BankTransactionAccTrans;
50 use SL::DB::Manager::Invoice;
51 use SL::DB::InvoiceItem;
52 use SL::DB::RecordTemplate;
54 use SL::DB::EmailJournal;
55 use SL::DB::ValidityToken;
56 use SL::Helper::Flash qw(flash flash_later);
57 use SL::Locale::String qw(t8);
58 use SL::Presenter::Tag;
59 use SL::Presenter::Chart;
60 use SL::Presenter::ItemsList;
61 use SL::ReportGenerator;
63 require "bin/mozilla/common.pl";
64 require "bin/mozilla/reportgenerator.pl";
69 # this is for our long dates
70 # $locale->text('January')
71 # $locale->text('February')
72 # $locale->text('March')
73 # $locale->text('April')
74 # $locale->text('May ')
75 # $locale->text('June')
76 # $locale->text('July')
77 # $locale->text('August')
78 # $locale->text('September')
79 # $locale->text('October')
80 # $locale->text('November')
81 # $locale->text('December')
83 # this is for our short month
84 # $locale->text('Jan')
85 # $locale->text('Feb')
86 # $locale->text('Mar')
87 # $locale->text('Apr')
88 # $locale->text('May')
89 # $locale->text('Jun')
90 # $locale->text('Jul')
91 # $locale->text('Aug')
92 # $locale->text('Sep')
93 # $locale->text('Oct')
94 # $locale->text('Nov')
95 # $locale->text('Dec')
97 sub _may_view_or_edit_this_invoice {
98 return 1 if $::auth->assert('ar_transactions', 1); # may edit all invoices
99 return 0 if !$::form->{id}; # creating new invoices isn't allowed without invoice_edit
100 return 0 if !$::form->{globalproject_id}; # existing records without a project ID are not allowed
101 return SL::DB::Project->new(id => $::form->{globalproject_id})->load->may_employee_view_project_invoices(SL::DB::Manager::Employee->current);
105 my $cache = $::request->cache('ar.pl::_assert_access');
107 $cache->{_may_view_or_edit_this_invoice} = _may_view_or_edit_this_invoice() if !exists $cache->{_may_view_or_edit_this_invoice};
108 $::form->show_generic_error($::locale->text("You do not have the permissions to access this function.")) if ! $cache->{_may_view_or_edit_this_invoice};
111 sub load_record_template {
112 $::auth->assert('ar_transactions');
114 # Load existing template and verify that its one for this module.
115 my $template = SL::DB::RecordTemplate
116 ->new(id => $::form->{id})
118 with_object => [ qw(customer payment currency record_items record_items.chart) ],
121 die "invalid template type" unless $template->template_type eq 'ar_transaction';
123 $template->substitute_variables;
125 # Clean the current $::form before rebuilding it from the template.
126 my $form_defaults = delete $::form->{form_defaults};
127 delete @{ $::form }{ grep { !m{^(?:script|login)$}i } keys %{ $::form } };
129 # Fill $::form from the template.
130 my $today = DateTime->today_local;
131 $::form->{title} = "Add";
132 $::form->{currency} = $template->currency->name;
133 $::form->{direct_debit} = $template->direct_debit;
134 $::form->{globalproject_id} = $template->project_id;
135 $::form->{transaction_description} = $template->transaction_description;
136 $::form->{AR_chart_id} = $template->ar_ap_chart_id;
137 $::form->{transdate} = $today->to_kivitendo;
138 $::form->{duedate} = $today->to_kivitendo;
139 $::form->{rowcount} = @{ $template->items };
140 $::form->{paidaccounts} = 1;
141 $::form->{$_} = $template->$_ for qw(department_id ordnumber taxincluded employee_id notes);
143 if ($template->customer) {
144 $::form->{customer_id} = $template->customer_id;
145 $::form->{customer} = $template->customer->name;
146 $::form->{duedate} = $template->customer->payment->calc_date(reference_date => $today)->to_kivitendo if $template->customer->payment;
150 foreach my $item (@{ $template->items }) {
153 my $active_taxkey = $item->chart->get_active_taxkey;
154 my $taxes = SL::DB::Manager::Tax->get_all(
155 where => [ chart_categories => { like => '%' . $item->chart->category . '%' }],
156 sort_by => 'taxkey, rate',
159 my $tax = first { $item->tax_id == $_->id } @{ $taxes };
160 $tax //= first { $active_taxkey->tax_id == $_->id } @{ $taxes };
161 $tax //= $taxes->[0];
168 $::form->{"AR_amount_chart_id_${row}"} = $item->chart_id;
169 $::form->{"previous_AR_amount_chart_id_${row}"} = $item->chart_id;
170 $::form->{"amount_${row}"} = $::form->format_amount(\%::myconfig, $item->amount1, 2);
171 $::form->{"taxchart_${row}"} = $item->tax_id . '--' . $tax->rate;
172 $::form->{"project_id_${row}"} = $item->project_id;
175 $::form->{$_} = $form_defaults->{$_} for keys %{ $form_defaults // {} };
177 flash('info', $::locale->text("The record template '#1' has been loaded.", $template->template_name));
179 $::form->{form_validity_token} = SL::DB::ValidityToken->create(scope => SL::DB::ValidityToken::SCOPE_SALES_INVOICE_POST())->token;
182 keep_rows_without_amount => 1,
183 dont_add_new_row => 1,
187 sub save_record_template {
188 $::auth->assert('ar_transactions');
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});
194 $js->dialog->close('#record_template_dialog');
197 $_->{chart_id} && (($_->{tax_id} // '') ne '')
199 +{ chart_id => $::form->{"AR_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,
204 } (1..($::form->{rowcount} || 1));
206 $template->assign_attributes(
207 template_type => 'ar_transaction',
208 template_name => $new_name,
210 currency_id => SL::DB::Manager::Currency->find_by(name => $::form->{currency})->id,
211 ar_ap_chart_id => $::form->{AR_chart_id} || undef,
212 customer_id => $::form->{customer_id} || undef,
213 department_id => $::form->{department_id} || undef,
214 project_id => $::form->{globalproject_id} || undef,
215 employee_id => $::form->{employee_id} || undef,
216 taxincluded => $::form->{taxincluded} ? 1 : 0,
217 direct_debit => $::form->{direct_debit} ? 1 : 0,
218 ordnumber => $::form->{ordnumber},
219 notes => $::form->{notes},
220 transaction_description => $::form->{transaction_description},
230 ->flash('error', $::locale->text("Saving the record template '#1' failed.", $new_name))
235 ->flash('info', $::locale->text("The record template '#1' has been saved.", $new_name))
240 $main::lxdebug->enter_sub();
242 $main::auth->assert('ar_transactions');
244 my $form = $main::form;
245 my %myconfig = %main::myconfig;
248 if(!exists $form->{addition} && ($form->{id} ne "")) {
249 $form->{snumbers} = qq|invnumber_| . $form->{invnumber};
250 $form->{addition} = "ADDED";
253 # /saving the history
255 $form->{title} = "Add";
256 $form->{callback} = "ar.pl?action=add" unless $form->{callback};
258 AR->get_transdate(\%myconfig, $form);
259 $form->{initial_transdate} = $form->{transdate};
260 $form->{initial_customer_id} = $form->{customer_id};
261 create_links(dont_save => 1);
262 $form->{transdate} = $form->{initial_transdate};
263 $form->{customer_id} = $form->{initial_customer_id} if $form->{initial_customer_id};
265 if ($form->{customer_id}) {
266 my $last_used_ar_chart = SL::DB::Customer->load_cached($form->{customer_id})->last_used_ar_chart;
267 $form->{"AR_amount_chart_id_1"} = $last_used_ar_chart->id if $last_used_ar_chart;
270 if (!$form->{form_validity_token}) {
271 $form->{form_validity_token} = SL::DB::ValidityToken->create(scope => SL::DB::ValidityToken::SCOPE_SALES_INVOICE_POST())->token;
275 $main::lxdebug->leave_sub();
278 sub add_from_email_journal {
279 die "No 'email_journal_id' was given." unless ($::form->{email_journal_id});
283 sub load_record_template_from_email_journal {
284 die "No 'email_journal_id' was given." unless ($::form->{email_journal_id});
285 &load_record_template;
288 sub edit_with_email_journal_workflow {
290 die "No 'email_journal_id' was given." unless ($::form->{email_journal_id});
291 $::form->{workflow_email_journal_id} = delete $::form->{email_journal_id};
292 $::form->{workflow_email_attachment_id} = delete $::form->{email_attachment_id};
293 $::form->{workflow_email_callback} = delete $::form->{callback};
299 $main::lxdebug->enter_sub();
301 # Delay access check to after the invoice's been loaded in
302 # "create_links" so that project-specific invoice rights can be
305 my $form = $main::form;
307 # show history button
308 $form->{javascript} = qq|<script type="text/javascript" src="js/show_history.js"></script>|;
309 #/show hhistory button
310 $form->{javascript} .= qq|<script type="text/javascript" src="js/common.js"></script>|;
311 $form->{title} = "Edit";
316 $main::lxdebug->leave_sub();
320 $main::lxdebug->enter_sub();
324 my $form = $main::form;
329 $main::lxdebug->leave_sub();
332 sub _retrieve_invoice_object {
333 return undef if !$::form->{id};
334 return $::form->{invoice_obj} if $::form->{invoice_obj} && $::form->{invoice_obj}->id == $::form->{id};
335 return SL::DB::Invoice->new(id => $::form->{id})->load;
339 $main::lxdebug->enter_sub();
341 # Delay access check to after the invoice's been loaded so that
342 # project-specific invoice rights can be evaluated.
345 my $form = $main::form;
346 my %myconfig = %main::myconfig;
348 $form->create_links("AR", \%myconfig, "customer");
349 $form->{invoice_obj} = _retrieve_invoice_object();
354 if (!$params{dont_save}) {
355 %saved = map { ($_ => $form->{$_}) } qw(direct_debit id taxincluded);
356 $saved{duedate} = $form->{duedate} if $form->{duedate};
357 $saved{currency} = $form->{currency} if $form->{currency};
360 IS->get_customer(\%myconfig, \%$form);
362 $form->{$_} = $saved{$_} for keys %saved;
363 $form->{rowcount} = 1;
364 $form->{AR_chart_id} = $form->{acc_trans} && $form->{acc_trans}->{AR} ? $form->{acc_trans}->{AR}->[0]->{chart_id} : $::instance_conf->get_ar_chart_id || $form->{AR_links}->{AR}->[0]->{chart_id};
367 $form->{defaultcurrency} = $form->get_default_currency(\%myconfig);
369 $form->{ALL_DEPARTMENTS} = SL::DB::Manager::Department->get_all_sorted;
371 # build the popup menus
372 $form->{taxincluded} = ($form->{id}) ? $form->{taxincluded} : "checked";
374 AR->setup_form($form);
377 ($form->datetonum($form->{transdate}, \%myconfig) <=
378 $form->datetonum($form->{closedto}, \%myconfig));
380 $main::lxdebug->leave_sub();
384 $main::lxdebug->enter_sub();
388 my $form = $main::form;
389 my %myconfig = %main::myconfig;
390 my $locale = $main::locale;
391 my $cgi = $::request->{cgi};
393 $form->{invoice_obj} = _retrieve_invoice_object();
395 my ($title, $readonly, $exchangerate, $rows);
396 my ($notes, $amount, $project);
398 $form->{initial_focus} = !($form->{amount_1} * 1) ? 'customer_id' : 'row_' . $form->{rowcount};
400 $title = $form->{title};
401 # $locale->text('Add Accounts Receivables Transaction')
402 # $locale->text('Edit Accounts Receivables Transaction')
403 $form->{title} = $locale->text("$title Accounts Receivables Transaction");
405 $form->{defaultcurrency} = $form->get_default_currency(\%myconfig);
406 if ($form->{currency} ne $form->{defaultcurrency}) {
407 ($form->{exchangerate}, $form->{record_forex}) = $form->check_exchangerate(\%myconfig, $form->{currency}, $form->{transdate}, "buy", $form->{id}, 'ar');
411 $rows = max 2, $form->numtextrows($form->{notes}, 50);
413 my @old_project_ids = grep { $_ } map { $form->{"project_id_$_"} } 1..$form->{rowcount};
415 $form->get_lists("projects" => { "key" => "ALL_PROJECTS",
417 "old_id" => \@old_project_ids },
418 "charts" => { "key" => "ALL_CHARTS",
419 "transdate" => $form->{transdate} },
422 $form->{ALL_DEPARTMENTS} = SL::DB::Manager::Department->get_all_sorted;
424 $_->{link_split} = { map { $_ => 1 } split/:/, $_->{link} } for @{ $form->{ALL_CHARTS} };
426 my %project_labels = map { $_->{id} => $_->{projectnumber} } @{ $form->{"ALL_PROJECTS"} };
428 my (@AR_paid_values, %AR_paid_labels, %bank_accounts);
429 my $default_ar_amount_chart_id;
430 # don't add manual bookings for charts which are assigned to real bank accounts
431 # and are flagged for use with bank import
432 my $bank_accounts = SL::DB::Manager::BankAccount->get_all();
433 foreach my $bank (@{ $bank_accounts }) {
434 if ($bank->use_with_bank_import) {
435 my $accno_paid_bank = $bank->chart->accno;
436 $bank_accounts{$accno_paid_bank} = 1;
439 foreach my $item (@{ $form->{ALL_CHARTS} }) {
440 if ($item->{link_split}{AR_amount}) {
441 $default_ar_amount_chart_id //= $item->{id};
443 } elsif ($item->{link_split}{AR_paid}) {
444 next if $bank_accounts{$item->{accno}};
445 push(@AR_paid_values, $item->{accno});
446 $AR_paid_labels{$item->{accno}} = "$item->{accno}--$item->{description}";
450 my $follow_up_vc = $form->{customer_id} ? SL::DB::Customer->load_cached($form->{customer_id})->name : '';
451 my $follow_up_trans_info = "$form->{invnumber} ($follow_up_vc)";
453 $::request->layout->add_javascripts("autocomplete_chart.js", "show_history.js", "follow_up.js", "kivi.Draft.js", "kivi.GL.js", "kivi.File.js", "kivi.RecordTemplate.js", "kivi.AR.js", "kivi.CustomerVendor.js", "kivi.Validator.js", "autocomplete_project.js");
454 # get the correct date for tax
455 my $transdate = $::form->{transdate} ? DateTime->from_kivitendo($::form->{transdate}) : DateTime->today_local;
456 my $deliverydate = $::form->{deliverydate} ? DateTime->from_kivitendo($::form->{deliverydate}) : undef;
457 my $taxdate = $deliverydate ? $deliverydate : $transdate;
462 for my $i (1 .. $form->{rowcount}) {
464 amount => $form->{"amount_$i"},
465 tax => $form->{"tax_$i"},
466 project_id => ($i==$form->{rowcount}) ? $form->{globalproject_id} : $form->{"project_id_$i"},
469 my (%taxchart_labels, @taxchart_values, $default_taxchart, $taxchart_to_use);
470 my $amount_chart_id = $form->{"AR_amount_chart_id_$i"} // $default_ar_amount_chart_id;
473 if ( $form->{"taxchart_$i"} ) {
474 ($used_tax_id) = split(/--/, $form->{"taxchart_$i"});
476 foreach my $item ( GL->get_active_taxes_for_chart($amount_chart_id, $taxdate, $used_tax_id) ) {
477 my $key = $item->id . "--" . $item->rate;
478 $first_taxchart //= $item;
479 $default_taxchart = $item if $item->{is_default};
480 $taxchart_to_use = $item if $key eq $form->{"taxchart_$i"};
482 push(@taxchart_values, $key);
483 $taxchart_labels{$key} = $item->taxkey . " - " . $item->taxdescription . " " . $item->rate * 100 . ' %';
486 $taxchart_to_use //= $default_taxchart // $first_taxchart;
487 my $selected_taxchart = $taxchart_to_use->id . '--' . $taxchart_to_use->rate;
489 $transaction->{selectAR_amount} =
490 SL::Presenter::Chart::picker("AR_amount_chart_id_$i", $amount_chart_id, style => "width: 400px", type => "AR_amount", class => ($form->{initial_focus} eq "row_$i" ? "initial_focus" : ""))
491 . SL::Presenter::Tag::hidden_tag("previous_AR_amount_chart_id_$i", $amount_chart_id);
493 $transaction->{taxchart} =
494 NTI($cgi->popup_menu('-name' => "taxchart_$i",
495 '-id' => "taxchart_$i",
496 '-style' => 'width:200px',
497 '-values' => \@taxchart_values,
498 '-labels' => \%taxchart_labels,
499 '-default' => $selected_taxchart));
501 push @transactions, $transaction;
504 $form->{invtotal_unformatted} = $form->{invtotal};
506 $form->{paidaccounts}++ if ($form->{"paid_$form->{paidaccounts}"});
508 my $now = $form->current_date(\%myconfig);
512 # reset form value of defaultcurrency_totalpaid, as it is currently a hidden and otherwise it gets accumulated after each update
513 # is only used if there are exchange rates
514 $form->{"defaultcurrency_totalpaid"} = 0;
516 for my $i (1 .. $form->{paidaccounts}) {
517 # hook for calc of of defaultcurrency_paid and check if banktransaction has a record exchangerate
518 if ($form->{"exchangerate_$i"} && $form->{"acc_trans_id_$i"}) {
519 # only check for bank transactions for payments that have already been saved
520 my $bt_acc_trans = SL::DB::Manager::BankTransactionAccTrans->find_by(acc_trans_id => $form->{"acc_trans_id_$i"});
522 if ($bt_acc_trans->bank_transaction->exchangerate > 0) {
523 $form->{"exchangerate_$i"} = $bt_acc_trans->bank_transaction->exchangerate;
524 $form->{"forex_$i"} = $form->{"exchangerate_$i"};
525 $form->{"record_forex_$i"} = 1;
528 if (!$form->{"fx_transaction_$i"}) {
529 # this is a banktransaction that was paid in internal currency. revert paid/defaultcurrency_paid
530 $form->{"defaultcurrency_paid_$i"} = $form->{"paid_$i"};
531 $form->{"paid_$i"} /= $form->{"exchangerate_$i"};
533 $form->{"defaultcurrency_paid_$i"} //= $form->{"paid_$i"} * $form->{"exchangerate_$i"};
534 $form->{"defaultcurrency_totalpaid"} += $form->{"defaultcurrency_paid_$i"};
535 } # end hook defaultcurrency_paid
538 paid => $form->{"paid_$i"},
539 exchangerate => $form->{"exchangerate_$i"} || '',
540 gldate => $form->{"gldate_$i"},
541 acc_trans_id => $form->{"acc_trans_id_$i"},
542 source => $form->{"source_$i"},
543 memo => $form->{"memo_$i"},
544 AR_paid => $form->{"AR_paid_$i"},
545 forex => $form->{"forex_$i"},
546 record_forex => $form->{"record_forex_$i"},
547 datepaid => $form->{"datepaid_$i"},
548 paid_project_id => $form->{"paid_project_id_$i"},
549 gldate => $form->{"gldate_$i"},
550 # only used if we have an fx currency
551 defaultcurrency_paid => $form->{"defaultcurrency_paid_$i"},
552 defaultcurrency_totalpaid => $form->{"defaultcurrency_totalpaid_$i"},
555 # default account for current assets (i.e. 1801 - SKR04) if no account is selected
556 $form->{accno_arap} = IS->get_standard_accno_current_assets(\%myconfig, \%$form);
558 $payment->{selectAR_paid} =
559 NTI($cgi->popup_menu('-name' => "AR_paid_$i",
560 '-id' => "AR_paid_$i",
561 '-values' => \@AR_paid_values,
562 '-labels' => \%AR_paid_labels,
563 '-default' => $payment->{AR_paid} || $form->{accno_arap}));
567 $payment->{changeable} =
568 SL::DB::Default->get->payments_changeable == 0 ? !$payment->{acc_trans_id} # never
569 : SL::DB::Default->get->payments_changeable == 2 ? $payment->{gldate} eq '' || $payment->{gldate} eq $now
572 #deaktivieren von gebuchten Zahlungen ausserhalb der Bücherkontrolle, vorher prüfen ob heute eingegeben
573 if ($form->date_closed($payment->{"gldate_$i"})) {
574 $payment->{changeable} = 0;
577 push @payments, $payment;
580 my @empty = grep { $_->{paid} eq '' } @payments;
582 (sort_by { DateTime->from_kivitendo($_->{datepaid}) } grep { $_->{paid} ne '' } @payments),
586 $form->{totalpaid} = sum map { $_->{paid} } @payments;
588 my $employees = SL::DB::Manager::Employee->get_all_sorted(
591 (id => $::form->{employee_id}) x !!$::form->{employee_id},
598 setup_ar_form_header_action_bar();
599 $::form->{paid_missing} = $form->{is_linked_bank_transaction} && $form->{invoice_obj}->forex ?
600 $form->{invoice_obj}->open_amount
601 : $::form->{invtotal} - $::form->{totalpaid};
604 print $::form->parse_html_template('ar/form_header', {
605 paid_missing => $::form->{paidmissing},
606 show_exch => ($::form->{defaultcurrency} && ($::form->{currency} ne $::form->{defaultcurrency})),
607 payments => \@payments,
608 transactions => \@transactions,
609 project_labels => \%project_labels,
611 AR_chart_id => $form->{AR_chart_id},
613 follow_up_trans_info => $follow_up_trans_info,
614 today => DateTime->today,
615 currencies => scalar(SL::DB::Manager::Currency->get_all_sorted),
616 employees => $employees,
619 $main::lxdebug->leave_sub();
623 $main::lxdebug->enter_sub();
627 my $form = $main::form;
628 my %myconfig = %main::myconfig;
629 my $locale = $main::locale;
630 my $cgi = $::request->{cgi};
633 my $follow_ups = FU->follow_ups('trans_id' => $form->{id}, 'not_done' => 1);
634 if ( @{ $follow_ups} ) {
635 $form->{follow_up_length} = scalar(@{$follow_ups});
636 $form->{follow_up_due_length} = sum(map({ $_->{due} * 1 } @{ $follow_ups }));
640 print $::form->parse_html_template('ar/form_footer');
642 $main::lxdebug->leave_sub();
646 $::auth->assert('ar_transactions');
648 SL::DB::Invoice->new(id => $::form->{id})->load->mark_as_paid;
649 $::form->redirect($::locale->text("Marked as paid"));
653 $::form->{transdate} = DateTime->today_local->to_kivitendo if !$::form->{transdate};
654 $::form->{gldate} = $::form->{transdate} if !$::form->{gldate};
655 $::form->{form_validity_token} = SL::DB::ValidityToken->create(scope => SL::DB::ValidityToken::SCOPE_SALES_INVOICE_POST())->token;
661 $main::lxdebug->enter_sub();
663 $main::auth->assert('ar_transactions');
665 my $form = $main::form;
666 my %myconfig = %main::myconfig;
670 my ($totaltax, $exchangerate);
672 $form->{invtotal} = 0;
674 delete @{ $form }{ grep { m/^tax_\d+$/ } keys %{ $form } };
676 map { $form->{$_} = $form->parse_amount(\%myconfig, $form->{$_}) }
677 qw(exchangerate creditlimit creditremaining);
679 my @flds = qw(amount AR_amount_chart_id projectnumber oldprojectnumber project_id taxchart tax);
683 for my $i (1 .. $form->{rowcount}) {
684 $form->{"amount_$i"} = $form->parse_amount(\%myconfig, $form->{"amount_$i"});
685 if ($form->{"amount_$i"} || $params{keep_rows_without_amount}) {
688 my ($taxkey, $rate) = split(/--/, $form->{"taxchart_$i"});
691 ($tmpnetamount,$form->{"tax_$i"}) = $form->calculate_tax($form->{"amount_$i"},$rate,$form->{taxincluded},2);
693 $totaltax += $form->{"tax_$i"};
694 map { $a[$j]->{$_} = $form->{"${_}_$i"} } @flds;
699 $form->redo_rows(\@flds, \@a, $count, $form->{rowcount});
700 $form->{rowcount} = $count + ($params{dont_add_new_row} ? 0 : 1);
701 map { $form->{invtotal} += $form->{"amount_$_"} } (1 .. $form->{rowcount});
703 $form->{forex} = $form->check_exchangerate( \%myconfig, $form->{currency}, $form->{transdate}, 'buy');
704 $form->{exchangerate} = $form->{forex} if $form->{forex};
706 $form->{invdate} = $form->{transdate};
708 if (($form->{previous_customer_id} || $form->{customer_id}) != $form->{customer_id}) {
709 IS->get_customer(\%myconfig, $form);
710 if (($form->{rowcount} == 1) && ($form->{amount_1} == 0)) {
711 my $last_used_ar_chart = SL::DB::Customer->load_cached($form->{customer_id})->last_used_ar_chart;
712 $form->{"AR_amount_chart_id_1"} = $last_used_ar_chart->id if $last_used_ar_chart;
717 ($form->{taxincluded}) ? $form->{invtotal} : $form->{invtotal} + $totaltax;
719 for my $i (1 .. $form->{paidaccounts}) {
720 if ($form->parse_amount(\%myconfig, $form->{"paid_$i"})) {
723 $form->parse_amount(\%myconfig, $form->{"${_}_$i"})
724 } qw(paid exchangerate);
726 $form->{totalpaid} += $form->{"paid_$i"};
728 $form->{"forex_$i"} = $form->check_exchangerate( \%myconfig, $form->{currency}, $form->{"datepaid_$i"}, 'buy');
729 $form->{"exchangerate_$i"} = $form->{"forex_$i"} if $form->{"forex_$i"};
733 $form->{creditremaining} -=
734 ($form->{invtotal} - $form->{totalpaid} + $form->{oldtotalpaid} -
735 $form->{oldinvtotal});
736 $form->{oldinvtotal} = $form->{invtotal};
737 $form->{oldtotalpaid} = $form->{totalpaid};
741 $main::lxdebug->leave_sub();
745 # ToDO: fix $closedto and $invdate
748 $main::lxdebug->enter_sub();
750 $main::auth->assert('ar_transactions');
752 my $form = $main::form;
753 my %myconfig = %main::myconfig;
754 my $locale = $main::locale;
756 $form->mtime_ischanged('ar');
757 $form->{defaultcurrency} = $form->get_default_currency(\%myconfig);
759 my $invdate = $form->datetonum($form->{transdate}, \%myconfig);
761 for my $i (1 .. $form->{paidaccounts}) {
763 if ($form->parse_amount(\%myconfig, $form->{"paid_$i"})) {
764 my $datepaid = $form->datetonum($form->{"datepaid_$i"}, \%myconfig);
766 $form->isblank("datepaid_$i", $locale->text('Payment date missing!'));
768 $form->error($locale->text('Cannot post transaction above the maximum future booking date!'))
769 if ($form->date_max_future($form->{"datepaid_$i"}, \%myconfig));
771 #Zusätzlich noch das Buchungsdatum in die Bücherkontrolle einbeziehen
772 # (Dient zur Prüfung ob ZE oder ZA geprüft werden soll)
773 $form->error($locale->text('Cannot post payment for a closed period!'))
774 if ($form->date_closed($form->{"datepaid_$i"}) && !$form->date_closed($form->{"gldate_$i"}, \%myconfig));
776 if ($form->{defaultcurrency} && ($form->{currency} ne $form->{defaultcurrency})) {
777 # $form->{"exchangerate_$i"} = $form->{exchangerate} if ($invdate == $datepaid);
778 $form->isblank("exchangerate_$i", $locale->text('Exchangerate for payment missing!'));
783 ($form->{AR}) = split /--/, $form->{AR};
784 ($form->{AR_paid}) = split /--/, $form->{AR_paid};
785 if (AR->post_payment(\%myconfig, \%$form)) {
786 $form->{snumbers} = qq|invnumber_| . $form->{invnumber};
787 $form->{what_done} = 'invoice';
788 $form->{addition} = "PAYMENT POSTED";
790 $form->redirect($locale->text('Payment posted!'))
792 $form->error($locale->text('Cannot post payment!'));
795 $main::lxdebug->leave_sub();
800 $main::auth->assert('ar_transactions');
802 my $form = $main::form;
809 $main::lxdebug->enter_sub();
811 $main::auth->assert('ar_transactions');
813 my $form = $main::form;
814 my %myconfig = %main::myconfig;
815 my $locale = $main::locale;
819 $form->mtime_ischanged('ar');
823 # check if there is an invoice number, invoice and due date
824 $form->isblank("transdate", $locale->text('Invoice Date missing!'));
825 $form->isblank("duedate", $locale->text('Due Date missing!'));
826 $form->isblank("customer_id", $locale->text('Customer missing!'));
828 if ($myconfig{mandatory_departments} && !$form->{department_id}) {
829 $form->{saved_message} = $::locale->text('You have to specify a department.');
834 my $closedto = $form->datetonum($form->{closedto}, \%myconfig);
835 my $transdate = $form->datetonum($form->{transdate}, \%myconfig);
837 $form->error($locale->text('Cannot post transaction above the maximum future booking date!'))
838 if ($form->date_max_future($transdate, \%myconfig));
840 $form->error($locale->text('Cannot post transaction for a closed period!')) if ($form->date_closed($form->{"transdate"}, \%myconfig));
842 $form->error($locale->text('Zero amount posting!'))
843 unless grep $_*1, map $form->parse_amount(\%myconfig, $form->{"amount_$_"}), 1..$form->{rowcount};
845 if ($form->{defaultcurrency} && ($form->{currency} ne $form->{defaultcurrency})) {
846 $form->isblank("exchangerate", $locale->text('Exchangerate missing!'));
847 $form->error($locale->text('Cannot post invoice with negative exchange rate'))
848 unless ($form->parse_amount(\%myconfig, $form->{"exchangerate"}) > 0);
853 for my $i (1 .. $form->{paidaccounts}) {
854 if ($form->parse_amount(\%myconfig, $form->{"paid_$i"})) {
855 $datepaid = $form->datetonum($form->{"datepaid_$i"}, \%myconfig);
857 $form->isblank("datepaid_$i", $locale->text('Payment date missing!'));
859 $form->error($locale->text('Cannot post transaction above the maximum future booking date!'))
860 if ($form->date_max_future($form->{"datepaid_$i"}, \%myconfig));
862 #Zusätzlich noch das Buchungsdatum in die Bücherkontrolle einbeziehen
863 # (Dient zur Prüfung ob ZE oder ZA geprüft werden soll)
864 $form->error($locale->text('Cannot post payment for a closed period!'))
865 if ($form->date_closed($form->{"datepaid_$i"}) && !$form->date_closed($form->{"gldate_$i"}, \%myconfig));
867 if ($form->{defaultcurrency} && ($form->{currency} ne $form->{defaultcurrency})) {
868 $form->{"exchangerate_$i"} = $form->{exchangerate} if ($transdate == $datepaid);
869 $form->isblank("exchangerate_$i", $locale->text('Exchangerate for payment missing!'));
874 # if oldcustomer ne customer redo form
875 if (($form->{previous_customer_id} || $form->{customer_id}) != $form->{customer_id}) {
877 $::dispatcher->end_request;
880 $form->{AR}{receivables} = $form->{ARselected};
883 $form->error($locale->text('Cannot post transaction!')) unless AR->post_transaction(\%myconfig, \%$form);
886 if(!exists $form->{addition} && $form->{id} ne "") {
887 $form->{snumbers} = "invnumber_$form->{invnumber}";
888 $form->{what_done} = "invoice";
889 $form->{addition} = "POSTED";
892 # /saving the history
894 if ($form->{email_journal_id} && $form->{id} ne "") {
895 my $ar_transaction = SL::DB::Invoice->new(id => $form->{id})->load;
896 my $email_journal = SL::DB::EmailJournal->new(
897 id => delete $form->{email_journal_id}
899 $email_journal->link_to_record_with_attachment($ar_transaction, delete $::form->{email_attachment_id});
903 my $msg = $locale->text("AR transaction '#1' posted (ID: #2)", $form->{invnumber}, $form->{id});
904 if ($::instance_conf->get_ar_add_doc && $::instance_conf->get_doc_storage) {
905 my $add_doc_url = build_std_url("script=ar.pl", 'action=edit', 'id=' . E($form->{id}));
906 SL::Helper::Flash::flash_later('info', $msg);
907 print $form->redirect_header($add_doc_url);
908 $::dispatcher->end_request;
911 $form->redirect($msg);
915 $main::lxdebug->leave_sub();
919 $main::lxdebug->enter_sub();
920 $main::auth->assert('ar_transactions');
921 my $locale = $main::locale;
927 my $callback = $form->{callback}
928 || "controller.pl?action=LoginScreen/user_login";
929 my $msg = $locale->text("AR transaction '#1' posted (ID: #2)", $form->{invnumber}, $form->{id});
930 SL::Helper::Flash::flash_later('info', $msg);
931 print $form->redirect_header($callback);
932 $::dispatcher->end_request;
934 $main::lxdebug->leave_sub();
938 $main::lxdebug->enter_sub();
940 $main::auth->assert('ar_transactions');
942 my $form = $main::form;
943 my %myconfig = %main::myconfig;
945 $form->{email_journal_id} = delete $form->{workflow_email_journal_id};
946 $form->{email_attachment_id} = delete $form->{workflow_email_attachment_id};
947 $form->{callback} = delete $form->{workflow_email_callback};
949 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);
950 $form->{paidaccounts} = 1;
953 my $today = DateTime->today_local;
954 $form->{transdate} = $today->to_kivitendo;
955 $form->{duedate} = $form->{transdate};
957 if ($form->{customer_id}) {
958 my $payment_terms = SL::DB::Customer->load_cached($form->{customer_id})->payment;
959 $form->{duedate} = $payment_terms->calc_date(reference_date => $today)->to_kivitendo if $payment_terms;
962 $form->{form_validity_token} = SL::DB::ValidityToken->create(scope => SL::DB::ValidityToken::SCOPE_SALES_INVOICE_POST())->token;
966 $main::lxdebug->leave_sub();
970 $::auth->assert('ar_transactions');
972 my $form = $main::form;
973 my %myconfig = %main::myconfig;
974 my $locale = $main::locale;
976 if (AR->delete_transaction(\%myconfig, \%$form)) {
978 if(!exists $form->{addition}) {
979 $form->{snumbers} = qq|invnumber_| . $form->{invnumber};
980 $form->{what_done} = "invoice";
981 $form->{addition} = "DELETED";
984 # /saving the history
985 $form->redirect($locale->text('Transaction deleted!'));
987 $form->error($locale->text('Cannot delete transaction!'));
990 sub setup_ar_search_action_bar {
993 for my $bar ($::request->layout->get('actionbar')) {
996 $::locale->text('Search'),
997 submit => [ '#form' ],
998 checks => [ 'kivi.validate_form' ],
999 accesskey => 'enter',
1003 $::request->layout->add_javascripts('kivi.Validator.js');
1006 sub setup_ar_transactions_action_bar {
1008 my $may_edit_create = $::auth->assert('invoice_edit', 1);
1010 my $webdav_enabled = SL::DB::Default->get->webdav
1011 && SL::DB::Default->get->webdav_documents;
1012 my $files_enabled = SL::DB::Default->get->doc_storage;
1014 for my $bar ($::request->layout->get('actionbar')) {
1017 $::locale->text('Print'),
1018 call => [ 'kivi.MassInvoiceCreatePrint.showMassPrintOptionsOrDownloadDirectly' ],
1019 disabled => !$may_edit_create ? t8('You do not have the permissions to access this function.')
1020 : !$params{num_rows} ? $::locale->text('The report doesn\'t contain entries.')
1024 action => [ $::locale->text('PDF-Export') ],
1027 submit => [ '#report_form', { action => 'Invoice/webdav_pdf_export' } ],
1028 checks => [ ['kivi.check_if_entries_selected', '[name="id[]"]'] ],
1029 disabled => !$webdav_enabled ? t8('WebDAV is not enabled.')
1034 submit => [ '#report_form', { action => 'Invoice/files_pdf_export' } ],
1035 checks => [ ['kivi.check_if_entries_selected', '[name="id[]"]'] ],
1036 disabled => !$files_enabled ? t8('No File Management enabled.')
1041 action => [ $::locale->text('Create new') ],
1043 $::locale->text('AR Transaction'),
1044 submit => [ '#create_new_form', { action => 'ar_transaction' } ],
1045 disabled => !$may_edit_create ? t8('You do not have the permissions to access this function.') : undef,
1048 $::locale->text('Sales Invoice'),
1049 submit => [ '#create_new_form', { action => 'sales_invoice' } ],
1050 disabled => !$may_edit_create ? t8('You do not have the permissions to access this function.') : undef,
1052 ], # end of combobox "Create new"
1058 $main::lxdebug->enter_sub();
1060 my $form = $main::form;
1061 my %myconfig = %main::myconfig;
1062 my $locale = $main::locale;
1063 my $cgi = $::request->{cgi};
1065 $form->{title} = $locale->text('Invoices, Credit Notes & AR Transactions');
1067 $form->{ALL_EMPLOYEES} = SL::DB::Manager::Employee ->get_all_sorted(query => [ deleted => 0 ]);
1068 $form->{ALL_DEPARTMENTS} = SL::DB::Manager::Department ->get_all_sorted;
1069 $form->{ALL_BUSINESS_TYPES} = SL::DB::Manager::Business ->get_all_sorted;
1070 $form->{ALL_TAXZONES} = SL::DB::Manager::TaxZone ->get_all_sorted;
1071 $form->{ALL_PAYMENT_TERMS} = SL::DB::Manager::PaymentTerm->get_all_sorted;
1073 $form->{CT_CUSTOM_VARIABLES} = CVar->get_configs('module' => 'CT');
1074 ($form->{CT_CUSTOM_VARIABLES_FILTER_CODE},
1075 $form->{CT_CUSTOM_VARIABLES_INCLUSION_CODE}) = CVar->render_search_options('variables' => $form->{CT_CUSTOM_VARIABLES},
1076 'include_prefix' => 'l_',
1077 'include_value' => 'Y');
1079 # constants and subs for template
1080 $form->{vc_keys} = sub { "$_[0]->{name}--$_[0]->{id}" };
1082 $::request->layout->add_javascripts("autocomplete_project.js");
1084 setup_ar_search_action_bar();
1087 print $form->parse_html_template('ar/search', { %myconfig });
1089 $main::lxdebug->leave_sub();
1092 sub create_subtotal_row {
1093 $main::lxdebug->enter_sub();
1095 my ($totals, $columns, $column_alignment, $subtotal_columns, $class) = @_;
1097 my $form = $main::form;
1098 my %myconfig = %main::myconfig;
1100 my $row = { map { $_ => { 'data' => '', 'class' => $class, 'align' => $column_alignment->{$_}, } } @{ $columns } };
1102 map { $row->{$_}->{data} = $form->format_amount(\%myconfig, $totals->{$_}, 2) } @{ $subtotal_columns };
1104 $row->{tax}->{data} = $form->format_amount(\%myconfig, $totals->{amount} - $totals->{netamount}, 2);
1106 map { $totals->{$_} = 0 } @{ $subtotal_columns };
1108 $main::lxdebug->leave_sub();
1113 sub ar_transactions {
1114 $main::lxdebug->enter_sub();
1116 my $form = $main::form;
1117 my %myconfig = %main::myconfig;
1118 my $locale = $main::locale;
1120 my ($callback, $href, @columns);
1123 report_generator_set_default_sort('transdate', 1);
1125 AR->ar_transactions(\%myconfig, \%$form);
1127 $form->{title} = $locale->text('Invoices, Credit Notes & AR Transactions');
1129 my $report = SL::ReportGenerator->new(\%myconfig, $form);
1132 ids transdate id type invnumber ordnumber cusordnumber donumber
1133 deliverydate name netamount tax amount paid datepaid due duedate
1134 transaction_description notes salesman employee shippingpoint shipvia
1135 marge_total marge_percent globalprojectnumber customernumber country
1136 ustid taxzone payment_terms charts customertype direct_debit
1137 dunning_description department attachments items customer_dunning_lock
1138 shiptoname shiptodepartment_1 shiptodepartment_2 shiptostreet
1139 shiptozipcode shiptocity shiptocountry
1142 my $ct_cvar_configs = CVar->get_configs('module' => 'CT');
1143 my @ct_includeable_custom_variables = grep { $_->{includeable} } @{ $ct_cvar_configs };
1144 my @ct_searchable_custom_variables = grep { $_->{searchable} } @{ $ct_cvar_configs };
1146 my %column_defs_cvars = map { +"cvar_$_->{name}" => { 'text' => $_->{description} } } @ct_includeable_custom_variables;
1147 push @columns, map { "cvar_$_->{name}" } @ct_includeable_custom_variables;
1149 my @hidden_variables = map { "l_${_}" } @columns;
1150 push @hidden_variables, "l_subtotal", qw(
1151 open closed customer invnumber ordnumber cusordnumber
1152 transaction_description notes project_id transdatefrom transdateto
1153 duedatefrom duedateto datepaidfrom datepaidto employee_id salesman_id
1154 business_id parts_partnumber parts_description department_id
1155 show_marked_as_closed show_not_mailed shippingpoint shipvia taxzone_id
1156 payment_id shiptoname shiptodepartment_1 shiptodepartment_2 shiptostreet
1157 shiptozipcode shiptocity shiptocountry
1159 push @hidden_variables, map { "cvar_$_->{name}" } @ct_searchable_custom_variables;
1161 $href = $params{want_binary_pdf} ? '' : build_std_url('action=ar_transactions', grep { $form->{$_} } @hidden_variables);
1164 'ids' => { raw_header_data => SL::Presenter::Tag::checkbox_tag("", id => "check_all", checkall => "[data-checkall=1]"), align => 'center' },
1165 'transdate' => { 'text' => $locale->text('Date'), },
1166 'id' => { 'text' => $locale->text('ID'), },
1167 'type' => { 'text' => $locale->text('Type'), },
1168 'invnumber' => { 'text' => $locale->text('Invoice'), },
1169 'ordnumber' => { 'text' => $locale->text('Order'), },
1170 'cusordnumber' => { 'text' => $locale->text('Customer Order Number'), },
1171 'donumber' => { 'text' => $locale->text('Delivery Order'), },
1172 'deliverydate' => { 'text' => $locale->text('Delivery Date'), },
1173 'name' => { 'text' => $locale->text('Customer'), },
1174 'netamount' => { 'text' => $locale->text('Amount'), },
1175 'tax' => { 'text' => $locale->text('Tax'), },
1176 'amount' => { 'text' => $locale->text('Total'), },
1177 'paid' => { 'text' => $locale->text('Paid'), },
1178 'datepaid' => { 'text' => $locale->text('Date Paid'), },
1179 'due' => { 'text' => $locale->text('Amount Due'), },
1180 'duedate' => { 'text' => $locale->text('Due Date'), },
1181 'transaction_description' => { 'text' => $locale->text('Transaction description'), },
1182 'notes' => { 'text' => $locale->text('Notes'), },
1183 'salesman' => { 'text' => $locale->text('Salesperson'), },
1184 'employee' => { 'text' => $locale->text('Employee'), },
1185 'shippingpoint' => { 'text' => $locale->text('Shipping Point'), },
1186 'shipvia' => { 'text' => $locale->text('Ship via'), },
1187 'globalprojectnumber' => { 'text' => $locale->text('Document Project Number'), },
1188 'marge_total' => { 'text' => $locale->text('Ertrag'), },
1189 'marge_percent' => { 'text' => $locale->text('Ertrag prozentual'), },
1190 'customernumber' => { 'text' => $locale->text('Customer Number'), },
1191 'country' => { 'text' => $locale->text('Country'), },
1192 'ustid' => { 'text' => $locale->text('USt-IdNr.'), },
1193 'taxzone' => { 'text' => $locale->text('Steuersatz'), },
1194 'payment_terms' => { 'text' => $locale->text('Payment Terms'), },
1195 'charts' => { 'text' => $locale->text('Chart'), },
1196 'customertype' => { 'text' => $locale->text('Customer type'), },
1197 'direct_debit' => { 'text' => $locale->text('direct debit'), },
1198 'department' => { 'text' => $locale->text('Department'), },
1199 dunning_description => { 'text' => $locale->text('Dunning level'), },
1200 attachments => { 'text' => $locale->text('Attachments'), },
1201 items => { 'text' => $locale->text('Positions'), },
1202 customer_dunning_lock => { 'text' => $locale->text('Dunning lock'), },
1203 shiptoname => { 'text' => $locale->text('Name (Shipping)'), },
1204 shiptodepartment_1 => { 'text' => $locale->text('Department 1 (Shipping)'), },
1205 shiptodepartment_2 => { 'text' => $locale->text('Department 2 (Shipping)'), },
1206 shiptostreet => { 'text' => $locale->text('Street (Shipping)'), },
1207 shiptozipcode => { 'text' => $locale->text('Zipcode (Shipping)'), },
1208 shiptocity => { 'text' => $locale->text('City (Shipping)'), },
1209 shiptocountry => { 'text' => $locale->text('Country (Shipping)'), },
1213 foreach my $name (qw(id transdate duedate invnumber ordnumber cusordnumber donumber deliverydate name datepaid employee shippingpoint shipvia transaction_description direct_debit department taxzone)) {
1214 my $sortdir = $form->{sort} eq $name ? 1 - $form->{sortdir} : $form->{sortdir};
1215 $column_defs{$name}->{link} = $href . "&sort=$name&sortdir=$sortdir";
1218 my %column_alignment = map { $_ => 'right' } qw(netamount tax amount paid due);
1220 $form->{"l_type"} = "Y";
1221 map { $column_defs{$_}->{visible} = $form->{"l_${_}"} ? 1 : 0 } @columns;
1223 $column_defs{ids}->{visible} = 'HTML';
1225 $report->set_columns(%column_defs);
1226 $report->set_column_order(@columns);
1228 $report->set_export_options('ar_transactions', @hidden_variables, qw(sort sortdir));
1230 $report->set_sort_indicator($form->{sort}, $form->{sortdir});
1232 CVar->add_custom_variables_to_report('module' => 'CT',
1233 'trans_id_field' => 'customer_id',
1234 'configs' => $ct_cvar_configs,
1235 'column_defs' => \%column_defs,
1236 'data' => $form->{AR});
1239 if ($form->{customer}) {
1240 push @options, $locale->text('Customer') . " : $form->{customer}";
1242 if ($form->{cp_name}) {
1243 push @options, $locale->text('Contact Person') . " : $form->{cp_name}";
1246 if ($form->{department_id}) {
1247 my $department = SL::DB::Manager::Department->find_by( id => $form->{department_id} );
1248 push @options, $locale->text('Department') . " : " . $department->description;
1250 if ($form->{invnumber}) {
1251 push @options, $locale->text('Invoice Number') . " : $form->{invnumber}";
1253 if ($form->{ordnumber}) {
1254 push @options, $locale->text('Order Number') . " : $form->{ordnumber}";
1256 if ($form->{cusordnumber}) {
1257 push @options, $locale->text('Customer Order Number') . " : $form->{cusordnumber}";
1259 if ($form->{notes}) {
1260 push @options, $locale->text('Notes') . " : $form->{notes}";
1262 if ($form->{transaction_description}) {
1263 push @options, $locale->text('Transaction description') . " : $form->{transaction_description}";
1265 if ($form->{payment_id}) {
1266 my $payment_term = SL::DB::Manager::PaymentTerm->find_by( id => $form->{payment_id} );
1267 push @options, $locale->text('Payment Term') . " : " . $payment_term->description;
1269 if ($form->{parts_partnumber}) {
1270 push @options, $locale->text('Part Number') . " : $form->{parts_partnumber}";
1272 if ($form->{parts_description}) {
1273 push @options, $locale->text('Part Description') . " : $form->{parts_description}";
1275 if ($form->{transdatefrom}) {
1276 push @options, $locale->text('From') . " " . $locale->date(\%myconfig, $form->{transdatefrom}, 1);
1278 if ($form->{transdateto}) {
1279 push @options, $locale->text('Bis') . " " . $locale->date(\%myconfig, $form->{transdateto}, 1);
1281 if ($form->{duedatefrom}) {
1282 push @options, $locale->text('Due Date') . " " . $locale->text('from') . " " . $locale->date(\%myconfig, $form->{duedatefrom}, 1);
1284 if ($form->{duedateto}) {
1285 push @options, $locale->text('Due Date') . " " . $locale->text('to') . " " . $locale->date(\%myconfig, $form->{duedateto}, 1);
1287 if ($form->{datepaidfrom}) {
1288 push @options, $locale->text('Date Paid') . " " . $locale->text('from') . " " . $locale->date(\%myconfig, $form->{datepaidfrom}, 1);
1290 if ($form->{datepaidto}) {
1291 push @options, $locale->text('Date Paid') . " " . $locale->text('to') . " " . $locale->date(\%myconfig, $form->{datepaidto}, 1);
1293 if ($form->{open}) {
1294 push @options, $locale->text('Open');
1296 if ($form->{employee_id}) {
1297 my $employee = SL::DB::Employee->new(id => $form->{employee_id})->load;
1298 push @options, $locale->text('Employee') . ' : ' . $employee->name;
1300 if ($form->{salesman_id}) {
1301 my $salesman = SL::DB::Employee->new(id => $form->{salesman_id})->load;
1302 push @options, $locale->text('Salesman') . ' : ' . $salesman->name;
1304 if ($form->{closed}) {
1305 push @options, $locale->text('Closed');
1307 if ($form->{shipvia}) {
1308 push @options, $locale->text('Ship via') . " : $form->{shipvia}";
1310 if ($form->{shippingpoint}) {
1311 push @options, $locale->text('Shipping Point') . " : $form->{shippingpoint}";
1313 if ($form->{shiptoname}) {
1314 push @options, $locale->text('Name (Shipping)') . " : $form->{shiptoname}";
1316 if ($form->{shiptodepartment_1}) {
1317 push @options, $locale->text('Department 1 (Shipping)') . " : $form->{shiptodepartment_1}";
1319 if ($form->{shiptodepartment_2}) {
1320 push @options, $locale->text('Department 2 (Shipping)') . " : $form->{shiptodepartment_2}";
1322 if ($form->{shiptostreet}) {
1323 push @options, $locale->text('Street (Shipping)') . " : $form->{shiptostreet}";
1325 if ($form->{shiptozipcode}) {
1326 push @options, $locale->text('Zipcode (Shipping)') . " : $form->{shiptozipcode}";
1328 if ($form->{shiptocity}) {
1329 push @options, $locale->text('City (Shipping)') . " : $form->{shiptocity}";
1331 if ($form->{shiptocountry}) {
1332 push @options, $locale->text('Country (Shipping)') . " : $form->{shiptocountry}";
1335 $form->{ALL_PRINTERS} = SL::DB::Manager::Printer->get_all_sorted;
1337 $report->set_options('top_info_text' => join("\n", @options),
1338 'raw_top_info_text' => $form->parse_html_template('ar/ar_transactions_header'),
1339 'raw_bottom_info_text' => $form->parse_html_template('ar/ar_transactions_bottom'),
1340 'output_format' => 'HTML',
1341 'title' => $form->{title},
1342 'attachment_basename' => $locale->text('invoice_list') . strftime('_%Y%m%d', localtime time),
1344 $report->set_options_from_form();
1345 $locale->set_numberformat_wo_thousands_separator(\%myconfig) if lc($report->{options}->{output_format}) eq 'csv';
1347 # add sort and escape callback, this one we use for the add sub
1348 $form->{callback} = $href .= "&sort=$form->{sort}";
1350 # escape callback for href
1351 $callback = $form->escape($href);
1353 my @subtotal_columns = qw(netamount amount paid due marge_total marge_percent);
1355 my %totals = map { $_ => 0 } @subtotal_columns;
1356 my %subtotals = map { $_ => 0 } @subtotal_columns;
1360 foreach my $ar (@{ $form->{AR} }) {
1361 $ar->{tax} = $ar->{amount} - $ar->{netamount};
1362 $ar->{due} = $ar->{amount} - $ar->{paid};
1364 map { $subtotals{$_} += $ar->{$_};
1365 $totals{$_} += $ar->{$_} } @subtotal_columns;
1367 $subtotals{marge_percent} = $subtotals{netamount} ? ($subtotals{marge_total} * 100 / $subtotals{netamount}) : 0;
1368 $totals{marge_percent} = $totals{netamount} ? ($totals{marge_total} * 100 / $totals{netamount} ) : 0;
1370 # Preserve $ar->{type} before changing it to the abbreviation letter for
1371 # getting files from file management below.
1372 $ar->{object_type} = $ar->{type};
1374 my $is_storno = $ar->{storno} && $ar->{storno_id};
1375 my $has_storno = $ar->{storno} && !$ar->{storno_id};
1377 if ($ar->{type} eq 'invoice_for_advance_payment') {
1379 $has_storno ? $locale->text("Invoice for Advance Payment with Storno (abbreviation)") :
1380 $is_storno ? $locale->text("Storno (one letter abbreviation)") :
1381 $locale->text("Invoice for Advance Payment (one letter abbreviation)");
1383 } elsif ($ar->{type} eq 'final_invoice') {
1384 $ar->{type} = t8('Final Invoice (one letter abbreviation)');
1388 $has_storno ? $locale->text("Invoice with Storno (abbreviation)") :
1389 $is_storno ? $locale->text("Storno (one letter abbreviation)") :
1390 $ar->{amount} < 0 ? $locale->text("Credit note (one letter abbreviation)") :
1391 $ar->{invoice} ? $locale->text("Invoice (one letter abbreviation)") :
1392 $locale->text("AR Transaction (abbreviation)");
1395 map { $ar->{$_} = $form->format_amount(\%myconfig, $ar->{$_}, 2) } qw(netamount tax amount paid due marge_total marge_percent);
1397 $ar->{direct_debit} = $ar->{direct_debit} ? $::locale->text('yes') : $::locale->text('no');
1401 foreach my $column (@columns) {
1402 next if ($column eq 'items');
1405 'data' => $ar->{$column},
1406 'align' => $column_alignment{$column},
1410 $row->{invnumber}->{link} = build_std_url("script=" . ($ar->{invoice} ? 'is.pl' : 'ar.pl'), 'action=edit')
1411 . "&id=" . E($ar->{id}) . "&callback=${callback}" unless $params{want_binary_pdf};
1414 raw_data => SL::Presenter::Tag::checkbox_tag("id[]", value => $ar->{id}, "data-checkall" => 1),
1419 if ($::instance_conf->get_doc_storage && $form->{l_attachments}) {
1420 my @files = SL::File->get_all_versions(object_id => $ar->{id},
1421 object_type => $ar->{object_type} || 'invoice',
1422 file_type => 'attachment',);
1423 if (scalar @files) {
1424 my $html = join '<br>', map { SL::Presenter::FileObject::file_object($_) } @files;
1425 my $text = join "\n", map { $_->file_name } @files;
1426 $row->{attachments} = { 'raw_data' => $html, data => $text };
1428 $row->{attachments} = { };
1433 if ($form->{l_items}) {
1434 my $items = SL::DB::Manager::InvoiceItem->get_all_sorted(where => [id => $ar->{item_ids}]);
1435 $row->{items}->{raw_data} = SL::Presenter::ItemsList::items_list($items) if lc($report->{options}->{output_format}) eq 'html';
1436 $row->{items}->{data} = SL::Presenter::ItemsList::items_list($items, as_text => 1) if lc($report->{options}->{output_format}) ne 'html';
1439 my $row_set = [ $row ];
1441 if (($form->{l_subtotal} eq 'Y')
1442 && (($idx == (scalar @{ $form->{AR} } - 1))
1443 || ($ar->{ $form->{sort} } ne $form->{AR}->[$idx + 1]->{ $form->{sort} }))) {
1444 push @{ $row_set }, create_subtotal_row(\%subtotals, \@columns, \%column_alignment, \@subtotal_columns, 'listsubtotal');
1447 $report->add_data($row_set);
1452 $report->add_separator();
1453 $report->add_data(create_subtotal_row(\%totals, \@columns, \%column_alignment, \@subtotal_columns, 'listtotal'));
1455 if ($params{want_binary_pdf}) {
1456 $report->generate_with_headers();
1457 return $report->generate_pdf_content(want_binary_pdf => 1);
1460 $::request->layout->add_javascripts('kivi.MassInvoiceCreatePrint.js');
1461 setup_ar_transactions_action_bar(num_rows => scalar(@{ $form->{AR} }));
1463 $report->generate_with_headers();
1465 $main::lxdebug->leave_sub();
1469 $main::lxdebug->enter_sub();
1471 $main::auth->assert('ar_transactions');
1473 my $form = $main::form;
1474 my %myconfig = %main::myconfig;
1475 my $locale = $main::locale;
1477 # don't cancel cancelled transactions
1478 if (IS->has_storno(\%myconfig, $form, 'ar')) {
1479 $form->{title} = $locale->text("Cancel Accounts Receivables Transaction");
1480 $form->error($locale->text("Transaction has already been cancelled!"));
1483 AR->storno($form, \%myconfig, $form->{id});
1485 # saving the history
1486 if(!exists $form->{addition} && $form->{id} ne "") {
1487 $form->{snumbers} = qq|invnumber_| . $form->{invnumber};
1488 $form->{addition} = "STORNO";
1489 $form->{what_done} = "invoice";
1490 $form->save_history;
1492 # /saving the history
1494 $form->redirect(sprintf $locale->text("Transaction %d cancelled."), $form->{storno_id});
1496 $main::lxdebug->leave_sub();
1499 sub setup_ar_form_header_action_bar {
1500 my $transdate = $::form->datetonum($::form->{transdate}, \%::myconfig);
1501 my $closedto = $::form->datetonum($::form->{closedto}, \%::myconfig);
1502 my $is_closed = $transdate <= $closedto;
1504 my $change_never = $::instance_conf->get_ar_changeable == 0;
1505 my $change_on_same_day_only = $::instance_conf->get_ar_changeable == 2 && ($::form->current_date(\%::myconfig) ne $::form->{gldate});
1507 my $is_storno = IS->is_storno(\%::myconfig, $::form, 'ar', $::form->{id});
1508 my $has_storno = IS->has_storno(\%::myconfig, $::form, 'ar');
1509 my $may_edit_create = $::auth->assert('ar_transactions', 1);
1511 my $is_linked_bank_transaction;
1513 && SL::DB::Manager::BankTransactionAccTrans->find_by(ar_id => $::form->{id})) {
1515 $is_linked_bank_transaction = 1;
1517 # add readonly state in $::form
1518 $::form->{readonly} = !$may_edit_create ? 1
1522 : ($::form->{id} && $change_never) ? 1
1523 : ($::form->{id} && $change_on_same_day_only) ? 1
1524 : $is_linked_bank_transaction ? 1
1526 # and is_linked_bank_transaction
1527 $::form->{is_linked_bank_transaction} = $is_linked_bank_transaction;
1528 for my $bar ($::request->layout->get('actionbar')) {
1532 submit => [ '#form', { action => "update" } ],
1533 id => 'update_button',
1534 checks => [ 'kivi.validate_form' ],
1535 disabled => !$may_edit_create ? t8('You must not change this AR transaction.') : undef,
1536 accesskey => 'enter',
1542 submit => [ '#form', { action => "post" } ],
1543 checks => [ 'kivi.validate_form', 'kivi.AR.check_fields_before_posting' ],
1544 disabled => !$may_edit_create ? t8('You must not change this AR transaction.')
1545 : $is_closed ? t8('The billing period has already been locked.')
1546 : $is_storno ? t8('A canceled invoice cannot be posted.')
1547 : ($::form->{id} && $change_never) ? t8('Changing invoices has been disabled in the configuration.')
1548 : ($::form->{id} && $change_on_same_day_only) ? t8('Invoices can only be changed on the day they are posted.')
1549 : $is_linked_bank_transaction ? t8('This transaction is linked with a bank transaction. Please undo and redo the bank transaction booking if needed.')
1553 t8('Post and Close'),
1554 submit => [ '#form', { action => "post_and_close" } ],
1555 checks => [ 'kivi.validate_form', 'kivi.AR.check_fields_before_posting' ],
1556 disabled => !$may_edit_create ? t8('You must not change this AR transaction.')
1557 : $is_closed ? t8('The billing period has already been locked.')
1558 : $is_storno ? t8('A canceled invoice cannot be posted.')
1559 : ($::form->{id} && $change_never) ? t8('Changing invoices has been disabled in the configuration.')
1560 : ($::form->{id} && $change_on_same_day_only) ? t8('Invoices can only be changed on the day they are posted.')
1561 : $is_linked_bank_transaction ? t8('This transaction is linked with a bank transaction. Please undo and redo the bank transaction booking if needed.')
1566 submit => [ '#form', { action => "post_payment" } ],
1567 disabled => !$may_edit_create ? t8('You must not change this AR transaction.')
1568 : !$::form->{id} ? t8('This invoice has not been posted yet.')
1569 : $is_linked_bank_transaction ? t8('This transaction is linked with a bank transaction. Please undo and redo the bank transaction booking if needed.')
1572 action => [ t8('Mark as paid'),
1573 submit => [ '#form', { action => "mark_as_paid" } ],
1574 confirm => t8('This will remove the invoice from showing as unpaid even if the unpaid amount does not match the amount. Proceed?'),
1575 disabled => !$may_edit_create ? t8('You must not change this AR transaction.')
1576 : !$::form->{id} ? t8('This invoice has not been posted yet.')
1578 only_if => $::instance_conf->get_is_show_mark_as_paid,
1580 ], # end of combobox "Post"
1583 action => [ t8('Storno'),
1584 submit => [ '#form', { action => "storno" } ],
1585 checks => [ 'kivi.validate_form', 'kivi.AR.check_fields_before_posting' ],
1586 confirm => t8('Do you really want to cancel this invoice?'),
1587 disabled => !$may_edit_create ? t8('You must not change this AR transaction.')
1588 : !$::form->{id} ? t8('This invoice has not been posted yet.')
1589 : $has_storno ? t8('This invoice has been canceled already.')
1590 : $is_storno ? t8('Reversal invoices cannot be canceled.')
1591 : $::form->{totalpaid} ? t8('Invoices with payments cannot be canceled.')
1594 action => [ t8('Delete'),
1595 submit => [ '#form', { action => "delete" } ],
1596 confirm => t8('Do you really want to delete this object?'),
1597 disabled => !$may_edit_create ? t8('You must not change this AR transaction.')
1598 : !$::form->{id} ? t8('This invoice has not been posted yet.')
1599 : $change_never ? t8('Changing invoices has been disabled in the configuration.')
1600 : $change_on_same_day_only ? t8('Invoices can only be changed on the day they are posted.')
1601 : $is_closed ? t8('The billing period has already been locked.')
1604 ], # end of combobox "Storno"
1609 action => [ t8('Workflow') ],
1612 submit => [ '#form', { action => "use_as_new" } ],
1613 checks => [ 'kivi.validate_form' ],
1614 disabled => !$may_edit_create ? t8('You must not change this AR transaction.')
1615 : !$::form->{id} ? t8('This invoice has not been posted yet.')
1618 ], # end of combobox "Workflow"
1621 action => [ t8('more') ],
1624 call => [ 'set_history_window', $::form->{id} * 1, 'glid' ],
1625 disabled => !$::form->{id} ? t8('This invoice has not been posted yet.') : undef,
1629 call => [ 'follow_up_window' ],
1630 disabled => !$::form->{id} ? t8('This invoice has not been posted yet.') : undef,
1633 t8('Record templates'),
1634 call => [ 'kivi.RecordTemplate.popup', 'ar_transaction' ],
1635 disabled => !$may_edit_create ? t8('You must not change this AR transaction.') : undef,
1639 call => [ 'kivi.Draft.popup', 'ar', 'invoice', $::form->{draft_id}, $::form->{draft_description} ],
1640 disabled => !$may_edit_create ? t8('You must not change this AR transaction.')
1641 : $::form->{id} ? t8('This invoice has already been posted.')
1642 : $is_closed ? t8('The billing period has already been locked.')
1645 ], # end of combobox "more"
1648 $::request->layout->add_javascripts('kivi.Validator.js');