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::MoreCommon qw(restore_form save_form);
43 use List::MoreUtils qw(any uniq);
44 use List::Util qw(max sum);
45 use List::UtilsBy qw(sort_by);
46 use English qw(-no_match_vars);
48 use SL::DB::BankTransactionAccTrans;
51 use SL::DB::Department;
53 use SL::DB::PaymentTerm;
55 require "bin/mozilla/common.pl";
56 require "bin/mozilla/io.pl";
64 sub _may_view_or_edit_this_invoice {
65 return 1 if $::auth->assert('invoice_edit', 1); # may edit all invoices
66 return 0 if !$::form->{id}; # creating new invoices isn't allowed without invoice_edit
67 return 0 if !$::form->{globalproject_id}; # existing records without a project ID are not allowed
68 return SL::DB::Project->new(id => $::form->{globalproject_id})->load->may_employee_view_project_invoices(SL::DB::Manager::Employee->current);
72 my $cache = $::request->cache('is.pl::_assert_access');
74 $cache->{_may_view_or_edit_this_invoice} = _may_view_or_edit_this_invoice() if !exists $cache->{_may_view_or_edit_this_invoice};
75 $::form->show_generic_error($::locale->text("You do not have the permissions to access this function.")) if ! $cache->{_may_view_or_edit_this_invoice};
79 $main::lxdebug->enter_sub();
81 my $form = $main::form;
82 my $locale = $main::locale;
84 $main::auth->assert('invoice_edit');
86 $form->{show_details} = $::myconfig{show_form_details};
88 if ($form->{type} eq "credit_note") {
89 $form->{title} = $locale->text('Add Credit Note');
91 if ($form->{storno}) {
92 $form->{title} = $locale->text('Add Storno Credit Note');
95 } elsif ($form->{type} eq "invoice_for_advance_payment") {
96 $form->{title} = $locale->text('Add Invoice for Advance Payment');
99 $form->{title} = $locale->text('Add Sales Invoice');
104 $form->{callback} = "$form->{script}?action=add&type=$form->{type}" unless $form->{callback};
106 invoice_links(is_new => 1);
110 $main::lxdebug->leave_sub();
114 $main::lxdebug->enter_sub();
116 # Delay access check to after the invoice's been loaded in
117 # "invoice_links" so that project-specific invoice rights can be
120 my $form = $main::form;
121 my $locale = $main::locale;
123 $form->{show_details} = $::myconfig{show_form_details};
124 $form->{taxincluded_changed_by_user} = 1;
126 # show history button
127 $form->{javascript} = qq|<script type="text/javascript" src="js/show_history.js"></script>|;
129 my ($language_id, $printer_id);
130 if ($form->{print_and_post}) {
131 $form->{action} = "print";
132 $form->{resubmit} = 1;
133 $language_id = $form->{language_id};
134 $printer_id = $form->{printer_id};
138 if ($form->{type} eq "credit_note") {
139 $form->{title} = $locale->text('Edit Credit Note');
140 $form->{title} = $locale->text('Edit Storno Credit Note') if $form->{storno};
142 } elsif ($form->{type} eq "invoice_for_advance_payment") {
143 $form->{title} = $locale->text('Edit Invoice for Advance Payment');
144 $form->{title} = $locale->text('Edit Storno Invoice for Advance Payment') if $form->{storno};
147 $form->{title} = $locale->text('Edit Sales Invoice');
148 $form->{title} = $locale->text('Edit Storno Invoice') if $form->{storno};
152 if ($form->{print_and_post}) {
153 $form->{language_id} = $language_id;
154 $form->{printer_id} = $printer_id;
159 $main::lxdebug->leave_sub();
163 $main::lxdebug->enter_sub();
165 # Delay access check to after the invoice's been loaded so that
166 # project-specific invoice rights can be evaluated.
169 my $form = $main::form;
170 my %myconfig = %main::myconfig;
172 $form->{vc} = 'customer';
175 $form->create_links("AR", \%myconfig, "customer");
179 my $editing = $form->{id};
181 $form->backup_vars(qw(payment_id language_id taxzone_id salesman_id
182 taxincluded currency cp_id intnotes id shipto_id
185 IS->get_customer(\%myconfig, \%$form);
187 $form->{billing_address_id} = $form->{default_billing_address_id} if $params{is_new};
189 $form->restore_vars(qw(id));
191 IS->retrieve_invoice(\%myconfig, \%$form);
192 $form->restore_vars(qw(payment_id language_id taxzone_id currency intnotes
193 cp_id shipto_id delivery_term_id));
194 $form->restore_vars(qw(taxincluded)) if $form->{id};
195 $form->restore_vars(qw(salesman_id)) if $editing;
197 $form->{employee} = "$form->{employee}--$form->{employee_id}";
200 $form->{forex} = $form->{exchangerate};
201 my $exchangerate = ($form->{exchangerate}) ? $form->{exchangerate} : 1;
203 foreach my $key (keys %{ $form->{AR_links} }) {
204 foreach my $ref (@{ $form->{AR_links}{$key} }) {
205 $form->{"select$key"} .= "<option>$ref->{accno}--$ref->{description}</option>\n";
208 if ($key eq "AR_paid") {
209 next unless $form->{acc_trans}{$key};
210 for my $i (1 .. scalar @{ $form->{acc_trans}{$key} }) {
211 $form->{"AR_paid_$i"} = "$form->{acc_trans}{$key}->[$i-1]->{accno}--$form->{acc_trans}{$key}->[$i-1]->{description}";
213 $form->{"acc_trans_id_$i"} = $form->{acc_trans}{$key}->[$i - 1]->{acc_trans_id};
215 $form->{"paid_$i"} = $form->{acc_trans}{$key}->[$i - 1]->{amount} * -1;
216 $form->{"datepaid_$i"} = $form->{acc_trans}{$key}->[$i - 1]->{transdate};
217 $form->{"gldate_$i"} = $form->{acc_trans}{$key}->[$i - 1]->{gldate};
218 $form->{"exchangerate_$i"} = $form->{acc_trans}{$key}->[$i - 1]->{exchangerate};
219 $form->{"forex_$i"} = $form->{"exchangerate_$i"};
220 $form->{"source_$i"} = $form->{acc_trans}{$key}->[$i - 1]->{source};
221 $form->{"memo_$i"} = $form->{acc_trans}{$key}->[$i - 1]->{memo};
223 $form->{paidaccounts} = $i;
226 $form->{$key} = "$form->{acc_trans}{$key}->[0]->{accno}--$form->{acc_trans}{$key}->[0]->{description}";
230 $form->{paidaccounts} = 1 unless (exists $form->{paidaccounts});
232 $form->{AR} = $form->{AR_1} unless $form->{id};
234 $form->{locked} = ($form->datetonum($form->{invdate}, \%myconfig)
235 <= $form->datetonum($form->{closedto}, \%myconfig));
237 $main::lxdebug->leave_sub();
240 sub prepare_invoice {
241 $main::lxdebug->enter_sub();
245 my $form = $main::form;
246 my %myconfig = %main::myconfig;
248 if ($form->{type} eq "credit_note") {
249 $form->{type} = "credit_note";
250 $form->{formname} = "credit_note";
252 } elsif ($form->{type} eq "invoice_for_advance_payment") {
253 $form->{type} = "invoice_for_advance_payment";
254 $form->{formname} = "invoice_for_advance_payment";
256 } elsif ($form->{formname} eq "proforma" ) {
257 $form->{type} = "invoice";
260 $form->{type} = "invoice";
261 $form->{formname} = "invoice";
268 foreach my $ref (@{ $form->{invoice_details} }) {
271 map { $form->{"${_}_$i"} = $ref->{$_} } keys %{$ref};
273 $form->{"discount_$i"} = $form->format_amount(\%myconfig, $form->{"discount_$i"} * 100);
274 my ($dec) = ($form->{"sellprice_$i"} =~ /\.(\d+)/);
276 my $decimalplaces = ($dec > 2) ? $dec : 2;
278 $form->{"sellprice_$i"} = $form->format_amount(\%myconfig, $form->{"sellprice_$i"}, $decimalplaces);
279 (my $dec_qty) = ($form->{"qty_$i"} =~ /\.(\d+)/);
280 $dec_qty = length $dec_qty;
282 $form->{"lastcost_$i"} = $form->format_amount(\%myconfig, $form->{"lastcost_$i"}, $decimalplaces);
284 $form->{"qty_$i"} = $form->format_amount(\%myconfig, $form->{"qty_$i"}, $dec_qty);
286 $form->{"sellprice_pg_$i"} = join ('--', $form->{"sellprice_$i"}, $form->{"pricegroup_id_$i"});
288 $form->{rowcount} = $i;
292 $main::lxdebug->leave_sub();
295 sub setup_is_action_bar {
298 my $change_never = $::instance_conf->get_is_changeable == 0;
299 my $change_on_same_day_only = $::instance_conf->get_is_changeable == 2 && ($form->current_date(\%::myconfig) ne $form->{gldate});
300 my $payments_balanced = ($::form->{oldtotalpaid} == 0);
301 my $has_storno = ($::form->{storno} && !$::form->{storno_id});
302 my $may_edit_create = $::auth->assert('invoice_edit', 1);
303 my $factur_x_enabled = $tmpl_var->{invoice_obj} && $tmpl_var->{invoice_obj}->customer->create_zugferd_invoices_for_this_customer;
304 my ($is_linked_bank_transaction, $warn_unlinked_delivery_order);
306 && SL::DB::Default->get->payments_changeable != 0
307 && SL::DB::Manager::BankTransactionAccTrans->find_by(ar_id => $::form->{id})) {
309 $is_linked_bank_transaction = 1;
311 if ($::instance_conf->get_warn_no_delivery_order_for_invoice && !$form->{id}) {
312 $warn_unlinked_delivery_order = 1 unless $form->{convert_from_do_ids};
315 my $has_further_invoice_for_advance_payment;
316 if ($form->{id} && $form->{type} eq "invoice_for_advance_payment") {
317 my $invoice_obj = SL::DB::Invoice->load_cached($form->{id});
318 my $lr = $invoice_obj->linked_records(direction => 'to', to => ['Invoice']);
319 $has_further_invoice_for_advance_payment = any {'SL::DB::Invoice' eq ref $_ && "invoice_for_advance_payment" eq $_->type} @$lr;
322 my $has_final_invoice;
323 if ($form->{id} && $form->{type} eq "invoice_for_advance_payment") {
324 my $invoice_obj = SL::DB::Invoice->load_cached($form->{id});
325 my $lr = $invoice_obj->linked_records(direction => 'to', to => ['Invoice']);
326 $has_final_invoice = any {'SL::DB::Invoice' eq ref $_ && "invoice" eq $_->invoice_type} @$lr;
329 for my $bar ($::request->layout->get('actionbar')) {
333 submit => [ '#form', { action => "update" } ],
334 disabled => !$may_edit_create ? t8('You must not change this invoice.')
335 : $form->{locked} ? t8('The billing period has already been locked.')
337 id => 'update_button',
338 accesskey => 'enter',
344 submit => [ '#form', { action => "post" } ],
345 checks => [ 'kivi.validate_form' ],
346 confirm => t8('The invoice is not linked with a sales delivery order. Post anyway?') x !!$warn_unlinked_delivery_order,
347 disabled => !$may_edit_create ? t8('You must not change this invoice.')
348 : $form->{locked} ? t8('The billing period has already been locked.')
349 : $form->{storno} ? t8('A canceled invoice cannot be posted.')
350 : ($form->{id} && $change_never) ? t8('Changing invoices has been disabled in the configuration.')
351 : ($form->{id} && $change_on_same_day_only) ? t8('Invoices can only be changed on the day they are posted.')
352 : $is_linked_bank_transaction ? t8('This transaction is linked with a bank transaction. Please undo and redo the bank transaction booking if needed.')
357 submit => [ '#form', { action => "post_payment" } ],
358 checks => [ 'kivi.validate_form' ],
359 disabled => !$may_edit_create ? t8('You must not change this invoice.')
360 : !$form->{id} ? t8('This invoice has not been posted yet.')
361 : $is_linked_bank_transaction ? t8('This transaction is linked with a bank transaction. Please undo and redo the bank transaction booking if needed.')
363 only_if => $form->{type} ne "invoice_for_advance_payment",
365 action => [ t8('Mark as paid'),
366 submit => [ '#form', { action => "mark_as_paid" } ],
367 confirm => t8('This will remove the invoice from showing as unpaid even if the unpaid amount does not match the amount. Proceed?'),
368 disabled => !$may_edit_create ? t8('You must not change this invoice.')
369 : !$form->{id} ? t8('This invoice has not been posted yet.')
371 only_if => $::instance_conf->get_is_show_mark_as_paid && $form->{type} ne "invoice_for_advance_payment",
373 ], # end of combobox "Post"
376 action => [ t8('Storno'),
377 submit => [ '#form', { action => "storno" } ],
378 confirm => t8('Do you really want to cancel this invoice?'),
379 checks => [ 'kivi.validate_form' ],
380 disabled => !$may_edit_create ? t8('You must not change this invoice.')
381 : !$form->{id} ? t8('This invoice has not been posted yet.')
382 : $form->{storno} ? t8('Cannot storno storno invoice!')
383 : $form->{locked} ? t8('The billing period has already been locked.')
384 : !$payments_balanced ? t8('Cancelling is disallowed. Either undo or balance the current payments until the open amount matches the invoice amount')
387 action => [ t8('Delete'),
388 submit => [ '#form', { action => "delete" } ],
389 confirm => t8('Do you really want to delete this object?'),
390 checks => [ 'kivi.validate_form' ],
391 disabled => !$may_edit_create ? t8('You must not change this invoice.')
392 : !$form->{id} ? t8('This invoice has not been posted yet.')
393 : $form->{locked} ? t8('The billing period has already been locked.')
394 : $change_never ? t8('Changing invoices has been disabled in the configuration.')
395 : $change_on_same_day_only ? t8('Invoices can only be changed on the day they are posted.')
396 : $has_storno ? t8('Can only delete the "Storno zu" part of the cancellation pair.')
399 ], # end of combobox "Storno"
404 action => [ t8('Workflow') ],
407 submit => [ '#form', { action => "use_as_new" } ],
408 checks => [ 'kivi.validate_form' ],
409 disabled => !$may_edit_create ? t8('You must not change this invoice.')
410 : !$form->{id} ? t8('This invoice has not been posted yet.')
414 t8('Further Invoice for Advance Payment'),
415 submit => [ '#form', { action => "further_invoice_for_advance_payment" } ],
416 checks => [ 'kivi.validate_form' ],
417 disabled => !$may_edit_create ? t8('You must not change this invoice.')
418 : !$form->{id} ? t8('This invoice has not been posted yet.')
419 : $has_further_invoice_for_advance_payment ? t8('This invoice has already a further invoice for advanced payment.')
420 : $has_final_invoice ? t8('This invoice has already a final invoice.')
422 only_if => $form->{type} eq "invoice_for_advance_payment",
426 submit => [ '#form', { action => "final_invoice" } ],
427 checks => [ 'kivi.validate_form' ],
428 disabled => !$may_edit_create ? t8('You must not change this invoice.')
429 : !$form->{id} ? t8('This invoice has not been posted yet.')
430 : $has_further_invoice_for_advance_payment ? t8('This invoice has a further invoice for advanced payment.')
431 : $has_final_invoice ? t8('This invoice has already a final invoice.')
433 only_if => $form->{type} eq "invoice_for_advance_payment",
437 submit => [ '#form', { action => "credit_note" } ],
438 checks => [ 'kivi.validate_form' ],
439 disabled => !$may_edit_create ? t8('You must not change this invoice.')
440 : $form->{type} eq "credit_note" ? t8('Credit notes cannot be converted into other credit notes.')
441 : !$form->{id} ? t8('This invoice has not been posted yet.')
442 : $form->{storno} ? t8('A canceled invoice cannot be used. Please undo the cancellation first.')
447 submit => [ '#form', { action => "order" } ],
448 checks => [ 'kivi.validate_form' ],
449 disabled => !$form->{id} ? t8('This invoice has not been posted yet.') : undef,
451 ], # end of combobox "Workflow"
454 action => [ t8('Export') ],
456 ($form->{id} ? t8('Print') : t8('Preview')),
457 call => [ 'kivi.SalesPurchase.show_print_dialog', $form->{id} ? 'print' : 'preview' ],
458 checks => [ 'kivi.validate_form' ],
459 disabled => !$may_edit_create ? t8('You must not print this invoice.')
460 : !$form->{id} && $form->{locked} ? t8('The billing period has already been locked.')
463 action => [ t8('Print and Post'),
464 call => [ 'kivi.SalesPurchase.show_print_dialog', 'print_and_post' ],
465 checks => [ 'kivi.validate_form' ],
466 confirm => t8('The invoice is not linked with a sales delivery order. Post anyway?') x !!$warn_unlinked_delivery_order,
467 disabled => !$may_edit_create ? t8('You must not change this invoice.')
468 : $form->{locked} ? t8('The billing period has already been locked.')
469 : $form->{storno} ? t8('A canceled invoice cannot be posted.')
470 : ($form->{id} && $change_never) ? t8('Changing invoices has been disabled in the configuration.')
471 : ($form->{id} && $change_on_same_day_only) ? t8('Invoices can only be changed on the day they are posted.')
472 : $is_linked_bank_transaction ? t8('This transaction is linked with a bank transaction. Please undo and redo the bank transaction booking if needed.')
475 action => [ t8('E Mail'),
476 call => [ 'kivi.SalesPurchase.show_email_dialog' ],
477 checks => [ 'kivi.validate_form' ],
478 disabled => !$may_edit_create ? t8('You must not print this invoice.')
479 : !$form->{id} ? t8('This invoice has not been posted yet.')
480 : $form->{postal_invoice} ? t8('This customer wants a postal invoices.')
483 action => [ t8('Factur-X/ZUGFeRD'),
484 submit => [ '#form', { action => "download_factur_x_xml" } ],
485 checks => [ 'kivi.validate_form' ],
486 disabled => !$may_edit_create ? t8('You must not print this invoice.')
487 : !$form->{id} ? t8('This invoice has not been posted yet.')
488 : !$factur_x_enabled ? t8('Creating Factur-X/ZUGFeRD invoices is not enabled for this customer.')
491 ], # end of combobox "Export"
494 action => [ t8('more') ],
497 call => [ 'set_history_window', $form->{id} * 1, 'glid' ],
498 disabled => !$form->{id} ? t8('This invoice has not been posted yet.') : undef,
502 call => [ 'follow_up_window' ],
503 disabled => !$form->{id} ? t8('This invoice has not been posted yet.') : undef,
507 call => [ 'kivi.Draft.popup', 'is', 'invoice', $form->{draft_id}, $form->{draft_description} ],
508 disabled => !$may_edit_create ? t8('You must not change this invoice.')
509 : $form->{id} ? t8('This invoice has already been posted.')
510 : $form->{locked} ? t8('The billing period has already been locked.')
513 ], # end of combobox "more"
516 $::request->layout->add_javascripts('kivi.Validator.js');
520 $main::lxdebug->enter_sub();
524 my $form = $main::form;
525 my %myconfig = %main::myconfig;
526 my $locale = $main::locale;
527 my $cgi = $::request->{cgi};
532 $TMPL_VAR{customer_obj} = SL::DB::Customer->load_cached($form->{customer_id}) if $form->{customer_id};
533 $TMPL_VAR{invoice_obj} = SL::DB::Invoice->load_cached($form->{id}) if $form->{id};
535 # only print, no mail
536 $form->{postal_invoice} = $TMPL_VAR{customer_obj}->postal_invoice if ref $TMPL_VAR{customer_obj} eq 'SL::DB::Customer';
538 my $current_employee = SL::DB::Manager::Employee->current;
539 $form->{employee_id} = $form->{old_employee_id} if $form->{old_employee_id};
540 $form->{salesman_id} = $form->{old_salesman_id} if $form->{old_salesman_id};
541 $form->{employee_id} ||= $current_employee->id;
542 $form->{salesman_id} ||= $current_employee->id;
544 $form->{defaultcurrency} = $form->get_default_currency(\%myconfig);
546 $form->get_lists("taxzones" => ($form->{id} ? "ALL_TAXZONES" : "ALL_ACTIVE_TAXZONES"),
547 "currencies" => "ALL_CURRENCIES",
548 "price_factors" => "ALL_PRICE_FACTORS");
550 $form->{ALL_DEPARTMENTS} = SL::DB::Manager::Department->get_all_sorted;
551 $form->{ALL_LANGUAGES} = SL::DB::Manager::Language->get_all_sorted;
554 my @old_project_ids = uniq grep { $_ } map { $_ * 1 } ($form->{"globalproject_id"}, map { $form->{"project_id_$_"} } 1..$form->{"rowcount"});
555 my @old_ids_cond = @old_project_ids ? (id => \@old_project_ids) : ();
557 if ($::instance_conf->get_customer_projects_only_in_sales) {
560 customer_id => $::form->{customer_id},
561 billable_customer_id => $::form->{customer_id},
566 and => [ active => 1, @customer_cond ],
570 $TMPL_VAR{ALL_PROJECTS} = SL::DB::Manager::Project->get_all_sorted(query => \@conditions);
571 $form->{ALL_PROJECTS} = $TMPL_VAR{ALL_PROJECTS}; # make projects available for second row drop-down in io.pl
572 $TMPL_VAR{ALL_EMPLOYEES} = SL::DB::Manager::Employee->get_all_sorted(query => [ or => [ id => $::form->{employee_id}, deleted => 0 ] ]);
573 $TMPL_VAR{ALL_SALESMEN} = SL::DB::Manager::Employee->get_all_sorted(query => [ or => [ id => $::form->{salesman_id}, deleted => 0 ] ]);
574 $TMPL_VAR{ALL_SHIPTO} = SL::DB::Manager::Shipto->get_all_sorted(query => [
575 or => [ trans_id => $::form->{"$::form->{vc}_id"} * 1, and => [ shipto_id => $::form->{shipto_id} * 1, trans_id => undef ] ]
577 $TMPL_VAR{ALL_CONTACTS} = SL::DB::Manager::Contact->get_all_sorted(query => [
579 cp_cv_id => $::form->{"$::form->{vc}_id"} * 1,
582 cp_id => $::form->{cp_id} * 1
587 # currencies and exchangerate
588 my @values = map { $_ } @{ $form->{ALL_CURRENCIES} };
589 my %labels = map { $_ => $_ } @{ $form->{ALL_CURRENCIES} };
590 $form->{currency} = $form->{defaultcurrency} unless $form->{currency};
591 $form->{show_exchangerate} = $form->{currency} ne $form->{defaultcurrency};
592 $TMPL_VAR{currencies} = NTI($::request->{cgi}->popup_menu('-name' => 'currency', '-default' => $form->{"currency"},
593 '-values' => \@values, '-labels' => \%labels,
594 '-onchange' => "document.getElementById('update_button').click();"
595 )) if scalar @values;
596 push @custom_hiddens, "forex";
597 push @custom_hiddens, "exchangerate" if $form->{forex};
599 $TMPL_VAR{creditwarning} = ($form->{creditlimit} != 0) && ($form->{creditremaining} < 0) && !$form->{update};
600 $TMPL_VAR{is_credit_remaining_negativ} = $form->{creditremaining} =~ /-/;
602 # set option selected
603 foreach my $item (qw(AR)) {
604 $form->{"select$item"} =~ s/ selected//;
605 $form->{"select$item"} =~ s/option>\Q$form->{$item}\E/option selected>$form->{$item}/;
608 $TMPL_VAR{is_type_invoice_for_advance_payment} = $form->{type} eq "invoice_for_advance_payment";
609 $TMPL_VAR{is_type_credit_note} = $form->{type} eq "credit_note";
610 $TMPL_VAR{is_format_html} = $form->{format} eq 'html';
611 $TMPL_VAR{dateformat} = $myconfig{dateformat};
612 $TMPL_VAR{numberformat} = $myconfig{numberformat};
615 $TMPL_VAR{HIDDENS} = [qw(
616 id type queued printed emailed vc discount
617 title creditlimit creditremaining tradediscount business closedto locked shipped storno storno_id
618 max_dunning_level dunning_amount dunning_description
619 taxaccounts cursor_fokus
620 convert_from_do_ids convert_from_oe_ids convert_from_ar_ids useasnew
624 map { $_.'_rate', $_.'_description', $_.'_taxnumber', $_.'_tax_id' } split / /, $form->{taxaccounts}];
626 $::request->{layout}->use_javascript(map { "${_}.js" } qw(kivi.Draft kivi.File kivi.SalesPurchase kivi.Part kivi.CustomerVendor kivi.Validator ckeditor/ckeditor ckeditor/adapters/jquery kivi.io client_js));
628 $TMPL_VAR{payment_terms_obj} = get_payment_terms_for_invoice();
629 $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};
631 setup_is_action_bar(\%TMPL_VAR);
635 print $form->parse_html_template("is/form_header", \%TMPL_VAR);
637 $main::lxdebug->leave_sub();
641 my @fields = qw(acc_trans_id gldate datepaid source memo paid AR_paid);
643 grep { $_->{paid} != 0 }
646 +{ map { ($_ => delete($::form->{"${_}_${idx}"})) } @fields }
647 } (1..$::form->{paidaccounts});
649 @payments = sort_by { DateTime->from_kivitendo($_->{datepaid}) } @payments;
651 $::form->{paidaccounts} = max scalar(@payments), 1;
653 foreach my $idx (1 .. scalar(@payments)) {
654 my $payment = $payments[$idx - 1];
655 $::form->{"${_}_${idx}"} = $payment->{$_} for @fields;
660 $main::lxdebug->enter_sub();
664 my $form = $main::form;
665 my %myconfig = %main::myconfig;
666 my $locale = $main::locale;
668 $form->{invtotal} = $form->{invsubtotal};
670 # tax, total and subtotal calculations
671 my ($tax, $subtotal);
672 $form->{taxaccounts_array} = [ split(/ /, $form->{taxaccounts}) ];
674 if( $form->{customer_id} && !$form->{taxincluded_changed_by_user} ) {
675 my $customer = SL::DB::Customer->load_cached($form->{customer_id});
676 $form->{taxincluded} = defined($customer->taxincluded_checked) ? $customer->taxincluded_checked : $myconfig{taxincluded_checked};
679 foreach my $item (@{ $form->{taxaccounts_array} }) {
680 if ($form->{"${item}_base"}) {
681 if ($form->{taxincluded}) {
682 $form->{"${item}_total"} = $form->round_amount( ($form->{"${item}_base"} * $form->{"${item}_rate"}
683 / (1 + $form->{"${item}_rate"})), 2);
684 $form->{"${item}_netto"} = $form->round_amount( ($form->{"${item}_base"} - $form->{"${item}_total"}), 2);
686 $form->{"${item}_total"} = $form->round_amount( $form->{"${item}_base"} * $form->{"${item}_rate"}, 2);
687 $form->{invtotal} += $form->{"${item}_total"};
692 my $grossamount = $form->{invtotal};
693 $form->{invtotal} = $form->round_amount( $form->{invtotal}, 2, 1 );
694 $form->{rounding} = $form->round_amount(
695 $form->{invtotal} - $form->round_amount($grossamount, 2),
701 $form->{follow_ups} = FU->follow_ups('trans_id' => $form->{id}, 'not_done' => 1) || [];
702 $form->{follow_ups_unfinished} = ( sum map { $_->{due} * 1 } @{ $form->{follow_ups} } ) || 0;
709 $form->{paidaccounts}++ if ($form->{"paid_$form->{paidaccounts}"});
710 $form->{paid_indices} = [ 1 .. $form->{paidaccounts} ];
712 # Standard Konto für Umlaufvermögen
713 my $accno_arap = IS->get_standard_accno_current_assets(\%myconfig, \%$form);
715 for my $i (1 .. $form->{paidaccounts}) {
716 $form->{"changeable_$i"} = 1;
717 if (SL::DB::Default->get->payments_changeable == 0) {
719 $form->{"changeable_$i"} = ($form->{"acc_trans_id_$i"})? 0 : 1;
720 } elsif (SL::DB::Default->get->payments_changeable == 2) {
722 $form->{"changeable_$i"} = (($form->{"gldate_$i"} eq '') ||
723 ($form->current_date(\%myconfig) eq $form->{"gldate_$i"}));
726 #deaktivieren von gebuchten Zahlungen ausserhalb der Bücherkontrolle, vorher prüfen ob heute eingegeben
727 if ($form->date_closed($form->{"gldate_$i"})) {
728 $form->{"changeable_$i"} = 0;
731 $form->{"selectAR_paid_$i"} = $form->{selectAR_paid};
732 if (!$form->{"AR_paid_$i"}) {
733 $form->{"selectAR_paid_$i"} =~ s/option>$accno_arap--(.*?)</option selected>$accno_arap--$1</;
735 $form->{"selectAR_paid_$i"} =~ s/option>\Q$form->{"AR_paid_$i"}\E/option selected>$form->{"AR_paid_$i"}/;
738 $totalpaid += $form->{"paid_$i"};
741 $form->{oldinvtotal} = $form->{invtotal};
743 $form->{ALL_DELIVERY_TERMS} = SL::DB::Manager::DeliveryTerm->get_all_sorted();
745 my $shipto_cvars = SL::DB::Shipto->new->cvars_by_config;
746 foreach my $var (@{ $shipto_cvars }) {
747 my $name = "shiptocvar_" . $var->config->name;
748 $var->value($form->{$name}) if exists $form->{$name};
751 print $form->parse_html_template('is/form_footer', {
752 is_type_invoice_for_advance_payment => ($form->{type} eq "invoice_for_advance_payment"),
753 is_type_credit_note => ($form->{type} eq "credit_note"),
754 totalpaid => $totalpaid,
755 paid_missing => $form->{invtotal} - $totalpaid,
756 print_options => setup_sales_purchase_print_options(),
757 show_storno => $form->{id} && !$form->{storno} && !IS->has_storno(\%myconfig, $form, "ar") && !$totalpaid,
758 show_delete => ($::instance_conf->get_is_changeable == 2)
759 ? ($form->current_date(\%myconfig) eq $form->{gldate})
760 : ($::instance_conf->get_is_changeable == 1),
761 today => DateTime->today,
762 vc_obj => $form->{customer_id} ? SL::DB::Customer->load_cached($form->{customer_id}) : undef,
763 shipto_cvars => $shipto_cvars,
765 ##print $form->parse_html_template('is/_payments'); # parser
766 ##print $form->parse_html_template('webdav/_list'); # parser
768 $main::lxdebug->leave_sub();
772 $::auth->assert('invoice_edit');
774 SL::DB::Invoice->new(id => $::form->{id})->load->mark_as_paid;
776 $::form->redirect($::locale->text("Marked as paid"));
780 # unless no lazy implementation of save draft without invdate
781 # set the current date like in version <= 3.4.1
782 $::form->{invdate} = DateTime->today->to_lxoffice;
787 $main::lxdebug->enter_sub();
791 my $form = $main::form;
792 my %myconfig = %main::myconfig;
794 my ($recursive_call) = @_;
796 $form->{print_and_post} = 0 if $form->{second_run};
797 my $taxincluded = $form->{taxincluded} ? "checked" : '';
800 if (($form->{previous_customer_id} || $form->{customer_id}) != $form->{customer_id}) {
801 $::form->{salesman_id} = SL::DB::Manager::Employee->current->id if exists $::form->{salesman_id};
803 IS->get_customer(\%myconfig, $form);
804 $::form->{billing_address_id} = $::form->{default_billing_address_id};
807 $form->{taxincluded} ||= $taxincluded;
809 if (!$form->{forex}) { # read exchangerate from input field (not hidden)
810 $form->{exchangerate} = $form->parse_amount(\%myconfig, $form->{exchangerate}) unless $recursive_call;
812 $form->{forex} = $form->check_exchangerate(\%myconfig, $form->{currency}, $form->{invdate}, 'buy');
813 $form->{exchangerate} = $form->{forex} if $form->{forex};
815 for my $i (1 .. $form->{paidaccounts}) {
816 next unless $form->{"paid_$i"};
817 map { $form->{"${_}_$i"} = $form->parse_amount(\%myconfig, $form->{"${_}_$i"}) } qw(paid exchangerate);
818 $form->{"forex_$i"} = $form->check_exchangerate(\%myconfig, $form->{currency}, $form->{"datepaid_$i"}, 'buy');
819 $form->{"exchangerate_$i"} = $form->{"forex_$i"} if $form->{"forex_$i"};
822 my $i = $form->{rowcount};
823 my $exchangerate = $form->{exchangerate} || 1;
825 # if last row empty, check the form otherwise retrieve new item
826 if ( ($form->{"partnumber_$i"} eq "")
827 && ($form->{"description_$i"} eq "")
828 && ($form->{"partsgroup_$i"} eq "")) {
830 $form->{creditremaining} += ($form->{oldinvtotal} - $form->{oldtotalpaid});
835 IS->retrieve_item(\%myconfig, \%$form);
837 my $rows = scalar @{ $form->{item_list} };
839 $form->{"discount_$i"} = $form->parse_amount(\%myconfig, $form->{"discount_$i"}) / 100.0;
840 $form->{"discount_$i"} ||= $form->{customer_discount};
843 $form->{"qty_$i"} = $form->parse_amount(\%myconfig, $form->{"qty_$i"});
844 if( !$form->{"qty_$i"} ) {
845 $form->{"qty_$i"} = 1;
850 select_item(mode => 'IS', pre_entered_qty => $form->{"qty_$i"});
851 $::dispatcher->end_request;
855 my $sellprice = $form->parse_amount(\%myconfig, $form->{"sellprice_$i"});
857 map { $form->{item_list}[$i]{$_} =~ s/\"/"/g } qw(partnumber description unit);
858 map { $form->{"${_}_$i"} = $form->{item_list}[0]{$_} } keys %{ $form->{item_list}[0] };
860 $form->{payment_id} = $form->{"part_payment_id_$i"} if $form->{"part_payment_id_$i"} ne "";
861 $form->{"discount_$i"} = 0 if $form->{"not_discountable_$i"};
863 $form->{"marge_price_factor_$i"} = $form->{item_list}->[0]->{price_factor};
865 ($sellprice || $form->{"sellprice_$i"}) =~ /\.(\d+)/;
866 my $decimalplaces = max 2, length $1;
869 $form->{"sellprice_$i"} = $sellprice;
871 my $record = _make_record();
872 my $price_source = SL::PriceSource->new(record_item => $record->items->[$i-1], record => $record);
873 my $best_price = $price_source->best_price;
874 my $best_discount = $price_source->best_discount;
877 $::form->{"sellprice_$i"} = $best_price->price;
878 $::form->{"active_price_source_$i"} = $best_price->source;
880 if ($best_discount) {
881 $::form->{"discount_$i"} = $best_discount->discount;
882 $::form->{"active_discount_source_$i"} = $best_discount->source;
885 # if there is an exchange rate adjust sellprice
886 $form->{"sellprice_$i"} /= $exchangerate;
889 $form->{"listprice_$i"} /= $exchangerate;
891 my $amount = $form->{"sellprice_$i"} * $form->{"qty_$i"} * (1 - $form->{"discount_$i"});
892 map { $form->{"${_}_base"} = 0 } split / /, $form->{taxaccounts};
893 map { $form->{"${_}_base"} += $amount } split / /, $form->{"taxaccounts_$i"};
894 map { $amount += ($form->{"${_}_base"} * $form->{"${_}_rate"}) } split / /, $form->{"taxaccounts_$i"} if !$form->{taxincluded};
896 $form->{creditremaining} -= $amount;
898 map { $form->{"${_}_$i"} = $form->format_amount(\%myconfig, $form->{"${_}_$i"}, $decimalplaces) } qw(sellprice lastcost);
900 $form->{"qty_$i"} = $form->format_amount(\%myconfig, $form->{"qty_$i"});
901 $form->{"discount_$i"} = $form->format_amount(\%myconfig, $form->{"discount_$i"} * 100.0);
908 # ok, so this is a new part
909 # ask if it is a part or service item
911 if ( $form->{"partsgroup_$i"}
912 && ($form->{"partnumber_$i" } eq "")
913 && ($form->{"description_$i"} eq "")) {
915 $form->{"discount_$i"} = "";
919 $form->{"id_$i"} = 0;
924 $main::lxdebug->leave_sub();
928 $main::lxdebug->enter_sub();
930 my $form = $main::form;
931 my %myconfig = %main::myconfig;
932 my $locale = $main::locale;
934 $main::auth->assert('invoice_edit');
936 $form->mtime_ischanged('ar') ;
937 my $invdate = $form->datetonum($form->{invdate}, \%myconfig);
939 $form->{defaultcurrency} = $form->get_default_currency(\%myconfig);
940 for my $i (1 .. $form->{paidaccounts}) {
941 if ($form->{"paid_$i"}) {
942 my $datepaid = $form->datetonum($form->{"datepaid_$i"}, \%myconfig);
944 $form->isblank("datepaid_$i", $locale->text('Payment date missing!'));
947 if ($form->{currency} ne $form->{defaultcurrency}) {
948 $form->{"exchangerate_$i"} = $form->{exchangerate}
949 if ($invdate == $datepaid);
950 $form->isblank("exchangerate_$i",
951 $locale->text('Exchangerate for payment missing!'));
953 $form->error($locale->text('Cannot post transaction above the maximum future booking date!'))
954 if ($form->date_max_future($form->{"datepaid_$i"}, \%myconfig));
956 #Zusätzlich noch das Buchungsdatum in die Bücherkontrolle einbeziehen
957 # (Dient zur Prüfung ob ZE oder ZA geprüft werden soll)
958 $form->error($locale->text('Cannot post payment for a closed period!'))
959 if ($form->date_closed($form->{"datepaid_$i"}) && !$form->date_closed($form->{"gldate_$i"}, \%myconfig));
963 ($form->{AR}) = split /--/, $form->{AR};
964 ($form->{AR_paid}) = split /--/, $form->{AR_paid};
966 if ( IS->post_payment(\%myconfig, \%$form) ) {
967 $form->{snumbers} = qq|invnumber_| . $form->{invnumber};
968 $form->{what_done} = 'invoice';
969 $form->{addition} = "PAYMENT POSTED";
971 $form->redirect($locale->text('Payment posted!'))
973 $form->error($locale->text('Cannot post payment!'));
976 $main::lxdebug->leave_sub();
980 $main::lxdebug->enter_sub();
982 my $form = $main::form;
983 my %myconfig = %main::myconfig;
984 my $locale = $main::locale;
986 $main::auth->assert('invoice_edit');
987 $form->mtime_ischanged('ar');
989 $form->{defaultcurrency} = $form->get_default_currency(\%myconfig);
990 $form->isblank("invdate", $locale->text('Invoice Date missing!'));
991 $form->isblank("customer_id", $locale->text('Customer missing!'));
992 $form->error($locale->text('Cannot post invoice for a closed period!'))
993 if ($form->date_closed($form->{"invdate"}, \%myconfig));
995 $form->{invnumber} =~ s/^\s*//g;
996 $form->{invnumber} =~ s/\s*$//g;
998 # if oldcustomer ne customer redo form
999 if (($form->{previous_customer_id} || $form->{customer_id}) != $form->{customer_id}) {
1001 $::dispatcher->end_request;
1004 if ($myconfig{mandatory_departments} && !$form->{department_id}) {
1005 $form->{saved_message} = $::locale->text('You have to specify a department.');
1010 if ($form->{second_run}) {
1011 $form->{print_and_post} = 0;
1014 remove_emptied_rows();
1017 my $closedto = $form->datetonum($form->{closedto}, \%myconfig);
1018 my $invdate = $form->datetonum($form->{invdate}, \%myconfig);
1020 $form->error($locale->text('Cannot post transaction above the maximum future booking date!'))
1021 if ($form->date_max_future($invdate, \%myconfig));
1022 $form->error($locale->text('Cannot post invoice for a closed period!'))
1023 if ($invdate <= $closedto);
1025 $form->isblank("exchangerate", $locale->text('Exchangerate missing!'))
1026 if ($form->{currency} ne $form->{defaultcurrency});
1027 # advance payment allows only one tax
1028 if ($form->{type} eq 'invoice_for_advance_payment') {
1029 my @current_taxaccounts = (split(/ /, $form->{taxaccounts}));
1030 $form->error($locale->text('Cannot post invoice for advance payment with more than one tax'))
1031 if (scalar @current_taxaccounts > 1);
1034 for my $i (1 .. $form->{paidaccounts}) {
1035 if ($form->parse_amount(\%myconfig, $form->{"paid_$i"})) {
1036 my $datepaid = $form->datetonum($form->{"datepaid_$i"}, \%myconfig);
1038 $form->isblank("datepaid_$i", $locale->text('Payment date missing!'));
1040 $form->error($locale->text('Cannot post transaction above the maximum future booking date!'))
1041 if ($form->date_max_future($form->{"datepaid_$i"}, \%myconfig));
1043 #Zusätzlich noch das Buchungsdatum in die Bücherkontrolle einbeziehen
1044 # (Dient zur Prüfung ob ZE oder ZA geprüft werden soll)
1045 $form->error($locale->text('Cannot post payment for a closed period!'))
1046 if ($form->date_closed($form->{"datepaid_$i"}) && !$form->date_closed($form->{"gldate_$i"}, \%myconfig));
1048 if ($form->{currency} ne $form->{defaultcurrency}) {
1049 $form->{"exchangerate_$i"} = $form->{exchangerate}
1050 if ($invdate == $datepaid);
1051 $form->isblank("exchangerate_$i",
1052 $locale->text('Exchangerate for payment missing!'));
1057 ($form->{AR}) = split /--/, $form->{AR};
1058 ($form->{AR_paid}) = split /--/, $form->{AR_paid};
1059 $form->{storno} ||= 0;
1061 $form->{label} = $form->{type} eq 'credit_note' ? $locale->text('Credit Note') : $locale->text('Invoice');
1063 $form->{id} = 0 if $form->{postasnew};
1065 # get new invnumber in sequence if no invnumber is given or if posasnew was requested
1066 if ($form->{postasnew}) {
1067 if ($form->{type} eq "credit_note") {
1068 undef($form->{cnnumber});
1070 undef($form->{invnumber});
1076 my $terms = get_payment_terms_for_invoice();
1077 $form->{duedate} = $terms->calc_date(reference_date => $form->{invdate}, due_date => $form->{duedate})->to_kivitendo if $terms;
1079 # If transfer_out is requested, get rose db handle and do post and
1080 # transfer out in one transaction. Otherwise just post the invoice.
1081 if ($::instance_conf->get_is_transfer_out && $form->{type} ne 'credit_note' && !$form->{storno}) {
1082 require SL::DB::Inventory;
1083 my $rose_db = SL::DB::Inventory->new->db;
1086 if (!$rose_db->with_transaction(sub {
1088 if (!IS->post_invoice(\%myconfig, \%$form, $rose_db->dbh)) {
1089 push @errors, $locale->text('Cannot post invoice!');
1090 die 'posting error';
1092 my $err = IS->transfer_out(\%$form, $rose_db->dbh);
1094 push @errors, @{ $err };
1095 die 'transfer error';
1100 push @errors, $EVAL_ERROR;
1101 $form->error($locale->text('Cannot post invoice and/or transfer out! Error message:') . "\n" . join("\n", @errors));
1106 push @errors, $rose_db->error;
1107 $form->error($locale->text('Cannot post invoice and/or transfer out! Error message:') . "\n" . join("\n", @errors));
1110 if (!IS->post_invoice(\%myconfig, \%$form)) {
1111 $form->error($locale->text('Cannot post invoice!'));
1115 if(!exists $form->{addition}) {
1116 $form->{snumbers} = 'invnumber' .'_'. $form->{invnumber}; # ($form->{type} eq 'credit_note' ? 'cnnumber' : 'invnumber') .'_'. $form->{invnumber};
1117 $form->{what_done} = 'invoice';
1118 $form->{addition} = $form->{print_and_post} ? "PRINTED AND POSTED" :
1119 $form->{storno} ? "STORNO" :
1121 $form->save_history;
1124 if (!$form->{no_redirect_after_post}) {
1125 $form->{action} = 'edit';
1126 $form->{script} = 'is.pl';
1127 $form->{callback} = build_std_url(qw(action edit id callback saved_message));
1128 $form->redirect($form->{label} . " $form->{invnumber} " . $locale->text('posted!'));
1131 $main::lxdebug->leave_sub();
1134 sub print_and_post {
1135 $main::lxdebug->enter_sub();
1137 my $form = $main::form;
1139 $main::auth->assert('invoice_edit');
1141 my $old_form = Form->new;
1142 $form->{no_redirect_after_post} = 1;
1143 $form->{print_and_post} = 1;
1147 $main::lxdebug->leave_sub();
1152 $main::lxdebug->enter_sub();
1154 my $form = $main::form;
1155 my %myconfig = %main::myconfig;
1157 $main::auth->assert('invoice_edit');
1159 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)};
1160 $form->{rowcount}--;
1161 $form->{paidaccounts} = 1;
1162 $form->{invdate} = $form->current_date(\%myconfig);
1163 my $terms = get_payment_terms_for_invoice();
1164 $form->{duedate} = $terms ? $terms->calc_date(reference_date => $form->{invdate})->to_kivitendo : $form->{invdate};
1165 $form->{employee_id} = SL::DB::Manager::Employee->current->id;
1166 $form->{forex} = $form->check_exchangerate(\%myconfig, $form->{currency}, $form->{invdate}, 'buy');
1167 $form->{exchangerate} = $form->{forex} if $form->{forex};
1169 $form->{"converted_from_invoice_id_$_"} = delete $form->{"invoice_id_$_"} for 1 .. $form->{"rowcount"};
1171 $form->{useasnew} = 1;
1174 $main::lxdebug->leave_sub();
1177 sub further_invoice_for_advance_payment {
1178 my $form = $main::form;
1179 my %myconfig = %main::myconfig;
1181 $main::auth->assert('invoice_edit');
1183 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)};
1184 $form->{convert_from_ar_ids} = $form->{id};
1186 $form->{rowcount}--;
1187 $form->{paidaccounts} = 1;
1188 $form->{invdate} = $form->current_date(\%myconfig);
1189 my $terms = get_payment_terms_for_invoice();
1190 $form->{duedate} = $terms ? $terms->calc_date(reference_date => $form->{invdate})->to_kivitendo : $form->{invdate};
1191 $form->{employee_id} = SL::DB::Manager::Employee->current->id;
1192 $form->{forex} = $form->check_exchangerate(\%myconfig, $form->{currency}, $form->{invdate}, 'buy');
1193 $form->{exchangerate} = $form->{forex} if $form->{forex};
1195 $form->{"converted_from_invoice_id_$_"} = delete $form->{"invoice_id_$_"} for 1 .. $form->{"rowcount"};
1201 my $form = $main::form;
1202 my %myconfig = %main::myconfig;
1204 $main::auth->assert('invoice_edit');
1206 # search all related invoices for advance payment
1208 # (order) -> invoice for adv. payment 1 -> invoice for adv. payment 2 -> invoice for adv. payment 3 -> final invoice
1210 # we are currently in the last invoice for adv. payment (3 in this example)
1211 my $related_invoices = IS->_get_invoices_for_advance_payment($form->{id});
1213 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)};
1215 $form->{convert_from_ar_ids} = $form->{id};
1217 $form->{type} = 'invoice';
1218 $form->{title} = t8('Edit Final Invoice');
1219 $form->{paidaccounts} = 1;
1220 $form->{invdate} = $form->current_date(\%myconfig);
1221 my $terms = get_payment_terms_for_invoice();
1222 $form->{duedate} = $terms ? $terms->calc_date(reference_date => $form->{invdate})->to_kivitendo : $form->{invdate};
1223 $form->{employee_id} = SL::DB::Manager::Employee->current->id;
1224 $form->{forex} = $form->check_exchangerate(\%myconfig, $form->{currency}, $form->{invdate}, 'buy');
1225 $form->{exchangerate} = $form->{forex} if $form->{forex};
1227 foreach my $i (1 .. $form->{"rowcount"}) {
1228 delete $form->{"id_$i"};
1229 delete $form->{"invoice_id_$i"};
1230 delete $form->{"parts_id_$i"};
1231 delete $form->{"partnumber_$i"};
1232 delete $form->{"description_$i"};
1235 remove_emptied_rows(1);
1238 foreach my $ri (@$related_invoices) {
1239 foreach my $item (@{$ri->items_sorted}) {
1241 $form->{"id_$i"} = $item->parts_id;
1242 $form->{"partnumber_$i"} = $item->part->partnumber;
1243 $form->{"discount_$i"} = $item->discount*100.0;
1244 $form->{"sellprice_$i"} = $item->fxsellprice;
1245 $form->{$_ . "_" . $i} = $item->$_ for qw(description longdescription qty price_factor_id unit sellprice active_price_source active_discount_source);
1247 $form->{$_ . "_" . $i} = $form->format_amount(\%myconfig, $form->{$_ . "_" . $i}) for qw(qty sellprice discount);
1250 $form->{rowcount} = $i;
1253 $::dispatcher->end_request;
1257 $main::lxdebug->enter_sub();
1259 my $form = $main::form;
1260 my %myconfig = %main::myconfig;
1261 my $locale = $main::locale;
1263 $main::auth->assert('invoice_edit');
1265 if ($form->{storno}) {
1266 $form->error($locale->text('Cannot storno storno invoice!'));
1269 if (IS->has_storno(\%myconfig, $form, "ar")) {
1270 $form->error($locale->text("Invoice has already been storno'd!"));
1272 if ($form->datetonum($form->{invdate}, \%myconfig) <= $form->datetonum($form->{closedto}, \%myconfig)) {
1273 $form->error($locale->text('Cannot storno invoice for a closed period!'));
1276 # save the history of invoice being stornoed
1277 $form->{snumbers} = qq|invnumber_| . $form->{invnumber};
1278 $form->{what_done} = 'invoice';
1279 $form->{addition} = "STORNO";
1280 $form->save_history;
1282 map({ my $key = $_; delete($form->{$key}) unless (grep({ $key eq $_ } qw(id login password type))); } keys(%{ $form }));
1288 # Payments must not be recorded for the new storno invoice.
1289 $form->{paidaccounts} = 0;
1290 map { my $key = $_; delete $form->{$key} if grep { $key =~ /^$_/ } qw(datepaid_ gldate_ acc_trans_id_ source_ memo_ paid_ exchangerate_ AR_paid_) } keys %{ $form };
1292 # record link invoice to storno
1293 $form->{convert_from_ar_ids} = $form->{id};
1294 $form->{storno_id} = $form->{id};
1295 $form->{storno} = 1;
1297 $form->{invnumber} = "Storno zu " . $form->{invnumber};
1298 $form->{invdate} = DateTime->today->to_lxoffice;
1299 $form->{rowcount}++;
1300 # set new ids for storno invoice
1301 # set new persistent ids for storno invoice items
1302 $form->{"converted_from_invoice_id_$_"} = delete $form->{"invoice_id_$_"} for 1 .. $form->{"rowcount"};
1305 $main::lxdebug->leave_sub();
1309 $main::lxdebug->enter_sub();
1311 my $form = $main::form;
1313 $main::auth->assert('invoice_edit');
1315 $form->{preview} = 1;
1316 my $old_form = Form->new;
1317 for (keys %$form) { $old_form->{$_} = $form->{$_} }
1319 &print_form($old_form);
1320 $main::lxdebug->leave_sub();
1325 $main::lxdebug->enter_sub();
1327 my $form = $main::form;
1328 my %myconfig = %main::myconfig;
1329 my $locale = $main::locale;
1331 $main::auth->assert('invoice_edit');
1333 $form->{transdate} = $form->{invdate} = $form->current_date(\%myconfig);
1335 $form->current_date(\%myconfig, $form->{invdate}, $form->{terms} * 1);
1337 $form->{convert_from_ar_ids} = $form->{id};
1339 $form->{rowcount}--;
1342 $form->{title} = $locale->text('Add Credit Note');
1343 $form->{script} = 'is.pl';
1345 # Bei Gutschriften bezug zur Rechnungsnummer
1346 $form->{invnumber_for_credit_note} = $form->{invnumber};
1347 # bo creates the id, reset it
1348 map { delete $form->{$_} }
1349 qw(id invnumber subject message cc bcc printed emailed queued);
1350 $form->{ $form->{vc} } =~ s/--.*//g;
1351 $form->{type} = "credit_note";
1354 map { $form->{"select$_"} = "" } ($form->{vc}, 'currency');
1356 # map { $form->{$_} = $form->parse_amount(\%myconfig, $form->{$_}) }
1357 # qw(creditlimit creditremaining);
1359 # set new persistent ids for credit note and link previous invoice id
1360 $form->{"converted_from_invoice_id_$_"} = delete $form->{"invoice_id_$_"} for 1 .. $form->{"rowcount"};
1362 my $currency = $form->{currency};
1365 $form->{currency} = $currency;
1366 $form->{forex} = $form->check_exchangerate( \%myconfig, $form->{currency}, $form->{invdate}, 'buy');
1367 $form->{exchangerate} = $form->{forex} || '';
1369 $form->{creditremaining} -= ($form->{oldinvtotal} - $form->{ordtotal});
1371 # bei Gutschriften werden Zahlungseingänge aus Rechnung nicht übernommen
1372 for my $i (1 .. $form->{paidaccounts}) {
1373 delete $form->{"paid_$i"};
1374 delete $form->{"source_$i"};
1375 delete $form->{"memo_$i"};
1376 delete $form->{"datepaid_$i"};
1377 delete $form->{"gldate_$i"};
1378 delete $form->{"acc_trans_id_$i"};
1379 delete $form->{"AR_paid_$i"};
1381 $form->{paidaccounts} = 1;
1387 $main::lxdebug->leave_sub();
1391 $::lxdebug->enter_sub;
1397 my $new_rowcount = $::form->{"rowcount"} * 1 + 1;
1398 $::form->{"project_id_${new_rowcount}"} = $::form->{"globalproject_id"};
1400 $::form->language_payment(\%::myconfig);
1402 Common::webdav_folder($::form);
1405 display_row(++$::form->{rowcount});
1408 $::lxdebug->leave_sub;
1412 $::auth->assert('invoice_edit');
1414 if (IS->delete_invoice(\%::myconfig, $::form)) {
1415 # saving the history
1416 if(!exists $::form->{addition}) {
1417 $::form->{snumbers} = 'invnumber' .'_'. $::form->{invnumber};
1418 $::form->{what_done} = 'invoice';
1419 $::form->{addition} = "DELETED";
1420 $::form->save_history;
1422 # /saving the history
1423 $::form->redirect($::locale->text('Invoice deleted!'));
1425 $::form->error($::locale->text('Cannot delete invoice!'));
1430 print update ship_to storno post_payment use_as_new credit_note
1431 delete post order preview post_and_e_mail print_and_post
1434 if ($::form->{"action_$action"}) {
1440 $::form->error($::locale->text('No action defined.'));