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 @req_trans_desc = qw(kivi.SalesPurchase.check_transaction_description) x!!$::instance_conf->get_require_transaction_description_ps;
261 for my $bar ($::request->layout->get('actionbar')) {
265 submit => [ '#form', { action_update => 1 } ],
266 disabled => $form->{locked} ? t8('The billing period has already been locked.') : undef,
267 id => 'update_button',
268 accesskey => 'enter',
274 submit => [ '#form', { action_post => 1 } ],
275 checks => [ @req_trans_desc ],
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 => 1 } ],
285 checks => [ @req_trans_desc ],
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 => 1 } ],
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 ]) x !!$::instance_conf->get_is_show_mark_as_paid,
293 ], # end of combobox "Post"
296 action => [ t8('Storno'),
297 submit => [ '#form', { action_storno => 1 } ],
298 confirm => t8('Do you really want to cancel this invoice?'),
299 checks => [ @req_trans_desc ],
300 disabled => !$form->{id} ? t8('This invoice has not been posted yet.') : undef,
302 action => [ t8('Delete'),
303 submit => [ '#form', { action_delete => 1 } ],
304 confirm => t8('Do you really want to delete this object?'),
305 checks => [ @req_trans_desc ],
306 disabled => !$form->{id} ? t8('This invoice has not been posted yet.')
307 : $form->{locked} ? t8('The billing period has already been locked.')
308 : $change_never ? t8('Changing invoices has been disabled in the configuration.')
309 : $change_on_same_day_only ? t8('Invoices can only be changed on the day they are posted.')
312 ], # end of combobox "Storno"
317 action => [ t8('Workflow') ],
320 submit => [ '#form', { action_use_as_new => 1 } ],
321 disabled => !$form->{id} ? t8('This invoice has not been posted yet.') : undef,
325 submit => [ '#form', { action_credit_note => 1 } ],
326 checks => [ @req_trans_desc ],
327 disabled => $form->{type} eq "credit_note" ? t8('Credit notes cannot be converted into other credit notes.')
328 : !$form->{id} ? t8('This invoice has not been posted yet.')
333 submit => [ '#form', { action_sales_order => 1 } ],
334 disabled => !$form->{id} ? t8('This invoice has not been posted yet.') : undef,
336 ], # end of combobox "Workflow"
339 action => [ t8('Export') ],
341 ($form->{id} ? t8('Print') : t8('Preview')),
342 submit => [ '#form', { action_print => 1 } ],
343 checks => [ @req_trans_desc ],
344 disabled => !$form->{id} && $form->{locked} ? t8('The billing period has already been locked.') : undef,
346 action => [ t8('E Mail'),
347 submit => [ '#form', { action_print => 1 } ],
348 checks => [ @req_trans_desc ],
349 disabled => !$form->{id} ? t8('This invoice has not been posted yet.') : undef,
351 ], # end of combobox "Export"
354 action => [ t8('more') ],
357 call => [ 'set_history_window', $form->{id} * 1, 'id' ],
358 disabled => !$form->{id} ? t8('This invoice has not been posted yet.') : undef,
362 call => [ 'follow_up_window' ],
363 disabled => !$form->{id} ? t8('This invoice has not been posted yet.') : undef,
367 call => [ 'kivi.Draft.popup', 'is', 'invoice', $form->{draft_id}, $form->{draft_description} ],
368 disabled => $form->{id} ? t8('This invoice has already been posted.')
369 : $form->{locked} ? t8('The billing period has already been locked.')
372 ], # end of combobox "more"
378 $main::lxdebug->enter_sub();
380 my $form = $main::form;
381 my %myconfig = %main::myconfig;
382 my $locale = $main::locale;
383 my $cgi = $::request->{cgi};
385 $main::auth->assert('invoice_edit');
390 $TMPL_VAR{customer_obj} = SL::DB::Customer->load_cached($form->{customer_id}) if $form->{customer_id};
391 $TMPL_VAR{invoice_obj} = SL::DB::Invoice->load_cached($form->{id}) if $form->{id};
393 $form->{employee_id} = $form->{old_employee_id} if $form->{old_employee_id};
394 $form->{salesman_id} = $form->{old_salesman_id} if $form->{old_salesman_id};
396 $form->{defaultcurrency} = $form->get_default_currency(\%myconfig);
398 $form->get_lists("taxzones" => ($form->{id} ? "ALL_TAXZONES" : "ALL_ACTIVE_TAXZONES"),
399 "currencies" => "ALL_CURRENCIES",
400 "price_factors" => "ALL_PRICE_FACTORS");
402 $form->{ALL_DEPARTMENTS} = SL::DB::Manager::Department->get_all_sorted;
405 my @old_project_ids = uniq grep { $_ } map { $_ * 1 } ($form->{"globalproject_id"}, map { $form->{"project_id_$_"} } 1..$form->{"rowcount"});
406 my @old_ids_cond = @old_project_ids ? (id => \@old_project_ids) : ();
408 if ($::instance_conf->get_customer_projects_only_in_sales) {
411 customer_id => $::form->{customer_id},
412 billable_customer_id => $::form->{customer_id},
417 and => [ active => 1, @customer_cond ],
421 $TMPL_VAR{ALL_PROJECTS} = SL::DB::Manager::Project->get_all_sorted(query => \@conditions);
422 $form->{ALL_PROJECTS} = $TMPL_VAR{ALL_PROJECTS}; # make projects available for second row drop-down in io.pl
423 $TMPL_VAR{ALL_EMPLOYEES} = SL::DB::Manager::Employee->get_all_sorted(query => [ or => [ id => $::form->{employee_id}, deleted => 0 ] ]);
424 $TMPL_VAR{ALL_SALESMEN} = SL::DB::Manager::Employee->get_all_sorted(query => [ or => [ id => $::form->{salesman_id}, deleted => 0 ] ]);
425 $TMPL_VAR{ALL_SHIPTO} = SL::DB::Manager::Shipto->get_all_sorted(query => [
426 or => [ trans_id => $::form->{"$::form->{vc}_id"} * 1, and => [ shipto_id => $::form->{shipto_id} * 1, trans_id => undef ] ]
428 $TMPL_VAR{ALL_CONTACTS} = SL::DB::Manager::Contact->get_all_sorted(query => [
430 cp_cv_id => $::form->{"$::form->{vc}_id"} * 1,
433 cp_id => $::form->{cp_id} * 1
438 # currencies and exchangerate
439 my @values = map { $_ } @{ $form->{ALL_CURRENCIES} };
440 my %labels = map { $_ => $_ } @{ $form->{ALL_CURRENCIES} };
441 $form->{currency} = $form->{defaultcurrency} unless $form->{currency};
442 $form->{show_exchangerate} = $form->{currency} ne $form->{defaultcurrency};
443 $TMPL_VAR{currencies} = NTI($::request->{cgi}->popup_menu('-name' => 'currency', '-default' => $form->{"currency"},
444 '-values' => \@values, '-labels' => \%labels,
445 '-onchange' => "document.getElementById('update_button').click();"
446 )) if scalar @values;
447 push @custom_hiddens, "forex";
448 push @custom_hiddens, "exchangerate" if $form->{forex};
450 $TMPL_VAR{creditwarning} = ($form->{creditlimit} != 0) && ($form->{creditremaining} < 0) && !$form->{update};
451 $TMPL_VAR{is_credit_remaining_negativ} = $form->{creditremaining} =~ /-/;
453 # set option selected
454 foreach my $item (qw(AR)) {
455 $form->{"select$item"} =~ s/ selected//;
456 $form->{"select$item"} =~ s/option>\Q$form->{$item}\E/option selected>$form->{$item}/;
459 $TMPL_VAR{is_type_credit_note} = $form->{type} eq "credit_note";
460 $TMPL_VAR{is_format_html} = $form->{format} eq 'html';
461 $TMPL_VAR{dateformat} = $myconfig{dateformat};
462 $TMPL_VAR{numberformat} = $myconfig{numberformat};
464 push @custom_hiddens, map { "shiptocvar_" . $_->name } @{ SL::DB::Manager::CustomVariableConfig->get_all(where => [ module => 'ShipTo' ]) };
467 $TMPL_VAR{HIDDENS} = [qw(
468 id type media format queued printed emailed title vc discount
469 title creditlimit creditremaining tradediscount business closedto locked shipped storno storno_id
470 max_dunning_level dunning_amount dunning_description
471 shiptoname shiptostreet shiptozipcode shiptocity shiptocountry shiptogln shiptocontact shiptophone shiptofax
472 shiptoemail shiptodepartment_1 shiptodepartment_2 shiptocp_gender message email subject cc bcc taxaccounts cursor_fokus
473 convert_from_do_ids convert_from_oe_ids convert_from_ar_ids useasnew
477 map { $_.'_rate', $_.'_description', $_.'_taxnumber' } split / /, $form->{taxaccounts}];
479 $::request->{layout}->use_javascript(map { "${_}.js" } qw(kivi.Draft kivi.File kivi.SalesPurchase kivi.Part ckeditor/ckeditor ckeditor/adapters/jquery kivi.io autocomplete_customer client_js));
481 $TMPL_VAR{payment_terms_obj} = get_payment_terms_for_invoice();
482 $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};
484 setup_is_action_bar();
488 print $form->parse_html_template("is/form_header", \%TMPL_VAR);
490 $main::lxdebug->leave_sub();
494 my @fields = qw(acc_trans_id gldate datepaid source memo paid AR_paid);
496 grep { $_->{paid} != 0 }
499 +{ map { ($_ => delete($::form->{"${_}_${idx}"})) } @fields }
500 } (1..$::form->{paidaccounts});
502 @payments = sort_by { DateTime->from_kivitendo($_->{datepaid}) } @payments;
504 $::form->{paidaccounts} = max scalar(@payments), 1;
506 foreach my $idx (1 .. scalar(@payments)) {
507 my $payment = $payments[$idx - 1];
508 $::form->{"${_}_${idx}"} = $payment->{$_} for @fields;
513 $main::lxdebug->enter_sub();
515 my $form = $main::form;
516 my %myconfig = %main::myconfig;
517 my $locale = $main::locale;
519 $main::auth->assert('invoice_edit');
521 $form->{invtotal} = $form->{invsubtotal};
524 $form->{rows} = max 2,
525 $form->numtextrows($form->{notes}, 26, 8),
526 $form->numtextrows($form->{intnotes}, 35, 8);
529 # tax, total and subtotal calculations
530 my ($tax, $subtotal);
531 $form->{taxaccounts_array} = [ split(/ /, $form->{taxaccounts}) ];
533 if( $form->{customer_id} && !$form->{taxincluded_changed_by_user} ) {
534 my $customer = SL::DB::Customer->load_cached($form->{customer_id});
535 $form->{taxincluded} = defined($customer->taxincluded_checked) ? $customer->taxincluded_checked : $myconfig{taxincluded_checked};
538 foreach my $item (@{ $form->{taxaccounts_array} }) {
539 if ($form->{"${item}_base"}) {
540 if ($form->{taxincluded}) {
541 $form->{"${item}_total"} = $form->round_amount( ($form->{"${item}_base"} * $form->{"${item}_rate"}
542 / (1 + $form->{"${item}_rate"})), 2);
543 $form->{"${item}_netto"} = $form->round_amount( ($form->{"${item}_base"} - $form->{"${item}_total"}), 2);
545 $form->{"${item}_total"} = $form->round_amount( $form->{"${item}_base"} * $form->{"${item}_rate"}, 2);
546 $form->{invtotal} += $form->{"${item}_total"};
551 my $grossamount = $form->{invtotal};
552 $form->{invtotal} = $form->round_amount( $form->{invtotal}, 2, 1 );
553 $form->{rounding} = $form->round_amount(
554 $form->{invtotal} - $form->round_amount($grossamount, 2),
560 $form->{follow_ups} = FU->follow_ups('trans_id' => $form->{id}, 'not_done' => 1) || [];
561 $form->{follow_ups_unfinished} = ( sum map { $_->{due} * 1 } @{ $form->{follow_ups} } ) || 0;
568 $form->{paidaccounts}++ if ($form->{"paid_$form->{paidaccounts}"});
569 $form->{paid_indices} = [ 1 .. $form->{paidaccounts} ];
571 # Standard Konto für Umlaufvermögen
572 my $accno_arap = IS->get_standard_accno_current_assets(\%myconfig, \%$form);
574 for my $i (1 .. $form->{paidaccounts}) {
575 $form->{"changeable_$i"} = 1;
576 if (SL::DB::Default->get->payments_changeable == 0) {
578 $form->{"changeable_$i"} = ($form->{"acc_trans_id_$i"})? 0 : 1;
579 } elsif (SL::DB::Default->get->payments_changeable == 2) {
581 $form->{"changeable_$i"} = (($form->{"gldate_$i"} eq '') ||
582 ($form->current_date(\%myconfig) eq $form->{"gldate_$i"}));
585 #deaktivieren von gebuchten Zahlungen ausserhalb der Bücherkontrolle, vorher prüfen ob heute eingegeben
586 if ($form->date_closed($form->{"gldate_$i"})) {
587 $form->{"changeable_$i"} = 0;
590 $form->{"selectAR_paid_$i"} = $form->{selectAR_paid};
591 if (!$form->{"AR_paid_$i"}) {
592 $form->{"selectAR_paid_$i"} =~ s/option>$accno_arap--(.*?)</option selected>$accno_arap--$1</;
594 $form->{"selectAR_paid_$i"} =~ s/option>\Q$form->{"AR_paid_$i"}\E/option selected>$form->{"AR_paid_$i"}/;
597 $totalpaid += $form->{"paid_$i"};
600 $form->{oldinvtotal} = $form->{invtotal};
602 $form->{ALL_DELIVERY_TERMS} = SL::DB::Manager::DeliveryTerm->get_all_sorted();
604 print $form->parse_html_template('is/form_footer', {
605 is_type_credit_note => ($form->{type} eq "credit_note"),
606 totalpaid => $totalpaid,
607 paid_missing => $form->{invtotal} - $totalpaid,
608 print_options => print_options(inline => 1),
609 show_storno => $form->{id} && !$form->{storno} && !IS->has_storno(\%myconfig, $form, "ar") && !$totalpaid,
610 show_delete => ($::instance_conf->get_is_changeable == 2)
611 ? ($form->current_date(\%myconfig) eq $form->{gldate})
612 : ($::instance_conf->get_is_changeable == 1),
613 today => DateTime->today,
615 ##print $form->parse_html_template('is/_payments'); # parser
616 ##print $form->parse_html_template('webdav/_list'); # parser
618 $main::lxdebug->leave_sub();
622 $::auth->assert('invoice_edit');
624 SL::DB::Invoice->new(id => $::form->{id})->load->mark_as_paid;
626 $::form->redirect($::locale->text("Marked as paid"));
634 $main::lxdebug->enter_sub();
636 my $form = $main::form;
637 my %myconfig = %main::myconfig;
639 $main::auth->assert('invoice_edit');
641 my ($recursive_call) = @_;
643 $form->{print_and_post} = 0 if $form->{second_run};
644 my $taxincluded = $form->{taxincluded} ? "checked" : '';
647 if (($form->{previous_customer_id} || $form->{customer_id}) != $form->{customer_id}) {
648 $::form->{salesman_id} = SL::DB::Manager::Employee->current->id if exists $::form->{salesman_id};
650 IS->get_customer(\%myconfig, $form);
653 $form->{taxincluded} ||= $taxincluded;
655 if (!$form->{forex}) { # read exchangerate from input field (not hidden)
656 $form->{exchangerate} = $form->parse_amount(\%myconfig, $form->{exchangerate}) unless $recursive_call;
658 $form->{forex} = $form->check_exchangerate(\%myconfig, $form->{currency}, $form->{invdate}, 'buy');
659 $form->{exchangerate} = $form->{forex} if $form->{forex};
661 for my $i (1 .. $form->{paidaccounts}) {
662 next unless $form->{"paid_$i"};
663 map { $form->{"${_}_$i"} = $form->parse_amount(\%myconfig, $form->{"${_}_$i"}) } qw(paid exchangerate);
664 if (!$form->{"forex_$i"}) { #read exchangerate from input field (not hidden)
665 $form->{exchangerate} = $form->{"exchangerate_$i"};
667 $form->{"forex_$i"} = $form->check_exchangerate(\%myconfig, $form->{currency}, $form->{"datepaid_$i"}, 'buy');
668 $form->{"exchangerate_$i"} = $form->{"forex_$i"} if $form->{"forex_$i"};
671 my $i = $form->{rowcount};
672 my $exchangerate = $form->{exchangerate} || 1;
674 # if last row empty, check the form otherwise retrieve new item
675 if ( ($form->{"partnumber_$i"} eq "")
676 && ($form->{"description_$i"} eq "")
677 && ($form->{"partsgroup_$i"} eq "")) {
679 $form->{creditremaining} += ($form->{oldinvtotal} - $form->{oldtotalpaid});
684 IS->retrieve_item(\%myconfig, \%$form);
686 my $rows = scalar @{ $form->{item_list} };
688 $form->{"discount_$i"} = $form->parse_amount(\%myconfig, $form->{"discount_$i"}) / 100.0;
689 $form->{"discount_$i"} ||= $form->{customer_discount};
692 $form->{"qty_$i"} = $form->parse_amount(\%myconfig, $form->{"qty_$i"});
693 if( !$form->{"qty_$i"} ) {
694 $form->{"qty_$i"} = 1;
699 select_item(mode => 'IS', pre_entered_qty => $form->{"qty_$i"});
700 $::dispatcher->end_request;
704 my $sellprice = $form->parse_amount(\%myconfig, $form->{"sellprice_$i"});
706 map { $form->{item_list}[$i]{$_} =~ s/\"/"/g } qw(partnumber description unit);
707 map { $form->{"${_}_$i"} = $form->{item_list}[0]{$_} } keys %{ $form->{item_list}[0] };
709 $form->{payment_id} = $form->{"part_payment_id_$i"} if $form->{"part_payment_id_$i"} ne "";
710 $form->{"discount_$i"} = 0 if $form->{"not_discountable_$i"};
712 $form->{"marge_price_factor_$i"} = $form->{item_list}->[0]->{price_factor};
714 ($sellprice || $form->{"sellprice_$i"}) =~ /\.(\d+)/;
715 my $decimalplaces = max 2, length $1;
718 $form->{"sellprice_$i"} = $sellprice;
720 my $record = _make_record();
721 my $price_source = SL::PriceSource->new(record_item => $record->items->[$i-1], record => $record);
722 my $best_price = $price_source->best_price;
723 my $best_discount = $price_source->best_discount;
726 $::form->{"sellprice_$i"} = $best_price->price;
727 $::form->{"active_price_source_$i"} = $best_price->source;
729 if ($best_discount) {
730 $::form->{"discount_$i"} = $best_discount->discount;
731 $::form->{"active_discount_source_$i"} = $best_discount->source;
734 # if there is an exchange rate adjust sellprice
735 $form->{"sellprice_$i"} /= $exchangerate;
738 $form->{"listprice_$i"} /= $exchangerate;
740 my $amount = $form->{"sellprice_$i"} * $form->{"qty_$i"} * (1 - $form->{"discount_$i"});
741 map { $form->{"${_}_base"} = 0 } split / /, $form->{taxaccounts};
742 map { $form->{"${_}_base"} += $amount } split / /, $form->{"taxaccounts_$i"};
743 map { $amount += ($form->{"${_}_base"} * $form->{"${_}_rate"}) } split / /, $form->{"taxaccounts_$i"} if !$form->{taxincluded};
745 $form->{creditremaining} -= $amount;
747 map { $form->{"${_}_$i"} = $form->format_amount(\%myconfig, $form->{"${_}_$i"}, $decimalplaces) } qw(sellprice lastcost);
749 $form->{"qty_$i"} = $form->format_amount(\%myconfig, $form->{"qty_$i"});
750 $form->{"discount_$i"} = $form->format_amount(\%myconfig, $form->{"discount_$i"} * 100.0);
757 # ok, so this is a new part
758 # ask if it is a part or service item
760 if ( $form->{"partsgroup_$i"}
761 && ($form->{"partsnumber_$i"} eq "")
762 && ($form->{"description_$i"} eq "")) {
764 $form->{"discount_$i"} = "";
768 $form->{"id_$i"} = 0;
773 $main::lxdebug->leave_sub();
777 $main::lxdebug->enter_sub();
779 my $form = $main::form;
780 my %myconfig = %main::myconfig;
781 my $locale = $main::locale;
783 $main::auth->assert('invoice_edit');
785 $form->mtime_ischanged('ar') ;
786 my $invdate = $form->datetonum($form->{invdate}, \%myconfig);
788 $form->{defaultcurrency} = $form->get_default_currency(\%myconfig);
789 for my $i (1 .. $form->{paidaccounts}) {
790 if ($form->{"paid_$i"}) {
791 my $datepaid = $form->datetonum($form->{"datepaid_$i"}, \%myconfig);
793 $form->isblank("datepaid_$i", $locale->text('Payment date missing!'));
796 if ($form->{currency} ne $form->{defaultcurrency}) {
797 $form->{"exchangerate_$i"} = $form->{exchangerate}
798 if ($invdate == $datepaid);
799 $form->isblank("exchangerate_$i",
800 $locale->text('Exchangerate for payment missing!'));
802 $form->error($locale->text('Cannot post transaction above the maximum future booking date!'))
803 if ($form->date_max_future($form->{"datepaid_$i"}, \%myconfig));
805 #Zusätzlich noch das Buchungsdatum in die Bücherkontrolle einbeziehen
806 # (Dient zur Prüfung ob ZE oder ZA geprüft werden soll)
807 $form->error($locale->text('Cannot post payment for a closed period!'))
808 if ($form->date_closed($form->{"datepaid_$i"}) && !$form->date_closed($form->{"gldate_$i"}, \%myconfig));
812 ($form->{AR}) = split /--/, $form->{AR};
813 ($form->{AR_paid}) = split /--/, $form->{AR_paid};
815 if ( IS->post_payment(\%myconfig, \%$form) ) {
816 $form->{snumbers} = qq|invnumber_| . $form->{invnumber};
817 $form->{what_done} = 'invoice';
818 $form->{addition} = "PAYMENT POSTED";
820 $form->redirect($locale->text('Payment posted!'))
822 $form->error($locale->text('Cannot post payment!'));
825 $main::lxdebug->leave_sub();
829 $main::lxdebug->enter_sub();
831 my $form = $main::form;
832 my %myconfig = %main::myconfig;
833 my $locale = $main::locale;
835 $main::auth->assert('invoice_edit');
836 $form->mtime_ischanged('ar');
838 $form->{defaultcurrency} = $form->get_default_currency(\%myconfig);
839 $form->isblank("invdate", $locale->text('Invoice Date missing!'));
840 $form->isblank("customer_id", $locale->text('Customer missing!'));
841 $form->error($locale->text('Cannot post invoice for a closed period!'))
842 if ($form->date_closed($form->{"invdate"}, \%myconfig));
844 $form->{invnumber} =~ s/^\s*//g;
845 $form->{invnumber} =~ s/\s*$//g;
847 # if oldcustomer ne customer redo form
848 if (($form->{previous_customer_id} || $form->{customer_id}) != $form->{customer_id}) {
850 $::dispatcher->end_request;
853 if ($myconfig{mandatory_departments} && !$form->{department_id}) {
854 $form->{saved_message} = $::locale->text('You have to specify a department.');
859 if ($form->{second_run}) {
860 $form->{print_and_post} = 0;
863 remove_emptied_rows();
866 my $closedto = $form->datetonum($form->{closedto}, \%myconfig);
867 my $invdate = $form->datetonum($form->{invdate}, \%myconfig);
869 $form->error($locale->text('Cannot post transaction above the maximum future booking date!'))
870 if ($form->date_max_future($invdate, \%myconfig));
871 $form->error($locale->text('Cannot post invoice for a closed period!'))
872 if ($invdate <= $closedto);
874 $form->isblank("exchangerate", $locale->text('Exchangerate missing!'))
875 if ($form->{currency} ne $form->{defaultcurrency});
877 for my $i (1 .. $form->{paidaccounts}) {
878 if ($form->parse_amount(\%myconfig, $form->{"paid_$i"})) {
879 my $datepaid = $form->datetonum($form->{"datepaid_$i"}, \%myconfig);
881 $form->isblank("datepaid_$i", $locale->text('Payment date missing!'));
883 $form->error($locale->text('Cannot post transaction above the maximum future booking date!'))
884 if ($form->date_max_future($form->{"datepaid_$i"}, \%myconfig));
886 #Zusätzlich noch das Buchungsdatum in die Bücherkontrolle einbeziehen
887 # (Dient zur Prüfung ob ZE oder ZA geprüft werden soll)
888 $form->error($locale->text('Cannot post payment for a closed period!'))
889 if ($form->date_closed($form->{"datepaid_$i"}) && !$form->date_closed($form->{"gldate_$i"}, \%myconfig));
891 if ($form->{currency} ne $form->{defaultcurrency}) {
892 $form->{"exchangerate_$i"} = $form->{exchangerate}
893 if ($invdate == $datepaid);
894 $form->isblank("exchangerate_$i",
895 $locale->text('Exchangerate for payment missing!'));
900 ($form->{AR}) = split /--/, $form->{AR};
901 ($form->{AR_paid}) = split /--/, $form->{AR_paid};
902 $form->{storno} ||= 0;
904 $form->{label} = $form->{type} eq 'credit_note' ? $locale->text('Credit Note') : $locale->text('Invoice');
906 $form->{id} = 0 if $form->{postasnew};
908 # get new invnumber in sequence if no invnumber is given or if posasnew was requested
909 if ($form->{postasnew}) {
910 if ($form->{type} eq "credit_note") {
911 undef($form->{cnnumber});
913 undef($form->{invnumber});
919 my $terms = get_payment_terms_for_invoice();
920 $form->{duedate} = $terms->calc_date(reference_date => $form->{invdate}, due_date => $form->{duedate})->to_kivitendo if $terms;
922 # If transfer_out is requested, get rose db handle and do post and
923 # transfer out in one transaction. Otherwise just post the invoice.
924 if ($::instance_conf->get_is_transfer_out && $form->{type} ne 'credit_note' && !$form->{storno}) {
925 require SL::DB::Inventory;
926 my $rose_db = SL::DB::Inventory->new->db;
929 if (!$rose_db->with_transaction(sub {
931 if (!IS->post_invoice(\%myconfig, \%$form, $rose_db->dbh)) {
932 push @errors, $locale->text('Cannot post invoice!');
935 my $err = IS->transfer_out(\%$form, $rose_db->dbh);
937 push @errors, @{ $err };
938 die 'transfer error';
943 push @errors, $EVAL_ERROR;
944 die 'transaction error';
949 push @errors, $rose_db->error;
950 $form->error($locale->text('Cannot post invoice and/or transfer out! Error message:') . "\n" . join("\n", @errors));
953 if (!IS->post_invoice(\%myconfig, \%$form)) {
954 $form->error($locale->text('Cannot post invoice!'));
958 if(!exists $form->{addition}) {
959 $form->{snumbers} = 'invnumber' .'_'. $form->{invnumber}; # ($form->{type} eq 'credit_note' ? 'cnnumber' : 'invnumber') .'_'. $form->{invnumber};
960 $form->{what_done} = 'invoice';
961 $form->{addition} = $form->{print_and_post} ? "PRINTED AND POSTED" :
962 $form->{storno} ? "STORNO" :
967 if (!$form->{no_redirect_after_post}) {
968 $form->{action} = 'edit';
969 $form->{script} = 'is.pl';
970 $form->{callback} = build_std_url(qw(action edit id callback saved_message));
971 $form->redirect($form->{label} . " $form->{invnumber} " . $locale->text('posted!'));
974 $main::lxdebug->leave_sub();
978 $main::lxdebug->enter_sub();
980 my $form = $main::form;
982 $main::auth->assert('invoice_edit');
984 my $old_form = Form->new;
985 $form->{no_redirect_after_post} = 1;
986 $form->{print_and_post} = 1;
990 $main::lxdebug->leave_sub();
995 $main::lxdebug->enter_sub();
997 my $form = $main::form;
998 my %myconfig = %main::myconfig;
1000 $main::auth->assert('invoice_edit');
1002 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)};
1003 $form->{rowcount}--;
1004 $form->{paidaccounts} = 1;
1005 $form->{invdate} = $form->current_date(\%myconfig);
1006 my $terms = get_payment_terms_for_invoice();
1007 $form->{duedate} = $terms ? $terms->calc_date(reference_date => $form->{invdate})->to_kivitendo : $form->{invdate};
1008 $form->{employee_id} = SL::DB::Manager::Employee->current->id;
1009 $form->{forex} = $form->check_exchangerate(\%myconfig, $form->{currency}, $form->{invdate}, 'buy');
1010 $form->{exchangerate} = $form->{forex} if $form->{forex};
1012 $form->{"converted_from_invoice_id_$_"} = delete $form->{"invoice_id_$_"} for 1 .. $form->{"rowcount"};
1014 $form->{useasnew} = 1;
1017 $main::lxdebug->leave_sub();
1021 $main::lxdebug->enter_sub();
1023 my $form = $main::form;
1024 my %myconfig = %main::myconfig;
1025 my $locale = $main::locale;
1027 $main::auth->assert('invoice_edit');
1029 if ($form->{storno}) {
1030 $form->error($locale->text('Cannot storno storno invoice!'));
1033 if (IS->has_storno(\%myconfig, $form, "ar")) {
1034 $form->error($locale->text("Invoice has already been storno'd!"));
1036 if ($form->datetonum($form->{invdate}, \%myconfig) <= $form->datetonum($form->{closedto}, \%myconfig)) {
1037 $form->error($locale->text('Cannot storno invoice for a closed period!'));
1040 # save the history of invoice being stornoed
1041 $form->{snumbers} = qq|invnumber_| . $form->{invnumber};
1042 $form->{what_done} = 'invoice';
1043 $form->{addition} = "STORNO";
1044 $form->save_history;
1046 map({ my $key = $_; delete($form->{$key}) unless (grep({ $key eq $_ } qw(id login password type))); } keys(%{ $form }));
1052 # Payments must not be recorded for the new storno invoice.
1053 $form->{paidaccounts} = 0;
1054 map { my $key = $_; delete $form->{$key} if grep { $key =~ /^$_/ } qw(datepaid_ gldate_ acc_trans_id_ source_ memo_ paid_ exchangerate_ AR_paid_) } keys %{ $form };
1056 # record link invoice to storno
1057 $form->{convert_from_ar_ids} = $form->{id};
1058 $form->{storno_id} = $form->{id};
1059 $form->{storno} = 1;
1061 $form->{invnumber} = "Storno zu " . $form->{invnumber};
1062 $form->{invdate} = DateTime->today->to_lxoffice;
1063 $form->{rowcount}++;
1064 # set new ids for storno invoice
1065 # set new persistent ids for storno invoice items
1066 $form->{"converted_from_invoice_id_$_"} = delete $form->{"invoice_id_$_"} for 1 .. $form->{"rowcount"};
1069 $main::lxdebug->leave_sub();
1073 $main::lxdebug->enter_sub();
1075 my $form = $main::form;
1077 $main::auth->assert('invoice_edit');
1079 $form->{preview} = 1;
1080 my $old_form = Form->new;
1081 for (keys %$form) { $old_form->{$_} = $form->{$_} }
1083 &print_form($old_form);
1084 $main::lxdebug->leave_sub();
1089 $main::lxdebug->enter_sub();
1091 my $form = $main::form;
1092 my %myconfig = %main::myconfig;
1093 my $locale = $main::locale;
1095 $main::auth->assert('invoice_edit');
1097 $form->{transdate} = $form->{invdate} = $form->current_date(\%myconfig);
1099 $form->current_date(\%myconfig, $form->{invdate}, $form->{terms} * 1);
1101 $form->{convert_from_ar_ids} = $form->{id};
1103 $form->{rowcount}--;
1106 $form->{title} = $locale->text('Add Credit Note');
1107 $form->{script} = 'is.pl';
1109 # Bei Gutschriften bezug zur Rechnungsnummer
1110 $form->{invnumber_for_credit_note} = $form->{invnumber};
1111 # bo creates the id, reset it
1112 map { delete $form->{$_} }
1113 qw(id invnumber subject message cc bcc printed emailed queued);
1114 $form->{ $form->{vc} } =~ s/--.*//g;
1115 $form->{type} = "credit_note";
1118 map { $form->{"select$_"} = "" } ($form->{vc}, 'currency');
1120 # map { $form->{$_} = $form->parse_amount(\%myconfig, $form->{$_}) }
1121 # qw(creditlimit creditremaining);
1123 # set new persistent ids for credit note and link previous invoice id
1124 $form->{"converted_from_invoice_id_$_"} = delete $form->{"invoice_id_$_"} for 1 .. $form->{"rowcount"};
1126 my $currency = $form->{currency};
1129 $form->{currency} = $currency;
1130 $form->{forex} = $form->check_exchangerate( \%myconfig, $form->{currency}, $form->{invdate}, 'buy');
1131 $form->{exchangerate} = $form->{forex} || '';
1133 $form->{creditremaining} -= ($form->{oldinvtotal} - $form->{ordtotal});
1135 # bei Gutschriften werden Zahlungseingänge aus Rechnung nicht übernommen
1136 for my $i (1 .. $form->{paidaccounts}) {
1137 delete $form->{"paid_$i"};
1138 delete $form->{"source_$i"};
1139 delete $form->{"memo_$i"};
1140 delete $form->{"datepaid_$i"};
1141 delete $form->{"gldate_$i"};
1142 delete $form->{"acc_trans_id_$i"};
1143 delete $form->{"AR_paid_$i"};
1145 $form->{paidaccounts} = 1;
1152 $main::lxdebug->leave_sub();
1156 $::lxdebug->enter_sub;
1158 $::auth->assert('invoice_edit');
1162 my $new_rowcount = $::form->{"rowcount"} * 1 + 1;
1163 $::form->{"project_id_${new_rowcount}"} = $::form->{"globalproject_id"};
1165 $::form->language_payment(\%::myconfig);
1167 Common::webdav_folder($::form);
1170 display_row(++$::form->{rowcount});
1173 $::lxdebug->leave_sub;
1177 $::auth->assert('invoice_edit');
1179 if (IS->delete_invoice(\%::myconfig, $::form)) {
1180 # saving the history
1181 if(!exists $::form->{addition}) {
1182 $::form->{snumbers} = 'invnumber' .'_'. $::form->{invnumber};
1183 $::form->{what_done} = 'invoice';
1184 $::form->{addition} = "DELETED";
1185 $::form->save_history;
1187 # /saving the history
1188 $::form->redirect($::locale->text('Invoice deleted!'));
1190 $::form->error($::locale->text('Cannot delete invoice!'));
1193 sub post_and_e_mail {
1198 $main::lxdebug->enter_sub();
1200 my $form = $main::form;
1202 $main::auth->assert('invoice_edit');
1205 $form->{no_redirect_after_post} = 1;
1207 my $saved_form = save_form();
1211 restore_form($saved_form, 0, qw(id invnumber));
1216 $main::lxdebug->leave_sub();
1221 print update ship_to e_mail storno post_payment use_as_new credit_note
1222 delete post order preview post_and_e_mail print_and_post
1225 if ($::form->{"action_$action"}) {
1231 $::form->error($::locale->text('No action defined.'));