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);
41 use List::MoreUtils qw(uniq);
42 use List::Util qw(max sum);
43 use List::UtilsBy qw(sort_by);
44 use English qw(-no_match_vars);
46 use SL::DB::BankTransactionAccTrans;
49 use SL::DB::Department;
51 use SL::DB::PaymentTerm;
53 require "bin/mozilla/common.pl";
54 require "bin/mozilla/io.pl";
62 sub _may_view_or_edit_this_invoice {
63 return 1 if $::auth->assert('invoice_edit', 1); # may edit all invoices
64 return 0 if !$::form->{id}; # creating new invoices isn't allowed without invoice_edit
65 return 0 if !$::form->{globalproject_id}; # existing records without a project ID are not allowed
66 return SL::DB::Project->new(id => $::form->{globalproject_id})->load->may_employee_view_project_invoices(SL::DB::Manager::Employee->current);
70 my $cache = $::request->cache('is.pl::_assert_access');
72 $cache->{_may_view_or_edit_this_invoice} = _may_view_or_edit_this_invoice() if !exists $cache->{_may_view_or_edit_this_invoice};
73 $::form->show_generic_error($::locale->text("You do not have the permissions to access this function.")) if ! $cache->{_may_view_or_edit_this_invoice};
77 $main::lxdebug->enter_sub();
79 my $form = $main::form;
80 my $locale = $main::locale;
82 $main::auth->assert('invoice_edit');
84 $form->{show_details} = $::myconfig{show_form_details};
86 if ($form->{type} eq "credit_note") {
87 $form->{title} = $locale->text('Add Credit Note');
89 if ($form->{storno}) {
90 $form->{title} = $locale->text('Add Storno Credit Note');
93 $form->{title} = $locale->text('Add Sales Invoice');
98 $form->{callback} = "$form->{script}?action=add&type=$form->{type}" unless $form->{callback};
104 $main::lxdebug->leave_sub();
108 $main::lxdebug->enter_sub();
110 # Delay access check to after the invoice's been loaded in
111 # "invoice_links" so that project-specific invoice rights can be
114 my $form = $main::form;
115 my $locale = $main::locale;
117 $form->{show_details} = $::myconfig{show_form_details};
118 $form->{taxincluded_changed_by_user} = 1;
120 # show history button
121 $form->{javascript} = qq|<script type="text/javascript" src="js/show_history.js"></script>|;
123 my ($language_id, $printer_id);
124 if ($form->{print_and_post}) {
125 $form->{action} = "print";
126 $form->{resubmit} = 1;
127 $language_id = $form->{language_id};
128 $printer_id = $form->{printer_id};
132 if ($form->{type} eq "credit_note") {
133 $form->{title} = $locale->text('Edit Credit Note');
134 $form->{title} = $locale->text('Edit Storno Credit Note') if $form->{storno};
136 $form->{title} = $locale->text('Edit Sales Invoice');
137 $form->{title} = $locale->text('Edit Storno Invoice') if $form->{storno};
141 if ($form->{print_and_post}) {
142 $form->{language_id} = $language_id;
143 $form->{printer_id} = $printer_id;
148 $main::lxdebug->leave_sub();
152 $main::lxdebug->enter_sub();
154 # Delay access check to after the invoice's been loaded so that
155 # project-specific invoice rights can be evaluated.
157 my $form = $main::form;
158 my %myconfig = %main::myconfig;
160 $form->{vc} = 'customer';
163 $form->create_links("AR", \%myconfig, "customer");
167 my $editing = $form->{id};
169 $form->backup_vars(qw(payment_id language_id taxzone_id salesman_id
170 taxincluded currency cp_id intnotes id shipto_id
173 IS->get_customer(\%myconfig, \%$form);
175 $form->restore_vars(qw(id));
177 IS->retrieve_invoice(\%myconfig, \%$form);
178 $form->restore_vars(qw(payment_id language_id taxzone_id currency intnotes
179 cp_id shipto_id delivery_term_id));
180 $form->restore_vars(qw(taxincluded)) if $form->{id};
181 $form->restore_vars(qw(salesman_id)) if $editing;
183 $form->{employee} = "$form->{employee}--$form->{employee_id}";
186 $form->{forex} = $form->{exchangerate};
187 my $exchangerate = ($form->{exchangerate}) ? $form->{exchangerate} : 1;
189 foreach my $key (keys %{ $form->{AR_links} }) {
190 foreach my $ref (@{ $form->{AR_links}{$key} }) {
191 $form->{"select$key"} .= "<option>$ref->{accno}--$ref->{description}</option>\n";
194 if ($key eq "AR_paid") {
195 next unless $form->{acc_trans}{$key};
196 for my $i (1 .. scalar @{ $form->{acc_trans}{$key} }) {
197 $form->{"AR_paid_$i"} = "$form->{acc_trans}{$key}->[$i-1]->{accno}--$form->{acc_trans}{$key}->[$i-1]->{description}";
199 $form->{"acc_trans_id_$i"} = $form->{acc_trans}{$key}->[$i - 1]->{acc_trans_id};
201 $form->{"paid_$i"} = $form->{acc_trans}{$key}->[$i - 1]->{amount} * -1;
202 $form->{"datepaid_$i"} = $form->{acc_trans}{$key}->[$i - 1]->{transdate};
203 $form->{"gldate_$i"} = $form->{acc_trans}{$key}->[$i - 1]->{gldate};
204 $form->{"exchangerate_$i"} = $form->{acc_trans}{$key}->[$i - 1]->{exchangerate};
205 $form->{"forex_$i"} = $form->{"exchangerate_$i"};
206 $form->{"source_$i"} = $form->{acc_trans}{$key}->[$i - 1]->{source};
207 $form->{"memo_$i"} = $form->{acc_trans}{$key}->[$i - 1]->{memo};
209 $form->{paidaccounts} = $i;
212 $form->{$key} = "$form->{acc_trans}{$key}->[0]->{accno}--$form->{acc_trans}{$key}->[0]->{description}";
216 $form->{paidaccounts} = 1 unless (exists $form->{paidaccounts});
218 $form->{AR} = $form->{AR_1} unless $form->{id};
220 $form->{locked} = ($form->datetonum($form->{invdate}, \%myconfig)
221 <= $form->datetonum($form->{closedto}, \%myconfig));
223 $main::lxdebug->leave_sub();
226 sub prepare_invoice {
227 $main::lxdebug->enter_sub();
231 my $form = $main::form;
232 my %myconfig = %main::myconfig;
234 if ($form->{type} eq "credit_note") {
235 $form->{type} = "credit_note";
236 $form->{formname} = "credit_note";
237 } elsif ($form->{formname} eq "proforma" ) {
238 $form->{type} = "invoice";
240 $form->{type} = "invoice";
241 $form->{formname} = "invoice";
248 foreach my $ref (@{ $form->{invoice_details} }) {
251 map { $form->{"${_}_$i"} = $ref->{$_} } keys %{$ref};
253 $form->{"discount_$i"} = $form->format_amount(\%myconfig, $form->{"discount_$i"} * 100);
254 my ($dec) = ($form->{"sellprice_$i"} =~ /\.(\d+)/);
256 my $decimalplaces = ($dec > 2) ? $dec : 2;
258 $form->{"sellprice_$i"} = $form->format_amount(\%myconfig, $form->{"sellprice_$i"}, $decimalplaces);
259 (my $dec_qty) = ($form->{"qty_$i"} =~ /\.(\d+)/);
260 $dec_qty = length $dec_qty;
262 $form->{"lastcost_$i"} = $form->format_amount(\%myconfig, $form->{"lastcost_$i"}, $decimalplaces);
264 $form->{"qty_$i"} = $form->format_amount(\%myconfig, $form->{"qty_$i"}, $dec_qty);
266 $form->{"sellprice_pg_$i"} = join ('--', $form->{"sellprice_$i"}, $form->{"pricegroup_id_$i"});
268 $form->{rowcount} = $i;
272 $main::lxdebug->leave_sub();
275 sub setup_is_action_bar {
277 my $change_never = $::instance_conf->get_is_changeable == 0;
278 my $change_on_same_day_only = $::instance_conf->get_is_changeable == 2 && ($form->current_date(\%::myconfig) ne $form->{gldate});
279 my $payments_balanced = ($::form->{oldtotalpaid} == 0);
280 my $has_storno = ($::form->{storno} && !$::form->{storno_id});
281 my $may_edit_create = $::auth->assert('invoice_edit', 1);
282 my $is_linked_bank_transaction;
284 && SL::DB::Default->get->payments_changeable != 0
285 && SL::DB::Manager::BankTransactionAccTrans->find_by(ar_id => $::form->{id})) {
287 $is_linked_bank_transaction = 1;
290 for my $bar ($::request->layout->get('actionbar')) {
294 submit => [ '#form', { action => "update" } ],
295 disabled => !$may_edit_create ? t8('You must not change this invoice.')
296 : $form->{locked} ? t8('The billing period has already been locked.')
298 id => 'update_button',
299 accesskey => 'enter',
305 submit => [ '#form', { action => "post" } ],
306 checks => [ 'kivi.validate_form' ],
307 disabled => !$may_edit_create ? t8('You must not change this invoice.')
308 : $form->{locked} ? t8('The billing period has already been locked.')
309 : $form->{storno} ? t8('A canceled invoice cannot be posted.')
310 : ($form->{id} && $change_never) ? t8('Changing invoices has been disabled in the configuration.')
311 : ($form->{id} && $change_on_same_day_only) ? t8('Invoices can only be changed on the day they are posted.')
312 : $is_linked_bank_transaction ? t8('This transaction is linked with a bank transaction. Please undo and redo the bank transaction booking if needed.')
317 submit => [ '#form', { action => "post_payment" } ],
318 checks => [ 'kivi.validate_form' ],
319 disabled => !$may_edit_create ? t8('You must not change this invoice.')
320 : !$form->{id} ? t8('This invoice has not been posted yet.')
321 : $is_linked_bank_transaction ? t8('This transaction is linked with a bank transaction. Please undo and redo the bank transaction booking if needed.')
324 action => [ t8('Mark as paid'),
325 submit => [ '#form', { action => "mark_as_paid" } ],
326 confirm => t8('This will remove the invoice from showing as unpaid even if the unpaid amount does not match the amount. Proceed?'),
327 disabled => !$may_edit_create ? t8('You must not change this invoice.')
328 : !$form->{id} ? t8('This invoice has not been posted yet.')
330 only_if => $::instance_conf->get_is_show_mark_as_paid,
332 ], # end of combobox "Post"
335 action => [ t8('Storno'),
336 submit => [ '#form', { action => "storno" } ],
337 confirm => t8('Do you really want to cancel this invoice?'),
338 checks => [ 'kivi.validate_form' ],
339 disabled => !$may_edit_create ? t8('You must not change this invoice.')
340 : !$form->{id} ? t8('This invoice has not been posted yet.')
341 : !$payments_balanced ? t8('Cancelling is disallowed. Either undo or balance the current payments until the open amount matches the invoice amount')
344 action => [ t8('Delete'),
345 submit => [ '#form', { action => "delete" } ],
346 confirm => t8('Do you really want to delete this object?'),
347 checks => [ 'kivi.validate_form' ],
348 disabled => !$may_edit_create ? t8('You must not change this invoice.')
349 : !$form->{id} ? t8('This invoice has not been posted yet.')
350 : $form->{locked} ? t8('The billing period has already been locked.')
351 : $change_never ? t8('Changing invoices has been disabled in the configuration.')
352 : $change_on_same_day_only ? t8('Invoices can only be changed on the day they are posted.')
353 : $has_storno ? t8('Can only delete the "Storno zu" part of the cancellation pair.')
356 ], # end of combobox "Storno"
361 action => [ t8('Workflow') ],
364 submit => [ '#form', { action => "use_as_new" } ],
365 checks => [ 'kivi.validate_form' ],
366 disabled => !$may_edit_create ? t8('You must not change this invoice.')
367 : !$form->{id} ? t8('This invoice has not been posted yet.')
372 submit => [ '#form', { action => "credit_note" } ],
373 checks => [ 'kivi.validate_form' ],
374 disabled => !$may_edit_create ? t8('You must not change this invoice.')
375 : $form->{type} eq "credit_note" ? t8('Credit notes cannot be converted into other credit notes.')
376 : !$form->{id} ? t8('This invoice has not been posted yet.')
381 submit => [ '#form', { action => "order" } ],
382 checks => [ 'kivi.validate_form' ],
383 disabled => !$form->{id} ? t8('This invoice has not been posted yet.') : undef,
385 ], # end of combobox "Workflow"
388 action => [ t8('Export') ],
390 ($form->{id} ? t8('Print') : t8('Preview')),
391 call => [ 'kivi.SalesPurchase.show_print_dialog', $form->{id} ? 'print' : 'preview' ],
392 checks => [ 'kivi.validate_form' ],
393 disabled => !$may_edit_create ? t8('You must not print this invoice.')
394 : !$form->{id} && $form->{locked} ? t8('The billing period has already been locked.')
397 action => [ t8('Print and Post'),
398 call => [ 'kivi.SalesPurchase.show_print_dialog', $form->{id} ? 'print' : 'print_and_post' ],
399 checks => [ 'kivi.validate_form' ],
400 disabled => !$may_edit_create ? t8('You must not change this invoice.')
401 : $form->{locked} ? t8('The billing period has already been locked.')
402 : $form->{storno} ? t8('A canceled invoice cannot be posted.')
403 : ($form->{id} && $change_never) ? t8('Changing invoices has been disabled in the configuration.')
404 : ($form->{id} && $change_on_same_day_only) ? t8('Invoices can only be changed on the day they are posted.')
405 : $is_linked_bank_transaction ? t8('This transaction is linked with a bank transaction. Please undo and redo the bank transaction booking if needed.')
408 action => [ t8('E Mail'),
409 call => [ 'kivi.SalesPurchase.show_email_dialog' ],
410 checks => [ 'kivi.validate_form' ],
411 disabled => !$may_edit_create ? t8('You must not print this invoice.')
412 : !$form->{id} ? t8('This invoice has not been posted yet.')
415 ], # end of combobox "Export"
418 action => [ t8('more') ],
421 call => [ 'set_history_window', $form->{id} * 1, 'glid' ],
422 disabled => !$form->{id} ? t8('This invoice has not been posted yet.') : undef,
426 call => [ 'follow_up_window' ],
427 disabled => !$form->{id} ? t8('This invoice has not been posted yet.') : undef,
431 call => [ 'kivi.Draft.popup', 'is', 'invoice', $form->{draft_id}, $form->{draft_description} ],
432 disabled => !$may_edit_create ? t8('You must not change this invoice.')
433 : $form->{id} ? t8('This invoice has already been posted.')
434 : $form->{locked} ? t8('The billing period has already been locked.')
437 ], # end of combobox "more"
440 $::request->layout->add_javascripts('kivi.Validator.js');
444 $main::lxdebug->enter_sub();
448 my $form = $main::form;
449 my %myconfig = %main::myconfig;
450 my $locale = $main::locale;
451 my $cgi = $::request->{cgi};
456 $TMPL_VAR{customer_obj} = SL::DB::Customer->load_cached($form->{customer_id}) if $form->{customer_id};
457 $TMPL_VAR{invoice_obj} = SL::DB::Invoice->load_cached($form->{id}) if $form->{id};
459 my $current_employee = SL::DB::Manager::Employee->current;
460 $form->{employee_id} = $form->{old_employee_id} if $form->{old_employee_id};
461 $form->{salesman_id} = $form->{old_salesman_id} if $form->{old_salesman_id};
462 $form->{employee_id} ||= $current_employee->id;
463 $form->{salesman_id} ||= $current_employee->id;
465 $form->{defaultcurrency} = $form->get_default_currency(\%myconfig);
467 $form->get_lists("taxzones" => ($form->{id} ? "ALL_TAXZONES" : "ALL_ACTIVE_TAXZONES"),
468 "currencies" => "ALL_CURRENCIES",
469 "price_factors" => "ALL_PRICE_FACTORS");
471 $form->{ALL_DEPARTMENTS} = SL::DB::Manager::Department->get_all_sorted;
472 $form->{ALL_LANGUAGES} = SL::DB::Manager::Language->get_all_sorted;
475 my @old_project_ids = uniq grep { $_ } map { $_ * 1 } ($form->{"globalproject_id"}, map { $form->{"project_id_$_"} } 1..$form->{"rowcount"});
476 my @old_ids_cond = @old_project_ids ? (id => \@old_project_ids) : ();
478 if ($::instance_conf->get_customer_projects_only_in_sales) {
481 customer_id => $::form->{customer_id},
482 billable_customer_id => $::form->{customer_id},
487 and => [ active => 1, @customer_cond ],
491 $TMPL_VAR{ALL_PROJECTS} = SL::DB::Manager::Project->get_all_sorted(query => \@conditions);
492 $form->{ALL_PROJECTS} = $TMPL_VAR{ALL_PROJECTS}; # make projects available for second row drop-down in io.pl
493 $TMPL_VAR{ALL_EMPLOYEES} = SL::DB::Manager::Employee->get_all_sorted(query => [ or => [ id => $::form->{employee_id}, deleted => 0 ] ]);
494 $TMPL_VAR{ALL_SALESMEN} = SL::DB::Manager::Employee->get_all_sorted(query => [ or => [ id => $::form->{salesman_id}, deleted => 0 ] ]);
495 $TMPL_VAR{ALL_SHIPTO} = SL::DB::Manager::Shipto->get_all_sorted(query => [
496 or => [ trans_id => $::form->{"$::form->{vc}_id"} * 1, and => [ shipto_id => $::form->{shipto_id} * 1, trans_id => undef ] ]
498 $TMPL_VAR{ALL_CONTACTS} = SL::DB::Manager::Contact->get_all_sorted(query => [
500 cp_cv_id => $::form->{"$::form->{vc}_id"} * 1,
503 cp_id => $::form->{cp_id} * 1
508 # currencies and exchangerate
509 my @values = map { $_ } @{ $form->{ALL_CURRENCIES} };
510 my %labels = map { $_ => $_ } @{ $form->{ALL_CURRENCIES} };
511 $form->{currency} = $form->{defaultcurrency} unless $form->{currency};
512 $form->{show_exchangerate} = $form->{currency} ne $form->{defaultcurrency};
513 $TMPL_VAR{currencies} = NTI($::request->{cgi}->popup_menu('-name' => 'currency', '-default' => $form->{"currency"},
514 '-values' => \@values, '-labels' => \%labels,
515 '-onchange' => "document.getElementById('update_button').click();"
516 )) if scalar @values;
517 push @custom_hiddens, "forex";
518 push @custom_hiddens, "exchangerate" if $form->{forex};
520 $TMPL_VAR{creditwarning} = ($form->{creditlimit} != 0) && ($form->{creditremaining} < 0) && !$form->{update};
521 $TMPL_VAR{is_credit_remaining_negativ} = $form->{creditremaining} =~ /-/;
523 # set option selected
524 foreach my $item (qw(AR)) {
525 $form->{"select$item"} =~ s/ selected//;
526 $form->{"select$item"} =~ s/option>\Q$form->{$item}\E/option selected>$form->{$item}/;
529 $TMPL_VAR{is_type_credit_note} = $form->{type} eq "credit_note";
530 $TMPL_VAR{is_format_html} = $form->{format} eq 'html';
531 $TMPL_VAR{dateformat} = $myconfig{dateformat};
532 $TMPL_VAR{numberformat} = $myconfig{numberformat};
535 $TMPL_VAR{HIDDENS} = [qw(
536 id type queued printed emailed vc discount
537 title creditlimit creditremaining tradediscount business closedto locked shipped storno storno_id
538 max_dunning_level dunning_amount dunning_description
539 taxaccounts cursor_fokus
540 convert_from_do_ids convert_from_oe_ids convert_from_ar_ids useasnew
544 map { $_.'_rate', $_.'_description', $_.'_taxnumber', $_.'_tax_id' } split / /, $form->{taxaccounts}];
546 $::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));
548 $TMPL_VAR{payment_terms_obj} = get_payment_terms_for_invoice();
549 $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};
551 setup_is_action_bar();
555 print $form->parse_html_template("is/form_header", \%TMPL_VAR);
557 $main::lxdebug->leave_sub();
561 my @fields = qw(acc_trans_id gldate datepaid source memo paid AR_paid);
563 grep { $_->{paid} != 0 }
566 +{ map { ($_ => delete($::form->{"${_}_${idx}"})) } @fields }
567 } (1..$::form->{paidaccounts});
569 @payments = sort_by { DateTime->from_kivitendo($_->{datepaid}) } @payments;
571 $::form->{paidaccounts} = max scalar(@payments), 1;
573 foreach my $idx (1 .. scalar(@payments)) {
574 my $payment = $payments[$idx - 1];
575 $::form->{"${_}_${idx}"} = $payment->{$_} for @fields;
580 $main::lxdebug->enter_sub();
584 my $form = $main::form;
585 my %myconfig = %main::myconfig;
586 my $locale = $main::locale;
588 $form->{invtotal} = $form->{invsubtotal};
590 # tax, total and subtotal calculations
591 my ($tax, $subtotal);
592 $form->{taxaccounts_array} = [ split(/ /, $form->{taxaccounts}) ];
594 if( $form->{customer_id} && !$form->{taxincluded_changed_by_user} ) {
595 my $customer = SL::DB::Customer->load_cached($form->{customer_id});
596 $form->{taxincluded} = defined($customer->taxincluded_checked) ? $customer->taxincluded_checked : $myconfig{taxincluded_checked};
599 foreach my $item (@{ $form->{taxaccounts_array} }) {
600 if ($form->{"${item}_base"}) {
601 if ($form->{taxincluded}) {
602 $form->{"${item}_total"} = $form->round_amount( ($form->{"${item}_base"} * $form->{"${item}_rate"}
603 / (1 + $form->{"${item}_rate"})), 2);
604 $form->{"${item}_netto"} = $form->round_amount( ($form->{"${item}_base"} - $form->{"${item}_total"}), 2);
606 $form->{"${item}_total"} = $form->round_amount( $form->{"${item}_base"} * $form->{"${item}_rate"}, 2);
607 $form->{invtotal} += $form->{"${item}_total"};
612 my $grossamount = $form->{invtotal};
613 $form->{invtotal} = $form->round_amount( $form->{invtotal}, 2, 1 );
614 $form->{rounding} = $form->round_amount(
615 $form->{invtotal} - $form->round_amount($grossamount, 2),
621 $form->{follow_ups} = FU->follow_ups('trans_id' => $form->{id}, 'not_done' => 1) || [];
622 $form->{follow_ups_unfinished} = ( sum map { $_->{due} * 1 } @{ $form->{follow_ups} } ) || 0;
629 $form->{paidaccounts}++ if ($form->{"paid_$form->{paidaccounts}"});
630 $form->{paid_indices} = [ 1 .. $form->{paidaccounts} ];
632 # Standard Konto für Umlaufvermögen
633 my $accno_arap = IS->get_standard_accno_current_assets(\%myconfig, \%$form);
635 for my $i (1 .. $form->{paidaccounts}) {
636 $form->{"changeable_$i"} = 1;
637 if (SL::DB::Default->get->payments_changeable == 0) {
639 $form->{"changeable_$i"} = ($form->{"acc_trans_id_$i"})? 0 : 1;
640 } elsif (SL::DB::Default->get->payments_changeable == 2) {
642 $form->{"changeable_$i"} = (($form->{"gldate_$i"} eq '') ||
643 ($form->current_date(\%myconfig) eq $form->{"gldate_$i"}));
646 #deaktivieren von gebuchten Zahlungen ausserhalb der Bücherkontrolle, vorher prüfen ob heute eingegeben
647 if ($form->date_closed($form->{"gldate_$i"})) {
648 $form->{"changeable_$i"} = 0;
651 $form->{"selectAR_paid_$i"} = $form->{selectAR_paid};
652 if (!$form->{"AR_paid_$i"}) {
653 $form->{"selectAR_paid_$i"} =~ s/option>$accno_arap--(.*?)</option selected>$accno_arap--$1</;
655 $form->{"selectAR_paid_$i"} =~ s/option>\Q$form->{"AR_paid_$i"}\E/option selected>$form->{"AR_paid_$i"}/;
658 $totalpaid += $form->{"paid_$i"};
661 $form->{oldinvtotal} = $form->{invtotal};
663 $form->{ALL_DELIVERY_TERMS} = SL::DB::Manager::DeliveryTerm->get_all_sorted();
665 my $shipto_cvars = SL::DB::Shipto->new->cvars_by_config;
666 foreach my $var (@{ $shipto_cvars }) {
667 my $name = "shiptocvar_" . $var->config->name;
668 $var->value($form->{$name}) if exists $form->{$name};
671 print $form->parse_html_template('is/form_footer', {
672 is_type_credit_note => ($form->{type} eq "credit_note"),
673 totalpaid => $totalpaid,
674 paid_missing => $form->{invtotal} - $totalpaid,
675 print_options => setup_sales_purchase_print_options(),
676 show_storno => $form->{id} && !$form->{storno} && !IS->has_storno(\%myconfig, $form, "ar") && !$totalpaid,
677 show_delete => ($::instance_conf->get_is_changeable == 2)
678 ? ($form->current_date(\%myconfig) eq $form->{gldate})
679 : ($::instance_conf->get_is_changeable == 1),
680 today => DateTime->today,
681 vc_obj => $form->{customer_id} ? SL::DB::Customer->load_cached($form->{customer_id}) : undef,
682 shipto_cvars => $shipto_cvars,
684 ##print $form->parse_html_template('is/_payments'); # parser
685 ##print $form->parse_html_template('webdav/_list'); # parser
687 $main::lxdebug->leave_sub();
691 $::auth->assert('invoice_edit');
693 SL::DB::Invoice->new(id => $::form->{id})->load->mark_as_paid;
695 $::form->redirect($::locale->text("Marked as paid"));
699 # unless no lazy implementation of save draft without invdate
700 # set the current date like in version <= 3.4.1
701 $::form->{invdate} = DateTime->today->to_lxoffice;
706 $main::lxdebug->enter_sub();
710 my $form = $main::form;
711 my %myconfig = %main::myconfig;
713 my ($recursive_call) = @_;
715 $form->{print_and_post} = 0 if $form->{second_run};
716 my $taxincluded = $form->{taxincluded} ? "checked" : '';
719 if (($form->{previous_customer_id} || $form->{customer_id}) != $form->{customer_id}) {
720 $::form->{salesman_id} = SL::DB::Manager::Employee->current->id if exists $::form->{salesman_id};
722 IS->get_customer(\%myconfig, $form);
725 $form->{taxincluded} ||= $taxincluded;
727 if (!$form->{forex}) { # read exchangerate from input field (not hidden)
728 $form->{exchangerate} = $form->parse_amount(\%myconfig, $form->{exchangerate}) unless $recursive_call;
730 $form->{forex} = $form->check_exchangerate(\%myconfig, $form->{currency}, $form->{invdate}, 'buy');
731 $form->{exchangerate} = $form->{forex} if $form->{forex};
733 for my $i (1 .. $form->{paidaccounts}) {
734 next unless $form->{"paid_$i"};
735 map { $form->{"${_}_$i"} = $form->parse_amount(\%myconfig, $form->{"${_}_$i"}) } qw(paid exchangerate);
736 $form->{"forex_$i"} = $form->check_exchangerate(\%myconfig, $form->{currency}, $form->{"datepaid_$i"}, 'buy');
737 $form->{"exchangerate_$i"} = $form->{"forex_$i"} if $form->{"forex_$i"};
740 my $i = $form->{rowcount};
741 my $exchangerate = $form->{exchangerate} || 1;
743 # if last row empty, check the form otherwise retrieve new item
744 if ( ($form->{"partnumber_$i"} eq "")
745 && ($form->{"description_$i"} eq "")
746 && ($form->{"partsgroup_$i"} eq "")) {
748 $form->{creditremaining} += ($form->{oldinvtotal} - $form->{oldtotalpaid});
753 IS->retrieve_item(\%myconfig, \%$form);
755 my $rows = scalar @{ $form->{item_list} };
757 $form->{"discount_$i"} = $form->parse_amount(\%myconfig, $form->{"discount_$i"}) / 100.0;
758 $form->{"discount_$i"} ||= $form->{customer_discount};
761 $form->{"qty_$i"} = $form->parse_amount(\%myconfig, $form->{"qty_$i"});
762 if( !$form->{"qty_$i"} ) {
763 $form->{"qty_$i"} = 1;
768 select_item(mode => 'IS', pre_entered_qty => $form->{"qty_$i"});
769 $::dispatcher->end_request;
773 my $sellprice = $form->parse_amount(\%myconfig, $form->{"sellprice_$i"});
775 map { $form->{item_list}[$i]{$_} =~ s/\"/"/g } qw(partnumber description unit);
776 map { $form->{"${_}_$i"} = $form->{item_list}[0]{$_} } keys %{ $form->{item_list}[0] };
778 $form->{payment_id} = $form->{"part_payment_id_$i"} if $form->{"part_payment_id_$i"} ne "";
779 $form->{"discount_$i"} = 0 if $form->{"not_discountable_$i"};
781 $form->{"marge_price_factor_$i"} = $form->{item_list}->[0]->{price_factor};
783 ($sellprice || $form->{"sellprice_$i"}) =~ /\.(\d+)/;
784 my $decimalplaces = max 2, length $1;
787 $form->{"sellprice_$i"} = $sellprice;
789 my $record = _make_record();
790 my $price_source = SL::PriceSource->new(record_item => $record->items->[$i-1], record => $record);
791 my $best_price = $price_source->best_price;
792 my $best_discount = $price_source->best_discount;
795 $::form->{"sellprice_$i"} = $best_price->price;
796 $::form->{"active_price_source_$i"} = $best_price->source;
798 if ($best_discount) {
799 $::form->{"discount_$i"} = $best_discount->discount;
800 $::form->{"active_discount_source_$i"} = $best_discount->source;
803 # if there is an exchange rate adjust sellprice
804 $form->{"sellprice_$i"} /= $exchangerate;
807 $form->{"listprice_$i"} /= $exchangerate;
809 my $amount = $form->{"sellprice_$i"} * $form->{"qty_$i"} * (1 - $form->{"discount_$i"});
810 map { $form->{"${_}_base"} = 0 } split / /, $form->{taxaccounts};
811 map { $form->{"${_}_base"} += $amount } split / /, $form->{"taxaccounts_$i"};
812 map { $amount += ($form->{"${_}_base"} * $form->{"${_}_rate"}) } split / /, $form->{"taxaccounts_$i"} if !$form->{taxincluded};
814 $form->{creditremaining} -= $amount;
816 map { $form->{"${_}_$i"} = $form->format_amount(\%myconfig, $form->{"${_}_$i"}, $decimalplaces) } qw(sellprice lastcost);
818 $form->{"qty_$i"} = $form->format_amount(\%myconfig, $form->{"qty_$i"});
819 $form->{"discount_$i"} = $form->format_amount(\%myconfig, $form->{"discount_$i"} * 100.0);
826 # ok, so this is a new part
827 # ask if it is a part or service item
829 if ( $form->{"partsgroup_$i"}
830 && ($form->{"partnumber_$i" } eq "")
831 && ($form->{"description_$i"} eq "")) {
833 $form->{"discount_$i"} = "";
837 $form->{"id_$i"} = 0;
842 $main::lxdebug->leave_sub();
846 $main::lxdebug->enter_sub();
848 my $form = $main::form;
849 my %myconfig = %main::myconfig;
850 my $locale = $main::locale;
852 $main::auth->assert('invoice_edit');
854 $form->mtime_ischanged('ar') ;
855 my $invdate = $form->datetonum($form->{invdate}, \%myconfig);
857 $form->{defaultcurrency} = $form->get_default_currency(\%myconfig);
858 for my $i (1 .. $form->{paidaccounts}) {
859 if ($form->{"paid_$i"}) {
860 my $datepaid = $form->datetonum($form->{"datepaid_$i"}, \%myconfig);
862 $form->isblank("datepaid_$i", $locale->text('Payment date missing!'));
865 if ($form->{currency} ne $form->{defaultcurrency}) {
866 $form->{"exchangerate_$i"} = $form->{exchangerate}
867 if ($invdate == $datepaid);
868 $form->isblank("exchangerate_$i",
869 $locale->text('Exchangerate for payment missing!'));
871 $form->error($locale->text('Cannot post transaction above the maximum future booking date!'))
872 if ($form->date_max_future($form->{"datepaid_$i"}, \%myconfig));
874 #Zusätzlich noch das Buchungsdatum in die Bücherkontrolle einbeziehen
875 # (Dient zur Prüfung ob ZE oder ZA geprüft werden soll)
876 $form->error($locale->text('Cannot post payment for a closed period!'))
877 if ($form->date_closed($form->{"datepaid_$i"}) && !$form->date_closed($form->{"gldate_$i"}, \%myconfig));
881 ($form->{AR}) = split /--/, $form->{AR};
882 ($form->{AR_paid}) = split /--/, $form->{AR_paid};
884 if ( IS->post_payment(\%myconfig, \%$form) ) {
885 $form->{snumbers} = qq|invnumber_| . $form->{invnumber};
886 $form->{what_done} = 'invoice';
887 $form->{addition} = "PAYMENT POSTED";
889 $form->redirect($locale->text('Payment posted!'))
891 $form->error($locale->text('Cannot post payment!'));
894 $main::lxdebug->leave_sub();
898 $main::lxdebug->enter_sub();
900 my $form = $main::form;
901 my %myconfig = %main::myconfig;
902 my $locale = $main::locale;
904 $main::auth->assert('invoice_edit');
905 $form->mtime_ischanged('ar');
907 $form->{defaultcurrency} = $form->get_default_currency(\%myconfig);
908 $form->isblank("invdate", $locale->text('Invoice Date missing!'));
909 $form->isblank("customer_id", $locale->text('Customer missing!'));
910 $form->error($locale->text('Cannot post invoice for a closed period!'))
911 if ($form->date_closed($form->{"invdate"}, \%myconfig));
913 $form->{invnumber} =~ s/^\s*//g;
914 $form->{invnumber} =~ s/\s*$//g;
916 # if oldcustomer ne customer redo form
917 if (($form->{previous_customer_id} || $form->{customer_id}) != $form->{customer_id}) {
919 $::dispatcher->end_request;
922 if ($myconfig{mandatory_departments} && !$form->{department_id}) {
923 $form->{saved_message} = $::locale->text('You have to specify a department.');
928 if ($form->{second_run}) {
929 $form->{print_and_post} = 0;
932 remove_emptied_rows();
935 my $closedto = $form->datetonum($form->{closedto}, \%myconfig);
936 my $invdate = $form->datetonum($form->{invdate}, \%myconfig);
938 $form->error($locale->text('Cannot post transaction above the maximum future booking date!'))
939 if ($form->date_max_future($invdate, \%myconfig));
940 $form->error($locale->text('Cannot post invoice for a closed period!'))
941 if ($invdate <= $closedto);
943 $form->isblank("exchangerate", $locale->text('Exchangerate missing!'))
944 if ($form->{currency} ne $form->{defaultcurrency});
946 for my $i (1 .. $form->{paidaccounts}) {
947 if ($form->parse_amount(\%myconfig, $form->{"paid_$i"})) {
948 my $datepaid = $form->datetonum($form->{"datepaid_$i"}, \%myconfig);
950 $form->isblank("datepaid_$i", $locale->text('Payment date missing!'));
952 $form->error($locale->text('Cannot post transaction above the maximum future booking date!'))
953 if ($form->date_max_future($form->{"datepaid_$i"}, \%myconfig));
955 #Zusätzlich noch das Buchungsdatum in die Bücherkontrolle einbeziehen
956 # (Dient zur Prüfung ob ZE oder ZA geprüft werden soll)
957 $form->error($locale->text('Cannot post payment for a closed period!'))
958 if ($form->date_closed($form->{"datepaid_$i"}) && !$form->date_closed($form->{"gldate_$i"}, \%myconfig));
960 if ($form->{currency} ne $form->{defaultcurrency}) {
961 $form->{"exchangerate_$i"} = $form->{exchangerate}
962 if ($invdate == $datepaid);
963 $form->isblank("exchangerate_$i",
964 $locale->text('Exchangerate for payment missing!'));
969 ($form->{AR}) = split /--/, $form->{AR};
970 ($form->{AR_paid}) = split /--/, $form->{AR_paid};
971 $form->{storno} ||= 0;
973 $form->{label} = $form->{type} eq 'credit_note' ? $locale->text('Credit Note') : $locale->text('Invoice');
975 $form->{id} = 0 if $form->{postasnew};
977 # get new invnumber in sequence if no invnumber is given or if posasnew was requested
978 if ($form->{postasnew}) {
979 if ($form->{type} eq "credit_note") {
980 undef($form->{cnnumber});
982 undef($form->{invnumber});
988 my $terms = get_payment_terms_for_invoice();
989 $form->{duedate} = $terms->calc_date(reference_date => $form->{invdate}, due_date => $form->{duedate})->to_kivitendo if $terms;
991 # If transfer_out is requested, get rose db handle and do post and
992 # transfer out in one transaction. Otherwise just post the invoice.
993 if ($::instance_conf->get_is_transfer_out && $form->{type} ne 'credit_note' && !$form->{storno}) {
994 require SL::DB::Inventory;
995 my $rose_db = SL::DB::Inventory->new->db;
998 if (!$rose_db->with_transaction(sub {
1000 if (!IS->post_invoice(\%myconfig, \%$form, $rose_db->dbh)) {
1001 push @errors, $locale->text('Cannot post invoice!');
1002 die 'posting error';
1004 my $err = IS->transfer_out(\%$form, $rose_db->dbh);
1006 push @errors, @{ $err };
1007 die 'transfer error';
1012 push @errors, $EVAL_ERROR;
1013 $form->error($locale->text('Cannot post invoice and/or transfer out! Error message:') . "\n" . join("\n", @errors));
1018 push @errors, $rose_db->error;
1019 $form->error($locale->text('Cannot post invoice and/or transfer out! Error message:') . "\n" . join("\n", @errors));
1022 if (!IS->post_invoice(\%myconfig, \%$form)) {
1023 $form->error($locale->text('Cannot post invoice!'));
1027 if(!exists $form->{addition}) {
1028 $form->{snumbers} = 'invnumber' .'_'. $form->{invnumber}; # ($form->{type} eq 'credit_note' ? 'cnnumber' : 'invnumber') .'_'. $form->{invnumber};
1029 $form->{what_done} = 'invoice';
1030 $form->{addition} = $form->{print_and_post} ? "PRINTED AND POSTED" :
1031 $form->{storno} ? "STORNO" :
1033 $form->save_history;
1036 if (!$form->{no_redirect_after_post}) {
1037 $form->{action} = 'edit';
1038 $form->{script} = 'is.pl';
1039 $form->{callback} = build_std_url(qw(action edit id callback saved_message));
1040 $form->redirect($form->{label} . " $form->{invnumber} " . $locale->text('posted!'));
1043 $main::lxdebug->leave_sub();
1046 sub print_and_post {
1047 $main::lxdebug->enter_sub();
1049 my $form = $main::form;
1051 $main::auth->assert('invoice_edit');
1053 my $old_form = Form->new;
1054 $form->{no_redirect_after_post} = 1;
1055 $form->{print_and_post} = 1;
1059 $main::lxdebug->leave_sub();
1064 $main::lxdebug->enter_sub();
1066 my $form = $main::form;
1067 my %myconfig = %main::myconfig;
1069 $main::auth->assert('invoice_edit');
1071 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)};
1072 $form->{rowcount}--;
1073 $form->{paidaccounts} = 1;
1074 $form->{invdate} = $form->current_date(\%myconfig);
1075 my $terms = get_payment_terms_for_invoice();
1076 $form->{duedate} = $terms ? $terms->calc_date(reference_date => $form->{invdate})->to_kivitendo : $form->{invdate};
1077 $form->{employee_id} = SL::DB::Manager::Employee->current->id;
1078 $form->{forex} = $form->check_exchangerate(\%myconfig, $form->{currency}, $form->{invdate}, 'buy');
1079 $form->{exchangerate} = $form->{forex} if $form->{forex};
1081 $form->{"converted_from_invoice_id_$_"} = delete $form->{"invoice_id_$_"} for 1 .. $form->{"rowcount"};
1083 $form->{useasnew} = 1;
1086 $main::lxdebug->leave_sub();
1090 $main::lxdebug->enter_sub();
1092 my $form = $main::form;
1093 my %myconfig = %main::myconfig;
1094 my $locale = $main::locale;
1096 $main::auth->assert('invoice_edit');
1098 if ($form->{storno}) {
1099 $form->error($locale->text('Cannot storno storno invoice!'));
1102 if (IS->has_storno(\%myconfig, $form, "ar")) {
1103 $form->error($locale->text("Invoice has already been storno'd!"));
1105 if ($form->datetonum($form->{invdate}, \%myconfig) <= $form->datetonum($form->{closedto}, \%myconfig)) {
1106 $form->error($locale->text('Cannot storno invoice for a closed period!'));
1109 # save the history of invoice being stornoed
1110 $form->{snumbers} = qq|invnumber_| . $form->{invnumber};
1111 $form->{what_done} = 'invoice';
1112 $form->{addition} = "STORNO";
1113 $form->save_history;
1115 map({ my $key = $_; delete($form->{$key}) unless (grep({ $key eq $_ } qw(id login password type))); } keys(%{ $form }));
1121 # Payments must not be recorded for the new storno invoice.
1122 $form->{paidaccounts} = 0;
1123 map { my $key = $_; delete $form->{$key} if grep { $key =~ /^$_/ } qw(datepaid_ gldate_ acc_trans_id_ source_ memo_ paid_ exchangerate_ AR_paid_) } keys %{ $form };
1125 # record link invoice to storno
1126 $form->{convert_from_ar_ids} = $form->{id};
1127 $form->{storno_id} = $form->{id};
1128 $form->{storno} = 1;
1130 $form->{invnumber} = "Storno zu " . $form->{invnumber};
1131 $form->{invdate} = DateTime->today->to_lxoffice;
1132 $form->{rowcount}++;
1133 # set new ids for storno invoice
1134 # set new persistent ids for storno invoice items
1135 $form->{"converted_from_invoice_id_$_"} = delete $form->{"invoice_id_$_"} for 1 .. $form->{"rowcount"};
1138 $main::lxdebug->leave_sub();
1142 $main::lxdebug->enter_sub();
1144 my $form = $main::form;
1146 $main::auth->assert('invoice_edit');
1148 $form->{preview} = 1;
1149 my $old_form = Form->new;
1150 for (keys %$form) { $old_form->{$_} = $form->{$_} }
1152 &print_form($old_form);
1153 $main::lxdebug->leave_sub();
1158 $main::lxdebug->enter_sub();
1160 my $form = $main::form;
1161 my %myconfig = %main::myconfig;
1162 my $locale = $main::locale;
1164 $main::auth->assert('invoice_edit');
1166 $form->{transdate} = $form->{invdate} = $form->current_date(\%myconfig);
1168 $form->current_date(\%myconfig, $form->{invdate}, $form->{terms} * 1);
1170 $form->{convert_from_ar_ids} = $form->{id};
1172 $form->{rowcount}--;
1175 $form->{title} = $locale->text('Add Credit Note');
1176 $form->{script} = 'is.pl';
1178 # Bei Gutschriften bezug zur Rechnungsnummer
1179 $form->{invnumber_for_credit_note} = $form->{invnumber};
1180 # bo creates the id, reset it
1181 map { delete $form->{$_} }
1182 qw(id invnumber subject message cc bcc printed emailed queued);
1183 $form->{ $form->{vc} } =~ s/--.*//g;
1184 $form->{type} = "credit_note";
1187 map { $form->{"select$_"} = "" } ($form->{vc}, 'currency');
1189 # map { $form->{$_} = $form->parse_amount(\%myconfig, $form->{$_}) }
1190 # qw(creditlimit creditremaining);
1192 # set new persistent ids for credit note and link previous invoice id
1193 $form->{"converted_from_invoice_id_$_"} = delete $form->{"invoice_id_$_"} for 1 .. $form->{"rowcount"};
1195 my $currency = $form->{currency};
1198 $form->{currency} = $currency;
1199 $form->{forex} = $form->check_exchangerate( \%myconfig, $form->{currency}, $form->{invdate}, 'buy');
1200 $form->{exchangerate} = $form->{forex} || '';
1202 $form->{creditremaining} -= ($form->{oldinvtotal} - $form->{ordtotal});
1204 # bei Gutschriften werden Zahlungseingänge aus Rechnung nicht übernommen
1205 for my $i (1 .. $form->{paidaccounts}) {
1206 delete $form->{"paid_$i"};
1207 delete $form->{"source_$i"};
1208 delete $form->{"memo_$i"};
1209 delete $form->{"datepaid_$i"};
1210 delete $form->{"gldate_$i"};
1211 delete $form->{"acc_trans_id_$i"};
1212 delete $form->{"AR_paid_$i"};
1214 $form->{paidaccounts} = 1;
1221 $main::lxdebug->leave_sub();
1225 $::lxdebug->enter_sub;
1231 my $new_rowcount = $::form->{"rowcount"} * 1 + 1;
1232 $::form->{"project_id_${new_rowcount}"} = $::form->{"globalproject_id"};
1234 $::form->language_payment(\%::myconfig);
1236 Common::webdav_folder($::form);
1239 display_row(++$::form->{rowcount});
1242 $::lxdebug->leave_sub;
1246 $::auth->assert('invoice_edit');
1248 if (IS->delete_invoice(\%::myconfig, $::form)) {
1249 # saving the history
1250 if(!exists $::form->{addition}) {
1251 $::form->{snumbers} = 'invnumber' .'_'. $::form->{invnumber};
1252 $::form->{what_done} = 'invoice';
1253 $::form->{addition} = "DELETED";
1254 $::form->save_history;
1256 # /saving the history
1257 $::form->redirect($::locale->text('Invoice deleted!'));
1259 $::form->error($::locale->text('Cannot delete invoice!'));
1264 print update ship_to storno post_payment use_as_new credit_note
1265 delete post order preview post_and_e_mail print_and_post
1268 if ($::form->{"action_$action"}) {
1274 $::form->error($::locale->text('No action defined.'));