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);
48 use SL::DB::Department;
50 use SL::DB::PaymentTerm;
52 require "bin/mozilla/common.pl";
53 require "bin/mozilla/io.pl";
62 $main::lxdebug->enter_sub();
64 my $form = $main::form;
65 my $locale = $main::locale;
67 $main::auth->assert('invoice_edit');
69 $form->{show_details} = $::myconfig{show_form_details};
71 if ($form->{type} eq "credit_note") {
72 $form->{title} = $locale->text('Add Credit Note');
74 if ($form->{storno}) {
75 $form->{title} = $locale->text('Add Storno Credit Note');
78 $form->{title} = $locale->text('Add Sales Invoice');
83 $form->{callback} = "$form->{script}?action=add&type=$form->{type}" unless $form->{callback};
89 $main::lxdebug->leave_sub();
93 $main::lxdebug->enter_sub();
95 my $form = $main::form;
96 my $locale = $main::locale;
98 $main::auth->assert('invoice_edit');
100 $form->{show_details} = $::myconfig{show_form_details};
101 $form->{taxincluded_changed_by_user} = 1;
103 # show history button
104 $form->{javascript} = qq|<script type="text/javascript" src="js/show_history.js"></script>|;
106 my ($language_id, $printer_id);
107 if ($form->{print_and_post}) {
108 $form->{action} = "print";
109 $form->{resubmit} = 1;
110 $language_id = $form->{language_id};
111 $printer_id = $form->{printer_id};
115 if ($form->{type} eq "credit_note") {
116 $form->{title} = $locale->text('Edit Credit Note');
117 $form->{title} = $locale->text('Edit Storno Credit Note') if $form->{storno};
119 $form->{title} = $locale->text('Edit Sales Invoice');
120 $form->{title} = $locale->text('Edit Storno Invoice') if $form->{storno};
124 if ($form->{print_and_post}) {
125 $form->{language_id} = $language_id;
126 $form->{printer_id} = $printer_id;
131 $main::lxdebug->leave_sub();
135 $main::lxdebug->enter_sub();
137 my $form = $main::form;
138 my %myconfig = %main::myconfig;
140 $main::auth->assert('invoice_edit');
142 $form->{vc} = 'customer';
145 $form->create_links("AR", \%myconfig, "customer");
147 my $editing = $form->{id};
149 $form->backup_vars(qw(payment_id language_id taxzone_id salesman_id
150 taxincluded currency cp_id intnotes id shipto_id
153 IS->get_customer(\%myconfig, \%$form);
155 $form->restore_vars(qw(id));
157 IS->retrieve_invoice(\%myconfig, \%$form);
158 $form->restore_vars(qw(payment_id language_id taxzone_id currency intnotes
159 cp_id shipto_id delivery_term_id));
160 $form->restore_vars(qw(taxincluded)) if $form->{id};
161 $form->restore_vars(qw(salesman_id)) if $editing;
163 $form->{employee} = "$form->{employee}--$form->{employee_id}";
166 $form->{forex} = $form->{exchangerate};
167 my $exchangerate = ($form->{exchangerate}) ? $form->{exchangerate} : 1;
169 foreach my $key (keys %{ $form->{AR_links} }) {
170 foreach my $ref (@{ $form->{AR_links}{$key} }) {
171 $form->{"select$key"} .= "<option>$ref->{accno}--$ref->{description}</option>\n";
174 if ($key eq "AR_paid") {
175 next unless $form->{acc_trans}{$key};
176 for my $i (1 .. scalar @{ $form->{acc_trans}{$key} }) {
177 $form->{"AR_paid_$i"} = "$form->{acc_trans}{$key}->[$i-1]->{accno}--$form->{acc_trans}{$key}->[$i-1]->{description}";
179 $form->{"acc_trans_id_$i"} = $form->{acc_trans}{$key}->[$i - 1]->{acc_trans_id};
181 $form->{"paid_$i"} = $form->{acc_trans}{$key}->[$i - 1]->{amount} * -1;
182 $form->{"datepaid_$i"} = $form->{acc_trans}{$key}->[$i - 1]->{transdate};
183 $form->{"gldate_$i"} = $form->{acc_trans}{$key}->[$i - 1]->{gldate};
184 $form->{"exchangerate_$i"} = $form->{acc_trans}{$key}->[$i - 1]->{exchangerate};
185 $form->{"forex_$i"} = $form->{"exchangerate_$i"};
186 $form->{"source_$i"} = $form->{acc_trans}{$key}->[$i - 1]->{source};
187 $form->{"memo_$i"} = $form->{acc_trans}{$key}->[$i - 1]->{memo};
189 $form->{paidaccounts} = $i;
192 $form->{$key} = "$form->{acc_trans}{$key}->[0]->{accno}--$form->{acc_trans}{$key}->[0]->{description}";
196 $form->{paidaccounts} = 1 unless (exists $form->{paidaccounts});
198 $form->{AR} = $form->{AR_1} unless $form->{id};
200 $form->{locked} = ($form->datetonum($form->{invdate}, \%myconfig)
201 <= $form->datetonum($form->{closedto}, \%myconfig));
203 $main::lxdebug->leave_sub();
206 sub prepare_invoice {
207 $main::lxdebug->enter_sub();
209 my $form = $main::form;
210 my %myconfig = %main::myconfig;
212 $main::auth->assert('invoice_edit');
214 if ($form->{type} eq "credit_note") {
215 $form->{type} = "credit_note";
216 $form->{formname} = "credit_note";
217 } elsif ($form->{formname} eq "proforma" ) {
218 $form->{type} = "invoice";
220 $form->{type} = "invoice";
221 $form->{formname} = "invoice";
228 foreach my $ref (@{ $form->{invoice_details} }) {
231 map { $form->{"${_}_$i"} = $ref->{$_} } keys %{$ref};
233 $form->{"discount_$i"} = $form->format_amount(\%myconfig, $form->{"discount_$i"} * 100);
234 my ($dec) = ($form->{"sellprice_$i"} =~ /\.(\d+)/);
236 my $decimalplaces = ($dec > 2) ? $dec : 2;
238 $form->{"sellprice_$i"} = $form->format_amount(\%myconfig, $form->{"sellprice_$i"}, $decimalplaces);
239 (my $dec_qty) = ($form->{"qty_$i"} =~ /\.(\d+)/);
240 $dec_qty = length $dec_qty;
242 $form->{"lastcost_$i"} = $form->format_amount(\%myconfig, $form->{"lastcost_$i"}, $decimalplaces);
244 $form->{"qty_$i"} = $form->format_amount(\%myconfig, $form->{"qty_$i"}, $dec_qty);
246 $form->{"sellprice_pg_$i"} = join ('--', $form->{"sellprice_$i"}, $form->{"pricegroup_id_$i"});
248 $form->{rowcount} = $i;
252 $main::lxdebug->leave_sub();
255 sub setup_is_action_bar {
257 my $change_never = $::instance_conf->get_is_changeable == 0;
258 my $change_on_same_day_only = $::instance_conf->get_is_changeable == 2 && ($form->current_date(\%::myconfig) ne $form->{gldate});
259 my $payments_balanced = ($::form->{oldtotalpaid} == 0);
260 my $has_storno = ($::form->{storno} && !$::form->{storno_id});
262 for my $bar ($::request->layout->get('actionbar')) {
266 submit => [ '#form', { action => "update" } ],
267 disabled => $form->{locked} ? t8('The billing period has already been locked.') : undef,
268 id => 'update_button',
269 checks => [ 'kivi.validate_form' ],
270 accesskey => 'enter',
276 submit => [ '#form', { action => "post" } ],
277 checks => [ 'kivi.validate_form' ],
278 disabled => $form->{locked} ? t8('The billing period has already been locked.')
279 : $form->{storno} ? t8('A canceled invoice cannot be posted.')
280 : ($form->{id} && $change_never) ? t8('Changing invoices has been disabled in the configuration.')
281 : ($form->{id} && $change_on_same_day_only) ? t8('Invoices can only be changed on the day they are posted.')
286 submit => [ '#form', { action => "post_payment" } ],
287 checks => [ 'kivi.validate_form' ],
288 disabled => !$form->{id} ? t8('This invoice has not been posted yet.') : undef,
290 action => [ t8('Mark as paid'),
291 submit => [ '#form', { action => "mark_as_paid" } ],
292 confirm => t8('This will remove the invoice from showing as unpaid even if the unpaid amount does not match the amount. Proceed?'),
293 disabled => !$form->{id} ? t8('This invoice has not been posted yet.') : undef,
294 only_if => $::instance_conf->get_is_show_mark_as_paid,
296 ], # end of combobox "Post"
299 action => [ t8('Storno'),
300 submit => [ '#form', { action => "storno" } ],
301 confirm => t8('Do you really want to cancel this invoice?'),
302 checks => [ 'kivi.validate_form' ],
303 disabled => !$form->{id} ? t8('This invoice has not been posted yet.')
304 : !$payments_balanced ? t8('Cancelling is disallowed. Either undo or balance the current payments until the open amount matches the invoice amount')
307 action => [ t8('Delete'),
308 submit => [ '#form', { action => "delete" } ],
309 confirm => t8('Do you really want to delete this object?'),
310 checks => [ 'kivi.validate_form' ],
311 disabled => !$form->{id} ? t8('This invoice has not been posted yet.')
312 : $form->{locked} ? t8('The billing period has already been locked.')
313 : $change_never ? t8('Changing invoices has been disabled in the configuration.')
314 : $change_on_same_day_only ? t8('Invoices can only be changed on the day they are posted.')
315 : $has_storno ? t8('Can only delete the "Storno zu" part of the cancellation pair.')
318 ], # end of combobox "Storno"
323 action => [ t8('Workflow') ],
326 submit => [ '#form', { action => "use_as_new" } ],
327 checks => [ 'kivi.validate_form' ],
328 disabled => !$form->{id} ? t8('This invoice has not been posted yet.') : undef,
332 submit => [ '#form', { action => "credit_note" } ],
333 checks => [ 'kivi.validate_form' ],
334 disabled => $form->{type} eq "credit_note" ? t8('Credit notes cannot be converted into other credit notes.')
335 : !$form->{id} ? t8('This invoice has not been posted yet.')
340 submit => [ '#form', { action => "order" } ],
341 checks => [ 'kivi.validate_form' ],
342 disabled => !$form->{id} ? t8('This invoice has not been posted yet.') : undef,
344 ], # end of combobox "Workflow"
347 action => [ t8('Export') ],
349 ($form->{id} ? t8('Print') : t8('Preview')),
350 call => [ 'kivi.SalesPurchase.show_print_dialog', $form->{id} ? 'print' : 'preview' ],
351 checks => [ 'kivi.validate_form' ],
352 disabled => !$form->{id} && $form->{locked} ? t8('The billing period has already been locked.') : undef,
354 action => [ t8('Print and Post'),
355 call => [ 'kivi.SalesPurchase.show_print_dialog', $form->{id} ? 'print' : 'print_and_post' ],
356 checks => [ 'kivi.validate_form' ],
357 disabled => $form->{id} ? t8('This invoice has already been posted.') : undef,,
359 action => [ t8('E Mail'),
360 call => [ 'kivi.SalesPurchase.show_email_dialog' ],
361 checks => [ 'kivi.validate_form' ],
362 disabled => !$form->{id} ? t8('This invoice has not been posted yet.') : undef,
364 ], # end of combobox "Export"
367 action => [ t8('more') ],
370 call => [ 'set_history_window', $form->{id} * 1, 'glid' ],
371 disabled => !$form->{id} ? t8('This invoice has not been posted yet.') : undef,
375 call => [ 'follow_up_window' ],
376 disabled => !$form->{id} ? t8('This invoice has not been posted yet.') : undef,
380 call => [ 'kivi.Draft.popup', 'is', 'invoice', $form->{draft_id}, $form->{draft_description} ],
381 disabled => $form->{id} ? t8('This invoice has already been posted.')
382 : $form->{locked} ? t8('The billing period has already been locked.')
385 ], # end of combobox "more"
388 $::request->layout->add_javascripts('kivi.Validator.js');
392 $main::lxdebug->enter_sub();
394 my $form = $main::form;
395 my %myconfig = %main::myconfig;
396 my $locale = $main::locale;
397 my $cgi = $::request->{cgi};
399 $main::auth->assert('invoice_edit');
404 $TMPL_VAR{customer_obj} = SL::DB::Customer->load_cached($form->{customer_id}) if $form->{customer_id};
405 $TMPL_VAR{invoice_obj} = SL::DB::Invoice->load_cached($form->{id}) if $form->{id};
407 my $current_employee = SL::DB::Manager::Employee->current;
408 $form->{employee_id} = $form->{old_employee_id} if $form->{old_employee_id};
409 $form->{salesman_id} = $form->{old_salesman_id} if $form->{old_salesman_id};
410 $form->{employee_id} ||= $current_employee->id;
411 $form->{salesman_id} ||= $current_employee->id;
413 $form->{defaultcurrency} = $form->get_default_currency(\%myconfig);
415 $form->get_lists("taxzones" => ($form->{id} ? "ALL_TAXZONES" : "ALL_ACTIVE_TAXZONES"),
416 "currencies" => "ALL_CURRENCIES",
417 "price_factors" => "ALL_PRICE_FACTORS");
419 $form->{ALL_DEPARTMENTS} = SL::DB::Manager::Department->get_all_sorted;
422 my @old_project_ids = uniq grep { $_ } map { $_ * 1 } ($form->{"globalproject_id"}, map { $form->{"project_id_$_"} } 1..$form->{"rowcount"});
423 my @old_ids_cond = @old_project_ids ? (id => \@old_project_ids) : ();
425 if ($::instance_conf->get_customer_projects_only_in_sales) {
428 customer_id => $::form->{customer_id},
429 billable_customer_id => $::form->{customer_id},
434 and => [ active => 1, @customer_cond ],
438 $TMPL_VAR{ALL_PROJECTS} = SL::DB::Manager::Project->get_all_sorted(query => \@conditions);
439 $form->{ALL_PROJECTS} = $TMPL_VAR{ALL_PROJECTS}; # make projects available for second row drop-down in io.pl
440 $TMPL_VAR{ALL_EMPLOYEES} = SL::DB::Manager::Employee->get_all_sorted(query => [ or => [ id => $::form->{employee_id}, deleted => 0 ] ]);
441 $TMPL_VAR{ALL_SALESMEN} = SL::DB::Manager::Employee->get_all_sorted(query => [ or => [ id => $::form->{salesman_id}, deleted => 0 ] ]);
442 $TMPL_VAR{ALL_SHIPTO} = SL::DB::Manager::Shipto->get_all_sorted(query => [
443 or => [ trans_id => $::form->{"$::form->{vc}_id"} * 1, and => [ shipto_id => $::form->{shipto_id} * 1, trans_id => undef ] ]
445 $TMPL_VAR{ALL_CONTACTS} = SL::DB::Manager::Contact->get_all_sorted(query => [
447 cp_cv_id => $::form->{"$::form->{vc}_id"} * 1,
450 cp_id => $::form->{cp_id} * 1
455 # currencies and exchangerate
456 my @values = map { $_ } @{ $form->{ALL_CURRENCIES} };
457 my %labels = map { $_ => $_ } @{ $form->{ALL_CURRENCIES} };
458 $form->{currency} = $form->{defaultcurrency} unless $form->{currency};
459 $form->{show_exchangerate} = $form->{currency} ne $form->{defaultcurrency};
460 $TMPL_VAR{currencies} = NTI($::request->{cgi}->popup_menu('-name' => 'currency', '-default' => $form->{"currency"},
461 '-values' => \@values, '-labels' => \%labels,
462 '-onchange' => "document.getElementById('update_button').click();"
463 )) if scalar @values;
464 push @custom_hiddens, "forex";
465 push @custom_hiddens, "exchangerate" if $form->{forex};
467 $TMPL_VAR{creditwarning} = ($form->{creditlimit} != 0) && ($form->{creditremaining} < 0) && !$form->{update};
468 $TMPL_VAR{is_credit_remaining_negativ} = $form->{creditremaining} =~ /-/;
470 # set option selected
471 foreach my $item (qw(AR)) {
472 $form->{"select$item"} =~ s/ selected//;
473 $form->{"select$item"} =~ s/option>\Q$form->{$item}\E/option selected>$form->{$item}/;
476 $TMPL_VAR{is_type_credit_note} = $form->{type} eq "credit_note";
477 $TMPL_VAR{is_format_html} = $form->{format} eq 'html';
478 $TMPL_VAR{dateformat} = $myconfig{dateformat};
479 $TMPL_VAR{numberformat} = $myconfig{numberformat};
482 $TMPL_VAR{HIDDENS} = [qw(
483 id type queued printed emailed vc discount
484 title creditlimit creditremaining tradediscount business closedto locked shipped storno storno_id
485 max_dunning_level dunning_amount dunning_description
486 taxaccounts cursor_fokus
487 convert_from_do_ids convert_from_oe_ids convert_from_ar_ids useasnew
491 map { $_.'_rate', $_.'_description', $_.'_taxnumber' } split / /, $form->{taxaccounts}];
493 $::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));
495 $TMPL_VAR{payment_terms_obj} = get_payment_terms_for_invoice();
496 $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};
498 setup_is_action_bar();
502 print $form->parse_html_template("is/form_header", \%TMPL_VAR);
504 $main::lxdebug->leave_sub();
508 my @fields = qw(acc_trans_id gldate datepaid source memo paid AR_paid);
510 grep { $_->{paid} != 0 }
513 +{ map { ($_ => delete($::form->{"${_}_${idx}"})) } @fields }
514 } (1..$::form->{paidaccounts});
516 @payments = sort_by { DateTime->from_kivitendo($_->{datepaid}) } @payments;
518 $::form->{paidaccounts} = max scalar(@payments), 1;
520 foreach my $idx (1 .. scalar(@payments)) {
521 my $payment = $payments[$idx - 1];
522 $::form->{"${_}_${idx}"} = $payment->{$_} for @fields;
527 $main::lxdebug->enter_sub();
529 my $form = $main::form;
530 my %myconfig = %main::myconfig;
531 my $locale = $main::locale;
533 $main::auth->assert('invoice_edit');
535 $form->{invtotal} = $form->{invsubtotal};
538 $form->{rows} = max 2,
539 $form->numtextrows($form->{notes}, 26, 8),
540 $form->numtextrows($form->{intnotes}, 35, 8);
543 # tax, total and subtotal calculations
544 my ($tax, $subtotal);
545 $form->{taxaccounts_array} = [ split(/ /, $form->{taxaccounts}) ];
547 if( $form->{customer_id} && !$form->{taxincluded_changed_by_user} ) {
548 my $customer = SL::DB::Customer->load_cached($form->{customer_id});
549 $form->{taxincluded} = defined($customer->taxincluded_checked) ? $customer->taxincluded_checked : $myconfig{taxincluded_checked};
552 foreach my $item (@{ $form->{taxaccounts_array} }) {
553 if ($form->{"${item}_base"}) {
554 if ($form->{taxincluded}) {
555 $form->{"${item}_total"} = $form->round_amount( ($form->{"${item}_base"} * $form->{"${item}_rate"}
556 / (1 + $form->{"${item}_rate"})), 2);
557 $form->{"${item}_netto"} = $form->round_amount( ($form->{"${item}_base"} - $form->{"${item}_total"}), 2);
559 $form->{"${item}_total"} = $form->round_amount( $form->{"${item}_base"} * $form->{"${item}_rate"}, 2);
560 $form->{invtotal} += $form->{"${item}_total"};
565 my $grossamount = $form->{invtotal};
566 $form->{invtotal} = $form->round_amount( $form->{invtotal}, 2, 1 );
567 $form->{rounding} = $form->round_amount(
568 $form->{invtotal} - $form->round_amount($grossamount, 2),
574 $form->{follow_ups} = FU->follow_ups('trans_id' => $form->{id}, 'not_done' => 1) || [];
575 $form->{follow_ups_unfinished} = ( sum map { $_->{due} * 1 } @{ $form->{follow_ups} } ) || 0;
582 $form->{paidaccounts}++ if ($form->{"paid_$form->{paidaccounts}"});
583 $form->{paid_indices} = [ 1 .. $form->{paidaccounts} ];
585 # Standard Konto für Umlaufvermögen
586 my $accno_arap = IS->get_standard_accno_current_assets(\%myconfig, \%$form);
588 for my $i (1 .. $form->{paidaccounts}) {
589 $form->{"changeable_$i"} = 1;
590 if (SL::DB::Default->get->payments_changeable == 0) {
592 $form->{"changeable_$i"} = ($form->{"acc_trans_id_$i"})? 0 : 1;
593 } elsif (SL::DB::Default->get->payments_changeable == 2) {
595 $form->{"changeable_$i"} = (($form->{"gldate_$i"} eq '') ||
596 ($form->current_date(\%myconfig) eq $form->{"gldate_$i"}));
599 #deaktivieren von gebuchten Zahlungen ausserhalb der Bücherkontrolle, vorher prüfen ob heute eingegeben
600 if ($form->date_closed($form->{"gldate_$i"})) {
601 $form->{"changeable_$i"} = 0;
604 $form->{"selectAR_paid_$i"} = $form->{selectAR_paid};
605 if (!$form->{"AR_paid_$i"}) {
606 $form->{"selectAR_paid_$i"} =~ s/option>$accno_arap--(.*?)</option selected>$accno_arap--$1</;
608 $form->{"selectAR_paid_$i"} =~ s/option>\Q$form->{"AR_paid_$i"}\E/option selected>$form->{"AR_paid_$i"}/;
611 $totalpaid += $form->{"paid_$i"};
614 $form->{oldinvtotal} = $form->{invtotal};
616 $form->{ALL_DELIVERY_TERMS} = SL::DB::Manager::DeliveryTerm->get_all_sorted();
618 print $form->parse_html_template('is/form_footer', {
619 is_type_credit_note => ($form->{type} eq "credit_note"),
620 totalpaid => $totalpaid,
621 paid_missing => $form->{invtotal} - $totalpaid,
622 print_options => setup_sales_purchase_print_options(),
623 show_storno => $form->{id} && !$form->{storno} && !IS->has_storno(\%myconfig, $form, "ar") && !$totalpaid,
624 show_delete => ($::instance_conf->get_is_changeable == 2)
625 ? ($form->current_date(\%myconfig) eq $form->{gldate})
626 : ($::instance_conf->get_is_changeable == 1),
627 today => DateTime->today,
628 vc_obj => $form->{customer_id} ? SL::DB::Customer->load_cached($form->{customer_id}) : undef,
630 ##print $form->parse_html_template('is/_payments'); # parser
631 ##print $form->parse_html_template('webdav/_list'); # parser
633 $main::lxdebug->leave_sub();
637 $::auth->assert('invoice_edit');
639 SL::DB::Invoice->new(id => $::form->{id})->load->mark_as_paid;
641 $::form->redirect($::locale->text("Marked as paid"));
645 # unless no lazy implementation of save draft without invdate
646 # set the current date like in version <= 3.4.1
647 $::form->{invdate} = DateTime->today->to_lxoffice;
652 $main::lxdebug->enter_sub();
654 my $form = $main::form;
655 my %myconfig = %main::myconfig;
657 $main::auth->assert('invoice_edit');
659 my ($recursive_call) = @_;
661 $form->{print_and_post} = 0 if $form->{second_run};
662 my $taxincluded = $form->{taxincluded} ? "checked" : '';
665 if (($form->{previous_customer_id} || $form->{customer_id}) != $form->{customer_id}) {
666 $::form->{salesman_id} = SL::DB::Manager::Employee->current->id if exists $::form->{salesman_id};
668 IS->get_customer(\%myconfig, $form);
671 $form->{taxincluded} ||= $taxincluded;
673 if (!$form->{forex}) { # read exchangerate from input field (not hidden)
674 $form->{exchangerate} = $form->parse_amount(\%myconfig, $form->{exchangerate}) unless $recursive_call;
676 $form->{forex} = $form->check_exchangerate(\%myconfig, $form->{currency}, $form->{invdate}, 'buy');
677 $form->{exchangerate} = $form->{forex} if $form->{forex};
679 for my $i (1 .. $form->{paidaccounts}) {
680 next unless $form->{"paid_$i"};
681 map { $form->{"${_}_$i"} = $form->parse_amount(\%myconfig, $form->{"${_}_$i"}) } qw(paid exchangerate);
682 if (!$form->{"forex_$i"}) { #read exchangerate from input field (not hidden)
683 $form->{exchangerate} = $form->{"exchangerate_$i"};
685 $form->{"forex_$i"} = $form->check_exchangerate(\%myconfig, $form->{currency}, $form->{"datepaid_$i"}, 'buy');
686 $form->{"exchangerate_$i"} = $form->{"forex_$i"} if $form->{"forex_$i"};
689 my $i = $form->{rowcount};
690 my $exchangerate = $form->{exchangerate} || 1;
692 # if last row empty, check the form otherwise retrieve new item
693 if ( ($form->{"partnumber_$i"} eq "")
694 && ($form->{"description_$i"} eq "")
695 && ($form->{"partsgroup_$i"} eq "")) {
697 $form->{creditremaining} += ($form->{oldinvtotal} - $form->{oldtotalpaid});
702 IS->retrieve_item(\%myconfig, \%$form);
704 my $rows = scalar @{ $form->{item_list} };
706 $form->{"discount_$i"} = $form->parse_amount(\%myconfig, $form->{"discount_$i"}) / 100.0;
707 $form->{"discount_$i"} ||= $form->{customer_discount};
710 $form->{"qty_$i"} = $form->parse_amount(\%myconfig, $form->{"qty_$i"});
711 if( !$form->{"qty_$i"} ) {
712 $form->{"qty_$i"} = 1;
717 select_item(mode => 'IS', pre_entered_qty => $form->{"qty_$i"});
718 $::dispatcher->end_request;
722 my $sellprice = $form->parse_amount(\%myconfig, $form->{"sellprice_$i"});
724 map { $form->{item_list}[$i]{$_} =~ s/\"/"/g } qw(partnumber description unit);
725 map { $form->{"${_}_$i"} = $form->{item_list}[0]{$_} } keys %{ $form->{item_list}[0] };
727 $form->{payment_id} = $form->{"part_payment_id_$i"} if $form->{"part_payment_id_$i"} ne "";
728 $form->{"discount_$i"} = 0 if $form->{"not_discountable_$i"};
730 $form->{"marge_price_factor_$i"} = $form->{item_list}->[0]->{price_factor};
732 ($sellprice || $form->{"sellprice_$i"}) =~ /\.(\d+)/;
733 my $decimalplaces = max 2, length $1;
736 $form->{"sellprice_$i"} = $sellprice;
738 my $record = _make_record();
739 my $price_source = SL::PriceSource->new(record_item => $record->items->[$i-1], record => $record);
740 my $best_price = $price_source->best_price;
741 my $best_discount = $price_source->best_discount;
744 $::form->{"sellprice_$i"} = $best_price->price;
745 $::form->{"active_price_source_$i"} = $best_price->source;
747 if ($best_discount) {
748 $::form->{"discount_$i"} = $best_discount->discount;
749 $::form->{"active_discount_source_$i"} = $best_discount->source;
752 # if there is an exchange rate adjust sellprice
753 $form->{"sellprice_$i"} /= $exchangerate;
756 $form->{"listprice_$i"} /= $exchangerate;
758 my $amount = $form->{"sellprice_$i"} * $form->{"qty_$i"} * (1 - $form->{"discount_$i"});
759 map { $form->{"${_}_base"} = 0 } split / /, $form->{taxaccounts};
760 map { $form->{"${_}_base"} += $amount } split / /, $form->{"taxaccounts_$i"};
761 map { $amount += ($form->{"${_}_base"} * $form->{"${_}_rate"}) } split / /, $form->{"taxaccounts_$i"} if !$form->{taxincluded};
763 $form->{creditremaining} -= $amount;
765 map { $form->{"${_}_$i"} = $form->format_amount(\%myconfig, $form->{"${_}_$i"}, $decimalplaces) } qw(sellprice lastcost);
767 $form->{"qty_$i"} = $form->format_amount(\%myconfig, $form->{"qty_$i"});
768 $form->{"discount_$i"} = $form->format_amount(\%myconfig, $form->{"discount_$i"} * 100.0);
775 # ok, so this is a new part
776 # ask if it is a part or service item
778 if ( $form->{"partsgroup_$i"}
779 && ($form->{"partnumber_$i" } eq "")
780 && ($form->{"description_$i"} eq "")) {
782 $form->{"discount_$i"} = "";
786 $form->{"id_$i"} = 0;
791 $main::lxdebug->leave_sub();
795 $main::lxdebug->enter_sub();
797 my $form = $main::form;
798 my %myconfig = %main::myconfig;
799 my $locale = $main::locale;
801 $main::auth->assert('invoice_edit');
803 $form->mtime_ischanged('ar') ;
804 my $invdate = $form->datetonum($form->{invdate}, \%myconfig);
806 $form->{defaultcurrency} = $form->get_default_currency(\%myconfig);
807 for my $i (1 .. $form->{paidaccounts}) {
808 if ($form->{"paid_$i"}) {
809 my $datepaid = $form->datetonum($form->{"datepaid_$i"}, \%myconfig);
811 $form->isblank("datepaid_$i", $locale->text('Payment date missing!'));
814 if ($form->{currency} ne $form->{defaultcurrency}) {
815 $form->{"exchangerate_$i"} = $form->{exchangerate}
816 if ($invdate == $datepaid);
817 $form->isblank("exchangerate_$i",
818 $locale->text('Exchangerate for payment missing!'));
820 $form->error($locale->text('Cannot post transaction above the maximum future booking date!'))
821 if ($form->date_max_future($form->{"datepaid_$i"}, \%myconfig));
823 #Zusätzlich noch das Buchungsdatum in die Bücherkontrolle einbeziehen
824 # (Dient zur Prüfung ob ZE oder ZA geprüft werden soll)
825 $form->error($locale->text('Cannot post payment for a closed period!'))
826 if ($form->date_closed($form->{"datepaid_$i"}) && !$form->date_closed($form->{"gldate_$i"}, \%myconfig));
830 ($form->{AR}) = split /--/, $form->{AR};
831 ($form->{AR_paid}) = split /--/, $form->{AR_paid};
833 if ( IS->post_payment(\%myconfig, \%$form) ) {
834 $form->{snumbers} = qq|invnumber_| . $form->{invnumber};
835 $form->{what_done} = 'invoice';
836 $form->{addition} = "PAYMENT POSTED";
838 $form->redirect($locale->text('Payment posted!'))
840 $form->error($locale->text('Cannot post payment!'));
843 $main::lxdebug->leave_sub();
847 $main::lxdebug->enter_sub();
849 my $form = $main::form;
850 my %myconfig = %main::myconfig;
851 my $locale = $main::locale;
853 $main::auth->assert('invoice_edit');
854 $form->mtime_ischanged('ar');
856 $form->{defaultcurrency} = $form->get_default_currency(\%myconfig);
857 $form->isblank("invdate", $locale->text('Invoice Date missing!'));
858 $form->isblank("customer_id", $locale->text('Customer missing!'));
859 $form->error($locale->text('Cannot post invoice for a closed period!'))
860 if ($form->date_closed($form->{"invdate"}, \%myconfig));
862 $form->{invnumber} =~ s/^\s*//g;
863 $form->{invnumber} =~ s/\s*$//g;
865 # if oldcustomer ne customer redo form
866 if (($form->{previous_customer_id} || $form->{customer_id}) != $form->{customer_id}) {
868 $::dispatcher->end_request;
871 if ($myconfig{mandatory_departments} && !$form->{department_id}) {
872 $form->{saved_message} = $::locale->text('You have to specify a department.');
877 if ($form->{second_run}) {
878 $form->{print_and_post} = 0;
881 remove_emptied_rows();
884 my $closedto = $form->datetonum($form->{closedto}, \%myconfig);
885 my $invdate = $form->datetonum($form->{invdate}, \%myconfig);
887 $form->error($locale->text('Cannot post transaction above the maximum future booking date!'))
888 if ($form->date_max_future($invdate, \%myconfig));
889 $form->error($locale->text('Cannot post invoice for a closed period!'))
890 if ($invdate <= $closedto);
892 $form->isblank("exchangerate", $locale->text('Exchangerate missing!'))
893 if ($form->{currency} ne $form->{defaultcurrency});
895 for my $i (1 .. $form->{paidaccounts}) {
896 if ($form->parse_amount(\%myconfig, $form->{"paid_$i"})) {
897 my $datepaid = $form->datetonum($form->{"datepaid_$i"}, \%myconfig);
899 $form->isblank("datepaid_$i", $locale->text('Payment date missing!'));
901 $form->error($locale->text('Cannot post transaction above the maximum future booking date!'))
902 if ($form->date_max_future($form->{"datepaid_$i"}, \%myconfig));
904 #Zusätzlich noch das Buchungsdatum in die Bücherkontrolle einbeziehen
905 # (Dient zur Prüfung ob ZE oder ZA geprüft werden soll)
906 $form->error($locale->text('Cannot post payment for a closed period!'))
907 if ($form->date_closed($form->{"datepaid_$i"}) && !$form->date_closed($form->{"gldate_$i"}, \%myconfig));
909 if ($form->{currency} ne $form->{defaultcurrency}) {
910 $form->{"exchangerate_$i"} = $form->{exchangerate}
911 if ($invdate == $datepaid);
912 $form->isblank("exchangerate_$i",
913 $locale->text('Exchangerate for payment missing!'));
918 ($form->{AR}) = split /--/, $form->{AR};
919 ($form->{AR_paid}) = split /--/, $form->{AR_paid};
920 $form->{storno} ||= 0;
922 $form->{label} = $form->{type} eq 'credit_note' ? $locale->text('Credit Note') : $locale->text('Invoice');
924 $form->{id} = 0 if $form->{postasnew};
926 # get new invnumber in sequence if no invnumber is given or if posasnew was requested
927 if ($form->{postasnew}) {
928 if ($form->{type} eq "credit_note") {
929 undef($form->{cnnumber});
931 undef($form->{invnumber});
937 my $terms = get_payment_terms_for_invoice();
938 $form->{duedate} = $terms->calc_date(reference_date => $form->{invdate}, due_date => $form->{duedate})->to_kivitendo if $terms;
940 # If transfer_out is requested, get rose db handle and do post and
941 # transfer out in one transaction. Otherwise just post the invoice.
942 if ($::instance_conf->get_is_transfer_out && $form->{type} ne 'credit_note' && !$form->{storno}) {
943 require SL::DB::Inventory;
944 my $rose_db = SL::DB::Inventory->new->db;
947 if (!$rose_db->with_transaction(sub {
949 if (!IS->post_invoice(\%myconfig, \%$form, $rose_db->dbh)) {
950 push @errors, $locale->text('Cannot post invoice!');
953 my $err = IS->transfer_out(\%$form, $rose_db->dbh);
955 push @errors, @{ $err };
956 die 'transfer error';
961 push @errors, $EVAL_ERROR;
962 $form->error($locale->text('Cannot post invoice and/or transfer out! Error message:') . "\n" . join("\n", @errors));
967 push @errors, $rose_db->error;
968 $form->error($locale->text('Cannot post invoice and/or transfer out! Error message:') . "\n" . join("\n", @errors));
971 if (!IS->post_invoice(\%myconfig, \%$form)) {
972 $form->error($locale->text('Cannot post invoice!'));
976 if(!exists $form->{addition}) {
977 $form->{snumbers} = 'invnumber' .'_'. $form->{invnumber}; # ($form->{type} eq 'credit_note' ? 'cnnumber' : 'invnumber') .'_'. $form->{invnumber};
978 $form->{what_done} = 'invoice';
979 $form->{addition} = $form->{print_and_post} ? "PRINTED AND POSTED" :
980 $form->{storno} ? "STORNO" :
985 if (!$form->{no_redirect_after_post}) {
986 $form->{action} = 'edit';
987 $form->{script} = 'is.pl';
988 $form->{callback} = build_std_url(qw(action edit id callback saved_message));
989 $form->redirect($form->{label} . " $form->{invnumber} " . $locale->text('posted!'));
992 $main::lxdebug->leave_sub();
996 $main::lxdebug->enter_sub();
998 my $form = $main::form;
1000 $main::auth->assert('invoice_edit');
1002 my $old_form = Form->new;
1003 $form->{no_redirect_after_post} = 1;
1004 $form->{print_and_post} = 1;
1008 $main::lxdebug->leave_sub();
1013 $main::lxdebug->enter_sub();
1015 my $form = $main::form;
1016 my %myconfig = %main::myconfig;
1018 $main::auth->assert('invoice_edit');
1020 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)};
1021 $form->{rowcount}--;
1022 $form->{paidaccounts} = 1;
1023 $form->{invdate} = $form->current_date(\%myconfig);
1024 my $terms = get_payment_terms_for_invoice();
1025 $form->{duedate} = $terms ? $terms->calc_date(reference_date => $form->{invdate})->to_kivitendo : $form->{invdate};
1026 $form->{employee_id} = SL::DB::Manager::Employee->current->id;
1027 $form->{forex} = $form->check_exchangerate(\%myconfig, $form->{currency}, $form->{invdate}, 'buy');
1028 $form->{exchangerate} = $form->{forex} if $form->{forex};
1030 $form->{"converted_from_invoice_id_$_"} = delete $form->{"invoice_id_$_"} for 1 .. $form->{"rowcount"};
1032 $form->{useasnew} = 1;
1035 $main::lxdebug->leave_sub();
1039 $main::lxdebug->enter_sub();
1041 my $form = $main::form;
1042 my %myconfig = %main::myconfig;
1043 my $locale = $main::locale;
1045 $main::auth->assert('invoice_edit');
1047 if ($form->{storno}) {
1048 $form->error($locale->text('Cannot storno storno invoice!'));
1051 if (IS->has_storno(\%myconfig, $form, "ar")) {
1052 $form->error($locale->text("Invoice has already been storno'd!"));
1054 if ($form->datetonum($form->{invdate}, \%myconfig) <= $form->datetonum($form->{closedto}, \%myconfig)) {
1055 $form->error($locale->text('Cannot storno invoice for a closed period!'));
1058 # save the history of invoice being stornoed
1059 $form->{snumbers} = qq|invnumber_| . $form->{invnumber};
1060 $form->{what_done} = 'invoice';
1061 $form->{addition} = "STORNO";
1062 $form->save_history;
1064 map({ my $key = $_; delete($form->{$key}) unless (grep({ $key eq $_ } qw(id login password type))); } keys(%{ $form }));
1070 # Payments must not be recorded for the new storno invoice.
1071 $form->{paidaccounts} = 0;
1072 map { my $key = $_; delete $form->{$key} if grep { $key =~ /^$_/ } qw(datepaid_ gldate_ acc_trans_id_ source_ memo_ paid_ exchangerate_ AR_paid_) } keys %{ $form };
1074 # record link invoice to storno
1075 $form->{convert_from_ar_ids} = $form->{id};
1076 $form->{storno_id} = $form->{id};
1077 $form->{storno} = 1;
1079 $form->{invnumber} = "Storno zu " . $form->{invnumber};
1080 $form->{invdate} = DateTime->today->to_lxoffice;
1081 $form->{rowcount}++;
1082 # set new ids for storno invoice
1083 # set new persistent ids for storno invoice items
1084 $form->{"converted_from_invoice_id_$_"} = delete $form->{"invoice_id_$_"} for 1 .. $form->{"rowcount"};
1087 $main::lxdebug->leave_sub();
1091 $main::lxdebug->enter_sub();
1093 my $form = $main::form;
1095 $main::auth->assert('invoice_edit');
1097 $form->{preview} = 1;
1098 my $old_form = Form->new;
1099 for (keys %$form) { $old_form->{$_} = $form->{$_} }
1101 &print_form($old_form);
1102 $main::lxdebug->leave_sub();
1107 $main::lxdebug->enter_sub();
1109 my $form = $main::form;
1110 my %myconfig = %main::myconfig;
1111 my $locale = $main::locale;
1113 $main::auth->assert('invoice_edit');
1115 $form->{transdate} = $form->{invdate} = $form->current_date(\%myconfig);
1117 $form->current_date(\%myconfig, $form->{invdate}, $form->{terms} * 1);
1119 $form->{convert_from_ar_ids} = $form->{id};
1121 $form->{rowcount}--;
1124 $form->{title} = $locale->text('Add Credit Note');
1125 $form->{script} = 'is.pl';
1127 # Bei Gutschriften bezug zur Rechnungsnummer
1128 $form->{invnumber_for_credit_note} = $form->{invnumber};
1129 # bo creates the id, reset it
1130 map { delete $form->{$_} }
1131 qw(id invnumber subject message cc bcc printed emailed queued);
1132 $form->{ $form->{vc} } =~ s/--.*//g;
1133 $form->{type} = "credit_note";
1136 map { $form->{"select$_"} = "" } ($form->{vc}, 'currency');
1138 # map { $form->{$_} = $form->parse_amount(\%myconfig, $form->{$_}) }
1139 # qw(creditlimit creditremaining);
1141 # set new persistent ids for credit note and link previous invoice id
1142 $form->{"converted_from_invoice_id_$_"} = delete $form->{"invoice_id_$_"} for 1 .. $form->{"rowcount"};
1144 my $currency = $form->{currency};
1147 $form->{currency} = $currency;
1148 $form->{forex} = $form->check_exchangerate( \%myconfig, $form->{currency}, $form->{invdate}, 'buy');
1149 $form->{exchangerate} = $form->{forex} || '';
1151 $form->{creditremaining} -= ($form->{oldinvtotal} - $form->{ordtotal});
1153 # bei Gutschriften werden Zahlungseingänge aus Rechnung nicht übernommen
1154 for my $i (1 .. $form->{paidaccounts}) {
1155 delete $form->{"paid_$i"};
1156 delete $form->{"source_$i"};
1157 delete $form->{"memo_$i"};
1158 delete $form->{"datepaid_$i"};
1159 delete $form->{"gldate_$i"};
1160 delete $form->{"acc_trans_id_$i"};
1161 delete $form->{"AR_paid_$i"};
1163 $form->{paidaccounts} = 1;
1170 $main::lxdebug->leave_sub();
1174 $::lxdebug->enter_sub;
1176 $::auth->assert('invoice_edit');
1180 my $new_rowcount = $::form->{"rowcount"} * 1 + 1;
1181 $::form->{"project_id_${new_rowcount}"} = $::form->{"globalproject_id"};
1183 $::form->language_payment(\%::myconfig);
1185 Common::webdav_folder($::form);
1188 display_row(++$::form->{rowcount});
1191 $::lxdebug->leave_sub;
1195 $::auth->assert('invoice_edit');
1197 if (IS->delete_invoice(\%::myconfig, $::form)) {
1198 # saving the history
1199 if(!exists $::form->{addition}) {
1200 $::form->{snumbers} = 'invnumber' .'_'. $::form->{invnumber};
1201 $::form->{what_done} = 'invoice';
1202 $::form->{addition} = "DELETED";
1203 $::form->save_history;
1205 # /saving the history
1206 $::form->redirect($::locale->text('Invoice deleted!'));
1208 $::form->error($::locale->text('Cannot delete invoice!'));
1213 print update ship_to storno post_payment use_as_new credit_note
1214 delete post order preview post_and_e_mail print_and_post
1217 if ($::form->{"action_$action"}) {
1223 $::form->error($::locale->text('No action defined.'));