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});
260 for my $bar ($::request->layout->get('actionbar')) {
264 submit => [ '#form', { action => "update" } ],
265 disabled => $form->{locked} ? t8('The billing period has already been locked.') : undef,
266 id => 'update_button',
267 checks => [ 'kivi.validate_form' ],
268 accesskey => 'enter',
274 submit => [ '#form', { action => "post" } ],
275 checks => [ 'kivi.validate_form' ],
276 disabled => $form->{locked} ? t8('The billing period has already been locked.')
277 : $form->{storno} ? t8('A canceled invoice cannot be posted.')
278 : ($form->{id} && $change_never) ? t8('Changing invoices has been disabled in the configuration.')
279 : ($form->{id} && $change_on_same_day_only) ? t8('Invoices can only be changed on the day they are posted.')
284 submit => [ '#form', { action => "post_payment" } ],
285 checks => [ 'kivi.validate_form' ],
286 disabled => !$form->{id} ? t8('This invoice has not been posted yet.') : undef,
288 action => [ t8('Mark as paid'),
289 submit => [ '#form', { action => "mark_as_paid" } ],
290 confirm => t8('This will remove the invoice from showing as unpaid even if the unpaid amount does not match the amount. Proceed?'),
291 disabled => !$form->{id} ? t8('This invoice has not been posted yet.') : undef,
292 only_if => $::instance_conf->get_is_show_mark_as_paid,
294 ], # end of combobox "Post"
297 action => [ t8('Storno'),
298 submit => [ '#form', { action => "storno" } ],
299 confirm => t8('Do you really want to cancel this invoice?'),
300 checks => [ 'kivi.validate_form' ],
301 disabled => !$form->{id} ? t8('This invoice has not been posted yet.') : undef,
303 action => [ t8('Delete'),
304 submit => [ '#form', { action => "delete" } ],
305 confirm => t8('Do you really want to delete this object?'),
306 checks => [ 'kivi.validate_form' ],
307 disabled => !$form->{id} ? t8('This invoice has not been posted yet.')
308 : $form->{locked} ? t8('The billing period has already been locked.')
309 : $change_never ? t8('Changing invoices has been disabled in the configuration.')
310 : $change_on_same_day_only ? t8('Invoices can only be changed on the day they are posted.')
313 ], # end of combobox "Storno"
318 action => [ t8('Workflow') ],
321 submit => [ '#form', { action => "use_as_new" } ],
322 checks => [ 'kivi.validate_form' ],
323 disabled => !$form->{id} ? t8('This invoice has not been posted yet.') : undef,
327 submit => [ '#form', { action => "credit_note" } ],
328 checks => [ 'kivi.validate_form' ],
329 disabled => $form->{type} eq "credit_note" ? t8('Credit notes cannot be converted into other credit notes.')
330 : !$form->{id} ? t8('This invoice has not been posted yet.')
335 submit => [ '#form', { action => "order" } ],
336 checks => [ 'kivi.validate_form' ],
337 disabled => !$form->{id} ? t8('This invoice has not been posted yet.') : undef,
339 ], # end of combobox "Workflow"
342 action => [ t8('Export') ],
344 ($form->{id} ? t8('Print') : t8('Preview')),
345 call => [ 'kivi.SalesPurchase.show_print_dialog', $form->{id} ? 'print' : 'preview' ],
346 checks => [ 'kivi.validate_form' ],
347 disabled => !$form->{id} && $form->{locked} ? t8('The billing period has already been locked.') : undef,
349 action => [ t8('Print and Post'),
350 call => [ 'kivi.SalesPurchase.show_print_dialog', $form->{id} ? 'print' : 'print_and_post' ],
351 checks => [ 'kivi.validate_form' ],
352 disabled => $form->{id} ? t8('This invoice has already been posted.') : undef,,
354 action => [ t8('E Mail'),
355 call => [ 'kivi.SalesPurchase.show_email_dialog' ],
356 checks => [ 'kivi.validate_form' ],
357 disabled => !$form->{id} ? t8('This invoice has not been posted yet.') : undef,
359 ], # end of combobox "Export"
362 action => [ t8('more') ],
365 call => [ 'set_history_window', $form->{id} * 1, 'glid' ],
366 disabled => !$form->{id} ? t8('This invoice has not been posted yet.') : undef,
370 call => [ 'follow_up_window' ],
371 disabled => !$form->{id} ? t8('This invoice has not been posted yet.') : undef,
375 call => [ 'kivi.Draft.popup', 'is', 'invoice', $form->{draft_id}, $form->{draft_description} ],
376 disabled => $form->{id} ? t8('This invoice has already been posted.')
377 : $form->{locked} ? t8('The billing period has already been locked.')
380 ], # end of combobox "more"
383 $::request->layout->add_javascripts('kivi.Validator.js');
387 $main::lxdebug->enter_sub();
389 my $form = $main::form;
390 my %myconfig = %main::myconfig;
391 my $locale = $main::locale;
392 my $cgi = $::request->{cgi};
394 $main::auth->assert('invoice_edit');
399 $TMPL_VAR{customer_obj} = SL::DB::Customer->load_cached($form->{customer_id}) if $form->{customer_id};
400 $TMPL_VAR{invoice_obj} = SL::DB::Invoice->load_cached($form->{id}) if $form->{id};
402 my $current_employee = SL::DB::Manager::Employee->current;
403 $form->{employee_id} = $form->{old_employee_id} if $form->{old_employee_id};
404 $form->{salesman_id} = $form->{old_salesman_id} if $form->{old_salesman_id};
405 $form->{employee_id} ||= $current_employee->id;
406 $form->{salesman_id} ||= $current_employee->id;
408 $form->{defaultcurrency} = $form->get_default_currency(\%myconfig);
410 $form->get_lists("taxzones" => ($form->{id} ? "ALL_TAXZONES" : "ALL_ACTIVE_TAXZONES"),
411 "currencies" => "ALL_CURRENCIES",
412 "price_factors" => "ALL_PRICE_FACTORS");
414 $form->{ALL_DEPARTMENTS} = SL::DB::Manager::Department->get_all_sorted;
417 my @old_project_ids = uniq grep { $_ } map { $_ * 1 } ($form->{"globalproject_id"}, map { $form->{"project_id_$_"} } 1..$form->{"rowcount"});
418 my @old_ids_cond = @old_project_ids ? (id => \@old_project_ids) : ();
420 if ($::instance_conf->get_customer_projects_only_in_sales) {
423 customer_id => $::form->{customer_id},
424 billable_customer_id => $::form->{customer_id},
429 and => [ active => 1, @customer_cond ],
433 $TMPL_VAR{ALL_PROJECTS} = SL::DB::Manager::Project->get_all_sorted(query => \@conditions);
434 $form->{ALL_PROJECTS} = $TMPL_VAR{ALL_PROJECTS}; # make projects available for second row drop-down in io.pl
435 $TMPL_VAR{ALL_EMPLOYEES} = SL::DB::Manager::Employee->get_all_sorted(query => [ or => [ id => $::form->{employee_id}, deleted => 0 ] ]);
436 $TMPL_VAR{ALL_SALESMEN} = SL::DB::Manager::Employee->get_all_sorted(query => [ or => [ id => $::form->{salesman_id}, deleted => 0 ] ]);
437 $TMPL_VAR{ALL_SHIPTO} = SL::DB::Manager::Shipto->get_all_sorted(query => [
438 or => [ trans_id => $::form->{"$::form->{vc}_id"} * 1, and => [ shipto_id => $::form->{shipto_id} * 1, trans_id => undef ] ]
440 $TMPL_VAR{ALL_CONTACTS} = SL::DB::Manager::Contact->get_all_sorted(query => [
442 cp_cv_id => $::form->{"$::form->{vc}_id"} * 1,
445 cp_id => $::form->{cp_id} * 1
450 # currencies and exchangerate
451 my @values = map { $_ } @{ $form->{ALL_CURRENCIES} };
452 my %labels = map { $_ => $_ } @{ $form->{ALL_CURRENCIES} };
453 $form->{currency} = $form->{defaultcurrency} unless $form->{currency};
454 $form->{show_exchangerate} = $form->{currency} ne $form->{defaultcurrency};
455 $TMPL_VAR{currencies} = NTI($::request->{cgi}->popup_menu('-name' => 'currency', '-default' => $form->{"currency"},
456 '-values' => \@values, '-labels' => \%labels,
457 '-onchange' => "document.getElementById('update_button').click();"
458 )) if scalar @values;
459 push @custom_hiddens, "forex";
460 push @custom_hiddens, "exchangerate" if $form->{forex};
462 $TMPL_VAR{creditwarning} = ($form->{creditlimit} != 0) && ($form->{creditremaining} < 0) && !$form->{update};
463 $TMPL_VAR{is_credit_remaining_negativ} = $form->{creditremaining} =~ /-/;
465 # set option selected
466 foreach my $item (qw(AR)) {
467 $form->{"select$item"} =~ s/ selected//;
468 $form->{"select$item"} =~ s/option>\Q$form->{$item}\E/option selected>$form->{$item}/;
471 $TMPL_VAR{is_type_credit_note} = $form->{type} eq "credit_note";
472 $TMPL_VAR{is_format_html} = $form->{format} eq 'html';
473 $TMPL_VAR{dateformat} = $myconfig{dateformat};
474 $TMPL_VAR{numberformat} = $myconfig{numberformat};
477 $TMPL_VAR{HIDDENS} = [qw(
478 id type queued printed emailed vc discount
479 title creditlimit creditremaining tradediscount business closedto locked shipped storno storno_id
480 max_dunning_level dunning_amount dunning_description
481 taxaccounts cursor_fokus
482 convert_from_do_ids convert_from_oe_ids convert_from_ar_ids useasnew
486 map { $_.'_rate', $_.'_description', $_.'_taxnumber' } split / /, $form->{taxaccounts}];
488 $::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));
490 $TMPL_VAR{payment_terms_obj} = get_payment_terms_for_invoice();
491 $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};
493 setup_is_action_bar();
497 print $form->parse_html_template("is/form_header", \%TMPL_VAR);
499 $main::lxdebug->leave_sub();
503 my @fields = qw(acc_trans_id gldate datepaid source memo paid AR_paid);
505 grep { $_->{paid} != 0 }
508 +{ map { ($_ => delete($::form->{"${_}_${idx}"})) } @fields }
509 } (1..$::form->{paidaccounts});
511 @payments = sort_by { DateTime->from_kivitendo($_->{datepaid}) } @payments;
513 $::form->{paidaccounts} = max scalar(@payments), 1;
515 foreach my $idx (1 .. scalar(@payments)) {
516 my $payment = $payments[$idx - 1];
517 $::form->{"${_}_${idx}"} = $payment->{$_} for @fields;
522 $main::lxdebug->enter_sub();
524 my $form = $main::form;
525 my %myconfig = %main::myconfig;
526 my $locale = $main::locale;
528 $main::auth->assert('invoice_edit');
530 $form->{invtotal} = $form->{invsubtotal};
533 $form->{rows} = max 2,
534 $form->numtextrows($form->{notes}, 26, 8),
535 $form->numtextrows($form->{intnotes}, 35, 8);
538 # tax, total and subtotal calculations
539 my ($tax, $subtotal);
540 $form->{taxaccounts_array} = [ split(/ /, $form->{taxaccounts}) ];
542 if( $form->{customer_id} && !$form->{taxincluded_changed_by_user} ) {
543 my $customer = SL::DB::Customer->load_cached($form->{customer_id});
544 $form->{taxincluded} = defined($customer->taxincluded_checked) ? $customer->taxincluded_checked : $myconfig{taxincluded_checked};
547 foreach my $item (@{ $form->{taxaccounts_array} }) {
548 if ($form->{"${item}_base"}) {
549 if ($form->{taxincluded}) {
550 $form->{"${item}_total"} = $form->round_amount( ($form->{"${item}_base"} * $form->{"${item}_rate"}
551 / (1 + $form->{"${item}_rate"})), 2);
552 $form->{"${item}_netto"} = $form->round_amount( ($form->{"${item}_base"} - $form->{"${item}_total"}), 2);
554 $form->{"${item}_total"} = $form->round_amount( $form->{"${item}_base"} * $form->{"${item}_rate"}, 2);
555 $form->{invtotal} += $form->{"${item}_total"};
560 my $grossamount = $form->{invtotal};
561 $form->{invtotal} = $form->round_amount( $form->{invtotal}, 2, 1 );
562 $form->{rounding} = $form->round_amount(
563 $form->{invtotal} - $form->round_amount($grossamount, 2),
569 $form->{follow_ups} = FU->follow_ups('trans_id' => $form->{id}, 'not_done' => 1) || [];
570 $form->{follow_ups_unfinished} = ( sum map { $_->{due} * 1 } @{ $form->{follow_ups} } ) || 0;
577 $form->{paidaccounts}++ if ($form->{"paid_$form->{paidaccounts}"});
578 $form->{paid_indices} = [ 1 .. $form->{paidaccounts} ];
580 # Standard Konto für Umlaufvermögen
581 my $accno_arap = IS->get_standard_accno_current_assets(\%myconfig, \%$form);
583 for my $i (1 .. $form->{paidaccounts}) {
584 $form->{"changeable_$i"} = 1;
585 if (SL::DB::Default->get->payments_changeable == 0) {
587 $form->{"changeable_$i"} = ($form->{"acc_trans_id_$i"})? 0 : 1;
588 } elsif (SL::DB::Default->get->payments_changeable == 2) {
590 $form->{"changeable_$i"} = (($form->{"gldate_$i"} eq '') ||
591 ($form->current_date(\%myconfig) eq $form->{"gldate_$i"}));
594 #deaktivieren von gebuchten Zahlungen ausserhalb der Bücherkontrolle, vorher prüfen ob heute eingegeben
595 if ($form->date_closed($form->{"gldate_$i"})) {
596 $form->{"changeable_$i"} = 0;
599 $form->{"selectAR_paid_$i"} = $form->{selectAR_paid};
600 if (!$form->{"AR_paid_$i"}) {
601 $form->{"selectAR_paid_$i"} =~ s/option>$accno_arap--(.*?)</option selected>$accno_arap--$1</;
603 $form->{"selectAR_paid_$i"} =~ s/option>\Q$form->{"AR_paid_$i"}\E/option selected>$form->{"AR_paid_$i"}/;
606 $totalpaid += $form->{"paid_$i"};
609 $form->{oldinvtotal} = $form->{invtotal};
611 $form->{ALL_DELIVERY_TERMS} = SL::DB::Manager::DeliveryTerm->get_all_sorted();
613 print $form->parse_html_template('is/form_footer', {
614 is_type_credit_note => ($form->{type} eq "credit_note"),
615 totalpaid => $totalpaid,
616 paid_missing => $form->{invtotal} - $totalpaid,
617 print_options => setup_sales_purchase_print_options(),
618 show_storno => $form->{id} && !$form->{storno} && !IS->has_storno(\%myconfig, $form, "ar") && !$totalpaid,
619 show_delete => ($::instance_conf->get_is_changeable == 2)
620 ? ($form->current_date(\%myconfig) eq $form->{gldate})
621 : ($::instance_conf->get_is_changeable == 1),
622 today => DateTime->today,
623 vc_obj => $form->{customer_id} ? SL::DB::Customer->load_cached($form->{customer_id}) : undef,
625 ##print $form->parse_html_template('is/_payments'); # parser
626 ##print $form->parse_html_template('webdav/_list'); # parser
628 $main::lxdebug->leave_sub();
632 $::auth->assert('invoice_edit');
634 SL::DB::Invoice->new(id => $::form->{id})->load->mark_as_paid;
636 $::form->redirect($::locale->text("Marked as paid"));
640 # unless no lazy implementation of save draft without invdate
641 # set the current date like in version <= 3.4.1
642 $::form->{invdate} = DateTime->today->to_lxoffice;
647 $main::lxdebug->enter_sub();
649 my $form = $main::form;
650 my %myconfig = %main::myconfig;
652 $main::auth->assert('invoice_edit');
654 my ($recursive_call) = @_;
656 $form->{print_and_post} = 0 if $form->{second_run};
657 my $taxincluded = $form->{taxincluded} ? "checked" : '';
660 if (($form->{previous_customer_id} || $form->{customer_id}) != $form->{customer_id}) {
661 $::form->{salesman_id} = SL::DB::Manager::Employee->current->id if exists $::form->{salesman_id};
663 IS->get_customer(\%myconfig, $form);
666 $form->{taxincluded} ||= $taxincluded;
668 if (!$form->{forex}) { # read exchangerate from input field (not hidden)
669 $form->{exchangerate} = $form->parse_amount(\%myconfig, $form->{exchangerate}) unless $recursive_call;
671 $form->{forex} = $form->check_exchangerate(\%myconfig, $form->{currency}, $form->{invdate}, 'buy');
672 $form->{exchangerate} = $form->{forex} if $form->{forex};
674 for my $i (1 .. $form->{paidaccounts}) {
675 next unless $form->{"paid_$i"};
676 map { $form->{"${_}_$i"} = $form->parse_amount(\%myconfig, $form->{"${_}_$i"}) } qw(paid exchangerate);
677 if (!$form->{"forex_$i"}) { #read exchangerate from input field (not hidden)
678 $form->{exchangerate} = $form->{"exchangerate_$i"};
680 $form->{"forex_$i"} = $form->check_exchangerate(\%myconfig, $form->{currency}, $form->{"datepaid_$i"}, 'buy');
681 $form->{"exchangerate_$i"} = $form->{"forex_$i"} if $form->{"forex_$i"};
684 my $i = $form->{rowcount};
685 my $exchangerate = $form->{exchangerate} || 1;
687 # if last row empty, check the form otherwise retrieve new item
688 if ( ($form->{"partnumber_$i"} eq "")
689 && ($form->{"description_$i"} eq "")
690 && ($form->{"partsgroup_$i"} eq "")) {
692 $form->{creditremaining} += ($form->{oldinvtotal} - $form->{oldtotalpaid});
697 IS->retrieve_item(\%myconfig, \%$form);
699 my $rows = scalar @{ $form->{item_list} };
701 $form->{"discount_$i"} = $form->parse_amount(\%myconfig, $form->{"discount_$i"}) / 100.0;
702 $form->{"discount_$i"} ||= $form->{customer_discount};
705 $form->{"qty_$i"} = $form->parse_amount(\%myconfig, $form->{"qty_$i"});
706 if( !$form->{"qty_$i"} ) {
707 $form->{"qty_$i"} = 1;
712 select_item(mode => 'IS', pre_entered_qty => $form->{"qty_$i"});
713 $::dispatcher->end_request;
717 my $sellprice = $form->parse_amount(\%myconfig, $form->{"sellprice_$i"});
719 map { $form->{item_list}[$i]{$_} =~ s/\"/"/g } qw(partnumber description unit);
720 map { $form->{"${_}_$i"} = $form->{item_list}[0]{$_} } keys %{ $form->{item_list}[0] };
722 $form->{payment_id} = $form->{"part_payment_id_$i"} if $form->{"part_payment_id_$i"} ne "";
723 $form->{"discount_$i"} = 0 if $form->{"not_discountable_$i"};
725 $form->{"marge_price_factor_$i"} = $form->{item_list}->[0]->{price_factor};
727 ($sellprice || $form->{"sellprice_$i"}) =~ /\.(\d+)/;
728 my $decimalplaces = max 2, length $1;
731 $form->{"sellprice_$i"} = $sellprice;
733 my $record = _make_record();
734 my $price_source = SL::PriceSource->new(record_item => $record->items->[$i-1], record => $record);
735 my $best_price = $price_source->best_price;
736 my $best_discount = $price_source->best_discount;
739 $::form->{"sellprice_$i"} = $best_price->price;
740 $::form->{"active_price_source_$i"} = $best_price->source;
742 if ($best_discount) {
743 $::form->{"discount_$i"} = $best_discount->discount;
744 $::form->{"active_discount_source_$i"} = $best_discount->source;
747 # if there is an exchange rate adjust sellprice
748 $form->{"sellprice_$i"} /= $exchangerate;
751 $form->{"listprice_$i"} /= $exchangerate;
753 my $amount = $form->{"sellprice_$i"} * $form->{"qty_$i"} * (1 - $form->{"discount_$i"});
754 map { $form->{"${_}_base"} = 0 } split / /, $form->{taxaccounts};
755 map { $form->{"${_}_base"} += $amount } split / /, $form->{"taxaccounts_$i"};
756 map { $amount += ($form->{"${_}_base"} * $form->{"${_}_rate"}) } split / /, $form->{"taxaccounts_$i"} if !$form->{taxincluded};
758 $form->{creditremaining} -= $amount;
760 map { $form->{"${_}_$i"} = $form->format_amount(\%myconfig, $form->{"${_}_$i"}, $decimalplaces) } qw(sellprice lastcost);
762 $form->{"qty_$i"} = $form->format_amount(\%myconfig, $form->{"qty_$i"});
763 $form->{"discount_$i"} = $form->format_amount(\%myconfig, $form->{"discount_$i"} * 100.0);
770 # ok, so this is a new part
771 # ask if it is a part or service item
773 if ( $form->{"partsgroup_$i"}
774 && ($form->{"partsnumber_$i"} eq "")
775 && ($form->{"description_$i"} eq "")) {
777 $form->{"discount_$i"} = "";
781 $form->{"id_$i"} = 0;
786 $main::lxdebug->leave_sub();
790 $main::lxdebug->enter_sub();
792 my $form = $main::form;
793 my %myconfig = %main::myconfig;
794 my $locale = $main::locale;
796 $main::auth->assert('invoice_edit');
798 $form->mtime_ischanged('ar') ;
799 my $invdate = $form->datetonum($form->{invdate}, \%myconfig);
801 $form->{defaultcurrency} = $form->get_default_currency(\%myconfig);
802 for my $i (1 .. $form->{paidaccounts}) {
803 if ($form->{"paid_$i"}) {
804 my $datepaid = $form->datetonum($form->{"datepaid_$i"}, \%myconfig);
806 $form->isblank("datepaid_$i", $locale->text('Payment date missing!'));
809 if ($form->{currency} ne $form->{defaultcurrency}) {
810 $form->{"exchangerate_$i"} = $form->{exchangerate}
811 if ($invdate == $datepaid);
812 $form->isblank("exchangerate_$i",
813 $locale->text('Exchangerate for payment missing!'));
815 $form->error($locale->text('Cannot post transaction above the maximum future booking date!'))
816 if ($form->date_max_future($form->{"datepaid_$i"}, \%myconfig));
818 #Zusätzlich noch das Buchungsdatum in die Bücherkontrolle einbeziehen
819 # (Dient zur Prüfung ob ZE oder ZA geprüft werden soll)
820 $form->error($locale->text('Cannot post payment for a closed period!'))
821 if ($form->date_closed($form->{"datepaid_$i"}) && !$form->date_closed($form->{"gldate_$i"}, \%myconfig));
825 ($form->{AR}) = split /--/, $form->{AR};
826 ($form->{AR_paid}) = split /--/, $form->{AR_paid};
828 if ( IS->post_payment(\%myconfig, \%$form) ) {
829 $form->{snumbers} = qq|invnumber_| . $form->{invnumber};
830 $form->{what_done} = 'invoice';
831 $form->{addition} = "PAYMENT POSTED";
833 $form->redirect($locale->text('Payment posted!'))
835 $form->error($locale->text('Cannot post payment!'));
838 $main::lxdebug->leave_sub();
842 $main::lxdebug->enter_sub();
844 my $form = $main::form;
845 my %myconfig = %main::myconfig;
846 my $locale = $main::locale;
848 $main::auth->assert('invoice_edit');
849 $form->mtime_ischanged('ar');
851 $form->{defaultcurrency} = $form->get_default_currency(\%myconfig);
852 $form->isblank("invdate", $locale->text('Invoice Date missing!'));
853 $form->isblank("customer_id", $locale->text('Customer missing!'));
854 $form->error($locale->text('Cannot post invoice for a closed period!'))
855 if ($form->date_closed($form->{"invdate"}, \%myconfig));
857 $form->{invnumber} =~ s/^\s*//g;
858 $form->{invnumber} =~ s/\s*$//g;
860 # if oldcustomer ne customer redo form
861 if (($form->{previous_customer_id} || $form->{customer_id}) != $form->{customer_id}) {
863 $::dispatcher->end_request;
866 if ($myconfig{mandatory_departments} && !$form->{department_id}) {
867 $form->{saved_message} = $::locale->text('You have to specify a department.');
872 if ($form->{second_run}) {
873 $form->{print_and_post} = 0;
876 remove_emptied_rows();
879 my $closedto = $form->datetonum($form->{closedto}, \%myconfig);
880 my $invdate = $form->datetonum($form->{invdate}, \%myconfig);
882 $form->error($locale->text('Cannot post transaction above the maximum future booking date!'))
883 if ($form->date_max_future($invdate, \%myconfig));
884 $form->error($locale->text('Cannot post invoice for a closed period!'))
885 if ($invdate <= $closedto);
887 $form->isblank("exchangerate", $locale->text('Exchangerate missing!'))
888 if ($form->{currency} ne $form->{defaultcurrency});
890 for my $i (1 .. $form->{paidaccounts}) {
891 if ($form->parse_amount(\%myconfig, $form->{"paid_$i"})) {
892 my $datepaid = $form->datetonum($form->{"datepaid_$i"}, \%myconfig);
894 $form->isblank("datepaid_$i", $locale->text('Payment date missing!'));
896 $form->error($locale->text('Cannot post transaction above the maximum future booking date!'))
897 if ($form->date_max_future($form->{"datepaid_$i"}, \%myconfig));
899 #Zusätzlich noch das Buchungsdatum in die Bücherkontrolle einbeziehen
900 # (Dient zur Prüfung ob ZE oder ZA geprüft werden soll)
901 $form->error($locale->text('Cannot post payment for a closed period!'))
902 if ($form->date_closed($form->{"datepaid_$i"}) && !$form->date_closed($form->{"gldate_$i"}, \%myconfig));
904 if ($form->{currency} ne $form->{defaultcurrency}) {
905 $form->{"exchangerate_$i"} = $form->{exchangerate}
906 if ($invdate == $datepaid);
907 $form->isblank("exchangerate_$i",
908 $locale->text('Exchangerate for payment missing!'));
913 ($form->{AR}) = split /--/, $form->{AR};
914 ($form->{AR_paid}) = split /--/, $form->{AR_paid};
915 $form->{storno} ||= 0;
917 $form->{label} = $form->{type} eq 'credit_note' ? $locale->text('Credit Note') : $locale->text('Invoice');
919 $form->{id} = 0 if $form->{postasnew};
921 # get new invnumber in sequence if no invnumber is given or if posasnew was requested
922 if ($form->{postasnew}) {
923 if ($form->{type} eq "credit_note") {
924 undef($form->{cnnumber});
926 undef($form->{invnumber});
932 my $terms = get_payment_terms_for_invoice();
933 $form->{duedate} = $terms->calc_date(reference_date => $form->{invdate}, due_date => $form->{duedate})->to_kivitendo if $terms;
935 # If transfer_out is requested, get rose db handle and do post and
936 # transfer out in one transaction. Otherwise just post the invoice.
937 if ($::instance_conf->get_is_transfer_out && $form->{type} ne 'credit_note' && !$form->{storno}) {
938 require SL::DB::Inventory;
939 my $rose_db = SL::DB::Inventory->new->db;
942 if (!$rose_db->with_transaction(sub {
944 if (!IS->post_invoice(\%myconfig, \%$form, $rose_db->dbh)) {
945 push @errors, $locale->text('Cannot post invoice!');
948 my $err = IS->transfer_out(\%$form, $rose_db->dbh);
950 push @errors, @{ $err };
951 die 'transfer error';
956 push @errors, $EVAL_ERROR;
957 $form->error($locale->text('Cannot post invoice and/or transfer out! Error message:') . "\n" . join("\n", @errors));
962 push @errors, $rose_db->error;
963 $form->error($locale->text('Cannot post invoice and/or transfer out! Error message:') . "\n" . join("\n", @errors));
966 if (!IS->post_invoice(\%myconfig, \%$form)) {
967 $form->error($locale->text('Cannot post invoice!'));
971 if(!exists $form->{addition}) {
972 $form->{snumbers} = 'invnumber' .'_'. $form->{invnumber}; # ($form->{type} eq 'credit_note' ? 'cnnumber' : 'invnumber') .'_'. $form->{invnumber};
973 $form->{what_done} = 'invoice';
974 $form->{addition} = $form->{print_and_post} ? "PRINTED AND POSTED" :
975 $form->{storno} ? "STORNO" :
980 if (!$form->{no_redirect_after_post}) {
981 $form->{action} = 'edit';
982 $form->{script} = 'is.pl';
983 $form->{callback} = build_std_url(qw(action edit id callback saved_message));
984 $form->redirect($form->{label} . " $form->{invnumber} " . $locale->text('posted!'));
987 $main::lxdebug->leave_sub();
991 $main::lxdebug->enter_sub();
993 my $form = $main::form;
995 $main::auth->assert('invoice_edit');
997 my $old_form = Form->new;
998 $form->{no_redirect_after_post} = 1;
999 $form->{print_and_post} = 1;
1003 $main::lxdebug->leave_sub();
1008 $main::lxdebug->enter_sub();
1010 my $form = $main::form;
1011 my %myconfig = %main::myconfig;
1013 $main::auth->assert('invoice_edit');
1015 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)};
1016 $form->{rowcount}--;
1017 $form->{paidaccounts} = 1;
1018 $form->{invdate} = $form->current_date(\%myconfig);
1019 my $terms = get_payment_terms_for_invoice();
1020 $form->{duedate} = $terms ? $terms->calc_date(reference_date => $form->{invdate})->to_kivitendo : $form->{invdate};
1021 $form->{employee_id} = SL::DB::Manager::Employee->current->id;
1022 $form->{forex} = $form->check_exchangerate(\%myconfig, $form->{currency}, $form->{invdate}, 'buy');
1023 $form->{exchangerate} = $form->{forex} if $form->{forex};
1025 $form->{"converted_from_invoice_id_$_"} = delete $form->{"invoice_id_$_"} for 1 .. $form->{"rowcount"};
1027 $form->{useasnew} = 1;
1030 $main::lxdebug->leave_sub();
1034 $main::lxdebug->enter_sub();
1036 my $form = $main::form;
1037 my %myconfig = %main::myconfig;
1038 my $locale = $main::locale;
1040 $main::auth->assert('invoice_edit');
1042 if ($form->{storno}) {
1043 $form->error($locale->text('Cannot storno storno invoice!'));
1046 if (IS->has_storno(\%myconfig, $form, "ar")) {
1047 $form->error($locale->text("Invoice has already been storno'd!"));
1049 if ($form->datetonum($form->{invdate}, \%myconfig) <= $form->datetonum($form->{closedto}, \%myconfig)) {
1050 $form->error($locale->text('Cannot storno invoice for a closed period!'));
1053 # save the history of invoice being stornoed
1054 $form->{snumbers} = qq|invnumber_| . $form->{invnumber};
1055 $form->{what_done} = 'invoice';
1056 $form->{addition} = "STORNO";
1057 $form->save_history;
1059 map({ my $key = $_; delete($form->{$key}) unless (grep({ $key eq $_ } qw(id login password type))); } keys(%{ $form }));
1065 # Payments must not be recorded for the new storno invoice.
1066 $form->{paidaccounts} = 0;
1067 map { my $key = $_; delete $form->{$key} if grep { $key =~ /^$_/ } qw(datepaid_ gldate_ acc_trans_id_ source_ memo_ paid_ exchangerate_ AR_paid_) } keys %{ $form };
1069 # record link invoice to storno
1070 $form->{convert_from_ar_ids} = $form->{id};
1071 $form->{storno_id} = $form->{id};
1072 $form->{storno} = 1;
1074 $form->{invnumber} = "Storno zu " . $form->{invnumber};
1075 $form->{invdate} = DateTime->today->to_lxoffice;
1076 $form->{rowcount}++;
1077 # set new ids for storno invoice
1078 # set new persistent ids for storno invoice items
1079 $form->{"converted_from_invoice_id_$_"} = delete $form->{"invoice_id_$_"} for 1 .. $form->{"rowcount"};
1082 $main::lxdebug->leave_sub();
1086 $main::lxdebug->enter_sub();
1088 my $form = $main::form;
1090 $main::auth->assert('invoice_edit');
1092 $form->{preview} = 1;
1093 my $old_form = Form->new;
1094 for (keys %$form) { $old_form->{$_} = $form->{$_} }
1096 &print_form($old_form);
1097 $main::lxdebug->leave_sub();
1102 $main::lxdebug->enter_sub();
1104 my $form = $main::form;
1105 my %myconfig = %main::myconfig;
1106 my $locale = $main::locale;
1108 $main::auth->assert('invoice_edit');
1110 $form->{transdate} = $form->{invdate} = $form->current_date(\%myconfig);
1112 $form->current_date(\%myconfig, $form->{invdate}, $form->{terms} * 1);
1114 $form->{convert_from_ar_ids} = $form->{id};
1116 $form->{rowcount}--;
1119 $form->{title} = $locale->text('Add Credit Note');
1120 $form->{script} = 'is.pl';
1122 # Bei Gutschriften bezug zur Rechnungsnummer
1123 $form->{invnumber_for_credit_note} = $form->{invnumber};
1124 # bo creates the id, reset it
1125 map { delete $form->{$_} }
1126 qw(id invnumber subject message cc bcc printed emailed queued);
1127 $form->{ $form->{vc} } =~ s/--.*//g;
1128 $form->{type} = "credit_note";
1131 map { $form->{"select$_"} = "" } ($form->{vc}, 'currency');
1133 # map { $form->{$_} = $form->parse_amount(\%myconfig, $form->{$_}) }
1134 # qw(creditlimit creditremaining);
1136 # set new persistent ids for credit note and link previous invoice id
1137 $form->{"converted_from_invoice_id_$_"} = delete $form->{"invoice_id_$_"} for 1 .. $form->{"rowcount"};
1139 my $currency = $form->{currency};
1142 $form->{currency} = $currency;
1143 $form->{forex} = $form->check_exchangerate( \%myconfig, $form->{currency}, $form->{invdate}, 'buy');
1144 $form->{exchangerate} = $form->{forex} || '';
1146 $form->{creditremaining} -= ($form->{oldinvtotal} - $form->{ordtotal});
1148 # bei Gutschriften werden Zahlungseingänge aus Rechnung nicht übernommen
1149 for my $i (1 .. $form->{paidaccounts}) {
1150 delete $form->{"paid_$i"};
1151 delete $form->{"source_$i"};
1152 delete $form->{"memo_$i"};
1153 delete $form->{"datepaid_$i"};
1154 delete $form->{"gldate_$i"};
1155 delete $form->{"acc_trans_id_$i"};
1156 delete $form->{"AR_paid_$i"};
1158 $form->{paidaccounts} = 1;
1165 $main::lxdebug->leave_sub();
1169 $::lxdebug->enter_sub;
1171 $::auth->assert('invoice_edit');
1175 my $new_rowcount = $::form->{"rowcount"} * 1 + 1;
1176 $::form->{"project_id_${new_rowcount}"} = $::form->{"globalproject_id"};
1178 $::form->language_payment(\%::myconfig);
1180 Common::webdav_folder($::form);
1183 display_row(++$::form->{rowcount});
1186 $::lxdebug->leave_sub;
1190 $::auth->assert('invoice_edit');
1192 if (IS->delete_invoice(\%::myconfig, $::form)) {
1193 # saving the history
1194 if(!exists $::form->{addition}) {
1195 $::form->{snumbers} = 'invnumber' .'_'. $::form->{invnumber};
1196 $::form->{what_done} = 'invoice';
1197 $::form->{addition} = "DELETED";
1198 $::form->save_history;
1200 # /saving the history
1201 $::form->redirect($::locale->text('Invoice deleted!'));
1203 $::form->error($::locale->text('Cannot delete invoice!'));
1208 print update ship_to storno post_payment use_as_new credit_note
1209 delete post order preview post_and_e_mail print_and_post
1212 if ($::form->{"action_$action"}) {
1218 $::form->error($::locale->text('No action defined.'));