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, $warn_unlinked_delivery_order);
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;
289 if ($::instance_conf->get_warn_no_delivery_order_for_invoice && !$form->{id}) {
290 $warn_unlinked_delivery_order = 1 unless $form->{convert_from_do_ids};
292 for my $bar ($::request->layout->get('actionbar')) {
296 submit => [ '#form', { action => "update" } ],
297 disabled => !$may_edit_create ? t8('You must not change this invoice.')
298 : $form->{locked} ? t8('The billing period has already been locked.')
300 id => 'update_button',
301 accesskey => 'enter',
307 submit => [ '#form', { action => "post" } ],
308 checks => [ 'kivi.validate_form' ],
309 confirm => t8('The invoice is not linked with a sales delivery order. Post anyway?') x !!$warn_unlinked_delivery_order,
310 disabled => !$may_edit_create ? t8('You must not change this invoice.')
311 : $form->{locked} ? t8('The billing period has already been locked.')
312 : $form->{storno} ? t8('A canceled invoice cannot be posted.')
313 : ($form->{id} && $change_never) ? t8('Changing invoices has been disabled in the configuration.')
314 : ($form->{id} && $change_on_same_day_only) ? t8('Invoices can only be changed on the day they are posted.')
315 : $is_linked_bank_transaction ? t8('This transaction is linked with a bank transaction. Please undo and redo the bank transaction booking if needed.')
320 submit => [ '#form', { action => "post_payment" } ],
321 checks => [ 'kivi.validate_form' ],
322 disabled => !$may_edit_create ? t8('You must not change this invoice.')
323 : !$form->{id} ? t8('This invoice has not been posted yet.')
324 : $is_linked_bank_transaction ? t8('This transaction is linked with a bank transaction. Please undo and redo the bank transaction booking if needed.')
327 action => [ t8('Mark as paid'),
328 submit => [ '#form', { action => "mark_as_paid" } ],
329 confirm => t8('This will remove the invoice from showing as unpaid even if the unpaid amount does not match the amount. Proceed?'),
330 disabled => !$may_edit_create ? t8('You must not change this invoice.')
331 : !$form->{id} ? t8('This invoice has not been posted yet.')
333 only_if => $::instance_conf->get_is_show_mark_as_paid,
335 ], # end of combobox "Post"
338 action => [ t8('Storno'),
339 submit => [ '#form', { action => "storno" } ],
340 confirm => t8('Do you really want to cancel this invoice?'),
341 checks => [ 'kivi.validate_form' ],
342 disabled => !$may_edit_create ? t8('You must not change this invoice.')
343 : !$form->{id} ? t8('This invoice has not been posted yet.')
344 : $form->{storno} ? t8('Cannot storno storno invoice!')
345 : $form->{locked} ? t8('The billing period has already been locked.')
346 : !$payments_balanced ? t8('Cancelling is disallowed. Either undo or balance the current payments until the open amount matches the invoice amount')
349 action => [ t8('Delete'),
350 submit => [ '#form', { action => "delete" } ],
351 confirm => t8('Do you really want to delete this object?'),
352 checks => [ 'kivi.validate_form' ],
353 disabled => !$may_edit_create ? t8('You must not change this invoice.')
354 : !$form->{id} ? t8('This invoice has not been posted yet.')
355 : $form->{locked} ? t8('The billing period has already been locked.')
356 : $change_never ? t8('Changing invoices has been disabled in the configuration.')
357 : $change_on_same_day_only ? t8('Invoices can only be changed on the day they are posted.')
358 : $has_storno ? t8('Can only delete the "Storno zu" part of the cancellation pair.')
361 ], # end of combobox "Storno"
366 action => [ t8('Workflow') ],
369 submit => [ '#form', { action => "use_as_new" } ],
370 checks => [ 'kivi.validate_form' ],
371 disabled => !$may_edit_create ? t8('You must not change this invoice.')
372 : !$form->{id} ? t8('This invoice has not been posted yet.')
377 submit => [ '#form', { action => "credit_note" } ],
378 checks => [ 'kivi.validate_form' ],
379 disabled => !$may_edit_create ? t8('You must not change this invoice.')
380 : $form->{type} eq "credit_note" ? t8('Credit notes cannot be converted into other credit notes.')
381 : !$form->{id} ? t8('This invoice has not been posted yet.')
382 : $form->{storno} ? t8('A canceled invoice cannot be used. Please undo the cancellation first.')
387 submit => [ '#form', { action => "order" } ],
388 checks => [ 'kivi.validate_form' ],
389 disabled => !$form->{id} ? t8('This invoice has not been posted yet.') : undef,
391 ], # end of combobox "Workflow"
394 action => [ t8('Export') ],
396 ($form->{id} ? t8('Print') : t8('Preview')),
397 call => [ 'kivi.SalesPurchase.show_print_dialog', $form->{id} ? 'print' : 'preview' ],
398 checks => [ 'kivi.validate_form' ],
399 disabled => !$may_edit_create ? t8('You must not print this invoice.')
400 : !$form->{id} && $form->{locked} ? t8('The billing period has already been locked.')
403 action => [ t8('Print and Post'),
404 call => [ 'kivi.SalesPurchase.show_print_dialog', 'print_and_post' ],
405 checks => [ 'kivi.validate_form' ],
406 confirm => t8('The invoice is not linked with a sales delivery order. Post anyway?') x !!$warn_unlinked_delivery_order,
407 disabled => !$may_edit_create ? t8('You must not change this invoice.')
408 : $form->{locked} ? t8('The billing period has already been locked.')
409 : $form->{storno} ? t8('A canceled invoice cannot be posted.')
410 : ($form->{id} && $change_never) ? t8('Changing invoices has been disabled in the configuration.')
411 : ($form->{id} && $change_on_same_day_only) ? t8('Invoices can only be changed on the day they are posted.')
412 : $is_linked_bank_transaction ? t8('This transaction is linked with a bank transaction. Please undo and redo the bank transaction booking if needed.')
415 action => [ t8('E Mail'),
416 call => [ 'kivi.SalesPurchase.show_email_dialog' ],
417 checks => [ 'kivi.validate_form' ],
418 disabled => !$may_edit_create ? t8('You must not print this invoice.')
419 : !$form->{id} ? t8('This invoice has not been posted yet.')
420 : $form->{postal_invoice} ? t8('This customer wants a postal invoices.')
423 ], # end of combobox "Export"
426 action => [ t8('more') ],
429 call => [ 'set_history_window', $form->{id} * 1, 'glid' ],
430 disabled => !$form->{id} ? t8('This invoice has not been posted yet.') : undef,
434 call => [ 'follow_up_window' ],
435 disabled => !$form->{id} ? t8('This invoice has not been posted yet.') : undef,
439 call => [ 'kivi.Draft.popup', 'is', 'invoice', $form->{draft_id}, $form->{draft_description} ],
440 disabled => !$may_edit_create ? t8('You must not change this invoice.')
441 : $form->{id} ? t8('This invoice has already been posted.')
442 : $form->{locked} ? t8('The billing period has already been locked.')
445 ], # end of combobox "more"
448 $::request->layout->add_javascripts('kivi.Validator.js');
452 $main::lxdebug->enter_sub();
456 my $form = $main::form;
457 my %myconfig = %main::myconfig;
458 my $locale = $main::locale;
459 my $cgi = $::request->{cgi};
464 $TMPL_VAR{customer_obj} = SL::DB::Customer->load_cached($form->{customer_id}) if $form->{customer_id};
465 $TMPL_VAR{invoice_obj} = SL::DB::Invoice->load_cached($form->{id}) if $form->{id};
467 # only print, no mail
468 $form->{postal_invoice} = $TMPL_VAR{customer_obj}->postal_invoice if ref $TMPL_VAR{customer_obj} eq 'SL::DB::Customer';
470 my $current_employee = SL::DB::Manager::Employee->current;
471 $form->{employee_id} = $form->{old_employee_id} if $form->{old_employee_id};
472 $form->{salesman_id} = $form->{old_salesman_id} if $form->{old_salesman_id};
473 $form->{employee_id} ||= $current_employee->id;
474 $form->{salesman_id} ||= $current_employee->id;
476 $form->{defaultcurrency} = $form->get_default_currency(\%myconfig);
478 $form->get_lists("taxzones" => ($form->{id} ? "ALL_TAXZONES" : "ALL_ACTIVE_TAXZONES"),
479 "currencies" => "ALL_CURRENCIES",
480 "price_factors" => "ALL_PRICE_FACTORS");
482 $form->{ALL_DEPARTMENTS} = SL::DB::Manager::Department->get_all_sorted;
483 $form->{ALL_LANGUAGES} = SL::DB::Manager::Language->get_all_sorted;
486 my @old_project_ids = uniq grep { $_ } map { $_ * 1 } ($form->{"globalproject_id"}, map { $form->{"project_id_$_"} } 1..$form->{"rowcount"});
487 my @old_ids_cond = @old_project_ids ? (id => \@old_project_ids) : ();
489 if ($::instance_conf->get_customer_projects_only_in_sales) {
492 customer_id => $::form->{customer_id},
493 billable_customer_id => $::form->{customer_id},
498 and => [ active => 1, @customer_cond ],
502 $TMPL_VAR{ALL_PROJECTS} = SL::DB::Manager::Project->get_all_sorted(query => \@conditions);
503 $form->{ALL_PROJECTS} = $TMPL_VAR{ALL_PROJECTS}; # make projects available for second row drop-down in io.pl
504 $TMPL_VAR{ALL_EMPLOYEES} = SL::DB::Manager::Employee->get_all_sorted(query => [ or => [ id => $::form->{employee_id}, deleted => 0 ] ]);
505 $TMPL_VAR{ALL_SALESMEN} = SL::DB::Manager::Employee->get_all_sorted(query => [ or => [ id => $::form->{salesman_id}, deleted => 0 ] ]);
506 $TMPL_VAR{ALL_SHIPTO} = SL::DB::Manager::Shipto->get_all_sorted(query => [
507 or => [ trans_id => $::form->{"$::form->{vc}_id"} * 1, and => [ shipto_id => $::form->{shipto_id} * 1, trans_id => undef ] ]
509 $TMPL_VAR{ALL_CONTACTS} = SL::DB::Manager::Contact->get_all_sorted(query => [
511 cp_cv_id => $::form->{"$::form->{vc}_id"} * 1,
514 cp_id => $::form->{cp_id} * 1
519 # currencies and exchangerate
520 my @values = map { $_ } @{ $form->{ALL_CURRENCIES} };
521 my %labels = map { $_ => $_ } @{ $form->{ALL_CURRENCIES} };
522 $form->{currency} = $form->{defaultcurrency} unless $form->{currency};
523 $form->{show_exchangerate} = $form->{currency} ne $form->{defaultcurrency};
524 $TMPL_VAR{currencies} = NTI($::request->{cgi}->popup_menu('-name' => 'currency', '-default' => $form->{"currency"},
525 '-values' => \@values, '-labels' => \%labels,
526 '-onchange' => "document.getElementById('update_button').click();"
527 )) if scalar @values;
528 push @custom_hiddens, "forex";
529 push @custom_hiddens, "exchangerate" if $form->{forex};
531 $TMPL_VAR{creditwarning} = ($form->{creditlimit} != 0) && ($form->{creditremaining} < 0) && !$form->{update};
532 $TMPL_VAR{is_credit_remaining_negativ} = $form->{creditremaining} =~ /-/;
534 # set option selected
535 foreach my $item (qw(AR)) {
536 $form->{"select$item"} =~ s/ selected//;
537 $form->{"select$item"} =~ s/option>\Q$form->{$item}\E/option selected>$form->{$item}/;
540 $TMPL_VAR{is_type_credit_note} = $form->{type} eq "credit_note";
541 $TMPL_VAR{is_format_html} = $form->{format} eq 'html';
542 $TMPL_VAR{dateformat} = $myconfig{dateformat};
543 $TMPL_VAR{numberformat} = $myconfig{numberformat};
546 $TMPL_VAR{HIDDENS} = [qw(
547 id type queued printed emailed vc discount
548 title creditlimit creditremaining tradediscount business closedto locked shipped storno storno_id
549 max_dunning_level dunning_amount dunning_description
550 taxaccounts cursor_fokus
551 convert_from_do_ids convert_from_oe_ids convert_from_ar_ids useasnew
555 map { $_.'_rate', $_.'_description', $_.'_taxnumber', $_.'_tax_id' } split / /, $form->{taxaccounts}];
557 $::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));
559 $TMPL_VAR{payment_terms_obj} = get_payment_terms_for_invoice();
560 $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};
562 setup_is_action_bar();
566 print $form->parse_html_template("is/form_header", \%TMPL_VAR);
568 $main::lxdebug->leave_sub();
572 my @fields = qw(acc_trans_id gldate datepaid source memo paid AR_paid);
574 grep { $_->{paid} != 0 }
577 +{ map { ($_ => delete($::form->{"${_}_${idx}"})) } @fields }
578 } (1..$::form->{paidaccounts});
580 @payments = sort_by { DateTime->from_kivitendo($_->{datepaid}) } @payments;
582 $::form->{paidaccounts} = max scalar(@payments), 1;
584 foreach my $idx (1 .. scalar(@payments)) {
585 my $payment = $payments[$idx - 1];
586 $::form->{"${_}_${idx}"} = $payment->{$_} for @fields;
591 $main::lxdebug->enter_sub();
595 my $form = $main::form;
596 my %myconfig = %main::myconfig;
597 my $locale = $main::locale;
599 $form->{invtotal} = $form->{invsubtotal};
601 # tax, total and subtotal calculations
602 my ($tax, $subtotal);
603 $form->{taxaccounts_array} = [ split(/ /, $form->{taxaccounts}) ];
605 if( $form->{customer_id} && !$form->{taxincluded_changed_by_user} ) {
606 my $customer = SL::DB::Customer->load_cached($form->{customer_id});
607 $form->{taxincluded} = defined($customer->taxincluded_checked) ? $customer->taxincluded_checked : $myconfig{taxincluded_checked};
610 foreach my $item (@{ $form->{taxaccounts_array} }) {
611 if ($form->{"${item}_base"}) {
612 if ($form->{taxincluded}) {
613 $form->{"${item}_total"} = $form->round_amount( ($form->{"${item}_base"} * $form->{"${item}_rate"}
614 / (1 + $form->{"${item}_rate"})), 2);
615 $form->{"${item}_netto"} = $form->round_amount( ($form->{"${item}_base"} - $form->{"${item}_total"}), 2);
617 $form->{"${item}_total"} = $form->round_amount( $form->{"${item}_base"} * $form->{"${item}_rate"}, 2);
618 $form->{invtotal} += $form->{"${item}_total"};
623 my $grossamount = $form->{invtotal};
624 $form->{invtotal} = $form->round_amount( $form->{invtotal}, 2, 1 );
625 $form->{rounding} = $form->round_amount(
626 $form->{invtotal} - $form->round_amount($grossamount, 2),
632 $form->{follow_ups} = FU->follow_ups('trans_id' => $form->{id}, 'not_done' => 1) || [];
633 $form->{follow_ups_unfinished} = ( sum map { $_->{due} * 1 } @{ $form->{follow_ups} } ) || 0;
640 $form->{paidaccounts}++ if ($form->{"paid_$form->{paidaccounts}"});
641 $form->{paid_indices} = [ 1 .. $form->{paidaccounts} ];
643 # Standard Konto für Umlaufvermögen
644 my $accno_arap = IS->get_standard_accno_current_assets(\%myconfig, \%$form);
646 for my $i (1 .. $form->{paidaccounts}) {
647 $form->{"changeable_$i"} = 1;
648 if (SL::DB::Default->get->payments_changeable == 0) {
650 $form->{"changeable_$i"} = ($form->{"acc_trans_id_$i"})? 0 : 1;
651 } elsif (SL::DB::Default->get->payments_changeable == 2) {
653 $form->{"changeable_$i"} = (($form->{"gldate_$i"} eq '') ||
654 ($form->current_date(\%myconfig) eq $form->{"gldate_$i"}));
657 #deaktivieren von gebuchten Zahlungen ausserhalb der Bücherkontrolle, vorher prüfen ob heute eingegeben
658 if ($form->date_closed($form->{"gldate_$i"})) {
659 $form->{"changeable_$i"} = 0;
662 $form->{"selectAR_paid_$i"} = $form->{selectAR_paid};
663 if (!$form->{"AR_paid_$i"}) {
664 $form->{"selectAR_paid_$i"} =~ s/option>$accno_arap--(.*?)</option selected>$accno_arap--$1</;
666 $form->{"selectAR_paid_$i"} =~ s/option>\Q$form->{"AR_paid_$i"}\E/option selected>$form->{"AR_paid_$i"}/;
669 $totalpaid += $form->{"paid_$i"};
672 $form->{oldinvtotal} = $form->{invtotal};
674 $form->{ALL_DELIVERY_TERMS} = SL::DB::Manager::DeliveryTerm->get_all_sorted();
676 my $shipto_cvars = SL::DB::Shipto->new->cvars_by_config;
677 foreach my $var (@{ $shipto_cvars }) {
678 my $name = "shiptocvar_" . $var->config->name;
679 $var->value($form->{$name}) if exists $form->{$name};
682 print $form->parse_html_template('is/form_footer', {
683 is_type_credit_note => ($form->{type} eq "credit_note"),
684 totalpaid => $totalpaid,
685 paid_missing => $form->{invtotal} - $totalpaid,
686 print_options => setup_sales_purchase_print_options(),
687 show_storno => $form->{id} && !$form->{storno} && !IS->has_storno(\%myconfig, $form, "ar") && !$totalpaid,
688 show_delete => ($::instance_conf->get_is_changeable == 2)
689 ? ($form->current_date(\%myconfig) eq $form->{gldate})
690 : ($::instance_conf->get_is_changeable == 1),
691 today => DateTime->today,
692 vc_obj => $form->{customer_id} ? SL::DB::Customer->load_cached($form->{customer_id}) : undef,
693 shipto_cvars => $shipto_cvars,
695 ##print $form->parse_html_template('is/_payments'); # parser
696 ##print $form->parse_html_template('webdav/_list'); # parser
698 $main::lxdebug->leave_sub();
702 $::auth->assert('invoice_edit');
704 SL::DB::Invoice->new(id => $::form->{id})->load->mark_as_paid;
706 $::form->redirect($::locale->text("Marked as paid"));
710 # unless no lazy implementation of save draft without invdate
711 # set the current date like in version <= 3.4.1
712 $::form->{invdate} = DateTime->today->to_lxoffice;
717 $main::lxdebug->enter_sub();
721 my $form = $main::form;
722 my %myconfig = %main::myconfig;
724 my ($recursive_call) = @_;
726 $form->{print_and_post} = 0 if $form->{second_run};
727 my $taxincluded = $form->{taxincluded} ? "checked" : '';
730 if (($form->{previous_customer_id} || $form->{customer_id}) != $form->{customer_id}) {
731 $::form->{salesman_id} = SL::DB::Manager::Employee->current->id if exists $::form->{salesman_id};
733 IS->get_customer(\%myconfig, $form);
736 $form->{taxincluded} ||= $taxincluded;
738 if (!$form->{forex}) { # read exchangerate from input field (not hidden)
739 $form->{exchangerate} = $form->parse_amount(\%myconfig, $form->{exchangerate}) unless $recursive_call;
741 $form->{forex} = $form->check_exchangerate(\%myconfig, $form->{currency}, $form->{invdate}, 'buy');
742 $form->{exchangerate} = $form->{forex} if $form->{forex};
744 for my $i (1 .. $form->{paidaccounts}) {
745 next unless $form->{"paid_$i"};
746 map { $form->{"${_}_$i"} = $form->parse_amount(\%myconfig, $form->{"${_}_$i"}) } qw(paid exchangerate);
747 $form->{"forex_$i"} = $form->check_exchangerate(\%myconfig, $form->{currency}, $form->{"datepaid_$i"}, 'buy');
748 $form->{"exchangerate_$i"} = $form->{"forex_$i"} if $form->{"forex_$i"};
751 my $i = $form->{rowcount};
752 my $exchangerate = $form->{exchangerate} || 1;
754 # if last row empty, check the form otherwise retrieve new item
755 if ( ($form->{"partnumber_$i"} eq "")
756 && ($form->{"description_$i"} eq "")
757 && ($form->{"partsgroup_$i"} eq "")) {
759 $form->{creditremaining} += ($form->{oldinvtotal} - $form->{oldtotalpaid});
764 IS->retrieve_item(\%myconfig, \%$form);
766 my $rows = scalar @{ $form->{item_list} };
768 $form->{"discount_$i"} = $form->parse_amount(\%myconfig, $form->{"discount_$i"}) / 100.0;
769 $form->{"discount_$i"} ||= $form->{customer_discount};
772 $form->{"qty_$i"} = $form->parse_amount(\%myconfig, $form->{"qty_$i"});
773 if( !$form->{"qty_$i"} ) {
774 $form->{"qty_$i"} = 1;
779 select_item(mode => 'IS', pre_entered_qty => $form->{"qty_$i"});
780 $::dispatcher->end_request;
784 my $sellprice = $form->parse_amount(\%myconfig, $form->{"sellprice_$i"});
786 map { $form->{item_list}[$i]{$_} =~ s/\"/"/g } qw(partnumber description unit);
787 map { $form->{"${_}_$i"} = $form->{item_list}[0]{$_} } keys %{ $form->{item_list}[0] };
789 $form->{payment_id} = $form->{"part_payment_id_$i"} if $form->{"part_payment_id_$i"} ne "";
790 $form->{"discount_$i"} = 0 if $form->{"not_discountable_$i"};
792 $form->{"marge_price_factor_$i"} = $form->{item_list}->[0]->{price_factor};
794 ($sellprice || $form->{"sellprice_$i"}) =~ /\.(\d+)/;
795 my $decimalplaces = max 2, length $1;
798 $form->{"sellprice_$i"} = $sellprice;
800 my $record = _make_record();
801 my $price_source = SL::PriceSource->new(record_item => $record->items->[$i-1], record => $record);
802 my $best_price = $price_source->best_price;
803 my $best_discount = $price_source->best_discount;
806 $::form->{"sellprice_$i"} = $best_price->price;
807 $::form->{"active_price_source_$i"} = $best_price->source;
809 if ($best_discount) {
810 $::form->{"discount_$i"} = $best_discount->discount;
811 $::form->{"active_discount_source_$i"} = $best_discount->source;
814 # if there is an exchange rate adjust sellprice
815 $form->{"sellprice_$i"} /= $exchangerate;
818 $form->{"listprice_$i"} /= $exchangerate;
820 my $amount = $form->{"sellprice_$i"} * $form->{"qty_$i"} * (1 - $form->{"discount_$i"});
821 map { $form->{"${_}_base"} = 0 } split / /, $form->{taxaccounts};
822 map { $form->{"${_}_base"} += $amount } split / /, $form->{"taxaccounts_$i"};
823 map { $amount += ($form->{"${_}_base"} * $form->{"${_}_rate"}) } split / /, $form->{"taxaccounts_$i"} if !$form->{taxincluded};
825 $form->{creditremaining} -= $amount;
827 map { $form->{"${_}_$i"} = $form->format_amount(\%myconfig, $form->{"${_}_$i"}, $decimalplaces) } qw(sellprice lastcost);
829 $form->{"qty_$i"} = $form->format_amount(\%myconfig, $form->{"qty_$i"});
830 $form->{"discount_$i"} = $form->format_amount(\%myconfig, $form->{"discount_$i"} * 100.0);
837 # ok, so this is a new part
838 # ask if it is a part or service item
840 if ( $form->{"partsgroup_$i"}
841 && ($form->{"partnumber_$i" } eq "")
842 && ($form->{"description_$i"} eq "")) {
844 $form->{"discount_$i"} = "";
848 $form->{"id_$i"} = 0;
853 $main::lxdebug->leave_sub();
857 $main::lxdebug->enter_sub();
859 my $form = $main::form;
860 my %myconfig = %main::myconfig;
861 my $locale = $main::locale;
863 $main::auth->assert('invoice_edit');
865 $form->mtime_ischanged('ar') ;
866 my $invdate = $form->datetonum($form->{invdate}, \%myconfig);
868 $form->{defaultcurrency} = $form->get_default_currency(\%myconfig);
869 for my $i (1 .. $form->{paidaccounts}) {
870 if ($form->{"paid_$i"}) {
871 my $datepaid = $form->datetonum($form->{"datepaid_$i"}, \%myconfig);
873 $form->isblank("datepaid_$i", $locale->text('Payment date missing!'));
876 if ($form->{currency} ne $form->{defaultcurrency}) {
877 $form->{"exchangerate_$i"} = $form->{exchangerate}
878 if ($invdate == $datepaid);
879 $form->isblank("exchangerate_$i",
880 $locale->text('Exchangerate for payment missing!'));
882 $form->error($locale->text('Cannot post transaction above the maximum future booking date!'))
883 if ($form->date_max_future($form->{"datepaid_$i"}, \%myconfig));
885 #Zusätzlich noch das Buchungsdatum in die Bücherkontrolle einbeziehen
886 # (Dient zur Prüfung ob ZE oder ZA geprüft werden soll)
887 $form->error($locale->text('Cannot post payment for a closed period!'))
888 if ($form->date_closed($form->{"datepaid_$i"}) && !$form->date_closed($form->{"gldate_$i"}, \%myconfig));
892 ($form->{AR}) = split /--/, $form->{AR};
893 ($form->{AR_paid}) = split /--/, $form->{AR_paid};
895 if ( IS->post_payment(\%myconfig, \%$form) ) {
896 $form->{snumbers} = qq|invnumber_| . $form->{invnumber};
897 $form->{what_done} = 'invoice';
898 $form->{addition} = "PAYMENT POSTED";
900 $form->redirect($locale->text('Payment posted!'))
902 $form->error($locale->text('Cannot post payment!'));
905 $main::lxdebug->leave_sub();
909 $main::lxdebug->enter_sub();
911 my $form = $main::form;
912 my %myconfig = %main::myconfig;
913 my $locale = $main::locale;
915 $main::auth->assert('invoice_edit');
916 $form->mtime_ischanged('ar');
918 $form->{defaultcurrency} = $form->get_default_currency(\%myconfig);
919 $form->isblank("invdate", $locale->text('Invoice Date missing!'));
920 $form->isblank("customer_id", $locale->text('Customer missing!'));
921 $form->error($locale->text('Cannot post invoice for a closed period!'))
922 if ($form->date_closed($form->{"invdate"}, \%myconfig));
924 $form->{invnumber} =~ s/^\s*//g;
925 $form->{invnumber} =~ s/\s*$//g;
927 # if oldcustomer ne customer redo form
928 if (($form->{previous_customer_id} || $form->{customer_id}) != $form->{customer_id}) {
930 $::dispatcher->end_request;
933 if ($myconfig{mandatory_departments} && !$form->{department_id}) {
934 $form->{saved_message} = $::locale->text('You have to specify a department.');
939 if ($form->{second_run}) {
940 $form->{print_and_post} = 0;
943 remove_emptied_rows();
946 my $closedto = $form->datetonum($form->{closedto}, \%myconfig);
947 my $invdate = $form->datetonum($form->{invdate}, \%myconfig);
949 $form->error($locale->text('Cannot post transaction above the maximum future booking date!'))
950 if ($form->date_max_future($invdate, \%myconfig));
951 $form->error($locale->text('Cannot post invoice for a closed period!'))
952 if ($invdate <= $closedto);
954 $form->isblank("exchangerate", $locale->text('Exchangerate missing!'))
955 if ($form->{currency} ne $form->{defaultcurrency});
957 for my $i (1 .. $form->{paidaccounts}) {
958 if ($form->parse_amount(\%myconfig, $form->{"paid_$i"})) {
959 my $datepaid = $form->datetonum($form->{"datepaid_$i"}, \%myconfig);
961 $form->isblank("datepaid_$i", $locale->text('Payment date 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));
971 if ($form->{currency} ne $form->{defaultcurrency}) {
972 $form->{"exchangerate_$i"} = $form->{exchangerate}
973 if ($invdate == $datepaid);
974 $form->isblank("exchangerate_$i",
975 $locale->text('Exchangerate for payment missing!'));
980 ($form->{AR}) = split /--/, $form->{AR};
981 ($form->{AR_paid}) = split /--/, $form->{AR_paid};
982 $form->{storno} ||= 0;
984 $form->{label} = $form->{type} eq 'credit_note' ? $locale->text('Credit Note') : $locale->text('Invoice');
986 $form->{id} = 0 if $form->{postasnew};
988 # get new invnumber in sequence if no invnumber is given or if posasnew was requested
989 if ($form->{postasnew}) {
990 if ($form->{type} eq "credit_note") {
991 undef($form->{cnnumber});
993 undef($form->{invnumber});
999 my $terms = get_payment_terms_for_invoice();
1000 $form->{duedate} = $terms->calc_date(reference_date => $form->{invdate}, due_date => $form->{duedate})->to_kivitendo if $terms;
1002 # If transfer_out is requested, get rose db handle and do post and
1003 # transfer out in one transaction. Otherwise just post the invoice.
1004 if ($::instance_conf->get_is_transfer_out && $form->{type} ne 'credit_note' && !$form->{storno}) {
1005 require SL::DB::Inventory;
1006 my $rose_db = SL::DB::Inventory->new->db;
1009 if (!$rose_db->with_transaction(sub {
1011 if (!IS->post_invoice(\%myconfig, \%$form, $rose_db->dbh)) {
1012 push @errors, $locale->text('Cannot post invoice!');
1013 die 'posting error';
1015 my $err = IS->transfer_out(\%$form, $rose_db->dbh);
1017 push @errors, @{ $err };
1018 die 'transfer error';
1023 push @errors, $EVAL_ERROR;
1024 $form->error($locale->text('Cannot post invoice and/or transfer out! Error message:') . "\n" . join("\n", @errors));
1029 push @errors, $rose_db->error;
1030 $form->error($locale->text('Cannot post invoice and/or transfer out! Error message:') . "\n" . join("\n", @errors));
1033 if (!IS->post_invoice(\%myconfig, \%$form)) {
1034 $form->error($locale->text('Cannot post invoice!'));
1038 if(!exists $form->{addition}) {
1039 $form->{snumbers} = 'invnumber' .'_'. $form->{invnumber}; # ($form->{type} eq 'credit_note' ? 'cnnumber' : 'invnumber') .'_'. $form->{invnumber};
1040 $form->{what_done} = 'invoice';
1041 $form->{addition} = $form->{print_and_post} ? "PRINTED AND POSTED" :
1042 $form->{storno} ? "STORNO" :
1044 $form->save_history;
1047 if (!$form->{no_redirect_after_post}) {
1048 $form->{action} = 'edit';
1049 $form->{script} = 'is.pl';
1050 $form->{callback} = build_std_url(qw(action edit id callback saved_message));
1051 $form->redirect($form->{label} . " $form->{invnumber} " . $locale->text('posted!'));
1054 $main::lxdebug->leave_sub();
1057 sub print_and_post {
1058 $main::lxdebug->enter_sub();
1060 my $form = $main::form;
1062 $main::auth->assert('invoice_edit');
1064 my $old_form = Form->new;
1065 $form->{no_redirect_after_post} = 1;
1066 $form->{print_and_post} = 1;
1070 $main::lxdebug->leave_sub();
1075 $main::lxdebug->enter_sub();
1077 my $form = $main::form;
1078 my %myconfig = %main::myconfig;
1080 $main::auth->assert('invoice_edit');
1082 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)};
1083 $form->{rowcount}--;
1084 $form->{paidaccounts} = 1;
1085 $form->{invdate} = $form->current_date(\%myconfig);
1086 my $terms = get_payment_terms_for_invoice();
1087 $form->{duedate} = $terms ? $terms->calc_date(reference_date => $form->{invdate})->to_kivitendo : $form->{invdate};
1088 $form->{employee_id} = SL::DB::Manager::Employee->current->id;
1089 $form->{forex} = $form->check_exchangerate(\%myconfig, $form->{currency}, $form->{invdate}, 'buy');
1090 $form->{exchangerate} = $form->{forex} if $form->{forex};
1092 $form->{"converted_from_invoice_id_$_"} = delete $form->{"invoice_id_$_"} for 1 .. $form->{"rowcount"};
1094 $form->{useasnew} = 1;
1097 $main::lxdebug->leave_sub();
1101 $main::lxdebug->enter_sub();
1103 my $form = $main::form;
1104 my %myconfig = %main::myconfig;
1105 my $locale = $main::locale;
1107 $main::auth->assert('invoice_edit');
1109 if ($form->{storno}) {
1110 $form->error($locale->text('Cannot storno storno invoice!'));
1113 if (IS->has_storno(\%myconfig, $form, "ar")) {
1114 $form->error($locale->text("Invoice has already been storno'd!"));
1116 if ($form->datetonum($form->{invdate}, \%myconfig) <= $form->datetonum($form->{closedto}, \%myconfig)) {
1117 $form->error($locale->text('Cannot storno invoice for a closed period!'));
1120 # save the history of invoice being stornoed
1121 $form->{snumbers} = qq|invnumber_| . $form->{invnumber};
1122 $form->{what_done} = 'invoice';
1123 $form->{addition} = "STORNO";
1124 $form->save_history;
1126 map({ my $key = $_; delete($form->{$key}) unless (grep({ $key eq $_ } qw(id login password type))); } keys(%{ $form }));
1132 # Payments must not be recorded for the new storno invoice.
1133 $form->{paidaccounts} = 0;
1134 map { my $key = $_; delete $form->{$key} if grep { $key =~ /^$_/ } qw(datepaid_ gldate_ acc_trans_id_ source_ memo_ paid_ exchangerate_ AR_paid_) } keys %{ $form };
1136 # record link invoice to storno
1137 $form->{convert_from_ar_ids} = $form->{id};
1138 $form->{storno_id} = $form->{id};
1139 $form->{storno} = 1;
1141 $form->{invnumber} = "Storno zu " . $form->{invnumber};
1142 $form->{invdate} = DateTime->today->to_lxoffice;
1143 $form->{rowcount}++;
1144 # set new ids for storno invoice
1145 # set new persistent ids for storno invoice items
1146 $form->{"converted_from_invoice_id_$_"} = delete $form->{"invoice_id_$_"} for 1 .. $form->{"rowcount"};
1149 $main::lxdebug->leave_sub();
1153 $main::lxdebug->enter_sub();
1155 my $form = $main::form;
1157 $main::auth->assert('invoice_edit');
1159 $form->{preview} = 1;
1160 my $old_form = Form->new;
1161 for (keys %$form) { $old_form->{$_} = $form->{$_} }
1163 &print_form($old_form);
1164 $main::lxdebug->leave_sub();
1169 $main::lxdebug->enter_sub();
1171 my $form = $main::form;
1172 my %myconfig = %main::myconfig;
1173 my $locale = $main::locale;
1175 $main::auth->assert('invoice_edit');
1177 $form->{transdate} = $form->{invdate} = $form->current_date(\%myconfig);
1179 $form->current_date(\%myconfig, $form->{invdate}, $form->{terms} * 1);
1181 $form->{convert_from_ar_ids} = $form->{id};
1183 $form->{rowcount}--;
1186 $form->{title} = $locale->text('Add Credit Note');
1187 $form->{script} = 'is.pl';
1189 # Bei Gutschriften bezug zur Rechnungsnummer
1190 $form->{invnumber_for_credit_note} = $form->{invnumber};
1191 # bo creates the id, reset it
1192 map { delete $form->{$_} }
1193 qw(id invnumber subject message cc bcc printed emailed queued);
1194 $form->{ $form->{vc} } =~ s/--.*//g;
1195 $form->{type} = "credit_note";
1198 map { $form->{"select$_"} = "" } ($form->{vc}, 'currency');
1200 # map { $form->{$_} = $form->parse_amount(\%myconfig, $form->{$_}) }
1201 # qw(creditlimit creditremaining);
1203 # set new persistent ids for credit note and link previous invoice id
1204 $form->{"converted_from_invoice_id_$_"} = delete $form->{"invoice_id_$_"} for 1 .. $form->{"rowcount"};
1206 my $currency = $form->{currency};
1209 $form->{currency} = $currency;
1210 $form->{forex} = $form->check_exchangerate( \%myconfig, $form->{currency}, $form->{invdate}, 'buy');
1211 $form->{exchangerate} = $form->{forex} || '';
1213 $form->{creditremaining} -= ($form->{oldinvtotal} - $form->{ordtotal});
1215 # bei Gutschriften werden Zahlungseingänge aus Rechnung nicht übernommen
1216 for my $i (1 .. $form->{paidaccounts}) {
1217 delete $form->{"paid_$i"};
1218 delete $form->{"source_$i"};
1219 delete $form->{"memo_$i"};
1220 delete $form->{"datepaid_$i"};
1221 delete $form->{"gldate_$i"};
1222 delete $form->{"acc_trans_id_$i"};
1223 delete $form->{"AR_paid_$i"};
1225 $form->{paidaccounts} = 1;
1232 $main::lxdebug->leave_sub();
1236 $::lxdebug->enter_sub;
1242 my $new_rowcount = $::form->{"rowcount"} * 1 + 1;
1243 $::form->{"project_id_${new_rowcount}"} = $::form->{"globalproject_id"};
1245 $::form->language_payment(\%::myconfig);
1247 Common::webdav_folder($::form);
1250 display_row(++$::form->{rowcount});
1253 $::lxdebug->leave_sub;
1257 $::auth->assert('invoice_edit');
1259 if (IS->delete_invoice(\%::myconfig, $::form)) {
1260 # saving the history
1261 if(!exists $::form->{addition}) {
1262 $::form->{snumbers} = 'invnumber' .'_'. $::form->{invnumber};
1263 $::form->{what_done} = 'invoice';
1264 $::form->{addition} = "DELETED";
1265 $::form->save_history;
1267 # /saving the history
1268 $::form->redirect($::locale->text('Invoice deleted!'));
1270 $::form->error($::locale->text('Cannot delete invoice!'));
1275 print update ship_to storno post_payment use_as_new credit_note
1276 delete post order preview post_and_e_mail print_and_post
1279 if ($::form->{"action_$action"}) {
1285 $::form->error($::locale->text('No action defined.'));