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');
98 } elsif ($form->{type} eq "final_invoice") {
99 $form->{title} = $locale->text('Final Invoice');
102 $form->{title} = $locale->text('Add Sales Invoice');
107 $form->{callback} = "$form->{script}?action=add&type=$form->{type}" unless $form->{callback};
109 invoice_links(is_new => 1);
113 $main::lxdebug->leave_sub();
117 $main::lxdebug->enter_sub();
119 # Delay access check to after the invoice's been loaded in
120 # "invoice_links" so that project-specific invoice rights can be
123 my $form = $main::form;
124 my $locale = $main::locale;
126 $form->{show_details} = $::myconfig{show_form_details};
127 $form->{taxincluded_changed_by_user} = 1;
129 # show history button
130 $form->{javascript} = qq|<script type="text/javascript" src="js/show_history.js"></script>|;
132 my ($language_id, $printer_id);
133 if ($form->{print_and_post}) {
134 $form->{action} = "print";
135 $form->{resubmit} = 1;
136 $language_id = $form->{language_id};
137 $printer_id = $form->{printer_id};
141 if ($form->{type} eq "credit_note") {
142 $form->{title} = $locale->text('Edit Credit Note');
143 $form->{title} = $locale->text('Edit Storno Credit Note') if $form->{storno};
145 } elsif ($form->{type} eq "invoice_for_advance_payment") {
146 $form->{title} = $locale->text('Edit Invoice for Advance Payment');
147 $form->{title} = $locale->text('Edit Storno Invoice for Advance Payment') if $form->{storno};
149 } elsif ($form->{type} eq "final_invoice") {
150 $form->{title} = $locale->text('Edit Final Invoice');
153 $form->{title} = $locale->text('Edit Sales Invoice');
154 $form->{title} = $locale->text('Edit Storno Invoice') if $form->{storno};
158 if ($form->{print_and_post}) {
159 $form->{language_id} = $language_id;
160 $form->{printer_id} = $printer_id;
165 $main::lxdebug->leave_sub();
169 $main::lxdebug->enter_sub();
171 # Delay access check to after the invoice's been loaded so that
172 # project-specific invoice rights can be evaluated.
175 my $form = $main::form;
176 my %myconfig = %main::myconfig;
178 $form->{vc} = 'customer';
181 $form->create_links("AR", \%myconfig, "customer");
185 my $editing = $form->{id};
187 $form->backup_vars(qw(payment_id language_id taxzone_id salesman_id
188 taxincluded currency cp_id intnotes id shipto_id
191 IS->get_customer(\%myconfig, \%$form);
193 $form->{billing_address_id} = $form->{default_billing_address_id} if $params{is_new};
195 $form->restore_vars(qw(id));
197 IS->retrieve_invoice(\%myconfig, \%$form);
198 $form->restore_vars(qw(payment_id language_id taxzone_id currency intnotes
199 cp_id shipto_id delivery_term_id));
200 $form->restore_vars(qw(taxincluded)) if $form->{id};
201 $form->restore_vars(qw(salesman_id)) if $editing;
203 $form->{employee} = "$form->{employee}--$form->{employee_id}";
206 $form->{forex} = $form->{exchangerate};
207 my $exchangerate = ($form->{exchangerate}) ? $form->{exchangerate} : 1;
209 foreach my $key (keys %{ $form->{AR_links} }) {
210 foreach my $ref (@{ $form->{AR_links}{$key} }) {
211 $form->{"select$key"} .= "<option>$ref->{accno}--$ref->{description}</option>\n";
214 if ($key eq "AR_paid") {
215 next unless $form->{acc_trans}{$key};
216 for my $i (1 .. scalar @{ $form->{acc_trans}{$key} }) {
217 $form->{"AR_paid_$i"} = "$form->{acc_trans}{$key}->[$i-1]->{accno}--$form->{acc_trans}{$key}->[$i-1]->{description}";
219 $form->{"acc_trans_id_$i"} = $form->{acc_trans}{$key}->[$i - 1]->{acc_trans_id};
221 $form->{"paid_$i"} = $form->{acc_trans}{$key}->[$i - 1]->{amount} * -1;
222 $form->{"datepaid_$i"} = $form->{acc_trans}{$key}->[$i - 1]->{transdate};
223 $form->{"gldate_$i"} = $form->{acc_trans}{$key}->[$i - 1]->{gldate};
224 $form->{"exchangerate_$i"} = $form->{acc_trans}{$key}->[$i - 1]->{exchangerate};
225 $form->{"forex_$i"} = $form->{"exchangerate_$i"};
226 $form->{"source_$i"} = $form->{acc_trans}{$key}->[$i - 1]->{source};
227 $form->{"memo_$i"} = $form->{acc_trans}{$key}->[$i - 1]->{memo};
229 $form->{paidaccounts} = $i;
232 $form->{$key} = "$form->{acc_trans}{$key}->[0]->{accno}--$form->{acc_trans}{$key}->[0]->{description}";
236 $form->{paidaccounts} = 1 unless (exists $form->{paidaccounts});
238 $form->{AR} = $form->{AR_1} unless $form->{id};
240 $form->{locked} = ($form->datetonum($form->{invdate}, \%myconfig)
241 <= $form->datetonum($form->{closedto}, \%myconfig));
243 $main::lxdebug->leave_sub();
246 sub prepare_invoice {
247 $main::lxdebug->enter_sub();
251 my $form = $main::form;
252 my %myconfig = %main::myconfig;
254 if ($form->{type} eq "credit_note") {
255 $form->{type} = "credit_note";
256 $form->{formname} = "credit_note";
258 } elsif ($form->{type} eq "invoice_for_advance_payment") {
259 $form->{type} = "invoice_for_advance_payment";
260 $form->{formname} = "invoice_for_advance_payment";
262 } elsif ($form->{type} eq "final_invoice") {
263 $form->{type} = "final_invoice";
264 $form->{formname} = "final_invoice";
266 } elsif ($form->{formname} eq "proforma" ) {
267 $form->{type} = "invoice";
270 $form->{type} = "invoice";
271 $form->{formname} = "invoice";
278 foreach my $ref (@{ $form->{invoice_details} }) {
281 map { $form->{"${_}_$i"} = $ref->{$_} } keys %{$ref};
283 $form->{"discount_$i"} = $form->format_amount(\%myconfig, $form->{"discount_$i"} * 100);
284 my ($dec) = ($form->{"sellprice_$i"} =~ /\.(\d+)/);
286 my $decimalplaces = ($dec > 2) ? $dec : 2;
288 $form->{"sellprice_$i"} = $form->format_amount(\%myconfig, $form->{"sellprice_$i"}, $decimalplaces);
289 (my $dec_qty) = ($form->{"qty_$i"} =~ /\.(\d+)/);
290 $dec_qty = length $dec_qty;
292 $form->{"lastcost_$i"} = $form->format_amount(\%myconfig, $form->{"lastcost_$i"}, $decimalplaces);
294 $form->{"qty_$i"} = $form->format_amount(\%myconfig, $form->{"qty_$i"}, $dec_qty);
296 $form->{"sellprice_pg_$i"} = join ('--', $form->{"sellprice_$i"}, $form->{"pricegroup_id_$i"});
298 $form->{rowcount} = $i;
302 $main::lxdebug->leave_sub();
305 sub setup_is_action_bar {
308 my $change_never = $::instance_conf->get_is_changeable == 0;
309 my $change_on_same_day_only = $::instance_conf->get_is_changeable == 2 && ($form->current_date(\%::myconfig) ne $form->{gldate});
310 my $payments_balanced = ($::form->{oldtotalpaid} == 0);
311 my $has_storno = ($::form->{storno} && !$::form->{storno_id});
312 my $may_edit_create = $::auth->assert('invoice_edit', 1);
313 my $factur_x_enabled = $tmpl_var->{invoice_obj} && $tmpl_var->{invoice_obj}->customer->create_zugferd_invoices_for_this_customer;
314 my ($is_linked_bank_transaction, $warn_unlinked_delivery_order);
316 && SL::DB::Default->get->payments_changeable != 0
317 && SL::DB::Manager::BankTransactionAccTrans->find_by(ar_id => $::form->{id})) {
319 $is_linked_bank_transaction = 1;
321 if ($::instance_conf->get_warn_no_delivery_order_for_invoice && !$form->{id}) {
322 $warn_unlinked_delivery_order = 1 unless $form->{convert_from_do_ids};
325 my $has_further_invoice_for_advance_payment;
326 if ($form->{id} && $form->{type} eq "invoice_for_advance_payment") {
327 my $invoice_obj = SL::DB::Invoice->load_cached($form->{id});
328 my $lr = $invoice_obj->linked_records(direction => 'to', to => ['Invoice']);
329 $has_further_invoice_for_advance_payment = any {'SL::DB::Invoice' eq ref $_ && "invoice_for_advance_payment" eq $_->type} @$lr;
332 my $has_final_invoice;
333 if ($form->{id} && $form->{type} eq "invoice_for_advance_payment") {
334 my $invoice_obj = SL::DB::Invoice->load_cached($form->{id});
335 my $lr = $invoice_obj->linked_records(direction => 'to', to => ['Invoice']);
336 $has_final_invoice = any {'SL::DB::Invoice' eq ref $_ && "invoice" eq $_->invoice_type} @$lr;
339 for my $bar ($::request->layout->get('actionbar')) {
343 submit => [ '#form', { action => "update" } ],
344 disabled => !$may_edit_create ? t8('You must not change this invoice.')
345 : $form->{locked} ? t8('The billing period has already been locked.')
347 id => 'update_button',
348 accesskey => 'enter',
354 submit => [ '#form', { action => "post" } ],
355 checks => [ 'kivi.validate_form' ],
356 confirm => t8('The invoice is not linked with a sales delivery order. Post anyway?') x !!$warn_unlinked_delivery_order,
357 disabled => !$may_edit_create ? t8('You must not change this invoice.')
358 : $form->{locked} ? t8('The billing period has already been locked.')
359 : $form->{storno} ? t8('A canceled invoice cannot be posted.')
360 : ($form->{id} && $change_never) ? t8('Changing invoices has been disabled in the configuration.')
361 : ($form->{id} && $change_on_same_day_only) ? t8('Invoices can only be changed on the day they are posted.')
362 : $is_linked_bank_transaction ? t8('This transaction is linked with a bank transaction. Please undo and redo the bank transaction booking if needed.')
367 submit => [ '#form', { action => "post_payment" } ],
368 checks => [ 'kivi.validate_form' ],
369 disabled => !$may_edit_create ? t8('You must not change this invoice.')
370 : !$form->{id} ? t8('This invoice has not been posted yet.')
371 : $is_linked_bank_transaction ? t8('This transaction is linked with a bank transaction. Please undo and redo the bank transaction booking if needed.')
373 only_if => $form->{type} ne "invoice_for_advance_payment",
375 action => [ t8('Mark as paid'),
376 submit => [ '#form', { action => "mark_as_paid" } ],
377 confirm => t8('This will remove the invoice from showing as unpaid even if the unpaid amount does not match the amount. Proceed?'),
378 disabled => !$may_edit_create ? t8('You must not change this invoice.')
379 : !$form->{id} ? t8('This invoice has not been posted yet.')
381 only_if => $::instance_conf->get_is_show_mark_as_paid && $form->{type} ne "invoice_for_advance_payment",
383 ], # end of combobox "Post"
386 action => [ t8('Storno'),
387 submit => [ '#form', { action => "storno" } ],
388 confirm => t8('Do you really want to cancel this invoice?'),
389 checks => [ 'kivi.validate_form' ],
390 disabled => !$may_edit_create ? t8('You must not change this invoice.')
391 : !$form->{id} ? t8('This invoice has not been posted yet.')
392 : $form->{storno} ? t8('Cannot storno storno invoice!')
393 : $form->{locked} ? t8('The billing period has already been locked.')
394 : !$payments_balanced ? t8('Cancelling is disallowed. Either undo or balance the current payments until the open amount matches the invoice amount')
397 action => [ t8('Delete'),
398 submit => [ '#form', { action => "delete" } ],
399 confirm => t8('Do you really want to delete this object?'),
400 checks => [ 'kivi.validate_form' ],
401 disabled => !$may_edit_create ? t8('You must not change this invoice.')
402 : !$form->{id} ? t8('This invoice has not been posted yet.')
403 : $form->{locked} ? t8('The billing period has already been locked.')
404 : $change_never ? t8('Changing invoices has been disabled in the configuration.')
405 : $change_on_same_day_only ? t8('Invoices can only be changed on the day they are posted.')
406 : $has_storno ? t8('Can only delete the "Storno zu" part of the cancellation pair.')
409 ], # end of combobox "Storno"
414 action => [ t8('Workflow') ],
417 submit => [ '#form', { action => "use_as_new" } ],
418 checks => [ 'kivi.validate_form' ],
419 disabled => !$may_edit_create ? t8('You must not change this invoice.')
420 : !$form->{id} ? t8('This invoice has not been posted yet.')
424 t8('Further Invoice for Advance Payment'),
425 submit => [ '#form', { action => "further_invoice_for_advance_payment" } ],
426 checks => [ 'kivi.validate_form' ],
427 disabled => !$may_edit_create ? t8('You must not change this invoice.')
428 : !$form->{id} ? t8('This invoice has not been posted yet.')
429 : $has_further_invoice_for_advance_payment ? t8('This invoice has already a further invoice for advanced payment.')
430 : $has_final_invoice ? t8('This invoice has already a final invoice.')
432 only_if => $form->{type} eq "invoice_for_advance_payment",
436 submit => [ '#form', { action => "final_invoice" } ],
437 checks => [ 'kivi.validate_form' ],
438 disabled => !$may_edit_create ? t8('You must not change this invoice.')
439 : !$form->{id} ? t8('This invoice has not been posted yet.')
440 : $has_further_invoice_for_advance_payment ? t8('This invoice has a further invoice for advanced payment.')
441 : $has_final_invoice ? t8('This invoice has already a final invoice.')
443 only_if => $form->{type} eq "invoice_for_advance_payment",
447 submit => [ '#form', { action => "credit_note" } ],
448 checks => [ 'kivi.validate_form' ],
449 disabled => !$may_edit_create ? t8('You must not change this invoice.')
450 : $form->{type} eq "credit_note" ? t8('Credit notes cannot be converted into other credit notes.')
451 : !$form->{id} ? t8('This invoice has not been posted yet.')
452 : $form->{storno} ? t8('A canceled invoice cannot be used. Please undo the cancellation first.')
457 submit => [ '#form', { action => "order" } ],
458 checks => [ 'kivi.validate_form' ],
459 disabled => !$form->{id} ? t8('This invoice has not been posted yet.') : undef,
461 ], # end of combobox "Workflow"
464 action => [ t8('Export') ],
466 ($form->{id} ? t8('Print') : t8('Preview')),
467 call => [ 'kivi.SalesPurchase.show_print_dialog', $form->{id} ? 'print' : 'preview' ],
468 checks => [ 'kivi.validate_form' ],
469 disabled => !$may_edit_create ? t8('You must not print this invoice.')
470 : !$form->{id} && $form->{locked} ? t8('The billing period has already been locked.')
473 action => [ t8('Print and Post'),
474 call => [ 'kivi.SalesPurchase.show_print_dialog', 'print_and_post' ],
475 checks => [ 'kivi.validate_form' ],
476 confirm => t8('The invoice is not linked with a sales delivery order. Post anyway?') x !!$warn_unlinked_delivery_order,
477 disabled => !$may_edit_create ? t8('You must not change this invoice.')
478 : $form->{locked} ? t8('The billing period has already been locked.')
479 : $form->{storno} ? t8('A canceled invoice cannot be posted.')
480 : ($form->{id} && $change_never) ? t8('Changing invoices has been disabled in the configuration.')
481 : ($form->{id} && $change_on_same_day_only) ? t8('Invoices can only be changed on the day they are posted.')
482 : $is_linked_bank_transaction ? t8('This transaction is linked with a bank transaction. Please undo and redo the bank transaction booking if needed.')
485 action => [ t8('E Mail'),
486 call => [ 'kivi.SalesPurchase.show_email_dialog' ],
487 checks => [ 'kivi.validate_form' ],
488 disabled => !$may_edit_create ? t8('You must not print this invoice.')
489 : !$form->{id} ? t8('This invoice has not been posted yet.')
490 : $form->{postal_invoice} ? t8('This customer wants a postal invoices.')
493 action => [ t8('Factur-X/ZUGFeRD'),
494 submit => [ '#form', { action => "download_factur_x_xml" } ],
495 checks => [ 'kivi.validate_form' ],
496 disabled => !$may_edit_create ? t8('You must not print this invoice.')
497 : !$form->{id} ? t8('This invoice has not been posted yet.')
498 : !$factur_x_enabled ? t8('Creating Factur-X/ZUGFeRD invoices is not enabled for this customer.')
501 ], # end of combobox "Export"
504 action => [ t8('more') ],
507 call => [ 'set_history_window', $form->{id} * 1, 'glid' ],
508 disabled => !$form->{id} ? t8('This invoice has not been posted yet.') : undef,
512 call => [ 'follow_up_window' ],
513 disabled => !$form->{id} ? t8('This invoice has not been posted yet.') : undef,
517 call => [ 'kivi.Draft.popup', 'is', 'invoice', $form->{draft_id}, $form->{draft_description} ],
518 disabled => !$may_edit_create ? t8('You must not change this invoice.')
519 : $form->{id} ? t8('This invoice has already been posted.')
520 : $form->{locked} ? t8('The billing period has already been locked.')
523 ], # end of combobox "more"
526 $::request->layout->add_javascripts('kivi.Validator.js');
530 $main::lxdebug->enter_sub();
534 my $form = $main::form;
535 my %myconfig = %main::myconfig;
536 my $locale = $main::locale;
537 my $cgi = $::request->{cgi};
542 $TMPL_VAR{customer_obj} = SL::DB::Customer->load_cached($form->{customer_id}) if $form->{customer_id};
543 $TMPL_VAR{invoice_obj} = SL::DB::Invoice->load_cached($form->{id}) if $form->{id};
545 # only print, no mail
546 $form->{postal_invoice} = $TMPL_VAR{customer_obj}->postal_invoice if ref $TMPL_VAR{customer_obj} eq 'SL::DB::Customer';
548 my $current_employee = SL::DB::Manager::Employee->current;
549 $form->{employee_id} = $form->{old_employee_id} if $form->{old_employee_id};
550 $form->{salesman_id} = $form->{old_salesman_id} if $form->{old_salesman_id};
551 $form->{employee_id} ||= $current_employee->id;
552 $form->{salesman_id} ||= $current_employee->id;
554 $form->{defaultcurrency} = $form->get_default_currency(\%myconfig);
556 $form->get_lists("taxzones" => ($form->{id} ? "ALL_TAXZONES" : "ALL_ACTIVE_TAXZONES"),
557 "currencies" => "ALL_CURRENCIES",
558 "price_factors" => "ALL_PRICE_FACTORS");
560 $form->{ALL_DEPARTMENTS} = SL::DB::Manager::Department->get_all_sorted;
561 $form->{ALL_LANGUAGES} = SL::DB::Manager::Language->get_all_sorted;
564 my @old_project_ids = uniq grep { $_ } map { $_ * 1 } ($form->{"globalproject_id"}, map { $form->{"project_id_$_"} } 1..$form->{"rowcount"});
565 my @old_ids_cond = @old_project_ids ? (id => \@old_project_ids) : ();
567 if ($::instance_conf->get_customer_projects_only_in_sales) {
570 customer_id => $::form->{customer_id},
571 billable_customer_id => $::form->{customer_id},
576 and => [ active => 1, @customer_cond ],
580 $TMPL_VAR{ALL_PROJECTS} = SL::DB::Manager::Project->get_all_sorted(query => \@conditions);
581 $form->{ALL_PROJECTS} = $TMPL_VAR{ALL_PROJECTS}; # make projects available for second row drop-down in io.pl
582 $TMPL_VAR{ALL_EMPLOYEES} = SL::DB::Manager::Employee->get_all_sorted(query => [ or => [ id => $::form->{employee_id}, deleted => 0 ] ]);
583 $TMPL_VAR{ALL_SALESMEN} = SL::DB::Manager::Employee->get_all_sorted(query => [ or => [ id => $::form->{salesman_id}, deleted => 0 ] ]);
584 $TMPL_VAR{ALL_SHIPTO} = SL::DB::Manager::Shipto->get_all_sorted(query => [
585 or => [ trans_id => $::form->{"$::form->{vc}_id"} * 1, and => [ shipto_id => $::form->{shipto_id} * 1, trans_id => undef ] ]
587 $TMPL_VAR{ALL_CONTACTS} = SL::DB::Manager::Contact->get_all_sorted(query => [
589 cp_cv_id => $::form->{"$::form->{vc}_id"} * 1,
592 cp_id => $::form->{cp_id} * 1
597 # currencies and exchangerate
598 my @values = map { $_ } @{ $form->{ALL_CURRENCIES} };
599 my %labels = map { $_ => $_ } @{ $form->{ALL_CURRENCIES} };
600 $form->{currency} = $form->{defaultcurrency} unless $form->{currency};
601 $form->{show_exchangerate} = $form->{currency} ne $form->{defaultcurrency};
602 $TMPL_VAR{currencies} = NTI($::request->{cgi}->popup_menu('-name' => 'currency', '-default' => $form->{"currency"},
603 '-values' => \@values, '-labels' => \%labels,
604 '-onchange' => "document.getElementById('update_button').click();"
605 )) if scalar @values;
606 push @custom_hiddens, "forex";
607 push @custom_hiddens, "exchangerate" if $form->{forex};
609 $TMPL_VAR{creditwarning} = ($form->{creditlimit} != 0) && ($form->{creditremaining} < 0) && !$form->{update};
610 $TMPL_VAR{is_credit_remaining_negativ} = $form->{creditremaining} =~ /-/;
612 # set option selected
613 foreach my $item (qw(AR)) {
614 $form->{"select$item"} =~ s/ selected//;
615 $form->{"select$item"} =~ s/option>\Q$form->{$item}\E/option selected>$form->{$item}/;
618 $TMPL_VAR{is_type_invoice_for_advance_payment} = $form->{type} eq "invoice_for_advance_payment";
619 $TMPL_VAR{is_type_credit_note} = $form->{type} eq "credit_note";
620 $TMPL_VAR{is_format_html} = $form->{format} eq 'html';
621 $TMPL_VAR{dateformat} = $myconfig{dateformat};
622 $TMPL_VAR{numberformat} = $myconfig{numberformat};
625 $TMPL_VAR{HIDDENS} = [qw(
626 id type queued printed emailed vc discount
627 title creditlimit creditremaining tradediscount business closedto locked shipped storno storno_id
628 max_dunning_level dunning_amount dunning_description
629 taxaccounts cursor_fokus
630 convert_from_do_ids convert_from_oe_ids convert_from_ar_ids useasnew
634 map { $_.'_rate', $_.'_description', $_.'_taxnumber', $_.'_tax_id' } split / /, $form->{taxaccounts}];
636 $::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));
638 $TMPL_VAR{payment_terms_obj} = get_payment_terms_for_invoice();
639 $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};
641 setup_is_action_bar(\%TMPL_VAR);
645 print $form->parse_html_template("is/form_header", \%TMPL_VAR);
647 $main::lxdebug->leave_sub();
651 my @fields = qw(acc_trans_id gldate datepaid source memo paid AR_paid);
653 grep { $_->{paid} != 0 }
656 +{ map { ($_ => delete($::form->{"${_}_${idx}"})) } @fields }
657 } (1..$::form->{paidaccounts});
659 @payments = sort_by { DateTime->from_kivitendo($_->{datepaid}) } @payments;
661 $::form->{paidaccounts} = max scalar(@payments), 1;
663 foreach my $idx (1 .. scalar(@payments)) {
664 my $payment = $payments[$idx - 1];
665 $::form->{"${_}_${idx}"} = $payment->{$_} for @fields;
670 $main::lxdebug->enter_sub();
674 my $form = $main::form;
675 my %myconfig = %main::myconfig;
676 my $locale = $main::locale;
678 $form->{invtotal} = $form->{invsubtotal};
680 # tax, total and subtotal calculations
681 my ($tax, $subtotal);
682 $form->{taxaccounts_array} = [ split(/ /, $form->{taxaccounts}) ];
684 if( $form->{customer_id} && !$form->{taxincluded_changed_by_user} ) {
685 my $customer = SL::DB::Customer->load_cached($form->{customer_id});
686 $form->{taxincluded} = defined($customer->taxincluded_checked) ? $customer->taxincluded_checked : $myconfig{taxincluded_checked};
689 foreach my $item (@{ $form->{taxaccounts_array} }) {
690 if ($form->{"${item}_base"}) {
691 if ($form->{taxincluded}) {
692 $form->{"${item}_total"} = $form->round_amount( ($form->{"${item}_base"} * $form->{"${item}_rate"}
693 / (1 + $form->{"${item}_rate"})), 2);
694 $form->{"${item}_netto"} = $form->round_amount( ($form->{"${item}_base"} - $form->{"${item}_total"}), 2);
696 $form->{"${item}_total"} = $form->round_amount( $form->{"${item}_base"} * $form->{"${item}_rate"}, 2);
697 $form->{invtotal} += $form->{"${item}_total"};
702 my $grossamount = $form->{invtotal};
703 $form->{invtotal} = $form->round_amount( $form->{invtotal}, 2, 1 );
704 $form->{rounding} = $form->round_amount(
705 $form->{invtotal} - $form->round_amount($grossamount, 2),
711 $form->{follow_ups} = FU->follow_ups('trans_id' => $form->{id}, 'not_done' => 1) || [];
712 $form->{follow_ups_unfinished} = ( sum map { $_->{due} * 1 } @{ $form->{follow_ups} } ) || 0;
719 $form->{paidaccounts}++ if ($form->{"paid_$form->{paidaccounts}"});
720 $form->{paid_indices} = [ 1 .. $form->{paidaccounts} ];
722 # Standard Konto für Umlaufvermögen
723 my $accno_arap = IS->get_standard_accno_current_assets(\%myconfig, \%$form);
725 for my $i (1 .. $form->{paidaccounts}) {
726 $form->{"changeable_$i"} = 1;
727 if (SL::DB::Default->get->payments_changeable == 0) {
729 $form->{"changeable_$i"} = ($form->{"acc_trans_id_$i"})? 0 : 1;
730 } elsif (SL::DB::Default->get->payments_changeable == 2) {
732 $form->{"changeable_$i"} = (($form->{"gldate_$i"} eq '') ||
733 ($form->current_date(\%myconfig) eq $form->{"gldate_$i"}));
736 #deaktivieren von gebuchten Zahlungen ausserhalb der Bücherkontrolle, vorher prüfen ob heute eingegeben
737 if ($form->date_closed($form->{"gldate_$i"})) {
738 $form->{"changeable_$i"} = 0;
741 $form->{"selectAR_paid_$i"} = $form->{selectAR_paid};
742 if (!$form->{"AR_paid_$i"}) {
743 $form->{"selectAR_paid_$i"} =~ s/option>$accno_arap--(.*?)</option selected>$accno_arap--$1</;
745 $form->{"selectAR_paid_$i"} =~ s/option>\Q$form->{"AR_paid_$i"}\E/option selected>$form->{"AR_paid_$i"}/;
748 $totalpaid += $form->{"paid_$i"};
751 $form->{oldinvtotal} = $form->{invtotal};
753 $form->{ALL_DELIVERY_TERMS} = SL::DB::Manager::DeliveryTerm->get_all_sorted();
755 my $shipto_cvars = SL::DB::Shipto->new->cvars_by_config;
756 foreach my $var (@{ $shipto_cvars }) {
757 my $name = "shiptocvar_" . $var->config->name;
758 $var->value($form->{$name}) if exists $form->{$name};
761 print $form->parse_html_template('is/form_footer', {
762 is_type_invoice_for_advance_payment => ($form->{type} eq "invoice_for_advance_payment"),
763 is_type_credit_note => ($form->{type} eq "credit_note"),
764 totalpaid => $totalpaid,
765 paid_missing => $form->{invtotal} - $totalpaid,
766 print_options => setup_sales_purchase_print_options(),
767 show_storno => $form->{id} && !$form->{storno} && !IS->has_storno(\%myconfig, $form, "ar") && !$totalpaid,
768 show_delete => ($::instance_conf->get_is_changeable == 2)
769 ? ($form->current_date(\%myconfig) eq $form->{gldate})
770 : ($::instance_conf->get_is_changeable == 1),
771 today => DateTime->today,
772 vc_obj => $form->{customer_id} ? SL::DB::Customer->load_cached($form->{customer_id}) : undef,
773 shipto_cvars => $shipto_cvars,
775 ##print $form->parse_html_template('is/_payments'); # parser
776 ##print $form->parse_html_template('webdav/_list'); # parser
778 $main::lxdebug->leave_sub();
782 $::auth->assert('invoice_edit');
784 SL::DB::Invoice->new(id => $::form->{id})->load->mark_as_paid;
786 $::form->redirect($::locale->text("Marked as paid"));
790 # unless no lazy implementation of save draft without invdate
791 # set the current date like in version <= 3.4.1
792 $::form->{invdate} = DateTime->today->to_lxoffice;
797 $main::lxdebug->enter_sub();
801 my $form = $main::form;
802 my %myconfig = %main::myconfig;
804 my ($recursive_call) = @_;
806 $form->{print_and_post} = 0 if $form->{second_run};
807 my $taxincluded = $form->{taxincluded} ? "checked" : '';
810 if (($form->{previous_customer_id} || $form->{customer_id}) != $form->{customer_id}) {
811 $::form->{salesman_id} = SL::DB::Manager::Employee->current->id if exists $::form->{salesman_id};
813 IS->get_customer(\%myconfig, $form);
814 $::form->{billing_address_id} = $::form->{default_billing_address_id};
817 $form->{taxincluded} ||= $taxincluded;
819 if (!$form->{forex}) { # read exchangerate from input field (not hidden)
820 $form->{exchangerate} = $form->parse_amount(\%myconfig, $form->{exchangerate}) unless $recursive_call;
822 $form->{forex} = $form->check_exchangerate(\%myconfig, $form->{currency}, $form->{invdate}, 'buy');
823 $form->{exchangerate} = $form->{forex} if $form->{forex};
825 for my $i (1 .. $form->{paidaccounts}) {
826 next unless $form->{"paid_$i"};
827 map { $form->{"${_}_$i"} = $form->parse_amount(\%myconfig, $form->{"${_}_$i"}) } qw(paid exchangerate);
828 $form->{"forex_$i"} = $form->check_exchangerate(\%myconfig, $form->{currency}, $form->{"datepaid_$i"}, 'buy');
829 $form->{"exchangerate_$i"} = $form->{"forex_$i"} if $form->{"forex_$i"};
832 my $i = $form->{rowcount};
833 my $exchangerate = $form->{exchangerate} || 1;
835 # if last row empty, check the form otherwise retrieve new item
836 if ( ($form->{"partnumber_$i"} eq "")
837 && ($form->{"description_$i"} eq "")
838 && ($form->{"partsgroup_$i"} eq "")) {
840 $form->{creditremaining} += ($form->{oldinvtotal} - $form->{oldtotalpaid});
845 IS->retrieve_item(\%myconfig, \%$form);
847 my $rows = scalar @{ $form->{item_list} };
849 $form->{"discount_$i"} = $form->parse_amount(\%myconfig, $form->{"discount_$i"}) / 100.0;
850 $form->{"discount_$i"} ||= $form->{customer_discount};
853 $form->{"qty_$i"} = $form->parse_amount(\%myconfig, $form->{"qty_$i"});
854 if( !$form->{"qty_$i"} ) {
855 $form->{"qty_$i"} = 1;
860 select_item(mode => 'IS', pre_entered_qty => $form->{"qty_$i"});
861 $::dispatcher->end_request;
865 my $sellprice = $form->parse_amount(\%myconfig, $form->{"sellprice_$i"});
867 map { $form->{item_list}[$i]{$_} =~ s/\"/"/g } qw(partnumber description unit);
868 map { $form->{"${_}_$i"} = $form->{item_list}[0]{$_} } keys %{ $form->{item_list}[0] };
870 $form->{payment_id} = $form->{"part_payment_id_$i"} if $form->{"part_payment_id_$i"} ne "";
871 $form->{"discount_$i"} = 0 if $form->{"not_discountable_$i"};
873 $form->{"marge_price_factor_$i"} = $form->{item_list}->[0]->{price_factor};
875 ($sellprice || $form->{"sellprice_$i"}) =~ /\.(\d+)/;
876 my $decimalplaces = max 2, length $1;
879 $form->{"sellprice_$i"} = $sellprice;
881 my $record = _make_record();
882 my $price_source = SL::PriceSource->new(record_item => $record->items->[$i-1], record => $record);
883 my $best_price = $price_source->best_price;
884 my $best_discount = $price_source->best_discount;
887 $::form->{"sellprice_$i"} = $best_price->price;
888 $::form->{"active_price_source_$i"} = $best_price->source;
890 if ($best_discount) {
891 $::form->{"discount_$i"} = $best_discount->discount;
892 $::form->{"active_discount_source_$i"} = $best_discount->source;
895 # if there is an exchange rate adjust sellprice
896 $form->{"sellprice_$i"} /= $exchangerate;
899 $form->{"listprice_$i"} /= $exchangerate;
901 my $amount = $form->{"sellprice_$i"} * $form->{"qty_$i"} * (1 - $form->{"discount_$i"});
902 map { $form->{"${_}_base"} = 0 } split / /, $form->{taxaccounts};
903 map { $form->{"${_}_base"} += $amount } split / /, $form->{"taxaccounts_$i"};
904 map { $amount += ($form->{"${_}_base"} * $form->{"${_}_rate"}) } split / /, $form->{"taxaccounts_$i"} if !$form->{taxincluded};
906 $form->{creditremaining} -= $amount;
908 map { $form->{"${_}_$i"} = $form->format_amount(\%myconfig, $form->{"${_}_$i"}, $decimalplaces) } qw(sellprice lastcost);
910 $form->{"qty_$i"} = $form->format_amount(\%myconfig, $form->{"qty_$i"});
911 $form->{"discount_$i"} = $form->format_amount(\%myconfig, $form->{"discount_$i"} * 100.0);
918 # ok, so this is a new part
919 # ask if it is a part or service item
921 if ( $form->{"partsgroup_$i"}
922 && ($form->{"partnumber_$i" } eq "")
923 && ($form->{"description_$i"} eq "")) {
925 $form->{"discount_$i"} = "";
929 $form->{"id_$i"} = 0;
934 $main::lxdebug->leave_sub();
938 $main::lxdebug->enter_sub();
940 my $form = $main::form;
941 my %myconfig = %main::myconfig;
942 my $locale = $main::locale;
944 $main::auth->assert('invoice_edit');
946 $form->mtime_ischanged('ar') ;
947 my $invdate = $form->datetonum($form->{invdate}, \%myconfig);
949 $form->{defaultcurrency} = $form->get_default_currency(\%myconfig);
950 for my $i (1 .. $form->{paidaccounts}) {
951 if ($form->{"paid_$i"}) {
952 my $datepaid = $form->datetonum($form->{"datepaid_$i"}, \%myconfig);
954 $form->isblank("datepaid_$i", $locale->text('Payment date missing!'));
957 if ($form->{currency} ne $form->{defaultcurrency}) {
958 $form->{"exchangerate_$i"} = $form->{exchangerate}
959 if ($invdate == $datepaid);
960 $form->isblank("exchangerate_$i",
961 $locale->text('Exchangerate for payment missing!'));
963 $form->error($locale->text('Cannot post transaction above the maximum future booking date!'))
964 if ($form->date_max_future($form->{"datepaid_$i"}, \%myconfig));
966 #Zusätzlich noch das Buchungsdatum in die Bücherkontrolle einbeziehen
967 # (Dient zur Prüfung ob ZE oder ZA geprüft werden soll)
968 $form->error($locale->text('Cannot post payment for a closed period!'))
969 if ($form->date_closed($form->{"datepaid_$i"}) && !$form->date_closed($form->{"gldate_$i"}, \%myconfig));
973 ($form->{AR}) = split /--/, $form->{AR};
974 ($form->{AR_paid}) = split /--/, $form->{AR_paid};
976 if ( IS->post_payment(\%myconfig, \%$form) ) {
977 $form->{snumbers} = qq|invnumber_| . $form->{invnumber};
978 $form->{what_done} = 'invoice';
979 $form->{addition} = "PAYMENT POSTED";
981 $form->redirect($locale->text('Payment posted!'))
983 $form->error($locale->text('Cannot post payment!'));
986 $main::lxdebug->leave_sub();
990 $main::lxdebug->enter_sub();
992 my $form = $main::form;
993 my %myconfig = %main::myconfig;
994 my $locale = $main::locale;
996 $main::auth->assert('invoice_edit');
997 $form->mtime_ischanged('ar');
999 $form->{defaultcurrency} = $form->get_default_currency(\%myconfig);
1000 $form->isblank("invdate", $locale->text('Invoice Date missing!'));
1001 $form->isblank("customer_id", $locale->text('Customer missing!'));
1002 $form->error($locale->text('Cannot post invoice for a closed period!'))
1003 if ($form->date_closed($form->{"invdate"}, \%myconfig));
1005 $form->{invnumber} =~ s/^\s*//g;
1006 $form->{invnumber} =~ s/\s*$//g;
1008 # if oldcustomer ne customer redo form
1009 if (($form->{previous_customer_id} || $form->{customer_id}) != $form->{customer_id}) {
1011 $::dispatcher->end_request;
1014 if ($myconfig{mandatory_departments} && !$form->{department_id}) {
1015 $form->{saved_message} = $::locale->text('You have to specify a department.');
1020 if ($form->{second_run}) {
1021 $form->{print_and_post} = 0;
1024 remove_emptied_rows();
1027 my $closedto = $form->datetonum($form->{closedto}, \%myconfig);
1028 my $invdate = $form->datetonum($form->{invdate}, \%myconfig);
1030 $form->error($locale->text('Cannot post transaction above the maximum future booking date!'))
1031 if ($form->date_max_future($invdate, \%myconfig));
1032 $form->error($locale->text('Cannot post invoice for a closed period!'))
1033 if ($invdate <= $closedto);
1035 $form->isblank("exchangerate", $locale->text('Exchangerate missing!'))
1036 if ($form->{currency} ne $form->{defaultcurrency});
1037 # advance payment allows only one tax
1038 if ($form->{type} eq 'invoice_for_advance_payment') {
1039 my @current_taxaccounts = (split(/ /, $form->{taxaccounts}));
1040 $form->error($locale->text('Cannot post invoice for advance payment with more than one tax'))
1041 if (scalar @current_taxaccounts > 1);
1044 for my $i (1 .. $form->{paidaccounts}) {
1045 if ($form->parse_amount(\%myconfig, $form->{"paid_$i"})) {
1046 my $datepaid = $form->datetonum($form->{"datepaid_$i"}, \%myconfig);
1048 $form->isblank("datepaid_$i", $locale->text('Payment date missing!'));
1050 $form->error($locale->text('Cannot post transaction above the maximum future booking date!'))
1051 if ($form->date_max_future($form->{"datepaid_$i"}, \%myconfig));
1053 #Zusätzlich noch das Buchungsdatum in die Bücherkontrolle einbeziehen
1054 # (Dient zur Prüfung ob ZE oder ZA geprüft werden soll)
1055 $form->error($locale->text('Cannot post payment for a closed period!'))
1056 if ($form->date_closed($form->{"datepaid_$i"}) && !$form->date_closed($form->{"gldate_$i"}, \%myconfig));
1058 if ($form->{currency} ne $form->{defaultcurrency}) {
1059 $form->{"exchangerate_$i"} = $form->{exchangerate}
1060 if ($invdate == $datepaid);
1061 $form->isblank("exchangerate_$i",
1062 $locale->text('Exchangerate for payment missing!'));
1067 ($form->{AR}) = split /--/, $form->{AR};
1068 ($form->{AR_paid}) = split /--/, $form->{AR_paid};
1069 $form->{storno} ||= 0;
1071 $form->{label} = $form->{type} eq 'credit_note' ? $locale->text('Credit Note') : $locale->text('Invoice');
1073 $form->{id} = 0 if $form->{postasnew};
1075 # get new invnumber in sequence if no invnumber is given or if posasnew was requested
1076 if ($form->{postasnew}) {
1077 if ($form->{type} eq "credit_note") {
1078 undef($form->{cnnumber});
1080 undef($form->{invnumber});
1086 my $terms = get_payment_terms_for_invoice();
1087 $form->{duedate} = $terms->calc_date(reference_date => $form->{invdate}, due_date => $form->{duedate})->to_kivitendo if $terms;
1089 # If transfer_out is requested, get rose db handle and do post and
1090 # transfer out in one transaction. Otherwise just post the invoice.
1091 if ($::instance_conf->get_is_transfer_out && $form->{type} ne 'credit_note' && !$form->{storno}) {
1092 require SL::DB::Inventory;
1093 my $rose_db = SL::DB::Inventory->new->db;
1096 if (!$rose_db->with_transaction(sub {
1098 if (!IS->post_invoice(\%myconfig, \%$form, $rose_db->dbh)) {
1099 push @errors, $locale->text('Cannot post invoice!');
1100 die 'posting error';
1102 my $err = IS->transfer_out(\%$form, $rose_db->dbh);
1104 push @errors, @{ $err };
1105 die 'transfer error';
1110 push @errors, $EVAL_ERROR;
1111 $form->error($locale->text('Cannot post invoice and/or transfer out! Error message:') . "\n" . join("\n", @errors));
1116 push @errors, $rose_db->error;
1117 $form->error($locale->text('Cannot post invoice and/or transfer out! Error message:') . "\n" . join("\n", @errors));
1120 if (!IS->post_invoice(\%myconfig, \%$form)) {
1121 $form->error($locale->text('Cannot post invoice!'));
1125 if(!exists $form->{addition}) {
1126 $form->{snumbers} = 'invnumber' .'_'. $form->{invnumber}; # ($form->{type} eq 'credit_note' ? 'cnnumber' : 'invnumber') .'_'. $form->{invnumber};
1127 $form->{what_done} = 'invoice';
1128 $form->{addition} = $form->{print_and_post} ? "PRINTED AND POSTED" :
1129 $form->{storno} ? "STORNO" :
1131 $form->save_history;
1134 if (!$form->{no_redirect_after_post}) {
1135 $form->{action} = 'edit';
1136 $form->{script} = 'is.pl';
1137 $form->{callback} = build_std_url(qw(action edit id callback saved_message));
1138 $form->redirect($form->{label} . " $form->{invnumber} " . $locale->text('posted!'));
1141 $main::lxdebug->leave_sub();
1144 sub print_and_post {
1145 $main::lxdebug->enter_sub();
1147 my $form = $main::form;
1149 $main::auth->assert('invoice_edit');
1151 my $old_form = Form->new;
1152 $form->{no_redirect_after_post} = 1;
1153 $form->{print_and_post} = 1;
1157 $main::lxdebug->leave_sub();
1162 $main::lxdebug->enter_sub();
1164 my $form = $main::form;
1165 my %myconfig = %main::myconfig;
1167 $main::auth->assert('invoice_edit');
1169 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)};
1170 $form->{rowcount}--;
1171 $form->{paidaccounts} = 1;
1172 $form->{invdate} = $form->current_date(\%myconfig);
1173 my $terms = get_payment_terms_for_invoice();
1174 $form->{duedate} = $terms ? $terms->calc_date(reference_date => $form->{invdate})->to_kivitendo : $form->{invdate};
1175 $form->{employee_id} = SL::DB::Manager::Employee->current->id;
1176 $form->{forex} = $form->check_exchangerate(\%myconfig, $form->{currency}, $form->{invdate}, 'buy');
1177 $form->{exchangerate} = $form->{forex} if $form->{forex};
1179 $form->{"converted_from_invoice_id_$_"} = delete $form->{"invoice_id_$_"} for 1 .. $form->{"rowcount"};
1181 $form->{useasnew} = 1;
1184 $main::lxdebug->leave_sub();
1187 sub further_invoice_for_advance_payment {
1188 my $form = $main::form;
1189 my %myconfig = %main::myconfig;
1191 $main::auth->assert('invoice_edit');
1193 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)};
1194 $form->{convert_from_ar_ids} = $form->{id};
1196 $form->{rowcount}--;
1197 $form->{paidaccounts} = 1;
1198 $form->{invdate} = $form->current_date(\%myconfig);
1199 my $terms = get_payment_terms_for_invoice();
1200 $form->{duedate} = $terms ? $terms->calc_date(reference_date => $form->{invdate})->to_kivitendo : $form->{invdate};
1201 $form->{employee_id} = SL::DB::Manager::Employee->current->id;
1202 $form->{forex} = $form->check_exchangerate(\%myconfig, $form->{currency}, $form->{invdate}, 'buy');
1203 $form->{exchangerate} = $form->{forex} if $form->{forex};
1205 $form->{"converted_from_invoice_id_$_"} = delete $form->{"invoice_id_$_"} for 1 .. $form->{"rowcount"};
1211 my $form = $main::form;
1212 my %myconfig = %main::myconfig;
1214 $main::auth->assert('invoice_edit');
1216 # search all related invoices for advance payment
1218 # (order) -> invoice for adv. payment 1 -> invoice for adv. payment 2 -> invoice for adv. payment 3 -> final invoice
1220 # we are currently in the last invoice for adv. payment (3 in this example)
1221 my $related_invoices = IS->_get_invoices_for_advance_payment($form->{id});
1223 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)};
1225 $form->{convert_from_ar_ids} = $form->{id};
1227 $form->{type} = 'final_invoice';
1228 $form->{title} = t8('Edit Final Invoice');
1229 $form->{paidaccounts} = 1;
1230 $form->{invdate} = $form->current_date(\%myconfig);
1231 my $terms = get_payment_terms_for_invoice();
1232 $form->{duedate} = $terms ? $terms->calc_date(reference_date => $form->{invdate})->to_kivitendo : $form->{invdate};
1233 $form->{employee_id} = SL::DB::Manager::Employee->current->id;
1234 $form->{forex} = $form->check_exchangerate(\%myconfig, $form->{currency}, $form->{invdate}, 'buy');
1235 $form->{exchangerate} = $form->{forex} if $form->{forex};
1237 foreach my $i (1 .. $form->{"rowcount"}) {
1238 delete $form->{"id_$i"};
1239 delete $form->{"invoice_id_$i"};
1240 delete $form->{"parts_id_$i"};
1241 delete $form->{"partnumber_$i"};
1242 delete $form->{"description_$i"};
1245 remove_emptied_rows(1);
1248 foreach my $ri (@$related_invoices) {
1249 foreach my $item (@{$ri->items_sorted}) {
1251 $form->{"id_$i"} = $item->parts_id;
1252 $form->{"partnumber_$i"} = $item->part->partnumber;
1253 $form->{"discount_$i"} = $item->discount*100.0;
1254 $form->{"sellprice_$i"} = $item->fxsellprice;
1255 $form->{$_ . "_" . $i} = $item->$_ for qw(description longdescription qty price_factor_id unit sellprice active_price_source active_discount_source);
1257 $form->{$_ . "_" . $i} = $form->format_amount(\%myconfig, $form->{$_ . "_" . $i}) for qw(qty sellprice discount);
1260 $form->{rowcount} = $i;
1263 $::dispatcher->end_request;
1267 $main::lxdebug->enter_sub();
1269 my $form = $main::form;
1270 my %myconfig = %main::myconfig;
1271 my $locale = $main::locale;
1273 $main::auth->assert('invoice_edit');
1275 if ($form->{storno}) {
1276 $form->error($locale->text('Cannot storno storno invoice!'));
1279 if (IS->has_storno(\%myconfig, $form, "ar")) {
1280 $form->error($locale->text("Invoice has already been storno'd!"));
1282 if ($form->datetonum($form->{invdate}, \%myconfig) <= $form->datetonum($form->{closedto}, \%myconfig)) {
1283 $form->error($locale->text('Cannot storno invoice for a closed period!'));
1286 # save the history of invoice being stornoed
1287 $form->{snumbers} = qq|invnumber_| . $form->{invnumber};
1288 $form->{what_done} = 'invoice';
1289 $form->{addition} = "STORNO";
1290 $form->save_history;
1292 map({ my $key = $_; delete($form->{$key}) unless (grep({ $key eq $_ } qw(id login password type))); } keys(%{ $form }));
1298 # Payments must not be recorded for the new storno invoice.
1299 $form->{paidaccounts} = 0;
1300 map { my $key = $_; delete $form->{$key} if grep { $key =~ /^$_/ } qw(datepaid_ gldate_ acc_trans_id_ source_ memo_ paid_ exchangerate_ AR_paid_) } keys %{ $form };
1302 # record link invoice to storno
1303 $form->{convert_from_ar_ids} = $form->{id};
1304 $form->{storno_id} = $form->{id};
1305 $form->{storno} = 1;
1307 $form->{invnumber} = "Storno zu " . $form->{invnumber};
1308 $form->{invdate} = DateTime->today->to_lxoffice;
1309 $form->{rowcount}++;
1310 # set new ids for storno invoice
1311 # set new persistent ids for storno invoice items
1312 $form->{"converted_from_invoice_id_$_"} = delete $form->{"invoice_id_$_"} for 1 .. $form->{"rowcount"};
1315 $main::lxdebug->leave_sub();
1319 $main::lxdebug->enter_sub();
1321 my $form = $main::form;
1323 $main::auth->assert('invoice_edit');
1325 $form->{preview} = 1;
1326 my $old_form = Form->new;
1327 for (keys %$form) { $old_form->{$_} = $form->{$_} }
1329 &print_form($old_form);
1330 $main::lxdebug->leave_sub();
1335 $main::lxdebug->enter_sub();
1337 my $form = $main::form;
1338 my %myconfig = %main::myconfig;
1339 my $locale = $main::locale;
1341 $main::auth->assert('invoice_edit');
1343 $form->{transdate} = $form->{invdate} = $form->current_date(\%myconfig);
1345 $form->current_date(\%myconfig, $form->{invdate}, $form->{terms} * 1);
1347 $form->{convert_from_ar_ids} = $form->{id};
1349 $form->{rowcount}--;
1352 $form->{title} = $locale->text('Add Credit Note');
1353 $form->{script} = 'is.pl';
1355 # Bei Gutschriften bezug zur Rechnungsnummer
1356 $form->{invnumber_for_credit_note} = $form->{invnumber};
1357 # bo creates the id, reset it
1358 map { delete $form->{$_} }
1359 qw(id invnumber subject message cc bcc printed emailed queued);
1360 $form->{ $form->{vc} } =~ s/--.*//g;
1361 $form->{type} = "credit_note";
1364 map { $form->{"select$_"} = "" } ($form->{vc}, 'currency');
1366 # map { $form->{$_} = $form->parse_amount(\%myconfig, $form->{$_}) }
1367 # qw(creditlimit creditremaining);
1369 # set new persistent ids for credit note and link previous invoice id
1370 $form->{"converted_from_invoice_id_$_"} = delete $form->{"invoice_id_$_"} for 1 .. $form->{"rowcount"};
1372 my $currency = $form->{currency};
1375 $form->{currency} = $currency;
1376 $form->{forex} = $form->check_exchangerate( \%myconfig, $form->{currency}, $form->{invdate}, 'buy');
1377 $form->{exchangerate} = $form->{forex} || '';
1379 $form->{creditremaining} -= ($form->{oldinvtotal} - $form->{ordtotal});
1381 # bei Gutschriften werden Zahlungseingänge aus Rechnung nicht übernommen
1382 for my $i (1 .. $form->{paidaccounts}) {
1383 delete $form->{"paid_$i"};
1384 delete $form->{"source_$i"};
1385 delete $form->{"memo_$i"};
1386 delete $form->{"datepaid_$i"};
1387 delete $form->{"gldate_$i"};
1388 delete $form->{"acc_trans_id_$i"};
1389 delete $form->{"AR_paid_$i"};
1391 $form->{paidaccounts} = 1;
1397 $main::lxdebug->leave_sub();
1401 $::lxdebug->enter_sub;
1407 my $new_rowcount = $::form->{"rowcount"} * 1 + 1;
1408 $::form->{"project_id_${new_rowcount}"} = $::form->{"globalproject_id"};
1410 $::form->language_payment(\%::myconfig);
1412 Common::webdav_folder($::form);
1415 display_row(++$::form->{rowcount});
1418 $::lxdebug->leave_sub;
1422 $::auth->assert('invoice_edit');
1424 if (IS->delete_invoice(\%::myconfig, $::form)) {
1425 # saving the history
1426 if(!exists $::form->{addition}) {
1427 $::form->{snumbers} = 'invnumber' .'_'. $::form->{invnumber};
1428 $::form->{what_done} = 'invoice';
1429 $::form->{addition} = "DELETED";
1430 $::form->save_history;
1432 # /saving the history
1433 $::form->redirect($::locale->text('Invoice deleted!'));
1435 $::form->error($::locale->text('Cannot delete invoice!'));
1440 print update ship_to storno post_payment use_as_new credit_note
1441 delete post order preview post_and_e_mail print_and_post
1444 if ($::form->{"action_$action"}) {
1450 $::form->error($::locale->text('No action defined.'));