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 1 if $::auth->assert('sales_invoice_view', 1); # viewing is allowed with this right
68 return 0 if !$::form->{globalproject_id}; # existing records without a project ID are not allowed
69 return SL::DB::Project->new(id => $::form->{globalproject_id})->load->may_employee_view_project_invoices(SL::DB::Manager::Employee->current);
73 my $cache = $::request->cache('is.pl::_assert_access');
75 $cache->{_may_view_or_edit_this_invoice} = _may_view_or_edit_this_invoice() if !exists $cache->{_may_view_or_edit_this_invoice};
76 $::form->show_generic_error($::locale->text("You do not have the permissions to access this function.")) if ! $cache->{_may_view_or_edit_this_invoice};
80 $main::lxdebug->enter_sub();
82 my $form = $main::form;
83 my $locale = $main::locale;
85 $main::auth->assert('invoice_edit');
87 $form->{show_details} = $::myconfig{show_form_details};
89 if ($form->{type} eq "credit_note") {
90 $form->{title} = $locale->text('Add Credit Note');
92 if ($form->{storno}) {
93 $form->{title} = $locale->text('Add Storno Credit Note');
96 } elsif ($form->{type} eq "invoice_for_advance_payment") {
97 $form->{title} = $locale->text('Add Invoice for Advance Payment');
99 } elsif ($form->{type} eq "final_invoice") {
100 $form->{title} = $locale->text('Add Final Invoice');
103 $form->{title} = $locale->text('Add Sales Invoice');
108 $form->{callback} = "$form->{script}?action=add&type=$form->{type}" unless $form->{callback};
110 invoice_links(is_new => 1);
114 $main::lxdebug->leave_sub();
118 $main::lxdebug->enter_sub();
120 # Delay access check to after the invoice's been loaded in
121 # "invoice_links" so that project-specific invoice rights can be
124 my $form = $main::form;
125 my $locale = $main::locale;
127 $form->{show_details} = $::myconfig{show_form_details};
128 $form->{taxincluded_changed_by_user} = 1;
130 # show history button
131 $form->{javascript} = qq|<script type="text/javascript" src="js/show_history.js"></script>|;
133 my ($language_id, $printer_id);
134 if ($form->{print_and_post}) {
135 $form->{action} = "print";
136 $form->{resubmit} = 1;
137 $language_id = $form->{language_id};
138 $printer_id = $form->{printer_id};
142 if ($form->{type} eq "credit_note") {
143 $form->{title} = $locale->text('Edit Credit Note');
144 $form->{title} = $locale->text('Edit Storno Credit Note') if $form->{storno};
146 } elsif ($form->{type} eq "invoice_for_advance_payment") {
147 $form->{title} = $locale->text('Edit Invoice for Advance Payment');
148 $form->{title} = $locale->text('Edit Storno Invoice for Advance Payment') if $form->{storno};
150 } elsif ($form->{type} eq "final_invoice") {
151 $form->{title} = $locale->text('Edit Final Invoice');
154 $form->{title} = $locale->text('Edit Sales Invoice');
155 $form->{title} = $locale->text('Edit Storno Invoice') if $form->{storno};
159 if ($form->{print_and_post}) {
160 $form->{language_id} = $language_id;
161 $form->{printer_id} = $printer_id;
166 $main::lxdebug->leave_sub();
170 $main::lxdebug->enter_sub();
172 # Delay access check to after the invoice's been loaded so that
173 # project-specific invoice rights can be evaluated.
176 my $form = $main::form;
177 my %myconfig = %main::myconfig;
179 $form->{vc} = 'customer';
182 $form->create_links("AR", \%myconfig, "customer");
186 my $editing = $form->{id};
188 $form->backup_vars(qw(payment_id language_id taxzone_id salesman_id
189 taxincluded currency cp_id intnotes id shipto_id
192 IS->get_customer(\%myconfig, \%$form);
194 $form->{billing_address_id} = $form->{default_billing_address_id} if $params{is_new};
196 $form->restore_vars(qw(id));
198 IS->retrieve_invoice(\%myconfig, \%$form);
199 $form->restore_vars(qw(payment_id language_id taxzone_id currency intnotes
200 cp_id shipto_id delivery_term_id));
201 $form->restore_vars(qw(taxincluded)) if $form->{id};
202 $form->restore_vars(qw(salesman_id)) if $editing;
204 $form->{employee} = "$form->{employee}--$form->{employee_id}";
207 $form->{forex} = $form->{exchangerate};
208 my $exchangerate = ($form->{exchangerate}) ? $form->{exchangerate} : 1;
210 foreach my $key (keys %{ $form->{AR_links} }) {
211 foreach my $ref (@{ $form->{AR_links}{$key} }) {
212 $form->{"select$key"} .= "<option>$ref->{accno}--$ref->{description}</option>\n";
215 if ($key eq "AR_paid") {
216 next unless $form->{acc_trans}{$key};
217 for my $i (1 .. scalar @{ $form->{acc_trans}{$key} }) {
218 $form->{"AR_paid_$i"} = "$form->{acc_trans}{$key}->[$i-1]->{accno}--$form->{acc_trans}{$key}->[$i-1]->{description}";
220 $form->{"acc_trans_id_$i"} = $form->{acc_trans}{$key}->[$i - 1]->{acc_trans_id};
222 $form->{"paid_$i"} = $form->{acc_trans}{$key}->[$i - 1]->{amount} * -1;
223 $form->{"datepaid_$i"} = $form->{acc_trans}{$key}->[$i - 1]->{transdate};
224 $form->{"gldate_$i"} = $form->{acc_trans}{$key}->[$i - 1]->{gldate};
225 $form->{"exchangerate_$i"} = $form->{acc_trans}{$key}->[$i - 1]->{exchangerate};
226 $form->{"forex_$i"} = $form->{"exchangerate_$i"};
227 $form->{"source_$i"} = $form->{acc_trans}{$key}->[$i - 1]->{source};
228 $form->{"memo_$i"} = $form->{acc_trans}{$key}->[$i - 1]->{memo};
230 $form->{paidaccounts} = $i;
233 $form->{$key} = "$form->{acc_trans}{$key}->[0]->{accno}--$form->{acc_trans}{$key}->[0]->{description}";
237 $form->{paidaccounts} = 1 unless (exists $form->{paidaccounts});
239 $form->{AR} = $form->{AR_1} unless $form->{id};
241 $form->{locked} = ($form->datetonum($form->{invdate}, \%myconfig)
242 <= $form->datetonum($form->{closedto}, \%myconfig));
244 $main::lxdebug->leave_sub();
247 sub prepare_invoice {
248 $main::lxdebug->enter_sub();
252 my $form = $main::form;
253 my %myconfig = %main::myconfig;
255 if ($form->{type} eq "credit_note") {
256 $form->{type} = "credit_note";
257 $form->{formname} = "credit_note";
259 } elsif ($form->{type} eq "invoice_for_advance_payment") {
260 $form->{type} = "invoice_for_advance_payment";
261 $form->{formname} = "invoice_for_advance_payment";
263 } elsif ($form->{type} eq "final_invoice") {
264 $form->{type} = "final_invoice";
265 $form->{formname} = "final_invoice";
267 } elsif ($form->{formname} eq "proforma" ) {
268 $form->{type} = "invoice";
271 $form->{type} = "invoice";
272 $form->{formname} = "invoice";
279 foreach my $ref (@{ $form->{invoice_details} }) {
282 map { $form->{"${_}_$i"} = $ref->{$_} } keys %{$ref};
284 $form->{"discount_$i"} = $form->format_amount(\%myconfig, $form->{"discount_$i"} * 100);
285 my ($dec) = ($form->{"sellprice_$i"} =~ /\.(\d+)/);
287 my $decimalplaces = ($dec > 2) ? $dec : 2;
289 $form->{"sellprice_$i"} = $form->format_amount(\%myconfig, $form->{"sellprice_$i"}, $decimalplaces);
290 (my $dec_qty) = ($form->{"qty_$i"} =~ /\.(\d+)/);
291 $dec_qty = length $dec_qty;
293 $form->{"lastcost_$i"} = $form->format_amount(\%myconfig, $form->{"lastcost_$i"}, $decimalplaces);
295 $form->{"qty_$i"} = $form->format_amount(\%myconfig, $form->{"qty_$i"}, $dec_qty);
297 $form->{"sellprice_pg_$i"} = join ('--', $form->{"sellprice_$i"}, $form->{"pricegroup_id_$i"});
299 $form->{rowcount} = $i;
303 $main::lxdebug->leave_sub();
306 sub setup_is_action_bar {
309 my $change_never = $::instance_conf->get_is_changeable == 0;
310 my $change_on_same_day_only = $::instance_conf->get_is_changeable == 2 && ($form->current_date(\%::myconfig) ne $form->{gldate});
311 my $payments_balanced = ($::form->{oldtotalpaid} == 0);
312 my $has_storno = ($::form->{storno} && !$::form->{storno_id});
313 my $may_edit_create = $::auth->assert('invoice_edit', 1);
314 my $factur_x_enabled = $tmpl_var->{invoice_obj} && $tmpl_var->{invoice_obj}->customer->create_zugferd_invoices_for_this_customer;
315 my ($is_linked_bank_transaction, $warn_unlinked_delivery_order);
317 && SL::DB::Default->get->payments_changeable != 0
318 && SL::DB::Manager::BankTransactionAccTrans->find_by(ar_id => $::form->{id})) {
320 $is_linked_bank_transaction = 1;
322 if ($::instance_conf->get_warn_no_delivery_order_for_invoice && !$form->{id}) {
323 $warn_unlinked_delivery_order = 1 unless $form->{convert_from_do_ids};
326 my $has_further_invoice_for_advance_payment;
327 if ($form->{id} && $form->{type} eq "invoice_for_advance_payment") {
328 my $invoice_obj = SL::DB::Invoice->load_cached($form->{id});
329 my $lr = $invoice_obj->linked_records(direction => 'to', to => ['Invoice']);
330 $has_further_invoice_for_advance_payment = any {'SL::DB::Invoice' eq ref $_ && "invoice_for_advance_payment" eq $_->type} @$lr;
333 my $has_final_invoice;
334 if ($form->{id} && $form->{type} eq "invoice_for_advance_payment") {
335 my $invoice_obj = SL::DB::Invoice->load_cached($form->{id});
336 my $lr = $invoice_obj->linked_records(direction => 'to', to => ['Invoice']);
337 $has_final_invoice = any {'SL::DB::Invoice' eq ref $_ && "final_invoice" eq $_->invoice_type} @$lr;
340 my $is_invoice_for_advance_payment_from_order;
341 if ($form->{id} && $form->{type} eq "invoice_for_advance_payment") {
342 my $invoice_obj = SL::DB::Invoice->load_cached($form->{id});
343 my $lr = $invoice_obj->linked_records(direction => 'from', from => ['Order']);
344 $is_invoice_for_advance_payment_from_order = scalar @$lr >= 1;
347 for my $bar ($::request->layout->get('actionbar')) {
351 submit => [ '#form', { action => "update" } ],
352 disabled => !$may_edit_create ? t8('You must not change this invoice.')
353 : $form->{locked} ? t8('The billing period has already been locked.')
355 id => 'update_button',
356 accesskey => 'enter',
362 submit => [ '#form', { action => "post" } ],
363 checks => [ 'kivi.validate_form' ],
364 confirm => t8('The invoice is not linked with a sales delivery order. Post anyway?') x !!$warn_unlinked_delivery_order,
365 disabled => !$may_edit_create ? t8('You must not change this invoice.')
366 : $form->{locked} ? t8('The billing period has already been locked.')
367 : $form->{storno} ? t8('A canceled invoice cannot be posted.')
368 : ($form->{id} && $change_never) ? t8('Changing invoices has been disabled in the configuration.')
369 : ($form->{id} && $change_on_same_day_only) ? t8('Invoices can only be changed on the day they are posted.')
370 : $is_linked_bank_transaction ? t8('This transaction is linked with a bank transaction. Please undo and redo the bank transaction booking if needed.')
375 submit => [ '#form', { action => "post_payment" } ],
376 checks => [ 'kivi.validate_form' ],
377 disabled => !$may_edit_create ? t8('You must not change this invoice.')
378 : !$form->{id} ? t8('This invoice has not been posted yet.')
379 : $is_linked_bank_transaction ? t8('This transaction is linked with a bank transaction. Please undo and redo the bank transaction booking if needed.')
381 only_if => $form->{type} ne "invoice_for_advance_payment",
383 action => [ t8('Mark as paid'),
384 submit => [ '#form', { action => "mark_as_paid" } ],
385 confirm => t8('This will remove the invoice from showing as unpaid even if the unpaid amount does not match the amount. Proceed?'),
386 disabled => !$may_edit_create ? t8('You must not change this invoice.')
387 : !$form->{id} ? t8('This invoice has not been posted yet.')
389 only_if => ($::instance_conf->get_is_show_mark_as_paid && $form->{type} ne "invoice_for_advance_payment") || $form->{type} eq 'final_invoice',
391 ], # end of combobox "Post"
394 action => [ t8('Storno'),
395 submit => [ '#form', { action => "storno" } ],
396 confirm => t8('Do you really want to cancel this invoice?'),
397 checks => [ 'kivi.validate_form' ],
398 disabled => !$may_edit_create ? t8('You must not change this invoice.')
399 : !$form->{id} ? t8('This invoice has not been posted yet.')
400 : $form->{storno} ? t8('Cannot storno storno invoice!')
401 : $form->{locked} ? t8('The billing period has already been locked.')
402 : !$payments_balanced ? t8('Cancelling is disallowed. Either undo or balance the current payments until the open amount matches the invoice amount')
405 action => [ t8('Delete'),
406 submit => [ '#form', { action => "delete" } ],
407 confirm => t8('Do you really want to delete this object?'),
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.')
411 : $form->{locked} ? t8('The billing period has already been locked.')
412 : $change_never ? t8('Changing invoices has been disabled in the configuration.')
413 : $change_on_same_day_only ? t8('Invoices can only be changed on the day they are posted.')
414 : $has_storno ? t8('Can only delete the "Storno zu" part of the cancellation pair.')
417 ], # end of combobox "Storno"
422 action => [ t8('Workflow') ],
425 submit => [ '#form', { action => "use_as_new" } ],
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.')
432 t8('Further Invoice for Advance Payment'),
433 submit => [ '#form', { action => "further_invoice_for_advance_payment" } ],
434 checks => [ 'kivi.validate_form' ],
435 disabled => !$may_edit_create ? t8('You must not change this invoice.')
436 : !$form->{id} ? t8('This invoice has not been posted yet.')
437 : $has_further_invoice_for_advance_payment ? t8('This invoice has already a further invoice for advanced payment.')
438 : $has_final_invoice ? t8('This invoice has already a final invoice.')
439 : $is_invoice_for_advance_payment_from_order ? t8('This invoice was added from an order. See there.')
441 only_if => $form->{type} eq "invoice_for_advance_payment",
445 submit => [ '#form', { action => "final_invoice" } ],
446 checks => [ 'kivi.validate_form' ],
447 disabled => !$may_edit_create ? t8('You must not change this invoice.')
448 : !$form->{id} ? t8('This invoice has not been posted yet.')
449 : $has_further_invoice_for_advance_payment ? t8('This invoice has a further invoice for advanced payment.')
450 : $has_final_invoice ? t8('This invoice has already a final invoice.')
451 : $is_invoice_for_advance_payment_from_order ? t8('This invoice was added from an order. See there.')
453 only_if => $form->{type} eq "invoice_for_advance_payment",
457 submit => [ '#form', { action => "credit_note" } ],
458 checks => [ 'kivi.validate_form' ],
459 disabled => !$may_edit_create ? t8('You must not change this invoice.')
460 : $form->{type} eq "credit_note" ? t8('Credit notes cannot be converted into other credit notes.')
461 : !$form->{id} ? t8('This invoice has not been posted yet.')
462 : $form->{storno} ? t8('A canceled invoice cannot be used. Please undo the cancellation first.')
467 submit => [ '#form', { action => "order" } ],
468 checks => [ 'kivi.validate_form' ],
469 disabled => !$form->{id} ? t8('This invoice has not been posted yet.') : undef,
471 ], # end of combobox "Workflow"
474 action => [ t8('Export') ],
476 ($form->{id} ? t8('Print') : t8('Preview')),
477 call => [ 'kivi.SalesPurchase.show_print_dialog', $form->{id} ? 'print' : 'preview' ],
478 checks => [ 'kivi.validate_form' ],
479 disabled => !$may_edit_create ? t8('You must not print this invoice.')
480 : !$form->{id} && $form->{locked} ? t8('The billing period has already been locked.')
483 action => [ t8('Print and Post'),
484 call => [ 'kivi.SalesPurchase.show_print_dialog', 'print_and_post' ],
485 checks => [ 'kivi.validate_form' ],
486 confirm => t8('The invoice is not linked with a sales delivery order. Post anyway?') x !!$warn_unlinked_delivery_order,
487 disabled => !$may_edit_create ? t8('You must not change this invoice.')
488 : $form->{locked} ? t8('The billing period has already been locked.')
489 : $form->{storno} ? t8('A canceled invoice cannot be posted.')
490 : ($form->{id} && $change_never) ? t8('Changing invoices has been disabled in the configuration.')
491 : ($form->{id} && $change_on_same_day_only) ? t8('Invoices can only be changed on the day they are posted.')
492 : $is_linked_bank_transaction ? t8('This transaction is linked with a bank transaction. Please undo and redo the bank transaction booking if needed.')
495 action => [ t8('E Mail'),
496 call => [ 'kivi.SalesPurchase.show_email_dialog' ],
497 checks => [ 'kivi.validate_form' ],
498 disabled => !$may_edit_create ? t8('You must not print this invoice.')
499 : !$form->{id} ? t8('This invoice has not been posted yet.')
500 : $form->{postal_invoice} ? t8('This customer wants a postal invoices.')
503 action => [ t8('Factur-X/ZUGFeRD'),
504 submit => [ '#form', { action => "download_factur_x_xml" } ],
505 checks => [ 'kivi.validate_form' ],
506 disabled => !$may_edit_create ? t8('You must not print this invoice.')
507 : !$form->{id} ? t8('This invoice has not been posted yet.')
508 : !$factur_x_enabled ? t8('Creating Factur-X/ZUGFeRD invoices is not enabled for this customer.')
511 ], # end of combobox "Export"
514 action => [ t8('more') ],
517 call => [ 'set_history_window', $form->{id} * 1, 'glid' ],
518 disabled => !$form->{id} ? t8('This invoice has not been posted yet.') : undef,
522 call => [ 'follow_up_window' ],
523 disabled => !$form->{id} ? t8('This invoice has not been posted yet.') : undef,
527 call => [ 'kivi.Draft.popup', 'is', 'invoice', $form->{draft_id}, $form->{draft_description} ],
528 disabled => !$may_edit_create ? t8('You must not change this invoice.')
529 : $form->{id} ? t8('This invoice has already been posted.')
530 : $form->{locked} ? t8('The billing period has already been locked.')
533 ], # end of combobox "more"
536 $::request->layout->add_javascripts('kivi.Validator.js');
540 $main::lxdebug->enter_sub();
544 my $form = $main::form;
545 my %myconfig = %main::myconfig;
546 my $locale = $main::locale;
547 my $cgi = $::request->{cgi};
552 $TMPL_VAR{customer_obj} = SL::DB::Customer->load_cached($form->{customer_id}) if $form->{customer_id};
553 $TMPL_VAR{invoice_obj} = SL::DB::Invoice->load_cached($form->{id}) if $form->{id};
555 # only print, no mail
556 $form->{postal_invoice} = $TMPL_VAR{customer_obj}->postal_invoice if ref $TMPL_VAR{customer_obj} eq 'SL::DB::Customer';
558 my $current_employee = SL::DB::Manager::Employee->current;
559 $form->{employee_id} = $form->{old_employee_id} if $form->{old_employee_id};
560 $form->{salesman_id} = $form->{old_salesman_id} if $form->{old_salesman_id};
561 $form->{employee_id} ||= $current_employee->id;
562 $form->{salesman_id} ||= $current_employee->id;
564 $form->{defaultcurrency} = $form->get_default_currency(\%myconfig);
566 $form->get_lists("taxzones" => ($form->{id} ? "ALL_TAXZONES" : "ALL_ACTIVE_TAXZONES"),
567 "currencies" => "ALL_CURRENCIES",
568 "price_factors" => "ALL_PRICE_FACTORS");
570 $form->{ALL_DEPARTMENTS} = SL::DB::Manager::Department->get_all_sorted;
571 $form->{ALL_LANGUAGES} = SL::DB::Manager::Language->get_all_sorted;
574 my @old_project_ids = uniq grep { $_ } map { $_ * 1 } ($form->{"globalproject_id"}, map { $form->{"project_id_$_"} } 1..$form->{"rowcount"});
575 my @old_ids_cond = @old_project_ids ? (id => \@old_project_ids) : ();
577 if ($::instance_conf->get_customer_projects_only_in_sales) {
580 customer_id => $::form->{customer_id},
581 billable_customer_id => $::form->{customer_id},
586 and => [ active => 1, @customer_cond ],
590 $TMPL_VAR{ALL_PROJECTS} = SL::DB::Manager::Project->get_all_sorted(query => \@conditions);
591 $form->{ALL_PROJECTS} = $TMPL_VAR{ALL_PROJECTS}; # make projects available for second row drop-down in io.pl
592 $TMPL_VAR{ALL_EMPLOYEES} = SL::DB::Manager::Employee->get_all_sorted(query => [ or => [ id => $::form->{employee_id}, deleted => 0 ] ]);
593 $TMPL_VAR{ALL_SALESMEN} = SL::DB::Manager::Employee->get_all_sorted(query => [ or => [ id => $::form->{salesman_id}, deleted => 0 ] ]);
594 $TMPL_VAR{ALL_SHIPTO} = SL::DB::Manager::Shipto->get_all_sorted(query => [
595 or => [ trans_id => $::form->{"$::form->{vc}_id"} * 1, and => [ shipto_id => $::form->{shipto_id} * 1, trans_id => undef ] ]
597 $TMPL_VAR{ALL_CONTACTS} = SL::DB::Manager::Contact->get_all_sorted(query => [
599 cp_cv_id => $::form->{"$::form->{vc}_id"} * 1,
602 cp_id => $::form->{cp_id} * 1
607 # currencies and exchangerate
608 my @values = map { $_ } @{ $form->{ALL_CURRENCIES} };
609 my %labels = map { $_ => $_ } @{ $form->{ALL_CURRENCIES} };
610 $form->{currency} = $form->{defaultcurrency} unless $form->{currency};
611 $form->{show_exchangerate} = $form->{currency} ne $form->{defaultcurrency};
612 $TMPL_VAR{currencies} = NTI($::request->{cgi}->popup_menu('-name' => 'currency', '-default' => $form->{"currency"},
613 '-values' => \@values, '-labels' => \%labels,
614 '-onchange' => "document.getElementById('update_button').click();"
615 )) if scalar @values;
616 push @custom_hiddens, "forex";
617 push @custom_hiddens, "exchangerate" if $form->{forex};
619 $TMPL_VAR{creditwarning} = ($form->{creditlimit} != 0) && ($form->{creditremaining} < 0) && !$form->{update};
620 $TMPL_VAR{is_credit_remaining_negativ} = $form->{creditremaining} =~ /-/;
622 # set option selected
623 foreach my $item (qw(AR)) {
624 $form->{"select$item"} =~ s/ selected//;
625 $form->{"select$item"} =~ s/option>\Q$form->{$item}\E/option selected>$form->{$item}/;
628 $TMPL_VAR{is_type_normal_invoice} = $form->{type} eq "invoice";
629 $TMPL_VAR{is_type_credit_note} = $form->{type} eq "credit_note";
630 $TMPL_VAR{is_format_html} = $form->{format} eq 'html';
631 $TMPL_VAR{dateformat} = $myconfig{dateformat};
632 $TMPL_VAR{numberformat} = $myconfig{numberformat};
635 $TMPL_VAR{HIDDENS} = [qw(
636 id type queued printed emailed vc discount
637 title creditlimit creditremaining tradediscount business closedto locked shipped storno storno_id
638 max_dunning_level dunning_amount dunning_description
639 taxaccounts cursor_fokus
640 convert_from_do_ids convert_from_oe_ids convert_from_ar_ids useasnew
644 map { $_.'_rate', $_.'_description', $_.'_taxnumber', $_.'_tax_id' } split / /, $form->{taxaccounts}];
646 $::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));
648 $TMPL_VAR{payment_terms_obj} = get_payment_terms_for_invoice();
649 $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};
651 setup_is_action_bar(\%TMPL_VAR);
655 print $form->parse_html_template("is/form_header", \%TMPL_VAR);
657 $main::lxdebug->leave_sub();
661 my @fields = qw(acc_trans_id gldate datepaid source memo paid AR_paid);
663 grep { $_->{paid} != 0 }
666 +{ map { ($_ => delete($::form->{"${_}_${idx}"})) } @fields }
667 } (1..$::form->{paidaccounts});
669 @payments = sort_by { DateTime->from_kivitendo($_->{datepaid}) } @payments;
671 $::form->{paidaccounts} = max scalar(@payments), 1;
673 foreach my $idx (1 .. scalar(@payments)) {
674 my $payment = $payments[$idx - 1];
675 $::form->{"${_}_${idx}"} = $payment->{$_} for @fields;
680 $main::lxdebug->enter_sub();
684 my $form = $main::form;
685 my %myconfig = %main::myconfig;
686 my $locale = $main::locale;
688 $form->{invtotal} = $form->{invsubtotal};
690 # tax, total and subtotal calculations
691 my ($tax, $subtotal);
692 $form->{taxaccounts_array} = [ split(/ /, $form->{taxaccounts}) ];
694 if( $form->{customer_id} && !$form->{taxincluded_changed_by_user} ) {
695 my $customer = SL::DB::Customer->load_cached($form->{customer_id});
696 $form->{taxincluded} = defined($customer->taxincluded_checked) ? $customer->taxincluded_checked : $myconfig{taxincluded_checked};
699 foreach my $item (@{ $form->{taxaccounts_array} }) {
700 if ($form->{"${item}_base"}) {
701 if ($form->{taxincluded}) {
702 $form->{"${item}_total"} = $form->round_amount( ($form->{"${item}_base"} * $form->{"${item}_rate"}
703 / (1 + $form->{"${item}_rate"})), 2);
704 $form->{"${item}_netto"} = $form->round_amount( ($form->{"${item}_base"} - $form->{"${item}_total"}), 2);
706 $form->{"${item}_total"} = $form->round_amount( $form->{"${item}_base"} * $form->{"${item}_rate"}, 2);
707 $form->{invtotal} += $form->{"${item}_total"};
712 my $grossamount = $form->{invtotal};
713 $form->{invtotal} = $form->round_amount( $form->{invtotal}, 2, 1 );
714 $form->{rounding} = $form->round_amount(
715 $form->{invtotal} - $form->round_amount($grossamount, 2),
721 $form->{follow_ups} = FU->follow_ups('trans_id' => $form->{id}, 'not_done' => 1) || [];
722 $form->{follow_ups_unfinished} = ( sum map { $_->{due} * 1 } @{ $form->{follow_ups} } ) || 0;
729 $form->{paidaccounts}++ if ($form->{"paid_$form->{paidaccounts}"});
730 $form->{paid_indices} = [ 1 .. $form->{paidaccounts} ];
732 # Standard Konto für Umlaufvermögen
733 my $accno_arap = IS->get_standard_accno_current_assets(\%myconfig, \%$form);
735 for my $i (1 .. $form->{paidaccounts}) {
736 $form->{"changeable_$i"} = 1;
737 if (SL::DB::Default->get->payments_changeable == 0) {
739 $form->{"changeable_$i"} = ($form->{"acc_trans_id_$i"})? 0 : 1;
740 } elsif (SL::DB::Default->get->payments_changeable == 2) {
742 $form->{"changeable_$i"} = (($form->{"gldate_$i"} eq '') ||
743 ($form->current_date(\%myconfig) eq $form->{"gldate_$i"}));
746 #deaktivieren von gebuchten Zahlungen ausserhalb der Bücherkontrolle, vorher prüfen ob heute eingegeben
747 if ($form->date_closed($form->{"gldate_$i"})) {
748 $form->{"changeable_$i"} = 0;
751 $form->{"selectAR_paid_$i"} = $form->{selectAR_paid};
752 if (!$form->{"AR_paid_$i"}) {
753 $form->{"selectAR_paid_$i"} =~ s/option>$accno_arap--(.*?)</option selected>$accno_arap--$1</;
755 $form->{"selectAR_paid_$i"} =~ s/option>\Q$form->{"AR_paid_$i"}\E/option selected>$form->{"AR_paid_$i"}/;
758 $totalpaid += $form->{"paid_$i"};
761 $form->{oldinvtotal} = $form->{invtotal};
763 $form->{ALL_DELIVERY_TERMS} = SL::DB::Manager::DeliveryTerm->get_all_sorted();
765 my $shipto_cvars = SL::DB::Shipto->new->cvars_by_config;
766 foreach my $var (@{ $shipto_cvars }) {
767 my $name = "shiptocvar_" . $var->config->name;
768 $var->value($form->{$name}) if exists $form->{$name};
771 print $form->parse_html_template('is/form_footer', {
772 is_type_normal_invoice => ($form->{type} eq "invoice"),
773 is_type_credit_note => ($form->{type} eq "credit_note"),
774 totalpaid => $totalpaid,
775 paid_missing => $form->{invtotal} - $totalpaid,
776 print_options => setup_sales_purchase_print_options(),
777 show_storno => $form->{id} && !$form->{storno} && !IS->has_storno(\%myconfig, $form, "ar") && !$totalpaid,
778 show_delete => ($::instance_conf->get_is_changeable == 2)
779 ? ($form->current_date(\%myconfig) eq $form->{gldate})
780 : ($::instance_conf->get_is_changeable == 1),
781 today => DateTime->today,
782 vc_obj => $form->{customer_id} ? SL::DB::Customer->load_cached($form->{customer_id}) : undef,
783 shipto_cvars => $shipto_cvars,
785 ##print $form->parse_html_template('is/_payments'); # parser
786 ##print $form->parse_html_template('webdav/_list'); # parser
788 $main::lxdebug->leave_sub();
792 $::auth->assert('invoice_edit');
794 SL::DB::Invoice->new(id => $::form->{id})->load->mark_as_paid;
796 $::form->redirect($::locale->text("Marked as paid"));
800 # unless no lazy implementation of save draft without invdate
801 # set the current date like in version <= 3.4.1
802 $::form->{invdate} = DateTime->today->to_lxoffice;
807 $main::lxdebug->enter_sub();
811 my $form = $main::form;
812 my %myconfig = %main::myconfig;
814 my ($recursive_call) = @_;
816 $form->{print_and_post} = 0 if $form->{second_run};
817 my $taxincluded = $form->{taxincluded} ? "checked" : '';
820 if (($form->{previous_customer_id} || $form->{customer_id}) != $form->{customer_id}) {
821 $::form->{salesman_id} = SL::DB::Manager::Employee->current->id if exists $::form->{salesman_id};
823 IS->get_customer(\%myconfig, $form);
824 $::form->{billing_address_id} = $::form->{default_billing_address_id};
827 $form->{taxincluded} ||= $taxincluded;
829 if (!$form->{forex}) { # read exchangerate from input field (not hidden)
830 $form->{exchangerate} = $form->parse_amount(\%myconfig, $form->{exchangerate}) unless $recursive_call;
832 $form->{forex} = $form->check_exchangerate(\%myconfig, $form->{currency}, $form->{invdate}, 'buy');
833 $form->{exchangerate} = $form->{forex} if $form->{forex};
835 for my $i (1 .. $form->{paidaccounts}) {
836 next unless $form->{"paid_$i"};
837 map { $form->{"${_}_$i"} = $form->parse_amount(\%myconfig, $form->{"${_}_$i"}) } qw(paid exchangerate);
838 $form->{"forex_$i"} = $form->check_exchangerate(\%myconfig, $form->{currency}, $form->{"datepaid_$i"}, 'buy');
839 $form->{"exchangerate_$i"} = $form->{"forex_$i"} if $form->{"forex_$i"};
842 my $i = $form->{rowcount};
843 my $exchangerate = $form->{exchangerate} || 1;
845 # if last row empty, check the form otherwise retrieve new item
846 if ( ($form->{"partnumber_$i"} eq "")
847 && ($form->{"description_$i"} eq "")
848 && ($form->{"partsgroup_$i"} eq "")) {
850 $form->{creditremaining} += ($form->{oldinvtotal} - $form->{oldtotalpaid});
855 IS->retrieve_item(\%myconfig, \%$form);
857 my $rows = scalar @{ $form->{item_list} };
859 $form->{"discount_$i"} = $form->parse_amount(\%myconfig, $form->{"discount_$i"}) / 100.0;
860 $form->{"discount_$i"} ||= $form->{customer_discount};
863 $form->{"qty_$i"} = $form->parse_amount(\%myconfig, $form->{"qty_$i"});
864 if( !$form->{"qty_$i"} ) {
865 $form->{"qty_$i"} = 1;
870 select_item(mode => 'IS', pre_entered_qty => $form->{"qty_$i"});
871 $::dispatcher->end_request;
875 my $sellprice = $form->parse_amount(\%myconfig, $form->{"sellprice_$i"});
877 map { $form->{item_list}[$i]{$_} =~ s/\"/"/g } qw(partnumber description unit);
878 map { $form->{"${_}_$i"} = $form->{item_list}[0]{$_} } keys %{ $form->{item_list}[0] };
880 $form->{payment_id} = $form->{"part_payment_id_$i"} if $form->{"part_payment_id_$i"} ne "";
881 $form->{"discount_$i"} = 0 if $form->{"not_discountable_$i"};
883 $form->{"marge_price_factor_$i"} = $form->{item_list}->[0]->{price_factor};
885 ($sellprice || $form->{"sellprice_$i"}) =~ /\.(\d+)/;
886 my $decimalplaces = max 2, length $1;
889 $form->{"sellprice_$i"} = $sellprice;
891 my $record = _make_record();
892 my $price_source = SL::PriceSource->new(record_item => $record->items->[$i-1], record => $record);
893 my $best_price = $price_source->best_price;
894 my $best_discount = $price_source->best_discount;
897 $::form->{"sellprice_$i"} = $best_price->price;
898 $::form->{"active_price_source_$i"} = $best_price->source;
900 if ($best_discount) {
901 $::form->{"discount_$i"} = $best_discount->discount;
902 $::form->{"active_discount_source_$i"} = $best_discount->source;
905 # if there is an exchange rate adjust sellprice
906 $form->{"sellprice_$i"} /= $exchangerate;
909 $form->{"listprice_$i"} /= $exchangerate;
911 my $amount = $form->{"sellprice_$i"} * $form->{"qty_$i"} * (1 - $form->{"discount_$i"});
912 map { $form->{"${_}_base"} = 0 } split / /, $form->{taxaccounts};
913 map { $form->{"${_}_base"} += $amount } split / /, $form->{"taxaccounts_$i"};
914 map { $amount += ($form->{"${_}_base"} * $form->{"${_}_rate"}) } split / /, $form->{"taxaccounts_$i"} if !$form->{taxincluded};
916 $form->{creditremaining} -= $amount;
918 map { $form->{"${_}_$i"} = $form->format_amount(\%myconfig, $form->{"${_}_$i"}, $decimalplaces) } qw(sellprice lastcost);
920 $form->{"qty_$i"} = $form->format_amount(\%myconfig, $form->{"qty_$i"});
921 $form->{"discount_$i"} = $form->format_amount(\%myconfig, $form->{"discount_$i"} * 100.0);
928 # ok, so this is a new part
929 # ask if it is a part or service item
931 if ( $form->{"partsgroup_$i"}
932 && ($form->{"partnumber_$i" } eq "")
933 && ($form->{"description_$i"} eq "")) {
935 $form->{"discount_$i"} = "";
939 $form->{"id_$i"} = 0;
944 $main::lxdebug->leave_sub();
948 $main::lxdebug->enter_sub();
950 my $form = $main::form;
951 my %myconfig = %main::myconfig;
952 my $locale = $main::locale;
954 $main::auth->assert('invoice_edit');
956 $form->mtime_ischanged('ar') ;
957 my $invdate = $form->datetonum($form->{invdate}, \%myconfig);
959 $form->{defaultcurrency} = $form->get_default_currency(\%myconfig);
960 for my $i (1 .. $form->{paidaccounts}) {
961 if ($form->{"paid_$i"}) {
962 my $datepaid = $form->datetonum($form->{"datepaid_$i"}, \%myconfig);
964 $form->isblank("datepaid_$i", $locale->text('Payment date missing!'));
967 if ($form->{currency} ne $form->{defaultcurrency}) {
968 $form->{"exchangerate_$i"} = $form->{exchangerate}
969 if ($invdate == $datepaid);
970 $form->isblank("exchangerate_$i",
971 $locale->text('Exchangerate for payment missing!'));
973 $form->error($locale->text('Cannot post transaction above the maximum future booking date!'))
974 if ($form->date_max_future($form->{"datepaid_$i"}, \%myconfig));
976 #Zusätzlich noch das Buchungsdatum in die Bücherkontrolle einbeziehen
977 # (Dient zur Prüfung ob ZE oder ZA geprüft werden soll)
978 $form->error($locale->text('Cannot post payment for a closed period!'))
979 if ($form->date_closed($form->{"datepaid_$i"}) && !$form->date_closed($form->{"gldate_$i"}, \%myconfig));
983 ($form->{AR}) = split /--/, $form->{AR};
984 ($form->{AR_paid}) = split /--/, $form->{AR_paid};
986 if ( IS->post_payment(\%myconfig, \%$form) ) {
987 $form->{snumbers} = qq|invnumber_| . $form->{invnumber};
988 $form->{what_done} = 'invoice';
989 $form->{addition} = "PAYMENT POSTED";
991 $form->redirect($locale->text('Payment posted!'))
993 $form->error($locale->text('Cannot post payment!'));
996 $main::lxdebug->leave_sub();
1000 $main::lxdebug->enter_sub();
1002 my $form = $main::form;
1003 my %myconfig = %main::myconfig;
1004 my $locale = $main::locale;
1006 $main::auth->assert('invoice_edit');
1007 $form->mtime_ischanged('ar');
1009 $form->{defaultcurrency} = $form->get_default_currency(\%myconfig);
1010 $form->isblank("invdate", $locale->text('Invoice Date missing!'));
1011 $form->isblank("customer_id", $locale->text('Customer missing!'));
1012 $form->error($locale->text('Cannot post invoice for a closed period!'))
1013 if ($form->date_closed($form->{"invdate"}, \%myconfig));
1015 $form->{invnumber} =~ s/^\s*//g;
1016 $form->{invnumber} =~ s/\s*$//g;
1018 # if oldcustomer ne customer redo form
1019 if (($form->{previous_customer_id} || $form->{customer_id}) != $form->{customer_id}) {
1021 $::dispatcher->end_request;
1024 if ($myconfig{mandatory_departments} && !$form->{department_id}) {
1025 $form->{saved_message} = $::locale->text('You have to specify a department.');
1030 if ($form->{second_run}) {
1031 $form->{print_and_post} = 0;
1034 remove_emptied_rows();
1037 my $closedto = $form->datetonum($form->{closedto}, \%myconfig);
1038 my $invdate = $form->datetonum($form->{invdate}, \%myconfig);
1040 $form->error($locale->text('Cannot post transaction above the maximum future booking date!'))
1041 if ($form->date_max_future($invdate, \%myconfig));
1042 $form->error($locale->text('Cannot post invoice for a closed period!'))
1043 if ($invdate <= $closedto);
1045 $form->isblank("exchangerate", $locale->text('Exchangerate missing!'))
1046 if ($form->{currency} ne $form->{defaultcurrency});
1047 # advance payment allows only one tax
1048 if ($form->{type} eq 'invoice_for_advance_payment') {
1049 my @current_taxaccounts = (split(/ /, $form->{taxaccounts}));
1050 $form->error($locale->text('Cannot post invoice for advance payment with more than one tax'))
1051 if (scalar @current_taxaccounts > 1);
1052 $form->error($locale->text('Cannot post invoice for advance payment with taxincluded'))
1053 if ($form->{taxincluded});
1056 for my $i (1 .. $form->{paidaccounts}) {
1057 if ($form->parse_amount(\%myconfig, $form->{"paid_$i"})) {
1058 my $datepaid = $form->datetonum($form->{"datepaid_$i"}, \%myconfig);
1060 $form->isblank("datepaid_$i", $locale->text('Payment date missing!'));
1062 $form->error($locale->text('Cannot post transaction above the maximum future booking date!'))
1063 if ($form->date_max_future($form->{"datepaid_$i"}, \%myconfig));
1065 #Zusätzlich noch das Buchungsdatum in die Bücherkontrolle einbeziehen
1066 # (Dient zur Prüfung ob ZE oder ZA geprüft werden soll)
1067 $form->error($locale->text('Cannot post payment for a closed period!'))
1068 if ($form->date_closed($form->{"datepaid_$i"}) && !$form->date_closed($form->{"gldate_$i"}, \%myconfig));
1070 if ($form->{currency} ne $form->{defaultcurrency}) {
1071 $form->{"exchangerate_$i"} = $form->{exchangerate}
1072 if ($invdate == $datepaid);
1073 $form->isblank("exchangerate_$i",
1074 $locale->text('Exchangerate for payment missing!'));
1079 ($form->{AR}) = split /--/, $form->{AR};
1080 ($form->{AR_paid}) = split /--/, $form->{AR_paid};
1081 $form->{storno} ||= 0;
1083 $form->{label} = $form->{type} eq 'credit_note' ? $locale->text('Credit Note') : $locale->text('Invoice');
1085 $form->{id} = 0 if $form->{postasnew};
1087 # get new invnumber in sequence if no invnumber is given or if posasnew was requested
1088 if ($form->{postasnew}) {
1089 if ($form->{type} eq "credit_note") {
1090 undef($form->{cnnumber});
1092 undef($form->{invnumber});
1098 my $terms = get_payment_terms_for_invoice();
1099 $form->{duedate} = $terms->calc_date(reference_date => $form->{invdate}, due_date => $form->{duedate})->to_kivitendo if $terms;
1101 # If transfer_out is requested, get rose db handle and do post and
1102 # transfer out in one transaction. Otherwise just post the invoice.
1103 if ($::instance_conf->get_is_transfer_out && $form->{type} ne 'credit_note' && !$form->{storno}) {
1104 require SL::DB::Inventory;
1105 my $rose_db = SL::DB::Inventory->new->db;
1108 if (!$rose_db->with_transaction(sub {
1110 if (!IS->post_invoice(\%myconfig, \%$form, $rose_db->dbh)) {
1111 push @errors, $locale->text('Cannot post invoice!');
1112 die 'posting error';
1114 my $err = IS->transfer_out(\%$form, $rose_db->dbh);
1116 push @errors, @{ $err };
1117 die 'transfer error';
1122 push @errors, $EVAL_ERROR;
1123 $form->error($locale->text('Cannot post invoice and/or transfer out! Error message:') . "\n" . join("\n", @errors));
1128 push @errors, $rose_db->error;
1129 $form->error($locale->text('Cannot post invoice and/or transfer out! Error message:') . "\n" . join("\n", @errors));
1132 if (!IS->post_invoice(\%myconfig, \%$form)) {
1133 $form->error($locale->text('Cannot post invoice!'));
1137 if(!exists $form->{addition}) {
1138 $form->{snumbers} = 'invnumber' .'_'. $form->{invnumber}; # ($form->{type} eq 'credit_note' ? 'cnnumber' : 'invnumber') .'_'. $form->{invnumber};
1139 $form->{what_done} = 'invoice';
1140 $form->{addition} = $form->{print_and_post} ? "PRINTED AND POSTED" :
1141 $form->{storno} ? "STORNO" :
1143 $form->save_history;
1146 if (!$form->{no_redirect_after_post}) {
1147 $form->{action} = 'edit';
1148 $form->{script} = 'is.pl';
1149 $form->{callback} = build_std_url(qw(action edit id callback saved_message));
1150 $form->redirect($form->{label} . " $form->{invnumber} " . $locale->text('posted!'));
1153 $main::lxdebug->leave_sub();
1156 sub print_and_post {
1157 $main::lxdebug->enter_sub();
1159 my $form = $main::form;
1161 $main::auth->assert('invoice_edit');
1163 my $old_form = Form->new;
1164 $form->{no_redirect_after_post} = 1;
1165 $form->{print_and_post} = 1;
1169 $main::lxdebug->leave_sub();
1174 $main::lxdebug->enter_sub();
1176 my $form = $main::form;
1177 my %myconfig = %main::myconfig;
1179 $main::auth->assert('invoice_edit');
1181 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)};
1182 $form->{rowcount}--;
1183 $form->{paidaccounts} = 1;
1184 $form->{invdate} = $form->current_date(\%myconfig);
1185 my $terms = get_payment_terms_for_invoice();
1186 $form->{duedate} = $terms ? $terms->calc_date(reference_date => $form->{invdate})->to_kivitendo : $form->{invdate};
1187 $form->{employee_id} = SL::DB::Manager::Employee->current->id;
1188 $form->{forex} = $form->check_exchangerate(\%myconfig, $form->{currency}, $form->{invdate}, 'buy');
1189 $form->{exchangerate} = $form->{forex} if $form->{forex};
1191 $form->{"converted_from_invoice_id_$_"} = delete $form->{"invoice_id_$_"} for 1 .. $form->{"rowcount"};
1193 $form->{useasnew} = 1;
1196 $main::lxdebug->leave_sub();
1199 sub further_invoice_for_advance_payment {
1200 my $form = $main::form;
1201 my %myconfig = %main::myconfig;
1203 $main::auth->assert('invoice_edit');
1205 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)};
1206 $form->{convert_from_ar_ids} = $form->{id};
1208 $form->{rowcount}--;
1209 $form->{paidaccounts} = 1;
1210 $form->{invdate} = $form->current_date(\%myconfig);
1211 my $terms = get_payment_terms_for_invoice();
1212 $form->{duedate} = $terms ? $terms->calc_date(reference_date => $form->{invdate})->to_kivitendo : $form->{invdate};
1213 $form->{employee_id} = SL::DB::Manager::Employee->current->id;
1214 $form->{forex} = $form->check_exchangerate(\%myconfig, $form->{currency}, $form->{invdate}, 'buy');
1215 $form->{exchangerate} = $form->{forex} if $form->{forex};
1217 $form->{"converted_from_invoice_id_$_"} = delete $form->{"invoice_id_$_"} for 1 .. $form->{"rowcount"};
1223 my $form = $main::form;
1224 my %myconfig = %main::myconfig;
1226 $main::auth->assert('invoice_edit');
1228 my $related_invoices = IS->_get_invoices_for_advance_payment($form->{id});
1230 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)};
1232 $form->{convert_from_ar_ids} = $form->{id};
1234 $form->{type} = 'final_invoice';
1235 $form->{title} = t8('Edit Final Invoice');
1236 $form->{paidaccounts} = 1;
1237 $form->{invdate} = $form->current_date(\%myconfig);
1238 my $terms = get_payment_terms_for_invoice();
1239 $form->{duedate} = $terms ? $terms->calc_date(reference_date => $form->{invdate})->to_kivitendo : $form->{invdate};
1240 $form->{employee_id} = SL::DB::Manager::Employee->current->id;
1241 $form->{forex} = $form->check_exchangerate(\%myconfig, $form->{currency}, $form->{invdate}, 'buy');
1242 $form->{exchangerate} = $form->{forex} if $form->{forex};
1244 foreach my $i (1 .. $form->{"rowcount"}) {
1245 delete $form->{"id_$i"};
1246 delete $form->{"invoice_id_$i"};
1247 delete $form->{"parts_id_$i"};
1248 delete $form->{"partnumber_$i"};
1249 delete $form->{"description_$i"};
1252 remove_emptied_rows(1);
1255 foreach my $ri (@$related_invoices) {
1256 foreach my $item (@{$ri->items_sorted}) {
1258 $form->{"id_$i"} = $item->parts_id;
1259 $form->{"partnumber_$i"} = $item->part->partnumber;
1260 $form->{"discount_$i"} = $item->discount*100.0;
1261 $form->{"sellprice_$i"} = $item->fxsellprice;
1262 $form->{$_ . "_" . $i} = $item->$_ for qw(description longdescription qty price_factor_id unit active_price_source active_discount_source);
1264 $form->{$_ . "_" . $i} = $form->format_amount(\%myconfig, $form->{$_ . "_" . $i}) for qw(qty sellprice discount);
1267 $form->{rowcount} = $i;
1270 $::dispatcher->end_request;
1274 $main::lxdebug->enter_sub();
1276 my $form = $main::form;
1277 my %myconfig = %main::myconfig;
1278 my $locale = $main::locale;
1280 $main::auth->assert('invoice_edit');
1282 if ($form->{storno}) {
1283 $form->error($locale->text('Cannot storno storno invoice!'));
1286 if (IS->has_storno(\%myconfig, $form, "ar")) {
1287 $form->error($locale->text("Invoice has already been storno'd!"));
1289 if ($form->datetonum($form->{invdate}, \%myconfig) <= $form->datetonum($form->{closedto}, \%myconfig)) {
1290 $form->error($locale->text('Cannot storno invoice for a closed period!'));
1293 # save the history of invoice being stornoed
1294 $form->{snumbers} = qq|invnumber_| . $form->{invnumber};
1295 $form->{what_done} = 'invoice';
1296 $form->{addition} = "STORNO";
1297 $form->save_history;
1299 map({ my $key = $_; delete($form->{$key}) unless (grep({ $key eq $_ } qw(id login password type))); } keys(%{ $form }));
1305 # Payments must not be recorded for the new storno invoice.
1306 $form->{paidaccounts} = 0;
1307 map { my $key = $_; delete $form->{$key} if grep { $key =~ /^$_/ } qw(datepaid_ gldate_ acc_trans_id_ source_ memo_ paid_ exchangerate_ AR_paid_) } keys %{ $form };
1309 # record link invoice to storno
1310 $form->{convert_from_ar_ids} = $form->{id};
1311 $form->{storno_id} = $form->{id};
1312 $form->{storno} = 1;
1314 $form->{invnumber} = "Storno zu " . $form->{invnumber};
1315 $form->{invdate} = DateTime->today->to_lxoffice;
1316 $form->{rowcount}++;
1317 # set new ids for storno invoice
1318 # set new persistent ids for storno invoice items
1319 $form->{"converted_from_invoice_id_$_"} = delete $form->{"invoice_id_$_"} for 1 .. $form->{"rowcount"};
1322 $main::lxdebug->leave_sub();
1326 $main::lxdebug->enter_sub();
1328 my $form = $main::form;
1330 $main::auth->assert('invoice_edit');
1332 $form->{preview} = 1;
1333 my $old_form = Form->new;
1334 for (keys %$form) { $old_form->{$_} = $form->{$_} }
1336 &print_form($old_form);
1337 $main::lxdebug->leave_sub();
1342 $main::lxdebug->enter_sub();
1344 my $form = $main::form;
1345 my %myconfig = %main::myconfig;
1346 my $locale = $main::locale;
1348 $main::auth->assert('invoice_edit');
1350 $form->{transdate} = $form->{invdate} = $form->current_date(\%myconfig);
1352 $form->current_date(\%myconfig, $form->{invdate}, $form->{terms} * 1);
1354 $form->{convert_from_ar_ids} = $form->{id};
1356 $form->{rowcount}--;
1359 $form->{title} = $locale->text('Add Credit Note');
1360 $form->{script} = 'is.pl';
1362 # Bei Gutschriften bezug zur Rechnungsnummer
1363 $form->{invnumber_for_credit_note} = $form->{invnumber};
1364 # bo creates the id, reset it
1365 map { delete $form->{$_} }
1366 qw(id invnumber subject message cc bcc printed emailed queued);
1367 $form->{ $form->{vc} } =~ s/--.*//g;
1368 $form->{type} = "credit_note";
1371 map { $form->{"select$_"} = "" } ($form->{vc}, 'currency');
1373 # map { $form->{$_} = $form->parse_amount(\%myconfig, $form->{$_}) }
1374 # qw(creditlimit creditremaining);
1376 # set new persistent ids for credit note and link previous invoice id
1377 $form->{"converted_from_invoice_id_$_"} = delete $form->{"invoice_id_$_"} for 1 .. $form->{"rowcount"};
1379 my $currency = $form->{currency};
1382 $form->{currency} = $currency;
1383 $form->{forex} = $form->check_exchangerate( \%myconfig, $form->{currency}, $form->{invdate}, 'buy');
1384 $form->{exchangerate} = $form->{forex} || '';
1386 $form->{creditremaining} -= ($form->{oldinvtotal} - $form->{ordtotal});
1388 # bei Gutschriften werden Zahlungseingänge aus Rechnung nicht übernommen
1389 for my $i (1 .. $form->{paidaccounts}) {
1390 delete $form->{"paid_$i"};
1391 delete $form->{"source_$i"};
1392 delete $form->{"memo_$i"};
1393 delete $form->{"datepaid_$i"};
1394 delete $form->{"gldate_$i"};
1395 delete $form->{"acc_trans_id_$i"};
1396 delete $form->{"AR_paid_$i"};
1398 $form->{paidaccounts} = 1;
1404 $main::lxdebug->leave_sub();
1408 $::lxdebug->enter_sub;
1414 my $new_rowcount = $::form->{"rowcount"} * 1 + 1;
1415 $::form->{"project_id_${new_rowcount}"} = $::form->{"globalproject_id"};
1417 $::form->language_payment(\%::myconfig);
1419 Common::webdav_folder($::form);
1422 display_row(++$::form->{rowcount});
1425 $::lxdebug->leave_sub;
1429 $::auth->assert('invoice_edit');
1431 if (IS->delete_invoice(\%::myconfig, $::form)) {
1432 # saving the history
1433 if(!exists $::form->{addition}) {
1434 $::form->{snumbers} = 'invnumber' .'_'. $::form->{invnumber};
1435 $::form->{what_done} = 'invoice';
1436 $::form->{addition} = "DELETED";
1437 $::form->save_history;
1439 # /saving the history
1440 $::form->redirect($::locale->text('Invoice deleted!'));
1442 $::form->error($::locale->text('Cannot delete invoice!'));
1447 print update ship_to storno post_payment use_as_new credit_note
1448 delete post order preview post_and_e_mail print_and_post
1451 if ($::form->{"action_$action"}) {
1457 $::form->error($::locale->text('No action defined.'));