1 #=====================================================================
4 # Based on SQL-Ledger Version 2.1.9
5 # Web http://www.lx-office.org
7 #=====================================================================
8 # SQL-Ledger Accounting
9 # Copyright (c) 1998-2002
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 # Inventory invoicing module
33 #======================================================================
38 use SL::Helper::UserPreferences::DisplayPreferences;
39 use SL::MoreCommon qw(restore_form save_form);
44 use List::MoreUtils qw(any uniq);
45 use List::Util qw(max sum);
46 use List::UtilsBy qw(sort_by);
47 use English qw(-no_match_vars);
49 use SL::DB::BankTransactionAccTrans;
53 use SL::DB::Department;
55 use SL::DB::PaymentTerm;
56 use SL::DB::Reclamation;
57 use SL::DB::EmailJournal;
58 use SL::DB::ValidityToken;
59 use SL::Helper::QrBillFunctions qw(get_ref_number_formatted);
61 require "bin/mozilla/common.pl";
62 require "bin/mozilla/io.pl";
70 sub _may_view_or_edit_this_invoice {
71 return 1 if $::auth->assert('invoice_edit', 1); # may edit all invoices
72 return 0 if !$::form->{id}; # creating new invoices isn't allowed without invoice_edit
73 return 1 if $::auth->assert('sales_invoice_view', 1); # viewing is allowed with this right
74 return 0 if !$::form->{globalproject_id}; # existing records without a project ID are not allowed
75 return SL::DB::Project->new(id => $::form->{globalproject_id})->load->may_employee_view_project_invoices(SL::DB::Manager::Employee->current);
79 my $cache = $::request->cache('is.pl::_assert_access');
81 $cache->{_may_view_or_edit_this_invoice} = _may_view_or_edit_this_invoice() if !exists $cache->{_may_view_or_edit_this_invoice};
82 $::form->show_generic_error($::locale->text("You do not have the permissions to access this function.")) if ! $cache->{_may_view_or_edit_this_invoice};
86 $main::lxdebug->enter_sub();
88 my $form = $main::form;
89 my $locale = $main::locale;
91 $main::auth->assert('invoice_edit');
93 $form->{show_details} = $::myconfig{show_form_details};
95 if ($form->{type} eq "credit_note") {
96 $form->{title} = $locale->text('Add Credit Note');
98 if ($form->{storno}) {
99 $form->{title} = $locale->text('Add Storno Credit Note');
102 } elsif ($form->{type} eq "invoice_for_advance_payment") {
103 $form->{title} = $locale->text('Add Invoice for Advance Payment');
105 } elsif ($form->{type} eq "final_invoice") {
106 $form->{title} = $locale->text('Add Final Invoice');
109 $form->{title} = $locale->text('Add Sales Invoice');
113 if (!$form->{form_validity_token}) {
114 $form->{form_validity_token} = SL::DB::ValidityToken->create(scope => SL::DB::ValidityToken::SCOPE_SALES_INVOICE_POST())->token;
117 $form->{callback} = "$form->{script}?action=add&type=$form->{type}" unless $form->{callback};
119 invoice_links(is_new => 1);
123 $main::lxdebug->leave_sub();
126 sub add_from_email_journal {
127 die "No 'email_journal_id' was given." unless ($::form->{email_journal_id});
131 sub edit_with_email_journal_workflow {
133 die "No 'email_journal_id' was given." unless ($::form->{email_journal_id});
134 $::form->{workflow_email_journal_id} = delete $::form->{email_journal_id};
135 $::form->{workflow_email_attachment_id} = delete $::form->{email_attachment_id};
136 $::form->{workflow_email_callback} = delete $::form->{callback};
142 $main::lxdebug->enter_sub();
144 # Delay access check to after the invoice's been loaded in
145 # "invoice_links" so that project-specific invoice rights can be
148 my $form = $main::form;
149 my $locale = $main::locale;
151 $form->{show_details} = $::myconfig{show_form_details};
152 $form->{taxincluded_changed_by_user} = 1;
154 # show history button
155 $form->{javascript} = qq|<script type="text/javascript" src="js/show_history.js"></script>|;
157 my ($language_id, $printer_id);
158 if ($form->{print_and_post}) {
159 $form->{action} = "print";
160 $form->{resubmit} = 1;
161 $language_id = $form->{language_id};
162 $printer_id = $form->{printer_id};
166 if ($form->{type} eq "credit_note") {
167 $form->{title} = $locale->text('Edit Credit Note');
168 $form->{title} = $locale->text('Edit Storno Credit Note') if $form->{storno};
170 } elsif ($form->{type} eq "invoice_for_advance_payment") {
171 $form->{title} = $locale->text('Edit Invoice for Advance Payment');
172 $form->{title} = $locale->text('Edit Storno Invoice for Advance Payment') if $form->{storno};
174 } elsif ($form->{type} eq "final_invoice") {
175 $form->{title} = $locale->text('Edit Final Invoice');
178 $form->{title} = $locale->text('Edit Sales Invoice');
179 $form->{title} = $locale->text('Edit Storno Invoice') if $form->{storno};
183 if ($form->{print_and_post}) {
184 $form->{language_id} = $language_id;
185 $form->{printer_id} = $printer_id;
190 $main::lxdebug->leave_sub();
194 $main::lxdebug->enter_sub();
196 # Delay access check to after the invoice's been loaded so that
197 # project-specific invoice rights can be evaluated.
200 my $form = $main::form;
201 my %myconfig = %main::myconfig;
203 $form->{vc} = 'customer';
206 $form->create_links("AR", \%myconfig, "customer");
208 my $transfer_chart_id = $::instance_conf->get_advance_payment_clearing_chart_id;
209 if ($transfer_chart_id) {
210 # remove transfer chart for select box AR
211 @{ $form->{AR_links}{AR} } = grep { $_->{chart_id} != $transfer_chart_id } @{ $form->{AR_links}{AR} };
216 my $editing = $form->{id};
218 $form->backup_vars(qw(payment_id language_id taxzone_id salesman_id
219 taxincluded currency cp_id intnotes id shipto_id
222 IS->get_customer(\%myconfig, \%$form);
224 $form->{billing_address_id} = $form->{default_billing_address_id} if $params{is_new};
226 $form->restore_vars(qw(id));
228 IS->retrieve_invoice(\%myconfig, \%$form);
229 $form->restore_vars(qw(payment_id language_id taxzone_id currency intnotes
230 cp_id shipto_id delivery_term_id));
231 $form->restore_vars(qw(taxincluded)) if $form->{id};
232 $form->restore_vars(qw(salesman_id)) if $editing;
234 $form->{employee} = "$form->{employee}--$form->{employee_id}";
237 $form->{forex} = $form->{exchangerate};
238 my $exchangerate = ($form->{exchangerate}) ? $form->{exchangerate} : 1;
240 foreach my $key (keys %{ $form->{AR_links} }) {
241 foreach my $ref (@{ $form->{AR_links}{$key} }) {
242 $form->{"select$key"} .= "<option>$ref->{accno}--$ref->{description}</option>\n";
245 if ($key eq "AR_paid") {
246 next unless $form->{acc_trans}{$key};
247 for my $i (1 .. scalar @{ $form->{acc_trans}{$key} }) {
248 $form->{"AR_paid_$i"} = "$form->{acc_trans}{$key}->[$i-1]->{accno}--$form->{acc_trans}{$key}->[$i-1]->{description}";
250 $form->{"acc_trans_id_$i"} = $form->{acc_trans}{$key}->[$i - 1]->{acc_trans_id};
252 $form->{"paid_$i"} = $form->{acc_trans}{$key}->[$i - 1]->{amount} * -1;
253 $form->{"datepaid_$i"} = $form->{acc_trans}{$key}->[$i - 1]->{transdate};
254 $form->{"gldate_$i"} = $form->{acc_trans}{$key}->[$i - 1]->{gldate};
255 $form->{"exchangerate_$i"} = $form->{acc_trans}{$key}->[$i - 1]->{exchangerate};
256 $form->{"forex_$i"} = $form->{"exchangerate_$i"};
257 $form->{"source_$i"} = $form->{acc_trans}{$key}->[$i - 1]->{source};
258 $form->{"memo_$i"} = $form->{acc_trans}{$key}->[$i - 1]->{memo};
259 $form->{"defaultcurrency_paid_$i"} = $form->{acc_trans}{$key}->[$i - 1]->{defaultcurrency_paid};
260 $form->{"fx_transaction_$i"} = $form->{acc_trans}{$key}->[$i - 1]->{fx_transaction};
263 $form->{paidaccounts} = $i;
264 # hook for calc of of defaultcurrency_paid and check if banktransaction has a record exchangerate
265 if ($form->{"exchangerate_$i"} && $form->{"acc_trans_id_$i"}) {
266 my $bt_acc_trans = SL::DB::Manager::BankTransactionAccTrans->find_by(acc_trans_id => $form->{"acc_trans_id_$i"});
268 if ($bt_acc_trans->bank_transaction->exchangerate > 0) {
269 $form->{"exchangerate_$i"} = $bt_acc_trans->bank_transaction->exchangerate;
270 $form->{"forex_$i"} = $form->{"exchangerate_$i"};
271 $form->{"record_forex_$i"} = 1;
274 if (!$form->{"fx_transaction_$i"}) {
275 # this is a banktransaction that was paid in internal currency. revert paid/defaultcurrency_paid
276 $form->{"defaultcurrency_paid_$i"} = $form->{"paid_$i"};
277 $form->{"paid_$i"} /= $form->{"exchangerate_$i"};
279 $form->{"defaultcurrency_paid_$i"} //= $form->{"paid_$i"} * $form->{"exchangerate_$i"};
280 $form->{"defaultcurrency_totalpaid"} += $form->{"defaultcurrency_paid_$i"};
281 } # end hook defaultcurrency_paid
285 $form->{$key} = "$form->{acc_trans}{$key}->[0]->{accno}--$form->{acc_trans}{$key}->[0]->{description}";
289 $form->{paidaccounts} = 1 unless (exists $form->{paidaccounts});
291 my ($chart_accno) = split /--/, $form->{AR}; # is empty if total is 0
292 $form->{AR_chart_id} = $form->{id} && $chart_accno ? SL::DB::Manager::Chart->find_by(accno => $chart_accno)->id
293 : $form->{AR_chart_id} ? $form->{AR_chart_id}
294 : $::instance_conf->get_ar_chart_id;
296 $form->{locked} = ($form->datetonum($form->{invdate}, \%myconfig)
297 <= $form->datetonum($form->{closedto}, \%myconfig));
299 $main::lxdebug->leave_sub();
302 sub prepare_invoice {
303 $main::lxdebug->enter_sub();
307 my $form = $main::form;
308 my %myconfig = %main::myconfig;
310 if ($form->{type} eq "credit_note") {
311 $form->{type} = "credit_note";
312 $form->{formname} = "credit_note";
314 } elsif ($form->{type} eq "invoice_for_advance_payment") {
315 $form->{type} = "invoice_for_advance_payment";
316 $form->{formname} = "invoice_for_advance_payment";
318 } elsif ($form->{type} eq "final_invoice") {
319 $form->{type} = "final_invoice";
320 $form->{formname} = "final_invoice";
322 } elsif ($form->{formname} eq "proforma" ) {
323 $form->{type} = "invoice";
326 $form->{type} = "invoice";
327 $form->{formname} = "invoice";
334 foreach my $ref (@{ $form->{invoice_details} }) {
337 map { $form->{"${_}_$i"} = $ref->{$_} } keys %{$ref};
339 $form->{"discount_$i"} = $form->format_amount(\%myconfig, $form->{"discount_$i"} * 100);
340 my ($dec) = ($form->{"sellprice_$i"} =~ /\.(\d+)/);
342 my $decimalplaces = ($dec > 2) ? $dec : 2;
344 $form->{"sellprice_$i"} = $form->format_amount(\%myconfig, $form->{"sellprice_$i"}, $decimalplaces);
345 (my $dec_qty) = ($form->{"qty_$i"} =~ /\.(\d+)/);
346 $dec_qty = length $dec_qty;
348 $form->{"lastcost_$i"} = $form->format_amount(\%myconfig, $form->{"lastcost_$i"}, $decimalplaces);
350 $form->{"qty_$i"} = $form->format_amount(\%myconfig, $form->{"qty_$i"}, $dec_qty);
352 $form->{"sellprice_pg_$i"} = join ('--', $form->{"sellprice_$i"}, $form->{"pricegroup_id_$i"});
354 $form->{rowcount} = $i;
358 $main::lxdebug->leave_sub();
361 sub setup_is_action_bar {
364 my $change_never = $::instance_conf->get_is_changeable == 0;
365 my $change_on_same_day_only = $::instance_conf->get_is_changeable == 2 && ($form->current_date(\%::myconfig) ne $form->{gldate});
366 my $payments_balanced = ($::form->{oldtotalpaid} == 0);
367 my $has_storno = ($::form->{storno} && !$::form->{storno_id});
368 my $may_edit_create = $::auth->assert('invoice_edit', 1);
369 my $factur_x_enabled = $tmpl_var->{invoice_obj} && $tmpl_var->{invoice_obj}->customer->create_zugferd_invoices_for_this_customer;
370 my ($is_linked_bank_transaction, $warn_unlinked_delivery_order);
372 && SL::DB::Default->get->payments_changeable != 0
373 && SL::DB::Manager::BankTransactionAccTrans->find_by(ar_id => $::form->{id})) {
375 $is_linked_bank_transaction = 1;
377 if ($::instance_conf->get_warn_no_delivery_order_for_invoice && !$form->{id}) {
378 $warn_unlinked_delivery_order = 1 unless $form->{convert_from_do_ids};
381 my $has_further_invoice_for_advance_payment;
382 if ($form->{id} && $form->{type} eq "invoice_for_advance_payment") {
383 my $invoice_obj = SL::DB::Invoice->load_cached($form->{id});
384 my $lr = $invoice_obj->linked_records(direction => 'to', to => ['Invoice']);
385 $has_further_invoice_for_advance_payment = any {'SL::DB::Invoice' eq ref $_ && "invoice_for_advance_payment" eq $_->type} @$lr;
388 my $has_final_invoice;
389 if ($form->{id} && $form->{type} eq "invoice_for_advance_payment") {
390 my $invoice_obj = SL::DB::Invoice->load_cached($form->{id});
391 my $lr = $invoice_obj->linked_records(direction => 'to', to => ['Invoice']);
392 $has_final_invoice = any {'SL::DB::Invoice' eq ref $_ && "final_invoice" eq $_->invoice_type} @$lr;
395 my $is_invoice_for_advance_payment_from_order;
396 if ($form->{id} && $form->{type} eq "invoice_for_advance_payment") {
397 my $invoice_obj = SL::DB::Invoice->load_cached($form->{id});
398 my $lr = $invoice_obj->linked_records(direction => 'from', from => ['Order']);
399 $is_invoice_for_advance_payment_from_order = scalar @$lr >= 1;
401 # add readonly state in tmpl_vars
402 $tmpl_var->{readonly} = !$may_edit_create ? 1
403 : $form->{locked} ? 1
404 : $form->{storno} ? 1
405 : ($form->{id} && $change_never) ? 1
406 : ($form->{id} && $change_on_same_day_only) ? 1
407 : $is_linked_bank_transaction ? 1
410 for my $bar ($::request->layout->get('actionbar')) {
414 submit => [ '#form', { action => "update" } ],
415 disabled => !$may_edit_create ? t8('You must not change this invoice.')
416 : $form->{locked} ? t8('The billing period has already been locked.')
418 id => 'update_button',
419 accesskey => 'enter',
425 submit => [ '#form', { action => "post" } ],
426 checks => [ 'kivi.validate_form' ],
427 confirm => t8('The invoice is not linked with a sales delivery order. Post anyway?') x !!$warn_unlinked_delivery_order,
428 disabled => !$may_edit_create ? t8('You must not change this invoice.')
429 : $form->{locked} ? t8('The billing period has already been locked.')
430 : $form->{storno} ? t8('A canceled invoice cannot be posted.')
431 : ($form->{id} && $change_never) ? t8('Changing invoices has been disabled in the configuration.')
432 : ($form->{id} && $change_on_same_day_only) ? t8('Invoices can only be changed on the day they are posted.')
433 : $is_linked_bank_transaction ? t8('This transaction is linked with a bank transaction. Please undo and redo the bank transaction booking if needed.')
437 t8('Post and Close'),
438 submit => [ '#form', { action => "post_and_close" } ],
439 checks => [ 'kivi.validate_form' ],
440 confirm => t8('The invoice is not linked with a sales delivery order. Post anyway?') x !!$warn_unlinked_delivery_order,
441 disabled => !$may_edit_create ? t8('You must not change this invoice.')
442 : $form->{locked} ? t8('The billing period has already been locked.')
443 : $form->{storno} ? t8('A canceled invoice cannot be posted.')
444 : ($form->{id} && $change_never) ? t8('Changing invoices has been disabled in the configuration.')
445 : ($form->{id} && $change_on_same_day_only) ? t8('Invoices can only be changed on the day they are posted.')
446 : $is_linked_bank_transaction ? t8('This transaction is linked with a bank transaction. Please undo and redo the bank transaction booking if needed.')
451 submit => [ '#form', { action => "post_payment" } ],
452 checks => [ 'kivi.validate_form' ],
453 disabled => !$may_edit_create ? t8('You must not change this invoice.')
454 : !$form->{id} ? t8('This invoice has not been posted yet.')
455 : $is_linked_bank_transaction ? t8('This transaction is linked with a bank transaction. Please undo and redo the bank transaction booking if needed.')
457 only_if => $form->{type} ne "invoice_for_advance_payment",
459 action => [ t8('Mark as paid'),
460 submit => [ '#form', { action => "mark_as_paid" } ],
461 confirm => t8('This will remove the invoice from showing as unpaid even if the unpaid amount does not match the amount. Proceed?'),
462 disabled => !$may_edit_create ? t8('You must not change this invoice.')
463 : !$form->{id} ? t8('This invoice has not been posted yet.')
465 only_if => ($::instance_conf->get_is_show_mark_as_paid && $form->{type} ne "invoice_for_advance_payment") || $form->{type} eq 'final_invoice',
467 ], # end of combobox "Post"
470 action => [ t8('Storno'),
471 submit => [ '#form', { action => "storno" } ],
472 confirm => t8('Do you really want to cancel this invoice?'),
473 checks => [ 'kivi.validate_form' ],
474 disabled => !$may_edit_create ? t8('You must not change this invoice.')
475 : !$form->{id} ? t8('This invoice has not been posted yet.')
476 : $form->{storno} ? t8('Cannot storno storno invoice!')
477 : $form->{locked} ? t8('The billing period has already been locked.')
478 : !$payments_balanced ? t8('Cancelling is disallowed. Either undo or balance the current payments until the open amount matches the invoice amount')
481 action => [ t8('Delete'),
482 submit => [ '#form', { action => "delete" } ],
483 confirm => t8('Do you really want to delete this object?'),
484 checks => [ 'kivi.validate_form' ],
485 disabled => !$may_edit_create ? t8('You must not change this invoice.')
486 : !$form->{id} ? t8('This invoice has not been posted yet.')
487 : $form->{locked} ? t8('The billing period has already been locked.')
488 : $change_never ? t8('Changing invoices has been disabled in the configuration.')
489 : $change_on_same_day_only ? t8('Invoices can only be changed on the day they are posted.')
490 : $has_storno ? t8('Can only delete the "Storno zu" part of the cancellation pair.')
493 ], # end of combobox "Storno"
498 action => [ t8('Workflow') ],
501 submit => [ '#form', { action => "use_as_new" } ],
502 checks => [ 'kivi.validate_form' ],
503 disabled => !$may_edit_create ? t8('You must not change this invoice.')
504 : !$form->{id} ? t8('This invoice has not been posted yet.')
508 t8('Further Invoice for Advance Payment'),
509 submit => [ '#form', { action => "further_invoice_for_advance_payment" } ],
510 checks => [ 'kivi.validate_form' ],
511 disabled => !$may_edit_create ? t8('You must not change this invoice.')
512 : !$form->{id} ? t8('This invoice has not been posted yet.')
513 : $has_further_invoice_for_advance_payment ? t8('This invoice has already a further invoice for advanced payment.')
514 : $has_final_invoice ? t8('This invoice has already a final invoice.')
515 : $is_invoice_for_advance_payment_from_order ? t8('This invoice was added from an order. See there.')
517 only_if => ($form->{type} eq "invoice_for_advance_payment" && $::instance_conf->get_show_invoice_for_advance_payment),
521 submit => [ '#form', { action => "final_invoice" } ],
522 checks => [ 'kivi.validate_form' ],
523 disabled => !$may_edit_create ? t8('You must not change this invoice.')
524 : !$form->{id} ? t8('This invoice has not been posted yet.')
525 : $has_further_invoice_for_advance_payment ? t8('This invoice has a further invoice for advanced payment.')
526 : $has_final_invoice ? t8('This invoice has already a final invoice.')
527 : $is_invoice_for_advance_payment_from_order ? t8('This invoice was added from an order. See there.')
529 only_if => ($form->{type} eq "invoice_for_advance_payment" && $::instance_conf->get_show_invoice_for_advance_payment),
533 submit => [ '#form', { action => "credit_note" } ],
534 checks => [ 'kivi.validate_form' ],
535 disabled => !$may_edit_create ? t8('You must not change this invoice.')
536 : $form->{type} eq "credit_note" ? t8('Credit notes cannot be converted into other credit notes.')
537 : !$form->{id} ? t8('This invoice has not been posted yet.')
538 : $form->{storno} ? t8('A canceled invoice cannot be used. Please undo the cancellation first.')
543 submit => [ '#form', { action => "order" } ],
544 checks => [ 'kivi.validate_form' ],
545 disabled => !$form->{id} ? t8('This invoice has not been posted yet.') : undef,
549 submit => ['#form', { action => "sales_reclamation" }], # can't call Reclamation directly
550 disabled => !$form->{id} ? t8('This invoice has not been posted yet.') : undef,
551 only_if => ($::instance_conf->get_show_sales_reclamation && $::form->{type} eq 'invoice' && !$::form->{storno}),
553 ], # end of combobox "Workflow"
556 action => [ t8('Export') ],
558 ($form->{id} ? t8('Print') : t8('Preview')),
559 call => [ 'kivi.SalesPurchase.show_print_dialog', $form->{id} ? 'print' : 'preview' ],
560 checks => [ 'kivi.validate_form' ],
561 disabled => !$may_edit_create ? t8('You must not print this invoice.')
562 : !$form->{id} && $form->{locked} ? t8('The billing period has already been locked.')
565 action => [ t8('Print and Post'),
566 call => [ 'kivi.SalesPurchase.show_print_dialog', 'print_and_post' ],
567 checks => [ 'kivi.validate_form' ],
568 confirm => t8('The invoice is not linked with a sales delivery order. Post anyway?') x !!$warn_unlinked_delivery_order,
569 disabled => !$may_edit_create ? t8('You must not change this invoice.')
570 : $form->{locked} ? t8('The billing period has already been locked.')
571 : $form->{storno} ? t8('A canceled invoice cannot be posted.')
572 : ($form->{id} && $change_never) ? t8('Changing invoices has been disabled in the configuration.')
573 : ($form->{id} && $change_on_same_day_only) ? t8('Invoices can only be changed on the day they are posted.')
574 : $is_linked_bank_transaction ? t8('This transaction is linked with a bank transaction. Please undo and redo the bank transaction booking if needed.')
577 action => [ t8('E Mail'),
578 call => [ 'kivi.SalesPurchase.show_email_dialog' ],
579 checks => [ 'kivi.validate_form' ],
580 disabled => !$may_edit_create ? t8('You must not print this invoice.')
581 : !$form->{id} ? t8('This invoice has not been posted yet.')
582 : $form->{postal_invoice} ? t8('This customer wants a postal invoices.')
585 action => [ t8('Factur-X/ZUGFeRD'),
586 submit => [ '#form', { action => "download_factur_x_xml" } ],
587 checks => [ 'kivi.validate_form' ],
588 disabled => !$may_edit_create ? t8('You must not print this invoice.')
589 : !$form->{id} ? t8('This invoice has not been posted yet.')
590 : !$factur_x_enabled ? t8('Creating Factur-X/ZUGFeRD invoices is not enabled for this customer.')
593 ], # end of combobox "Export"
596 action => [ t8('more') ],
599 call => [ 'set_history_window', $form->{id} * 1, 'glid' ],
600 disabled => !$form->{id} ? t8('This invoice has not been posted yet.') : undef,
604 call => [ 'follow_up_window' ],
605 disabled => !$form->{id} ? t8('This invoice has not been posted yet.') : undef,
609 call => [ 'kivi.Draft.popup', 'is', 'invoice', $form->{draft_id}, $form->{draft_description} ],
610 disabled => !$may_edit_create ? t8('You must not change this invoice.')
611 : $form->{id} ? t8('This invoice has already been posted.')
612 : $form->{locked} ? t8('The billing period has already been locked.')
615 ], # end of combobox "more"
618 $::request->layout->add_javascripts('kivi.Validator.js');
622 $main::lxdebug->enter_sub();
626 my $form = $main::form;
627 my %myconfig = %main::myconfig;
628 my $locale = $main::locale;
629 my $cgi = $::request->{cgi};
634 $TMPL_VAR{customer_obj} = SL::DB::Customer->load_cached($form->{customer_id}) if $form->{customer_id};
635 $TMPL_VAR{invoice_obj} = SL::DB::Invoice->load_cached($form->{id}) if $form->{id};
637 # only print, no mail
638 $form->{postal_invoice} = $TMPL_VAR{customer_obj}->postal_invoice if ref $TMPL_VAR{customer_obj} eq 'SL::DB::Customer';
640 my $current_employee = SL::DB::Manager::Employee->current;
641 $form->{employee_id} = $form->{old_employee_id} if $form->{old_employee_id};
642 $form->{salesman_id} = $form->{old_salesman_id} if $form->{old_salesman_id};
643 $form->{employee_id} ||= $current_employee->id;
644 $form->{salesman_id} ||= $current_employee->id;
646 $form->{defaultcurrency} = $form->get_default_currency(\%myconfig);
648 if( $form->{customer_id} && !$form->{taxincluded_changed_by_user} ) {
649 my $customer = SL::DB::Customer->load_cached($form->{customer_id});
650 $form->{taxincluded} = defined($customer->taxincluded_checked) ? $customer->taxincluded_checked : $myconfig{taxincluded_checked};
652 $TMPL_VAR{taxincluded} = $form->{taxincluded};
654 $form->get_lists("taxzones" => ($form->{id} ? "ALL_TAXZONES" : "ALL_ACTIVE_TAXZONES"),
655 "currencies" => "ALL_CURRENCIES",
656 "price_factors" => "ALL_PRICE_FACTORS");
658 $form->{ALL_DEPARTMENTS} = SL::DB::Manager::Department->get_all_sorted;
659 $form->{ALL_LANGUAGES} = SL::DB::Manager::Language->get_all_sorted;
660 $form->{ALL_DELIVERY_TERMS} = SL::DB::Manager::DeliveryTerm->get_valid($form->{delivery_term_id});
663 my @old_project_ids = uniq grep { $_ } map { $_ * 1 } ($form->{"globalproject_id"}, map { $form->{"project_id_$_"} } 1..$form->{"rowcount"});
664 my @old_ids_cond = @old_project_ids ? (id => \@old_project_ids) : ();
666 if ($::instance_conf->get_customer_projects_only_in_sales) {
669 customer_id => $::form->{customer_id},
670 billable_customer_id => $::form->{customer_id},
675 and => [ active => 1, @customer_cond ],
679 $TMPL_VAR{ALL_PROJECTS} = SL::DB::Manager::Project->get_all_sorted(query => \@conditions);
680 $form->{ALL_PROJECTS} = $TMPL_VAR{ALL_PROJECTS}; # make projects available for second row drop-down in io.pl
681 $TMPL_VAR{ALL_EMPLOYEES} = SL::DB::Manager::Employee->get_all_sorted(query => [ or => [ id => $::form->{employee_id}, deleted => 0 ] ]);
682 $TMPL_VAR{ALL_SALESMEN} = SL::DB::Manager::Employee->get_all_sorted(query => [ or => [ id => $::form->{salesman_id}, deleted => 0 ] ]);
683 $TMPL_VAR{ALL_SHIPTO} = SL::DB::Manager::Shipto->get_all_sorted(query => [
684 or => [ and => [ trans_id => $::form->{"$::form->{vc}_id"} * 1, module => 'CT' ], and => [ shipto_id => $::form->{shipto_id} * 1, trans_id => undef ] ]
686 $TMPL_VAR{ALL_CONTACTS} = SL::DB::Manager::Contact->get_all_sorted(query => [
688 cp_cv_id => $::form->{"$::form->{vc}_id"} * 1,
691 cp_id => $::form->{cp_id} * 1
696 # currencies and exchangerate
697 my @values = map { $_ } @{ $form->{ALL_CURRENCIES} };
698 my %labels = map { $_ => $_ } @{ $form->{ALL_CURRENCIES} };
699 $form->{currency} = $form->{defaultcurrency} unless $form->{currency};
700 $form->{show_exchangerate} = $form->{currency} ne $form->{defaultcurrency};
701 $TMPL_VAR{currencies} = NTI($::request->{cgi}->popup_menu('-name' => 'currency', '-default' => $form->{"currency"},
702 '-values' => \@values, '-labels' => \%labels,
703 '-onchange' => "document.getElementById('update_button').click();"
704 )) if scalar @values;
705 push @custom_hiddens, "forex";
706 push @custom_hiddens, "exchangerate" if $form->{forex};
708 $TMPL_VAR{creditwarning} = ($form->{creditlimit} != 0) && ($form->{creditremaining} < 0) && !$form->{update};
709 $TMPL_VAR{is_credit_remaining_negativ} = $form->{creditremaining} =~ /-/;
712 my $has_qr_reference = $::instance_conf->get_create_qrbill_invoices == 1 &&
713 $form->{formname} eq 'invoice' ? 1 : 0;
714 $TMPL_VAR{has_qr_reference} = $has_qr_reference;
716 if ($has_qr_reference && defined $form->{qr_reference}) {
717 $TMPL_VAR{qr_reference_formatted} = get_ref_number_formatted($form->{qr_reference});
720 # set option selected
721 foreach my $item (qw(AR)) {
722 $form->{"select$item"} =~ s/ selected//;
723 $form->{"select$item"} =~ s/option>\Q$form->{$item}\E/option selected>$form->{$item}/;
726 $TMPL_VAR{is_type_normal_invoice} = $form->{type} eq "invoice";
727 $TMPL_VAR{is_type_credit_note} = $form->{type} eq "credit_note";
728 $TMPL_VAR{is_format_html} = $form->{format} eq 'html';
729 $TMPL_VAR{dateformat} = $myconfig{dateformat};
730 $TMPL_VAR{numberformat} = $myconfig{numberformat};
731 $TMPL_VAR{longdescription_dialog_size_percentage} = SL::Helper::UserPreferences::DisplayPreferences->new()->get_longdescription_dialog_size_percentage();
734 $TMPL_VAR{HIDDENS} = [qw(
735 id type queued printed emailed vc discount
736 title creditlimit creditremaining tradediscount business closedto locked shipped storno storno_id
737 max_dunning_level dunning_amount dunning_description
738 taxaccounts cursor_fokus
739 convert_from_reclamations_ids convert_from_do_ids convert_from_oe_ids convert_from_ar_ids useasnew
743 map { $_.'_rate', $_.'_description', $_.'_taxnumber', $_.'_tax_id' } split / /, $form->{taxaccounts}];
745 $::request->{layout}->use_javascript(map { "${_}.js" } qw(kivi.Draft kivi.File kivi.SalesPurchase kivi.Part kivi.CustomerVendor kivi.Validator ckeditor5/ckeditor ckeditor5/translations/de kivi.io client_js autocomplete_chart));
747 $TMPL_VAR{payment_terms_obj} = get_payment_terms_for_invoice();
748 $form->{duedate} = $TMPL_VAR{payment_terms_obj}->calc_date(reference_date => $form->{invdate}, due_date => $form->{duedate})->to_kivitendo if $TMPL_VAR{payment_terms_obj};
750 setup_is_action_bar(\%TMPL_VAR);
754 print $form->parse_html_template("is/form_header", \%TMPL_VAR);
756 $main::lxdebug->leave_sub();
760 my @fields = qw(acc_trans_id gldate datepaid source memo paid AR_paid);
762 grep { $_->{paid} != 0 }
765 +{ map { ($_ => delete($::form->{"${_}_${idx}"})) } @fields }
766 } (1..$::form->{paidaccounts});
768 @payments = sort_by { DateTime->from_kivitendo($_->{datepaid}) } @payments;
770 $::form->{paidaccounts} = max scalar(@payments), 1;
772 foreach my $idx (1 .. scalar(@payments)) {
773 my $payment = $payments[$idx - 1];
774 $::form->{"${_}_${idx}"} = $payment->{$_} for @fields;
779 $main::lxdebug->enter_sub();
783 my $form = $main::form;
784 my %myconfig = %main::myconfig;
785 my $locale = $main::locale;
787 $form->{invtotal} = $form->{invsubtotal};
789 # tax, total and subtotal calculations
790 my ($tax, $subtotal);
791 $form->{taxaccounts_array} = [ split(/ /, $form->{taxaccounts}) ];
793 foreach my $item (@{ $form->{taxaccounts_array} }) {
794 if ($form->{"${item}_base"}) {
795 if ($form->{taxincluded}) {
796 $form->{"${item}_total"} = $form->round_amount( ($form->{"${item}_base"} * $form->{"${item}_rate"}
797 / (1 + $form->{"${item}_rate"})), 2);
798 $form->{"${item}_netto"} = $form->round_amount( ($form->{"${item}_base"} - $form->{"${item}_total"}), 2);
800 $form->{"${item}_total"} = $form->round_amount( $form->{"${item}_base"} * $form->{"${item}_rate"}, 2);
801 $form->{invtotal} += $form->{"${item}_total"};
806 my $grossamount = $form->{invtotal};
807 $form->{invtotal} = $form->round_amount( $form->{invtotal}, 2, 1 );
808 $form->{rounding} = $form->round_amount(
809 $form->{invtotal} - $form->round_amount($grossamount, 2),
815 $form->{follow_ups} = FU->follow_ups('trans_id' => $form->{id}, 'not_done' => 1) || [];
816 $form->{follow_ups_unfinished} = ( sum map { $_->{due} * 1 } @{ $form->{follow_ups} } ) || 0;
823 $form->{paidaccounts}++ if ($form->{"paid_$form->{paidaccounts}"});
824 $form->{paid_indices} = [ 1 .. $form->{paidaccounts} ];
826 # Standard Konto für Umlaufvermögen
827 my $accno_arap = IS->get_standard_accno_current_assets(\%myconfig, \%$form);
829 for my $i (1 .. $form->{paidaccounts}) {
830 $form->{"changeable_$i"} = 1;
831 if (SL::DB::Default->get->payments_changeable == 0) {
833 $form->{"changeable_$i"} = ($form->{"acc_trans_id_$i"})? 0 : 1;
834 } elsif (SL::DB::Default->get->payments_changeable == 2) {
836 $form->{"changeable_$i"} = (($form->{"gldate_$i"} eq '') ||
837 ($form->current_date(\%myconfig) eq $form->{"gldate_$i"}));
840 #deaktivieren von gebuchten Zahlungen ausserhalb der Bücherkontrolle, vorher prüfen ob heute eingegeben
841 if ($form->date_closed($form->{"gldate_$i"})) {
842 $form->{"changeable_$i"} = 0;
844 # don't add manual bookings for charts which are assigned to real bank accounts
845 # and are flagged for use with bank import
846 my $bank_accounts = SL::DB::Manager::BankAccount->get_all();
847 foreach my $bank (@{ $bank_accounts }) {
848 if ($bank->use_with_bank_import) {
849 my $accno_paid_bank = $bank->chart->accno;
850 $form->{selectAR_paid} =~ s/<option>$accno_paid_bank--(.*?)<\/option>//;
854 $form->{"selectAR_paid_$i"} = $form->{selectAR_paid};
855 if (!$form->{"AR_paid_$i"}) {
856 $form->{"selectAR_paid_$i"} =~ s/option>$accno_arap--(.*?)</option selected>$accno_arap--$1</;
858 $form->{"selectAR_paid_$i"} =~ s/option>\Q$form->{"AR_paid_$i"}\E/option selected>$form->{"AR_paid_$i"}/;
861 $totalpaid += $form->{"paid_$i"};
864 $form->{oldinvtotal} = $form->{invtotal};
866 my $shipto_cvars = SL::DB::Shipto->new->cvars_by_config;
867 foreach my $var (@{ $shipto_cvars }) {
868 my $name = "shiptocvar_" . $var->config->name;
869 $var->value($form->{$name}) if exists $form->{$name};
872 print $form->parse_html_template('is/form_footer', {
873 is_type_normal_invoice => ($form->{type} eq "invoice"),
874 is_type_credit_note => ($form->{type} eq "credit_note"),
875 totalpaid => $totalpaid,
876 paid_missing => $form->{invtotal} - $totalpaid,
877 print_options => setup_sales_purchase_print_options(),
878 show_storno => $form->{id} && !$form->{storno} && !IS->has_storno(\%myconfig, $form, "ar") && !$totalpaid,
879 show_delete => ($::instance_conf->get_is_changeable == 2)
880 ? ($form->current_date(\%myconfig) eq $form->{gldate})
881 : ($::instance_conf->get_is_changeable == 1),
882 today => DateTime->today,
883 vc_obj => $form->{customer_id} ? SL::DB::Customer->load_cached($form->{customer_id}) : undef,
884 shipto_cvars => $shipto_cvars,
886 ##print $form->parse_html_template('is/_payments'); # parser
887 ##print $form->parse_html_template('webdav/_list'); # parser
889 $main::lxdebug->leave_sub();
893 $::auth->assert('invoice_edit');
895 SL::DB::Invoice->new(id => $::form->{id})->load->mark_as_paid;
897 $::form->redirect($::locale->text("Marked as paid"));
901 # unless no lazy implementation of save draft without invdate
902 # set the current date like in version <= 3.4.1
903 $::form->{invdate} = DateTime->today->to_lxoffice;
904 $::form->{form_validity_token} = SL::DB::ValidityToken->create(scope => SL::DB::ValidityToken::SCOPE_SALES_INVOICE_POST())->token;
909 $main::lxdebug->enter_sub();
913 my $form = $main::form;
914 my %myconfig = %main::myconfig;
916 my ($recursive_call) = @_;
918 $form->{print_and_post} = 0 if $form->{second_run};
921 if (($form->{previous_customer_id} || $form->{customer_id}) != $form->{customer_id}) {
922 $::form->{salesman_id} = SL::DB::Manager::Employee->current->id if exists $::form->{salesman_id};
924 IS->get_customer(\%myconfig, $form);
925 $::form->{billing_address_id} = $::form->{default_billing_address_id};
928 $form->{defaultcurrency} = $form->get_default_currency(\%myconfig);
929 if ($form->{defaultcurrency} ne $form->{currency}) {
930 if ($form->{exchangerate}) { # user input OR first default -> leave this value
931 $form->{exchangerate} = $form->parse_amount(\%myconfig, $form->{exchangerate}) unless $recursive_call;
932 # does this differ from daily default?
933 my $current_daily_rate = $form->check_exchangerate(\%myconfig, $form->{currency}, $form->{invdate}, 'buy');
934 $form->{record_forex} = $current_daily_rate > 0 && $current_daily_rate != $form->{exchangerate}
936 } else { # no value, but get defaults -> maybe user changes invdate as well ...
937 ($form->{exchangerate}, $form->{record_forex}) = $form->check_exchangerate(\%myconfig, $form->{currency},
938 $form->{invdate}, 'buy', $form->{id}, 'ar');
941 for my $i (1 .. $form->{paidaccounts}) {
942 next unless $form->{"paid_$i"};
943 map { $form->{"${_}_$i"} = $form->parse_amount(\%myconfig, $form->{"${_}_$i"}) } qw(paid exchangerate);
944 $form->{"forex_$i"} = $form->check_exchangerate(\%myconfig, $form->{currency}, $form->{"datepaid_$i"}, 'buy');
945 $form->{"exchangerate_$i"} = $form->{"forex_$i"} if $form->{"forex_$i"};
948 my $i = $form->{rowcount};
949 my $exchangerate = $form->{exchangerate} || 1;
951 # if last row empty, check the form otherwise retrieve new item
952 if ( ($form->{"partnumber_$i"} eq "")
953 && ($form->{"description_$i"} eq "")
954 && ($form->{"partsgroup_$i"} eq "")) {
956 $form->{creditremaining} += ($form->{oldinvtotal} - $form->{oldtotalpaid});
961 IS->retrieve_item(\%myconfig, \%$form);
963 my $rows = scalar @{ $form->{item_list} };
965 $form->{"discount_$i"} = $form->parse_amount(\%myconfig, $form->{"discount_$i"}) / 100.0;
966 $form->{"discount_$i"} ||= $form->{customer_discount};
969 $form->{"qty_$i"} = $form->parse_amount(\%myconfig, $form->{"qty_$i"});
970 if( !$form->{"qty_$i"} ) {
971 $form->{"qty_$i"} = 1;
976 select_item(mode => 'IS', pre_entered_qty => $form->{"qty_$i"});
977 $::dispatcher->end_request;
981 my $sellprice = $form->parse_amount(\%myconfig, $form->{"sellprice_$i"});
983 map { $form->{item_list}[$i]{$_} =~ s/\"/"/g } qw(partnumber description unit);
984 map { $form->{"${_}_$i"} = $form->{item_list}[0]{$_} } keys %{ $form->{item_list}[0] };
986 $form->{payment_id} = $form->{"part_payment_id_$i"} if $form->{"part_payment_id_$i"} ne "";
987 $form->{"discount_$i"} = 0 if $form->{"not_discountable_$i"};
989 $form->{"marge_price_factor_$i"} = $form->{item_list}->[0]->{price_factor};
991 ($sellprice || $form->{"sellprice_$i"}) =~ /\.(\d+)/;
992 my $decimalplaces = max 2, length $1;
995 $form->{"sellprice_$i"} = $sellprice;
997 my $record = _make_record();
998 my $price_source = SL::PriceSource->new(record_item => $record->items->[$i-1], record => $record);
999 my $best_price = $price_source->best_price;
1000 my $best_discount = $price_source->best_discount;
1003 $::form->{"sellprice_$i"} = $best_price->price;
1004 $::form->{"active_price_source_$i"} = $best_price->source;
1006 if ($best_discount) {
1007 $::form->{"discount_$i"} = $best_discount->discount;
1008 $::form->{"active_discount_source_$i"} = $best_discount->source;
1011 # if there is an exchange rate adjust sellprice
1012 $form->{"sellprice_$i"} /= $exchangerate;
1015 $form->{"listprice_$i"} /= $exchangerate;
1017 my $amount = $form->{"sellprice_$i"} * $form->{"qty_$i"} * (1 - $form->{"discount_$i"});
1018 map { $form->{"${_}_base"} = 0 } split / /, $form->{taxaccounts};
1019 map { $form->{"${_}_base"} += $amount } split / /, $form->{"taxaccounts_$i"};
1020 map { $amount += ($form->{"${_}_base"} * $form->{"${_}_rate"}) } split / /, $form->{"taxaccounts_$i"} if !$form->{taxincluded};
1022 $form->{creditremaining} -= $amount;
1024 map { $form->{"${_}_$i"} = $form->format_amount(\%myconfig, $form->{"${_}_$i"}, $decimalplaces) } qw(sellprice lastcost);
1026 $form->{"qty_$i"} = $form->format_amount(\%myconfig, $form->{"qty_$i"});
1027 $form->{"discount_$i"} = $form->format_amount(\%myconfig, $form->{"discount_$i"} * 100.0);
1034 # ok, so this is a new part
1035 # ask if it is a part or service item
1037 if ( $form->{"partsgroup_$i"}
1038 && ($form->{"partnumber_$i" } eq "")
1039 && ($form->{"description_$i"} eq "")) {
1040 $form->{rowcount}--;
1041 $form->{"discount_$i"} = "";
1045 $form->{"id_$i"} = 0;
1050 $main::lxdebug->leave_sub();
1054 $main::lxdebug->enter_sub();
1056 my $form = $main::form;
1057 my %myconfig = %main::myconfig;
1058 my $locale = $main::locale;
1060 $main::auth->assert('invoice_edit');
1062 $form->mtime_ischanged('ar') ;
1063 my $invdate = $form->datetonum($form->{invdate}, \%myconfig);
1065 $form->{defaultcurrency} = $form->get_default_currency(\%myconfig);
1066 for my $i (1 .. $form->{paidaccounts}) {
1067 if ($form->{"paid_$i"}) {
1068 my $datepaid = $form->datetonum($form->{"datepaid_$i"}, \%myconfig);
1070 $form->isblank("datepaid_$i", $locale->text('Payment date missing!'));
1073 if ($form->{currency} ne $form->{defaultcurrency}) {
1074 $form->{"exchangerate_$i"} = $form->{exchangerate}
1075 if ($invdate == $datepaid);
1076 $form->isblank("exchangerate_$i",
1077 $locale->text('Exchangerate for payment missing!'));
1079 $form->error($locale->text('Cannot post transaction above the maximum future booking date!'))
1080 if ($form->date_max_future($form->{"datepaid_$i"}, \%myconfig));
1082 #Zusätzlich noch das Buchungsdatum in die Bücherkontrolle einbeziehen
1083 # (Dient zur Prüfung ob ZE oder ZA geprüft werden soll)
1084 $form->error($locale->text('Cannot post payment for a closed period!'))
1085 if ($form->date_closed($form->{"datepaid_$i"}) && !$form->date_closed($form->{"gldate_$i"}, \%myconfig));
1089 #($form->{AR}) = split /--/, $form->{AR};
1090 $form->{AR} = SL::DB::Manager::Chart->find_by( id => $form->{AR_chart_id} )->accno;
1091 ($form->{AR_paid}) = split /--/, $form->{AR_paid};
1093 if ( IS->post_payment(\%myconfig, \%$form) ) {
1094 $form->{snumbers} = qq|invnumber_| . $form->{invnumber};
1095 $form->{what_done} = 'invoice';
1096 $form->{addition} = "PAYMENT POSTED";
1097 $form->save_history;
1098 $form->redirect($locale->text('Payment posted!'))
1100 $form->error($locale->text('Cannot post payment!'));
1103 $main::lxdebug->leave_sub();
1107 $main::lxdebug->enter_sub();
1109 my $form = $main::form;
1110 my %myconfig = %main::myconfig;
1111 my $locale = $main::locale;
1113 $main::auth->assert('invoice_edit');
1114 $form->mtime_ischanged('ar');
1116 $form->{defaultcurrency} = $form->get_default_currency(\%myconfig);
1117 $form->isblank("invdate", $locale->text('Invoice Date missing!'));
1118 $form->isblank("customer_id", $locale->text('Customer missing!'));
1119 $form->error($locale->text('Cannot post invoice for a closed period!'))
1120 if ($form->date_closed($form->{"invdate"}, \%myconfig));
1122 $form->{invnumber} =~ s/^\s*//g;
1123 $form->{invnumber} =~ s/\s*$//g;
1125 # if oldcustomer ne customer redo form
1126 if (($form->{previous_customer_id} || $form->{customer_id}) != $form->{customer_id}) {
1128 $::dispatcher->end_request;
1131 if ($myconfig{mandatory_departments} && !$form->{department_id}) {
1132 $form->{saved_message} = $::locale->text('You have to specify a department.');
1137 if ($form->{second_run}) {
1138 $form->{print_and_post} = 0;
1141 remove_emptied_rows();
1144 my $closedto = $form->datetonum($form->{closedto}, \%myconfig);
1145 my $invdate = $form->datetonum($form->{invdate}, \%myconfig);
1147 $form->error($locale->text('Cannot post transaction above the maximum future booking date!'))
1148 if ($form->date_max_future($invdate, \%myconfig));
1149 $form->error($locale->text('Cannot post invoice for a closed period!'))
1150 if ($invdate <= $closedto);
1152 if ($form->{currency} ne $form->{defaultcurrency}) {
1153 $form->isblank("exchangerate", $locale->text('Exchangerate missing!'));
1154 $form->error($locale->text('Cannot post invoice with negative exchange rate'))
1155 unless ($form->parse_amount(\%myconfig, $form->{"exchangerate"}) > 0);
1158 # advance payment allows only one tax
1159 if ($form->{type} eq 'invoice_for_advance_payment') {
1160 my @current_taxaccounts = (split(/ /, $form->{taxaccounts}));
1161 $form->error($locale->text('Cannot post invoice for advance payment with more than one tax'))
1162 if (scalar @current_taxaccounts > 1);
1163 $form->error($locale->text('Cannot post invoice for advance payment with taxincluded'))
1164 if ($form->{taxincluded});
1167 for my $i (1 .. $form->{paidaccounts}) {
1168 if ($form->parse_amount(\%myconfig, $form->{"paid_$i"})) {
1169 my $datepaid = $form->datetonum($form->{"datepaid_$i"}, \%myconfig);
1171 $form->isblank("datepaid_$i", $locale->text('Payment date missing!'));
1173 $form->error($locale->text('Cannot post transaction above the maximum future booking date!'))
1174 if ($form->date_max_future($form->{"datepaid_$i"}, \%myconfig));
1176 #Zusätzlich noch das Buchungsdatum in die Bücherkontrolle einbeziehen
1177 # (Dient zur Prüfung ob ZE oder ZA geprüft werden soll)
1178 $form->error($locale->text('Cannot post payment for a closed period!'))
1179 if ($form->date_closed($form->{"datepaid_$i"}) && !$form->date_closed($form->{"gldate_$i"}, \%myconfig));
1181 if ($form->{currency} ne $form->{defaultcurrency}) {
1182 $form->{"exchangerate_$i"} = $form->{exchangerate}
1183 if ($invdate == $datepaid);
1184 $form->isblank("exchangerate_$i",
1185 $locale->text('Exchangerate for payment missing!'));
1190 #($form->{AR}) = split /--/, $form->{AR};
1191 $form->{AR} = SL::DB::Manager::Chart->find_by( id => $form->{AR_chart_id} )->accno;
1192 ($form->{AR_paid}) = split /--/, $form->{AR_paid};
1193 $form->{storno} ||= 0;
1195 $form->{label} = $form->{type} eq 'credit_note' ? $locale->text('Credit Note') : $locale->text('Invoice');
1199 my $terms = get_payment_terms_for_invoice();
1200 $form->{duedate} = $terms->calc_date(reference_date => $form->{invdate}, due_date => $form->{duedate})->to_kivitendo if $terms;
1202 # If transfer_out is requested, get rose db handle and do post and
1203 # transfer out in one transaction. Otherwise just post the invoice.
1204 if ($::instance_conf->get_is_transfer_out && $form->{type} ne 'credit_note' && !$form->{storno}) {
1205 require SL::DB::Inventory;
1206 my $rose_db = SL::DB::Inventory->new->db;
1209 if (!$rose_db->with_transaction(sub {
1211 if (!IS->post_invoice(\%myconfig, \%$form, $rose_db->dbh)) {
1212 push @errors, $locale->text('Cannot post invoice!');
1213 die 'posting error';
1215 my $err = IS->transfer_out(\%$form, $rose_db->dbh);
1217 push @errors, @{ $err };
1218 die 'transfer error';
1223 push @errors, $EVAL_ERROR;
1224 $form->error($locale->text('Cannot post invoice and/or transfer out! Error message:') . "\n" . join("\n", @errors));
1229 push @errors, $rose_db->error;
1230 $form->error($locale->text('Cannot post invoice and/or transfer out! Error message:') . "\n" . join("\n", @errors));
1233 if (!IS->post_invoice(\%myconfig, \%$form)) {
1234 $form->error($locale->text('Cannot post invoice!'));
1238 if(!exists $form->{addition}) {
1239 $form->{snumbers} = 'invnumber' .'_'. $form->{invnumber}; # ($form->{type} eq 'credit_note' ? 'cnnumber' : 'invnumber') .'_'. $form->{invnumber};
1240 $form->{what_done} = 'invoice';
1241 $form->{addition} = $form->{print_and_post} ? "PRINTED AND POSTED" :
1242 $form->{storno} ? "STORNO" :
1244 $form->save_history;
1247 if ($form->{email_journal_id} && $form->{id} ne "") {
1248 my $invoice = SL::DB::Invoice->new(id => $form->{id})->load;
1249 my $email_journal = SL::DB::EmailJournal->new(
1250 id => delete $form->{email_journal_id}
1252 $email_journal->link_to_record_with_attachment($invoice, delete $::form->{email_attachment_id});
1255 if (!$form->{no_redirect_after_post}) {
1256 $form->{action} = 'edit';
1257 $form->{script} = 'is.pl';
1258 $form->{callback} = build_std_url(qw(action edit id callback saved_message));
1259 $form->redirect($form->{label} . " $form->{invnumber} " . $locale->text('posted!'));
1262 $main::lxdebug->leave_sub();
1265 sub post_and_close {
1266 $main::lxdebug->enter_sub();
1267 my $locale = $main::locale;
1270 $form->{no_redirect_after_post} = 1;
1273 my $callback = $form->{callback}
1274 || "controller.pl?action=LoginScreen/user_login";
1275 my $msg = $form->{label} . " $form->{invnumber} " . $locale->text('posted!');
1276 SL::Helper::Flash::flash_later('info', $msg);
1277 print $form->redirect_header($callback);
1278 $::dispatcher->end_request;
1280 $main::lxdebug->leave_sub();
1283 sub print_and_post {
1284 $main::lxdebug->enter_sub();
1286 my $form = $main::form;
1288 $main::auth->assert('invoice_edit');
1290 my $old_form = Form->new;
1291 $form->{no_redirect_after_post} = 1;
1292 $form->{print_and_post} = 1;
1296 $main::lxdebug->leave_sub();
1301 $main::lxdebug->enter_sub();
1303 my $form = $main::form;
1304 my %myconfig = %main::myconfig;
1306 $main::auth->assert('invoice_edit');
1308 $form->{email_journal_id} = delete $form->{workflow_email_journal_id};
1309 $form->{email_attachment_id} = delete $form->{workflow_email_attachment_id};
1310 $form->{callback} = delete $form->{workflow_email_callback};
1312 delete @{ $form }{qw(printed emailed queued invnumber invdate exchangerate forex deliverydate id datepaid_1 gldate_1 acc_trans_id_1 source_1 memo_1 paid_1 exchangerate_1 AP_paid_1 storno locked qr_unstructured_message)};
1313 $form->{rowcount}--;
1314 $form->{paidaccounts} = 1;
1315 $form->{invdate} = $form->current_date(\%myconfig);
1316 my $terms = get_payment_terms_for_invoice();
1317 $form->{duedate} = $terms ? $terms->calc_date(reference_date => $form->{invdate})->to_kivitendo : $form->{invdate};
1318 $form->{employee_id} = SL::DB::Manager::Employee->current->id;
1319 $form->{forex} = $form->check_exchangerate(\%myconfig, $form->{currency}, $form->{invdate}, 'buy');
1320 $form->{exchangerate} = $form->{forex} if $form->{forex};
1321 $form->{form_validity_token} = SL::DB::ValidityToken->create(scope => SL::DB::ValidityToken::SCOPE_SALES_INVOICE_POST())->token;
1323 $form->{"converted_from_invoice_id_$_"} = delete $form->{"invoice_id_$_"} for 1 .. $form->{"rowcount"};
1325 $form->{useasnew} = 1;
1328 $main::lxdebug->leave_sub();
1331 sub further_invoice_for_advance_payment {
1332 my $form = $main::form;
1333 my %myconfig = %main::myconfig;
1335 $main::auth->assert('invoice_edit');
1337 $form->{email_journal_id} = delete $form->{workflow_email_journal_id};
1338 $form->{email_attachment_id} = delete $form->{workflow_email_attachment_id};
1339 $form->{callback} = delete $form->{workflow_email_callback};
1341 delete @{ $form }{qw(printed emailed queued invnumber invdate exchangerate forex deliverydate datepaid_1 gldate_1 acc_trans_id_1 source_1 memo_1 paid_1 exchangerate_1 AP_paid_1 storno locked)};
1342 $form->{convert_from_ar_ids} = $form->{id};
1344 $form->{rowcount}--;
1345 $form->{paidaccounts} = 1;
1346 $form->{invdate} = $form->current_date(\%myconfig);
1347 my $terms = get_payment_terms_for_invoice();
1348 $form->{duedate} = $terms ? $terms->calc_date(reference_date => $form->{invdate})->to_kivitendo : $form->{invdate};
1349 $form->{employee_id} = SL::DB::Manager::Employee->current->id;
1350 $form->{forex} = $form->check_exchangerate(\%myconfig, $form->{currency}, $form->{invdate}, 'buy');
1351 $form->{exchangerate} = $form->{forex} if $form->{forex};
1352 $form->{form_validity_token} = SL::DB::ValidityToken->create(scope => SL::DB::ValidityToken::SCOPE_SALES_INVOICE_POST())->token;
1354 $form->{"converted_from_invoice_id_$_"} = delete $form->{"invoice_id_$_"} for 1 .. $form->{"rowcount"};
1360 my $form = $main::form;
1361 my %myconfig = %main::myconfig;
1363 $main::auth->assert('invoice_edit');
1365 $form->{email_journal_id} = delete $form->{workflow_email_journal_id};
1366 $form->{email_attachment_id} = delete $form->{workflow_email_attachment_id};
1367 $form->{callback} = delete $form->{workflow_email_callback};
1369 my $related_invoices = IS->_get_invoices_for_advance_payment($form->{id});
1371 delete @{ $form }{qw(printed emailed queued invnumber invdate exchangerate forex deliverydate datepaid_1 gldate_1 acc_trans_id_1 source_1 memo_1 paid_1 exchangerate_1 AP_paid_1 storno locked)};
1373 $form->{convert_from_ar_ids} = $form->{id};
1375 $form->{type} = 'final_invoice';
1376 $form->{title} = t8('Edit Final Invoice');
1377 $form->{paidaccounts} = 1;
1378 $form->{invdate} = $form->current_date(\%myconfig);
1379 my $terms = get_payment_terms_for_invoice();
1380 $form->{duedate} = $terms ? $terms->calc_date(reference_date => $form->{invdate})->to_kivitendo : $form->{invdate};
1381 $form->{employee_id} = SL::DB::Manager::Employee->current->id;
1382 $form->{forex} = $form->check_exchangerate(\%myconfig, $form->{currency}, $form->{invdate}, 'buy');
1383 $form->{exchangerate} = $form->{forex} if $form->{forex};
1384 $form->{form_validity_token} = SL::DB::ValidityToken->create(scope => SL::DB::ValidityToken::SCOPE_SALES_INVOICE_POST())->token;
1386 foreach my $i (1 .. $form->{"rowcount"}) {
1387 delete $form->{"id_$i"};
1388 delete $form->{"invoice_id_$i"};
1389 delete $form->{"parts_id_$i"};
1390 delete $form->{"partnumber_$i"};
1391 delete $form->{"description_$i"};
1394 remove_emptied_rows(1);
1397 foreach my $ri (@$related_invoices) {
1398 foreach my $item (@{$ri->items_sorted}) {
1400 $form->{"id_$i"} = $item->parts_id;
1401 $form->{"partnumber_$i"} = $item->part->partnumber;
1402 $form->{"discount_$i"} = $item->discount*100.0;
1403 $form->{"sellprice_$i"} = $item->fxsellprice;
1404 $form->{$_ . "_" . $i} = $item->$_ for qw(description longdescription qty price_factor_id unit active_price_source active_discount_source);
1406 $form->{$_ . "_" . $i} = $form->format_amount(\%myconfig, $form->{$_ . "_" . $i}) for qw(qty sellprice discount);
1409 $form->{rowcount} = $i;
1412 $::dispatcher->end_request;
1416 $main::lxdebug->enter_sub();
1418 my $form = $main::form;
1419 my %myconfig = %main::myconfig;
1420 my $locale = $main::locale;
1422 $main::auth->assert('invoice_edit');
1424 if ($form->{storno}) {
1425 $form->error($locale->text('Cannot storno storno invoice!'));
1428 if (IS->has_storno(\%myconfig, $form, "ar")) {
1429 $form->error($locale->text("Invoice has already been storno'd!"));
1431 if ($form->datetonum($form->{invdate}, \%myconfig) <= $form->datetonum($form->{closedto}, \%myconfig)) {
1432 $form->error($locale->text('Cannot storno invoice for a closed period!'));
1435 # save the history of invoice being stornoed
1436 $form->{snumbers} = qq|invnumber_| . $form->{invnumber};
1437 $form->{what_done} = 'invoice';
1438 $form->{addition} = "STORNO";
1439 $form->save_history;
1441 my $email_journal_id = delete $form->{workflow_email_journal_id};
1442 my $email_attachment_id = delete $form->{workflow_email_attachment_id};
1443 my $callback = delete $form->{workflow_email_callback};
1444 map({ my $key = $_; delete($form->{$key}) unless (grep({ $key eq $_ } qw(id login password type))); } keys(%{ $form }));
1446 $form->{email_journal_id} = $email_journal_id;
1447 $form->{email_attachment_id} = $email_attachment_id;
1448 $form->{callback} = $callback;
1454 # Payments must not be recorded for the new storno invoice.
1455 $form->{paidaccounts} = 0;
1456 map { my $key = $_; delete $form->{$key} if grep { $key =~ /^$_/ } qw(datepaid_ gldate_ acc_trans_id_ source_ memo_ paid_ exchangerate_ AR_paid_) } keys %{ $form };
1458 # record link invoice to storno
1459 $form->{convert_from_ar_ids} = $form->{id};
1460 $form->{storno_id} = $form->{id};
1461 $form->{storno} = 1;
1463 $form->{invnumber} = "Storno zu " . $form->{invnumber};
1464 $form->{invdate} = DateTime->today->to_lxoffice;
1465 $form->{rowcount}++;
1466 # set new ids for storno invoice
1467 # set new persistent ids for storno invoice items
1468 $form->{"converted_from_invoice_id_$_"} = delete $form->{"invoice_id_$_"} for 1 .. $form->{"rowcount"};
1470 $form->{form_validity_token} = SL::DB::ValidityToken->create(scope => SL::DB::ValidityToken::SCOPE_SALES_INVOICE_POST())->token;
1471 # post expects the field as user input
1472 $form->{exchangerate} = $form->format_amount(\%myconfig, $form->{exchangerate});
1473 $form->{script} = 'is.pl';
1474 if ($form->{callback}) {
1479 $main::lxdebug->leave_sub();
1483 $main::lxdebug->enter_sub();
1485 my $form = $main::form;
1487 $main::auth->assert('invoice_edit');
1489 $form->{preview} = 1;
1490 my $old_form = Form->new;
1491 for (keys %$form) { $old_form->{$_} = $form->{$_} }
1493 &print_form($old_form);
1494 $main::lxdebug->leave_sub();
1499 $main::lxdebug->enter_sub();
1501 my $form = $main::form;
1502 my %myconfig = %main::myconfig;
1503 my $locale = $main::locale;
1505 $main::auth->assert('invoice_edit');
1507 $form->{email_journal_id} = delete $form->{workflow_email_journal_id};
1508 $form->{email_attachment_id} = delete $form->{workflow_email_attachment_id};
1509 $form->{callback} = delete $form->{workflow_email_callback};
1511 $form->{form_validity_token} = SL::DB::ValidityToken->create(scope => SL::DB::ValidityToken::SCOPE_SALES_INVOICE_POST())->token;
1513 $form->{transdate} = $form->{invdate} = $form->current_date(\%myconfig);
1515 $form->current_date(\%myconfig, $form->{invdate}, $form->{terms} * 1);
1517 $form->{convert_from_ar_ids} = $form->{id};
1519 $form->{rowcount}--;
1522 $form->{title} = $locale->text('Add Credit Note');
1523 $form->{script} = 'is.pl';
1525 # Bei Gutschriften bezug zur Rechnungsnummer
1526 $form->{invnumber_for_credit_note} = $form->{invnumber};
1527 # bo creates the id, reset it
1528 map { delete $form->{$_} }
1529 qw(id invnumber subject message cc bcc printed emailed queued);
1530 $form->{ $form->{vc} } =~ s/--.*//g;
1531 $form->{type} = "credit_note";
1534 map { $form->{"select$_"} = "" } ($form->{vc}, 'currency');
1536 # map { $form->{$_} = $form->parse_amount(\%myconfig, $form->{$_}) }
1537 # qw(creditlimit creditremaining);
1539 # set new persistent ids for credit note and link previous invoice id
1540 $form->{"converted_from_invoice_id_$_"} = delete $form->{"invoice_id_$_"} for 1 .. $form->{"rowcount"};
1542 my $currency = $form->{currency};
1545 $form->{currency} = $currency;
1546 $form->{forex} = $form->check_exchangerate( \%myconfig, $form->{currency}, $form->{invdate}, 'buy');
1547 $form->{exchangerate} = $form->{forex} || '';
1549 $form->{creditremaining} -= ($form->{oldinvtotal} - $form->{ordtotal});
1551 # bei Gutschriften werden Zahlungseingänge aus Rechnung nicht übernommen
1552 for my $i (1 .. $form->{paidaccounts}) {
1553 delete $form->{"paid_$i"};
1554 delete $form->{"source_$i"};
1555 delete $form->{"memo_$i"};
1556 delete $form->{"datepaid_$i"};
1557 delete $form->{"gldate_$i"};
1558 delete $form->{"acc_trans_id_$i"};
1559 delete $form->{"AR_paid_$i"};
1561 $form->{paidaccounts} = 1;
1567 $main::lxdebug->leave_sub();
1570 sub credit_note_from_reclamation {
1571 $main::lxdebug->enter_sub();
1573 $main::auth->assert('invoice_edit');
1575 my $form = $main::form;
1576 my %myconfig = %main::myconfig;
1577 my $locale = $main::locale;
1579 if (!$form->{form_validity_token}) {
1580 $form->{form_validity_token} = SL::DB::ValidityToken->create(scope => SL::DB::ValidityToken::SCOPE_SALES_INVOICE_POST())->token;
1583 my $from_id = delete $form->{from_id};
1584 my $reclamation = SL::DB::Reclamation->new(id => $from_id)->load;
1586 $reclamation->flatten_to_form($form, format_amounts => 1);
1588 # set new persistent ids for credit note and link previous reclamation id
1589 $form->{convert_from_reclamations_ids} = $form->{id};
1592 $form->{"converted_from_reclamation_items_id_$_"} = delete $form->{"reclamation_items_id_$_"} for 1 .. $form->{"rowcount"};
1594 $form->{transdate} = $form->{invdate} = $form->current_date(\%myconfig);
1596 $form->current_date(\%myconfig, $form->{invdate}, $form->{terms} * 1);
1598 $form->{title} = $locale->text('Add Credit Note');
1599 $form->{script} = 'is.pl';
1601 # bo creates the id, reset it
1602 map { delete $form->{$_} }
1603 qw(id invnumber subject message cc bcc printed emailed queued);
1604 $form->{ $form->{vc} } =~ s/--.*//g;
1606 $form->{type} = "credit_note";
1608 my $currency = $form->{currency};
1610 $form->{currency} = $currency;
1611 $form->{forex} = $form->check_exchangerate( \%myconfig, $form->{currency}, $form->{invdate}, 'buy');
1612 $form->{exchangerate} = $form->{forex} || '';
1614 $form->{creditremaining} -= ($form->{oldinvtotal} - $form->{ordtotal});
1620 $main::lxdebug->leave_sub();
1624 $::lxdebug->enter_sub;
1630 my $new_rowcount = $::form->{"rowcount"} * 1 + 1;
1631 $::form->{"project_id_${new_rowcount}"} = $::form->{"globalproject_id"};
1633 $::form->language_payment(\%::myconfig);
1635 Common::webdav_folder($::form);
1638 display_row(++$::form->{rowcount});
1641 $::lxdebug->leave_sub;
1645 $::auth->assert('invoice_edit');
1647 if (IS->delete_invoice(\%::myconfig, $::form)) {
1648 # saving the history
1649 if(!exists $::form->{addition}) {
1650 $::form->{snumbers} = 'invnumber' .'_'. $::form->{invnumber};
1651 $::form->{what_done} = 'invoice';
1652 $::form->{addition} = "DELETED";
1653 $::form->save_history;
1655 # /saving the history
1656 $::form->redirect($::locale->text('Invoice deleted!'));
1658 $::form->error($::locale->text('Cannot delete invoice!'));
1663 print update ship_to storno post_payment use_as_new credit_note
1664 delete post order preview post_and_e_mail print_and_post
1667 if ($::form->{"action_$action"}) {
1673 $::form->error($::locale->text('No action defined.'));