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();
256 $main::lxdebug->enter_sub();
258 my $form = $main::form;
259 my %myconfig = %main::myconfig;
260 my $locale = $main::locale;
261 my $cgi = $::request->{cgi};
263 $main::auth->assert('invoice_edit');
268 $TMPL_VAR{customer_obj} = SL::DB::Customer->load_cached($form->{customer_id}) if $form->{customer_id};
269 $TMPL_VAR{invoice_obj} = SL::DB::Invoice->load_cached($form->{id}) if $form->{id};
271 $form->{employee_id} = $form->{old_employee_id} if $form->{old_employee_id};
272 $form->{salesman_id} = $form->{old_salesman_id} if $form->{old_salesman_id};
274 $form->{defaultcurrency} = $form->get_default_currency(\%myconfig);
276 $form->get_lists("taxzones" => ($form->{id} ? "ALL_TAXZONES" : "ALL_ACTIVE_TAXZONES"),
277 "currencies" => "ALL_CURRENCIES",
278 "price_factors" => "ALL_PRICE_FACTORS");
280 $form->{ALL_DEPARTMENTS} = SL::DB::Manager::Department->get_all_sorted;
283 my @old_project_ids = uniq grep { $_ } map { $_ * 1 } ($form->{"globalproject_id"}, map { $form->{"project_id_$_"} } 1..$form->{"rowcount"});
284 my @old_ids_cond = @old_project_ids ? (id => \@old_project_ids) : ();
286 if ($::instance_conf->get_customer_projects_only_in_sales) {
289 customer_id => $::form->{customer_id},
290 billable_customer_id => $::form->{customer_id},
295 and => [ active => 1, @customer_cond ],
299 $TMPL_VAR{ALL_PROJECTS} = SL::DB::Manager::Project->get_all_sorted(query => \@conditions);
300 $form->{ALL_PROJECTS} = $TMPL_VAR{ALL_PROJECTS}; # make projects available for second row drop-down in io.pl
301 $TMPL_VAR{ALL_EMPLOYEES} = SL::DB::Manager::Employee->get_all_sorted(query => [ or => [ id => $::form->{employee_id}, deleted => 0 ] ]);
302 $TMPL_VAR{ALL_SALESMEN} = SL::DB::Manager::Employee->get_all_sorted(query => [ or => [ id => $::form->{salesman_id}, deleted => 0 ] ]);
303 $TMPL_VAR{ALL_SHIPTO} = SL::DB::Manager::Shipto->get_all_sorted(query => [
304 or => [ trans_id => $::form->{"$::form->{vc}_id"} * 1, and => [ shipto_id => $::form->{shipto_id} * 1, trans_id => undef ] ]
306 $TMPL_VAR{ALL_CONTACTS} = SL::DB::Manager::Contact->get_all_sorted(query => [
308 cp_cv_id => $::form->{"$::form->{vc}_id"} * 1,
311 cp_id => $::form->{cp_id} * 1
316 # currencies and exchangerate
317 my @values = map { $_ } @{ $form->{ALL_CURRENCIES} };
318 my %labels = map { $_ => $_ } @{ $form->{ALL_CURRENCIES} };
319 $form->{currency} = $form->{defaultcurrency} unless $form->{currency};
320 $form->{show_exchangerate} = $form->{currency} ne $form->{defaultcurrency};
321 $TMPL_VAR{currencies} = NTI($::request->{cgi}->popup_menu('-name' => 'currency', '-default' => $form->{"currency"},
322 '-values' => \@values, '-labels' => \%labels,
323 '-onchange' => "document.getElementById('update_button').click();"
324 )) if scalar @values;
325 push @custom_hiddens, "forex";
326 push @custom_hiddens, "exchangerate" if $form->{forex};
328 $TMPL_VAR{creditwarning} = ($form->{creditlimit} != 0) && ($form->{creditremaining} < 0) && !$form->{update};
329 $TMPL_VAR{is_credit_remaining_negativ} = $form->{creditremaining} =~ /-/;
331 # set option selected
332 foreach my $item (qw(AR)) {
333 $form->{"select$item"} =~ s/ selected//;
334 $form->{"select$item"} =~ s/option>\Q$form->{$item}\E/option selected>$form->{$item}/;
337 $TMPL_VAR{is_type_credit_note} = $form->{type} eq "credit_note";
338 $TMPL_VAR{is_format_html} = $form->{format} eq 'html';
339 $TMPL_VAR{dateformat} = $myconfig{dateformat};
340 $TMPL_VAR{numberformat} = $myconfig{numberformat};
342 push @custom_hiddens, map { "shiptocvar_" . $_->name } @{ SL::DB::Manager::CustomVariableConfig->get_all(where => [ module => 'ShipTo' ]) };
345 $TMPL_VAR{HIDDENS} = [qw(
346 id type media format queued printed emailed title vc discount
347 title creditlimit creditremaining tradediscount business closedto locked shipped storno storno_id
348 max_dunning_level dunning_amount dunning_description
349 shiptoname shiptostreet shiptozipcode shiptocity shiptocountry shiptogln shiptocontact shiptophone shiptofax
350 shiptoemail shiptodepartment_1 shiptodepartment_2 shiptocp_gender message email subject cc bcc taxaccounts cursor_fokus
351 convert_from_do_ids convert_from_oe_ids convert_from_ar_ids useasnew
355 map { $_.'_rate', $_.'_description', $_.'_taxnumber' } split / /, $form->{taxaccounts}];
357 $::request->{layout}->use_javascript(map { "${_}.js" } qw(kivi.Draft kivi.SalesPurchase ckeditor/ckeditor ckeditor/adapters/jquery kivi.io autocomplete_customer autocomplete_part client_js));
359 $TMPL_VAR{payment_terms_obj} = get_payment_terms_for_invoice();
360 $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};
364 print $form->parse_html_template("is/form_header", \%TMPL_VAR);
366 $main::lxdebug->leave_sub();
370 my @fields = qw(acc_trans_id gldate datepaid source memo paid AR_paid);
372 grep { $_->{paid} != 0 }
375 +{ map { ($_ => delete($::form->{"${_}_${idx}"})) } @fields }
376 } (1..$::form->{paidaccounts});
378 @payments = sort_by { DateTime->from_kivitendo($_->{datepaid}) } @payments;
380 $::form->{paidaccounts} = max scalar(@payments), 1;
382 foreach my $idx (1 .. scalar(@payments)) {
383 my $payment = $payments[$idx - 1];
384 $::form->{"${_}_${idx}"} = $payment->{$_} for @fields;
389 $main::lxdebug->enter_sub();
391 my $form = $main::form;
392 my %myconfig = %main::myconfig;
393 my $locale = $main::locale;
395 $main::auth->assert('invoice_edit');
397 $form->{invtotal} = $form->{invsubtotal};
400 $form->{rows} = max 2,
401 $form->numtextrows($form->{notes}, 26, 8),
402 $form->numtextrows($form->{intnotes}, 35, 8);
405 # tax, total and subtotal calculations
406 my ($tax, $subtotal);
407 $form->{taxaccounts_array} = [ split(/ /, $form->{taxaccounts}) ];
409 if( $form->{customer_id} && !$form->{taxincluded_changed_by_user} ) {
410 my $customer = SL::DB::Customer->load_cached($form->{customer_id});
411 $form->{taxincluded} = defined($customer->taxincluded_checked) ? $customer->taxincluded_checked : $myconfig{taxincluded_checked};
414 foreach my $item (@{ $form->{taxaccounts_array} }) {
415 if ($form->{"${item}_base"}) {
416 if ($form->{taxincluded}) {
417 $form->{"${item}_total"} = $form->round_amount( ($form->{"${item}_base"} * $form->{"${item}_rate"}
418 / (1 + $form->{"${item}_rate"})), 2);
419 $form->{"${item}_netto"} = $form->round_amount( ($form->{"${item}_base"} - $form->{"${item}_total"}), 2);
421 $form->{"${item}_total"} = $form->round_amount( $form->{"${item}_base"} * $form->{"${item}_rate"}, 2);
422 $form->{invtotal} += $form->{"${item}_total"};
427 my $grossamount = $form->{invtotal};
428 $form->{invtotal} = $form->round_amount( $form->{invtotal}, 2, 1 );
429 $form->{rounding} = $form->round_amount(
430 $form->{invtotal} - $form->round_amount($grossamount, 2),
436 $form->{follow_ups} = FU->follow_ups('trans_id' => $form->{id}, 'not_done' => 1) || [];
437 $form->{follow_ups_unfinished} = ( sum map { $_->{due} * 1 } @{ $form->{follow_ups} } ) || 0;
444 $form->{paidaccounts}++ if ($form->{"paid_$form->{paidaccounts}"});
445 $form->{paid_indices} = [ 1 .. $form->{paidaccounts} ];
447 # Standard Konto für Umlaufvermögen
448 my $accno_arap = IS->get_standard_accno_current_assets(\%myconfig, \%$form);
450 for my $i (1 .. $form->{paidaccounts}) {
451 $form->{"changeable_$i"} = 1;
452 if (SL::DB::Default->get->payments_changeable == 0) {
454 $form->{"changeable_$i"} = ($form->{"acc_trans_id_$i"})? 0 : 1;
455 } elsif (SL::DB::Default->get->payments_changeable == 2) {
457 $form->{"changeable_$i"} = (($form->{"gldate_$i"} eq '') ||
458 ($form->current_date(\%myconfig) eq $form->{"gldate_$i"}));
461 #deaktivieren von gebuchten Zahlungen ausserhalb der Bücherkontrolle, vorher prüfen ob heute eingegeben
462 if ($form->date_closed($form->{"gldate_$i"})) {
463 $form->{"changeable_$i"} = 0;
466 $form->{"selectAR_paid_$i"} = $form->{selectAR_paid};
467 if (!$form->{"AR_paid_$i"}) {
468 $form->{"selectAR_paid_$i"} =~ s/option>$accno_arap--(.*?)</option selected>$accno_arap--$1</;
470 $form->{"selectAR_paid_$i"} =~ s/option>\Q$form->{"AR_paid_$i"}\E/option selected>$form->{"AR_paid_$i"}/;
473 $totalpaid += $form->{"paid_$i"};
476 $form->{oldinvtotal} = $form->{invtotal};
478 $form->{ALL_DELIVERY_TERMS} = SL::DB::Manager::DeliveryTerm->get_all_sorted();
480 print $form->parse_html_template('is/form_footer', {
481 is_type_credit_note => ($form->{type} eq "credit_note"),
482 totalpaid => $totalpaid,
483 paid_missing => $form->{invtotal} - $totalpaid,
484 print_options => print_options(inline => 1),
485 show_storno => $form->{id} && !$form->{storno} && !IS->has_storno(\%myconfig, $form, "ar") && !$totalpaid,
486 show_delete => ($::instance_conf->get_is_changeable == 2)
487 ? ($form->current_date(\%myconfig) eq $form->{gldate})
488 : ($::instance_conf->get_is_changeable == 1),
489 today => DateTime->today,
491 ##print $form->parse_html_template('is/_payments'); # parser
492 ##print $form->parse_html_template('webdav/_list'); # parser
494 $main::lxdebug->leave_sub();
498 $::auth->assert('invoice_edit');
500 SL::DB::Invoice->new(id => $::form->{id})->load->mark_as_paid;
502 $::form->redirect($::locale->text("Marked as paid"));
510 $main::lxdebug->enter_sub();
512 my $form = $main::form;
513 my %myconfig = %main::myconfig;
515 $main::auth->assert('invoice_edit');
517 my ($recursive_call) = @_;
519 $form->{print_and_post} = 0 if $form->{second_run};
520 my $taxincluded = $form->{taxincluded} ? "checked" : '';
523 if (($form->{previous_customer_id} || $form->{customer_id}) != $form->{customer_id}) {
524 $::form->{salesman_id} = SL::DB::Manager::Employee->current->id if exists $::form->{salesman_id};
526 IS->get_customer(\%myconfig, $form);
529 $form->{taxincluded} ||= $taxincluded;
531 if (!$form->{forex}) { # read exchangerate from input field (not hidden)
532 $form->{exchangerate} = $form->parse_amount(\%myconfig, $form->{exchangerate}) unless $recursive_call;
534 $form->{forex} = $form->check_exchangerate(\%myconfig, $form->{currency}, $form->{invdate}, 'buy');
535 $form->{exchangerate} = $form->{forex} if $form->{forex};
537 for my $i (1 .. $form->{paidaccounts}) {
538 next unless $form->{"paid_$i"};
539 map { $form->{"${_}_$i"} = $form->parse_amount(\%myconfig, $form->{"${_}_$i"}) } qw(paid exchangerate);
540 if (!$form->{"forex_$i"}) { #read exchangerate from input field (not hidden)
541 $form->{exchangerate} = $form->{"exchangerate_$i"};
543 $form->{"forex_$i"} = $form->check_exchangerate(\%myconfig, $form->{currency}, $form->{"datepaid_$i"}, 'buy');
544 $form->{"exchangerate_$i"} = $form->{"forex_$i"} if $form->{"forex_$i"};
547 my $i = $form->{rowcount};
548 my $exchangerate = $form->{exchangerate} || 1;
550 # if last row empty, check the form otherwise retrieve new item
551 if ( ($form->{"partnumber_$i"} eq "")
552 && ($form->{"description_$i"} eq "")
553 && ($form->{"partsgroup_$i"} eq "")) {
555 $form->{creditremaining} += ($form->{oldinvtotal} - $form->{oldtotalpaid});
560 IS->retrieve_item(\%myconfig, \%$form);
562 my $rows = scalar @{ $form->{item_list} };
564 $form->{"discount_$i"} = $form->parse_amount(\%myconfig, $form->{"discount_$i"}) / 100.0;
565 $form->{"discount_$i"} ||= $form->{customer_discount};
568 $form->{"qty_$i"} = $form->parse_amount(\%myconfig, $form->{"qty_$i"});
569 if( !$form->{"qty_$i"} ) {
570 $form->{"qty_$i"} = 1;
575 select_item(mode => 'IS', pre_entered_qty => $form->{"qty_$i"});
576 $::dispatcher->end_request;
580 my $sellprice = $form->parse_amount(\%myconfig, $form->{"sellprice_$i"});
582 map { $form->{item_list}[$i]{$_} =~ s/\"/"/g } qw(partnumber description unit);
583 map { $form->{"${_}_$i"} = $form->{item_list}[0]{$_} } keys %{ $form->{item_list}[0] };
585 $form->{payment_id} = $form->{"part_payment_id_$i"} if $form->{"part_payment_id_$i"} ne "";
586 $form->{"discount_$i"} = 0 if $form->{"not_discountable_$i"};
588 $form->{"marge_price_factor_$i"} = $form->{item_list}->[0]->{price_factor};
590 ($sellprice || $form->{"sellprice_$i"}) =~ /\.(\d+)/;
591 my $decimalplaces = max 2, length $1;
594 $form->{"sellprice_$i"} = $sellprice;
596 my $record = _make_record();
597 my $price_source = SL::PriceSource->new(record_item => $record->items->[$i-1], record => $record);
598 my $best_price = $price_source->best_price;
599 my $best_discount = $price_source->best_discount;
602 $::form->{"sellprice_$i"} = $best_price->price;
603 $::form->{"active_price_source_$i"} = $best_price->source;
605 if ($best_discount) {
606 $::form->{"discount_$i"} = $best_discount->discount;
607 $::form->{"active_discount_source_$i"} = $best_discount->source;
610 # if there is an exchange rate adjust sellprice
611 $form->{"sellprice_$i"} /= $exchangerate;
614 $form->{"listprice_$i"} /= $exchangerate;
616 my $amount = $form->{"sellprice_$i"} * $form->{"qty_$i"} * (1 - $form->{"discount_$i"});
617 map { $form->{"${_}_base"} = 0 } split / /, $form->{taxaccounts};
618 map { $form->{"${_}_base"} += $amount } split / /, $form->{"taxaccounts_$i"};
619 map { $amount += ($form->{"${_}_base"} * $form->{"${_}_rate"}) } split / /, $form->{"taxaccounts_$i"} if !$form->{taxincluded};
621 $form->{creditremaining} -= $amount;
623 map { $form->{"${_}_$i"} = $form->format_amount(\%myconfig, $form->{"${_}_$i"}, $decimalplaces) } qw(sellprice lastcost);
625 $form->{"qty_$i"} = $form->format_amount(\%myconfig, $form->{"qty_$i"});
626 $form->{"discount_$i"} = $form->format_amount(\%myconfig, $form->{"discount_$i"} * 100.0);
633 # ok, so this is a new part
634 # ask if it is a part or service item
636 if ( $form->{"partsgroup_$i"}
637 && ($form->{"partsnumber_$i"} eq "")
638 && ($form->{"description_$i"} eq "")) {
640 $form->{"discount_$i"} = "";
644 $form->{"id_$i"} = 0;
649 $main::lxdebug->leave_sub();
653 $main::lxdebug->enter_sub();
655 my $form = $main::form;
656 my %myconfig = %main::myconfig;
657 my $locale = $main::locale;
659 $main::auth->assert('invoice_edit');
661 $form->mtime_ischanged('ar') ;
662 my $invdate = $form->datetonum($form->{invdate}, \%myconfig);
664 $form->{defaultcurrency} = $form->get_default_currency(\%myconfig);
665 for my $i (1 .. $form->{paidaccounts}) {
666 if ($form->{"paid_$i"}) {
667 my $datepaid = $form->datetonum($form->{"datepaid_$i"}, \%myconfig);
669 $form->isblank("datepaid_$i", $locale->text('Payment date missing!'));
672 if ($form->{currency} ne $form->{defaultcurrency}) {
673 $form->{"exchangerate_$i"} = $form->{exchangerate}
674 if ($invdate == $datepaid);
675 $form->isblank("exchangerate_$i",
676 $locale->text('Exchangerate for payment missing!'));
678 $form->error($locale->text('Cannot post transaction above the maximum future booking date!'))
679 if ($form->date_max_future($form->{"datepaid_$i"}, \%myconfig));
681 #Zusätzlich noch das Buchungsdatum in die Bücherkontrolle einbeziehen
682 # (Dient zur Prüfung ob ZE oder ZA geprüft werden soll)
683 $form->error($locale->text('Cannot post payment for a closed period!'))
684 if ($form->date_closed($form->{"datepaid_$i"}) && !$form->date_closed($form->{"gldate_$i"}, \%myconfig));
688 ($form->{AR}) = split /--/, $form->{AR};
689 ($form->{AR_paid}) = split /--/, $form->{AR_paid};
691 if ( IS->post_payment(\%myconfig, \%$form) ) {
692 $form->{snumbers} = qq|invnumber_| . $form->{invnumber};
693 $form->{what_done} = 'invoice';
694 $form->{addition} = "PAYMENT POSTED";
696 $form->redirect($locale->text('Payment posted!'))
698 $form->error($locale->text('Cannot post payment!'));
701 $main::lxdebug->leave_sub();
705 $main::lxdebug->enter_sub();
707 my $form = $main::form;
708 my %myconfig = %main::myconfig;
709 my $locale = $main::locale;
711 $main::auth->assert('invoice_edit');
712 $form->mtime_ischanged('ar');
714 $form->{defaultcurrency} = $form->get_default_currency(\%myconfig);
715 $form->isblank("invdate", $locale->text('Invoice Date missing!'));
716 $form->isblank("customer_id", $locale->text('Customer missing!'));
717 $form->error($locale->text('Cannot post invoice for a closed period!'))
718 if ($form->date_closed($form->{"invdate"}, \%myconfig));
720 $form->{invnumber} =~ s/^\s*//g;
721 $form->{invnumber} =~ s/\s*$//g;
723 # if oldcustomer ne customer redo form
724 if (($form->{previous_customer_id} || $form->{customer_id}) != $form->{customer_id}) {
726 $::dispatcher->end_request;
729 if ($myconfig{mandatory_departments} && !$form->{department_id}) {
730 $form->{saved_message} = $::locale->text('You have to specify a department.');
735 if ($form->{second_run}) {
736 $form->{print_and_post} = 0;
739 remove_emptied_rows();
742 my $closedto = $form->datetonum($form->{closedto}, \%myconfig);
743 my $invdate = $form->datetonum($form->{invdate}, \%myconfig);
745 $form->error($locale->text('Cannot post transaction above the maximum future booking date!'))
746 if ($form->date_max_future($invdate, \%myconfig));
747 $form->error($locale->text('Cannot post invoice for a closed period!'))
748 if ($invdate <= $closedto);
750 $form->isblank("exchangerate", $locale->text('Exchangerate missing!'))
751 if ($form->{currency} ne $form->{defaultcurrency});
753 for my $i (1 .. $form->{paidaccounts}) {
754 if ($form->parse_amount(\%myconfig, $form->{"paid_$i"})) {
755 my $datepaid = $form->datetonum($form->{"datepaid_$i"}, \%myconfig);
757 $form->isblank("datepaid_$i", $locale->text('Payment date missing!'));
759 $form->error($locale->text('Cannot post transaction above the maximum future booking date!'))
760 if ($form->date_max_future($form->{"datepaid_$i"}, \%myconfig));
762 #Zusätzlich noch das Buchungsdatum in die Bücherkontrolle einbeziehen
763 # (Dient zur Prüfung ob ZE oder ZA geprüft werden soll)
764 $form->error($locale->text('Cannot post payment for a closed period!'))
765 if ($form->date_closed($form->{"datepaid_$i"}) && !$form->date_closed($form->{"gldate_$i"}, \%myconfig));
767 if ($form->{currency} ne $form->{defaultcurrency}) {
768 $form->{"exchangerate_$i"} = $form->{exchangerate}
769 if ($invdate == $datepaid);
770 $form->isblank("exchangerate_$i",
771 $locale->text('Exchangerate for payment missing!'));
776 ($form->{AR}) = split /--/, $form->{AR};
777 ($form->{AR_paid}) = split /--/, $form->{AR_paid};
778 $form->{storno} ||= 0;
780 $form->{label} = $form->{type} eq 'credit_note' ? $locale->text('Credit Note') : $locale->text('Invoice');
782 $form->{id} = 0 if $form->{postasnew};
784 # get new invnumber in sequence if no invnumber is given or if posasnew was requested
785 if ($form->{postasnew}) {
786 if ($form->{type} eq "credit_note") {
787 undef($form->{cnnumber});
789 undef($form->{invnumber});
795 my $terms = get_payment_terms_for_invoice();
796 $form->{duedate} = $terms->calc_date(reference_date => $form->{invdate}, due_date => $form->{due_due})->to_kivitendo if $terms;
798 # If transfer_out is requested, get rose db handle and do post and
799 # transfer out in one transaction. Otherwise just post the invoice.
800 if ($::instance_conf->get_is_transfer_out && $form->{type} ne 'credit_note' && !$form->{storno}) {
801 require SL::DB::Inventory;
802 my $rose_db = SL::DB::Inventory->new->db;
805 if (!$rose_db->with_transaction(sub {
807 if (!IS->post_invoice(\%myconfig, \%$form, $rose_db->dbh)) {
808 push @errors, $locale->text('Cannot post invoice!');
811 my $err = IS->transfer_out(\%$form, $rose_db->dbh);
813 push @errors, @{ $err };
814 die 'transfer error';
819 push @errors, $EVAL_ERROR;
820 die 'transaction error';
825 push @errors, $rose_db->error;
826 $form->error($locale->text('Cannot post invoice and/or transfer out! Error message:') . "\n" . join("\n", @errors));
829 if (!IS->post_invoice(\%myconfig, \%$form)) {
830 $form->error($locale->text('Cannot post invoice!'));
834 if(!exists $form->{addition}) {
835 $form->{snumbers} = 'invnumber' .'_'. $form->{invnumber}; # ($form->{type} eq 'credit_note' ? 'cnnumber' : 'invnumber') .'_'. $form->{invnumber};
836 $form->{what_done} = 'invoice';
837 $form->{addition} = $form->{print_and_post} ? "PRINTED AND POSTED" :
838 $form->{storno} ? "STORNO" :
843 if (!$form->{no_redirect_after_post}) {
844 $form->{action} = 'edit';
845 $form->{script} = 'is.pl';
846 $form->{callback} = build_std_url(qw(action edit id callback saved_message));
847 $form->redirect($form->{label} . " $form->{invnumber} " . $locale->text('posted!'));
850 $main::lxdebug->leave_sub();
854 $main::lxdebug->enter_sub();
856 my $form = $main::form;
858 $main::auth->assert('invoice_edit');
860 my $old_form = Form->new;
861 $form->{no_redirect_after_post} = 1;
862 $form->{print_and_post} = 1;
866 $main::lxdebug->leave_sub();
871 $main::lxdebug->enter_sub();
873 my $form = $main::form;
874 my %myconfig = %main::myconfig;
876 $main::auth->assert('invoice_edit');
878 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)};
880 $form->{paidaccounts} = 1;
881 $form->{invdate} = $form->current_date(\%myconfig);
882 my $terms = get_payment_terms_for_invoice();
883 $form->{duedate} = $terms ? $terms->calc_date(reference_date => $form->{invdate})->to_kivitendo : $form->{invdate};
884 $form->{employee_id} = SL::DB::Manager::Employee->current->id;
885 $form->{forex} = $form->check_exchangerate(\%myconfig, $form->{currency}, $form->{invdate}, 'buy');
886 $form->{exchangerate} = $form->{forex} if $form->{forex};
888 $form->{"converted_from_invoice_id_$_"} = delete $form->{"invoice_id_$_"} for 1 .. $form->{"rowcount"};
890 $form->{useasnew} = 1;
893 $main::lxdebug->leave_sub();
897 $main::lxdebug->enter_sub();
899 my $form = $main::form;
900 my %myconfig = %main::myconfig;
901 my $locale = $main::locale;
903 $main::auth->assert('invoice_edit');
905 if ($form->{storno}) {
906 $form->error($locale->text('Cannot storno storno invoice!'));
909 if (IS->has_storno(\%myconfig, $form, "ar")) {
910 $form->error($locale->text("Invoice has already been storno'd!"));
912 if ($form->datetonum($form->{invdate}, \%myconfig) <= $form->datetonum($form->{closedto}, \%myconfig)) {
913 $form->error($locale->text('Cannot storno invoice for a closed period!'));
916 # save the history of invoice being stornoed
917 $form->{snumbers} = qq|invnumber_| . $form->{invnumber};
918 $form->{what_done} = 'invoice';
919 $form->{addition} = "STORNO";
922 map({ my $key = $_; delete($form->{$key}) unless (grep({ $key eq $_ } qw(id login password type))); } keys(%{ $form }));
928 # Payments must not be recorded for the new storno invoice.
929 $form->{paidaccounts} = 0;
930 map { my $key = $_; delete $form->{$key} if grep { $key =~ /^$_/ } qw(datepaid_ gldate_ acc_trans_id_ source_ memo_ paid_ exchangerate_ AR_paid_) } keys %{ $form };
932 # record link invoice to storno
933 $form->{convert_from_ar_ids} = $form->{id};
934 $form->{storno_id} = $form->{id};
937 $form->{invnumber} = "Storno zu " . $form->{invnumber};
938 $form->{invdate} = DateTime->today->to_lxoffice;
940 # set new ids for storno invoice
941 # set new persistent ids for storno invoice items
942 $form->{"converted_from_invoice_id_$_"} = delete $form->{"invoice_id_$_"} for 1 .. $form->{"rowcount"};
945 $main::lxdebug->leave_sub();
949 $main::lxdebug->enter_sub();
951 my $form = $main::form;
953 $main::auth->assert('invoice_edit');
955 $form->{preview} = 1;
956 my $old_form = Form->new;
957 for (keys %$form) { $old_form->{$_} = $form->{$_} }
959 &print_form($old_form);
960 $main::lxdebug->leave_sub();
965 $main::lxdebug->enter_sub();
967 my $form = $main::form;
968 my %myconfig = %main::myconfig;
969 my $locale = $main::locale;
971 $main::auth->assert('invoice_edit');
973 $form->{transdate} = $form->{invdate} = $form->current_date(\%myconfig);
975 $form->current_date(\%myconfig, $form->{invdate}, $form->{terms} * 1);
977 $form->{convert_from_ar_ids} = $form->{id};
982 $form->{title} = $locale->text('Add Credit Note');
983 $form->{script} = 'is.pl';
985 # Bei Gutschriften bezug zur Rechnungsnummer
986 $form->{invnumber_for_credit_note} = $form->{invnumber};
987 # bo creates the id, reset it
988 map { delete $form->{$_} }
989 qw(id invnumber subject message cc bcc printed emailed queued);
990 $form->{ $form->{vc} } =~ s/--.*//g;
991 $form->{type} = "credit_note";
994 map { $form->{"select$_"} = "" } ($form->{vc}, 'currency');
996 # map { $form->{$_} = $form->parse_amount(\%myconfig, $form->{$_}) }
997 # qw(creditlimit creditremaining);
999 # set new persistent ids for credit note and link previous invoice id
1000 $form->{"converted_from_invoice_id_$_"} = delete $form->{"invoice_id_$_"} for 1 .. $form->{"rowcount"};
1002 my $currency = $form->{currency};
1005 $form->{currency} = $currency;
1006 $form->{forex} = $form->check_exchangerate( \%myconfig, $form->{currency}, $form->{invdate}, 'buy');
1007 $form->{exchangerate} = $form->{forex} || '';
1009 $form->{creditremaining} -= ($form->{oldinvtotal} - $form->{ordtotal});
1011 # bei Gutschriften werden Zahlungseingänge aus Rechnung nicht übernommen
1012 for my $i (1 .. $form->{paidaccounts}) {
1013 delete $form->{"paid_$i"};
1014 delete $form->{"source_$i"};
1015 delete $form->{"memo_$i"};
1016 delete $form->{"datepaid_$i"};
1017 delete $form->{"gldate_$i"};
1018 delete $form->{"acc_trans_id_$i"};
1019 delete $form->{"AR_paid_$i"};
1021 $form->{paidaccounts} = 1;
1028 $main::lxdebug->leave_sub();
1032 $::lxdebug->enter_sub;
1034 $::auth->assert('invoice_edit');
1038 my $new_rowcount = $::form->{"rowcount"} * 1 + 1;
1039 $::form->{"project_id_${new_rowcount}"} = $::form->{"globalproject_id"};
1041 $::form->language_payment(\%::myconfig);
1043 Common::webdav_folder($::form);
1046 display_row(++$::form->{rowcount});
1049 $::lxdebug->leave_sub;
1053 $::auth->assert('invoice_edit');
1055 if (IS->delete_invoice(\%::myconfig, $::form)) {
1056 # saving the history
1057 if(!exists $::form->{addition}) {
1058 $::form->{snumbers} = 'invnumber' .'_'. $::form->{invnumber};
1059 $::form->{what_done} = 'invoice';
1060 $::form->{addition} = "DELETED";
1061 $::form->save_history;
1063 # /saving the history
1064 $::form->redirect($::locale->text('Invoice deleted!'));
1066 $::form->error($::locale->text('Cannot delete invoice!'));
1069 sub post_and_e_mail {
1074 $main::lxdebug->enter_sub();
1076 my $form = $main::form;
1078 $main::auth->assert('invoice_edit');
1081 $form->{no_redirect_after_post} = 1;
1083 my $saved_form = save_form();
1087 restore_form($saved_form, 0, qw(id invnumber));
1092 $main::lxdebug->leave_sub();
1097 print update ship_to e_mail storno post_payment use_as_new credit_note
1098 delete post order preview post_and_e_mail print_and_post
1101 if ($::form->{"action_$action"}) {
1107 $::form->error($::locale->text('No action defined.'));