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/io.pl";
53 require "bin/mozilla/arap.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";
218 $form->{type} = "invoice";
219 $form->{formname} = "invoice";
226 foreach my $ref (@{ $form->{invoice_details} }) {
229 map { $form->{"${_}_$i"} = $ref->{$_} } keys %{$ref};
231 $form->{"discount_$i"} = $form->format_amount(\%myconfig, $form->{"discount_$i"} * 100);
232 my ($dec) = ($form->{"sellprice_$i"} =~ /\.(\d+)/);
234 my $decimalplaces = ($dec > 2) ? $dec : 2;
236 $form->{"sellprice_$i"} = $form->format_amount(\%myconfig, $form->{"sellprice_$i"}, $decimalplaces);
237 (my $dec_qty) = ($form->{"qty_$i"} =~ /\.(\d+)/);
238 $dec_qty = length $dec_qty;
240 $form->{"lastcost_$i"} = $form->format_amount(\%myconfig, $form->{"lastcost_$i"}, $decimalplaces);
242 $form->{"qty_$i"} = $form->format_amount(\%myconfig, $form->{"qty_$i"}, $dec_qty);
244 $form->{"sellprice_pg_$i"} = join ('--', $form->{"sellprice_$i"}, $form->{"pricegroup_id_$i"});
246 $form->{rowcount} = $i;
250 $main::lxdebug->leave_sub();
254 $main::lxdebug->enter_sub();
256 my $form = $main::form;
257 my %myconfig = %main::myconfig;
258 my $locale = $main::locale;
259 my $cgi = $::request->{cgi};
261 $main::auth->assert('invoice_edit');
266 $TMPL_VAR{customer_obj} = SL::DB::Customer->load_cached($form->{customer_id}) if $form->{customer_id};
267 $TMPL_VAR{invoice_obj} = SL::DB::Invoice->load_cached($form->{id}) if $form->{id};
269 $form->{employee_id} = $form->{old_employee_id} if $form->{old_employee_id};
270 $form->{salesman_id} = $form->{old_salesman_id} if $form->{old_salesman_id};
272 $form->{defaultcurrency} = $form->get_default_currency(\%myconfig);
274 $form->get_lists("taxzones" => ($form->{id} ? "ALL_TAXZONES" : "ALL_ACTIVE_TAXZONES"),
275 "currencies" => "ALL_CURRENCIES",
276 "price_factors" => "ALL_PRICE_FACTORS");
278 $form->{ALL_DEPARTMENTS} = SL::DB::Manager::Department->get_all_sorted;
281 my @old_project_ids = uniq grep { $_ } map { $_ * 1 } ($form->{"globalproject_id"}, map { $form->{"project_id_$_"} } 1..$form->{"rowcount"});
282 my @old_ids_cond = @old_project_ids ? (id => \@old_project_ids) : ();
284 if ($::instance_conf->get_customer_projects_only_in_sales) {
287 customer_id => $::form->{customer_id},
288 billable_customer_id => $::form->{customer_id},
293 and => [ active => 1, @customer_cond ],
297 $TMPL_VAR{ALL_PROJECTS} = SL::DB::Manager::Project->get_all_sorted(query => \@conditions);
298 $form->{ALL_PROJECTS} = $TMPL_VAR{ALL_PROJECTS}; # make projects available for second row drop-down in io.pl
299 $TMPL_VAR{ALL_EMPLOYEES} = SL::DB::Manager::Employee->get_all_sorted(query => [ or => [ id => $::form->{employee_id}, deleted => 0 ] ]);
300 $TMPL_VAR{ALL_SALESMEN} = SL::DB::Manager::Employee->get_all_sorted(query => [ or => [ id => $::form->{salesman_id}, deleted => 0 ] ]);
301 $TMPL_VAR{ALL_SHIPTO} = SL::DB::Manager::Shipto->get_all_sorted(query => [
302 or => [ trans_id => $::form->{"$::form->{vc}_id"} * 1, and => [ shipto_id => $::form->{shipto_id} * 1, trans_id => undef ] ]
304 $TMPL_VAR{ALL_CONTACTS} = SL::DB::Manager::Contact->get_all_sorted(query => [
306 cp_cv_id => $::form->{"$::form->{vc}_id"} * 1,
309 cp_id => $::form->{cp_id} * 1
314 # currencies and exchangerate
315 my @values = map { $_ } @{ $form->{ALL_CURRENCIES} };
316 my %labels = map { $_ => $_ } @{ $form->{ALL_CURRENCIES} };
317 $form->{currency} = $form->{defaultcurrency} unless $form->{currency};
318 $form->{show_exchangerate} = $form->{currency} ne $form->{defaultcurrency};
319 $TMPL_VAR{currencies} = NTI($::request->{cgi}->popup_menu('-name' => 'currency', '-default' => $form->{"currency"},
320 '-values' => \@values, '-labels' => \%labels,
321 '-onchange' => "document.getElementById('update_button').click();"
322 )) if scalar @values;
323 push @custom_hiddens, "forex";
324 push @custom_hiddens, "exchangerate" if $form->{forex};
326 $TMPL_VAR{creditwarning} = ($form->{creditlimit} != 0) && ($form->{creditremaining} < 0) && !$form->{update};
327 $TMPL_VAR{is_credit_remaining_negativ} = $form->{creditremaining} =~ /-/;
329 # set option selected
330 foreach my $item (qw(AR)) {
331 $form->{"select$item"} =~ s/ selected//;
332 $form->{"select$item"} =~ s/option>\Q$form->{$item}\E/option selected>$form->{$item}/;
335 $TMPL_VAR{is_type_credit_note} = $form->{type} eq "credit_note";
336 $TMPL_VAR{is_format_html} = $form->{format} eq 'html';
337 $TMPL_VAR{dateformat} = $myconfig{dateformat};
338 $TMPL_VAR{numberformat} = $myconfig{numberformat};
340 push @custom_hiddens, map { "shiptocvar_" . $_->name } @{ SL::DB::Manager::CustomVariableConfig->get_all(where => [ module => 'ShipTo' ]) };
343 $TMPL_VAR{HIDDENS} = [qw(
344 id type media format queued printed emailed title vc discount
345 title creditlimit creditremaining tradediscount business closedto locked shipped storno storno_id
346 max_dunning_level dunning_amount dunning_description
347 shiptoname shiptostreet shiptozipcode shiptocity shiptocountry shiptogln shiptocontact shiptophone shiptofax
348 shiptoemail shiptodepartment_1 shiptodepartment_2 shiptocp_gender message email subject cc bcc taxaccounts cursor_fokus
349 convert_from_do_ids convert_from_oe_ids convert_from_ar_ids useasnew
353 map { $_.'_rate', $_.'_description', $_.'_taxnumber' } split / /, $form->{taxaccounts}];
355 $::request->{layout}->use_javascript(map { "${_}.js" } qw(kivi.Draft kivi.SalesPurchase ckeditor/ckeditor ckeditor/adapters/jquery kivi.io autocomplete_customer autocomplete_part client_js));
357 $TMPL_VAR{payment_terms_obj} = get_payment_terms_for_invoice();
358 $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};
362 print $form->parse_html_template("is/form_header", \%TMPL_VAR);
364 $main::lxdebug->leave_sub();
368 my @fields = qw(acc_trans_id gldate datepaid source memo paid AR_paid);
370 grep { $_->{paid} != 0 }
373 +{ map { ($_ => delete($::form->{"${_}_${idx}"})) } @fields }
374 } (1..$::form->{paidaccounts});
376 @payments = sort_by { DateTime->from_kivitendo($_->{datepaid}) } @payments;
378 $::form->{paidaccounts} = max scalar(@payments), 1;
380 foreach my $idx (1 .. scalar(@payments)) {
381 my $payment = $payments[$idx - 1];
382 $::form->{"${_}_${idx}"} = $payment->{$_} for @fields;
387 $main::lxdebug->enter_sub();
389 my $form = $main::form;
390 my %myconfig = %main::myconfig;
391 my $locale = $main::locale;
393 $main::auth->assert('invoice_edit');
395 $form->{invtotal} = $form->{invsubtotal};
398 $form->{rows} = max 2,
399 $form->numtextrows($form->{notes}, 26, 8),
400 $form->numtextrows($form->{intnotes}, 35, 8);
403 # tax, total and subtotal calculations
404 my ($tax, $subtotal);
405 $form->{taxaccounts_array} = [ split(/ /, $form->{taxaccounts}) ];
407 if( $form->{customer_id} && !$form->{taxincluded_changed_by_user} ) {
408 my $customer = SL::DB::Customer->load_cached($form->{customer_id});
409 $form->{taxincluded} = defined($customer->taxincluded_checked) ? $customer->taxincluded_checked : $myconfig{taxincluded_checked};
412 foreach my $item (@{ $form->{taxaccounts_array} }) {
413 if ($form->{"${item}_base"}) {
414 if ($form->{taxincluded}) {
415 $form->{"${item}_total"} = $form->round_amount( ($form->{"${item}_base"} * $form->{"${item}_rate"}
416 / (1 + $form->{"${item}_rate"})), 2);
417 $form->{"${item}_netto"} = $form->round_amount( ($form->{"${item}_base"} - $form->{"${item}_total"}), 2);
419 $form->{"${item}_total"} = $form->round_amount( $form->{"${item}_base"} * $form->{"${item}_rate"}, 2);
420 $form->{invtotal} += $form->{"${item}_total"};
425 my $grossamount = $form->{invtotal};
426 $form->{invtotal} = $form->round_amount( $form->{invtotal}, 2, 1 );
427 $form->{rounding} = $form->round_amount(
428 $form->{invtotal} - $form->round_amount($grossamount, 2),
434 $form->{follow_ups} = FU->follow_ups('trans_id' => $form->{id}, 'not_done' => 1) || [];
435 $form->{follow_ups_unfinished} = ( sum map { $_->{due} * 1 } @{ $form->{follow_ups} } ) || 0;
442 $form->{paidaccounts}++ if ($form->{"paid_$form->{paidaccounts}"});
443 $form->{paid_indices} = [ 1 .. $form->{paidaccounts} ];
445 # Standard Konto für Umlaufvermögen
446 my $accno_arap = IS->get_standard_accno_current_assets(\%myconfig, \%$form);
448 for my $i (1 .. $form->{paidaccounts}) {
449 $form->{"changeable_$i"} = 1;
450 if (SL::DB::Default->get->payments_changeable == 0) {
452 $form->{"changeable_$i"} = ($form->{"acc_trans_id_$i"})? 0 : 1;
453 } elsif (SL::DB::Default->get->payments_changeable == 2) {
455 $form->{"changeable_$i"} = (($form->{"gldate_$i"} eq '') ||
456 ($form->current_date(\%myconfig) eq $form->{"gldate_$i"}));
459 #deaktivieren von gebuchten Zahlungen ausserhalb der Bücherkontrolle, vorher prüfen ob heute eingegeben
460 if ($form->date_closed($form->{"gldate_$i"})) {
461 $form->{"changeable_$i"} = 0;
464 $form->{"selectAR_paid_$i"} = $form->{selectAR_paid};
465 if (!$form->{"AR_paid_$i"}) {
466 $form->{"selectAR_paid_$i"} =~ s/option>$accno_arap--(.*?)</option selected>$accno_arap--$1</;
468 $form->{"selectAR_paid_$i"} =~ s/option>\Q$form->{"AR_paid_$i"}\E/option selected>$form->{"AR_paid_$i"}/;
471 $totalpaid += $form->{"paid_$i"};
474 $form->{oldinvtotal} = $form->{invtotal};
476 $form->{ALL_DELIVERY_TERMS} = SL::DB::Manager::DeliveryTerm->get_all_sorted();
478 print $form->parse_html_template('is/form_footer', {
479 is_type_credit_note => ($form->{type} eq "credit_note"),
480 totalpaid => $totalpaid,
481 paid_missing => $form->{invtotal} - $totalpaid,
482 print_options => print_options(inline => 1),
483 show_storno => $form->{id} && !$form->{storno} && !IS->has_storno(\%myconfig, $form, "ar") && !$totalpaid,
484 show_delete => ($::instance_conf->get_is_changeable == 2)
485 ? ($form->current_date(\%myconfig) eq $form->{gldate})
486 : ($::instance_conf->get_is_changeable == 1),
487 today => DateTime->today,
489 ##print $form->parse_html_template('is/_payments'); # parser
490 ##print $form->parse_html_template('webdav/_list'); # parser
492 $main::lxdebug->leave_sub();
496 $::auth->assert('invoice_edit');
498 SL::DB::Invoice->new(id => $::form->{id})->load->mark_as_paid;
500 $::form->redirect($::locale->text("Marked as paid"));
508 $main::lxdebug->enter_sub();
510 my $form = $main::form;
511 my %myconfig = %main::myconfig;
513 $main::auth->assert('invoice_edit');
515 my ($recursive_call) = @_;
517 $form->{print_and_post} = 0 if $form->{second_run};
518 my $taxincluded = $form->{taxincluded} ? "checked" : '';
521 if (($form->{previous_customer_id} || $form->{customer_id}) != $form->{customer_id}) {
522 $::form->{salesman_id} = SL::DB::Manager::Employee->current->id if exists $::form->{salesman_id};
524 IS->get_customer(\%myconfig, $form);
527 $form->{taxincluded} ||= $taxincluded;
529 if (!$form->{forex}) { # read exchangerate from input field (not hidden)
530 $form->{exchangerate} = $form->parse_amount(\%myconfig, $form->{exchangerate}) unless $recursive_call;
532 $form->{forex} = $form->check_exchangerate(\%myconfig, $form->{currency}, $form->{invdate}, 'buy');
533 $form->{exchangerate} = $form->{forex} if $form->{forex};
535 for my $i (1 .. $form->{paidaccounts}) {
536 next unless $form->{"paid_$i"};
537 map { $form->{"${_}_$i"} = $form->parse_amount(\%myconfig, $form->{"${_}_$i"}) } qw(paid exchangerate);
538 if (!$form->{"forex_$i"}) { #read exchangerate from input field (not hidden)
539 $form->{exchangerate} = $form->{"exchangerate_$i"};
541 $form->{"forex_$i"} = $form->check_exchangerate(\%myconfig, $form->{currency}, $form->{"datepaid_$i"}, 'buy');
542 $form->{"exchangerate_$i"} = $form->{"forex_$i"} if $form->{"forex_$i"};
545 my $i = $form->{rowcount};
546 my $exchangerate = $form->{exchangerate} || 1;
548 # if last row empty, check the form otherwise retrieve new item
549 if ( ($form->{"partnumber_$i"} eq "")
550 && ($form->{"description_$i"} eq "")
551 && ($form->{"partsgroup_$i"} eq "")) {
553 $form->{creditremaining} += ($form->{oldinvtotal} - $form->{oldtotalpaid});
558 IS->retrieve_item(\%myconfig, \%$form);
560 my $rows = scalar @{ $form->{item_list} };
562 $form->{"discount_$i"} = $form->parse_amount(\%myconfig, $form->{"discount_$i"}) / 100.0;
563 $form->{"discount_$i"} ||= $form->{customer_discount};
566 $form->{"qty_$i"} = $form->parse_amount(\%myconfig, $form->{"qty_$i"});
567 if( !$form->{"qty_$i"} ) {
568 $form->{"qty_$i"} = 1;
573 select_item(mode => 'IS', pre_entered_qty => $form->{"qty_$i"});
574 $::dispatcher->end_request;
578 my $sellprice = $form->parse_amount(\%myconfig, $form->{"sellprice_$i"});
580 map { $form->{item_list}[$i]{$_} =~ s/\"/"/g } qw(partnumber description unit);
581 map { $form->{"${_}_$i"} = $form->{item_list}[0]{$_} } keys %{ $form->{item_list}[0] };
583 $form->{payment_id} = $form->{"part_payment_id_$i"} if $form->{"part_payment_id_$i"} ne "";
584 $form->{"discount_$i"} = 0 if $form->{"not_discountable_$i"};
586 $form->{"marge_price_factor_$i"} = $form->{item_list}->[0]->{price_factor};
588 ($sellprice || $form->{"sellprice_$i"}) =~ /\.(\d+)/;
589 my $decimalplaces = max 2, length $1;
592 $form->{"sellprice_$i"} = $sellprice;
594 my $record = _make_record();
595 my $price_source = SL::PriceSource->new(record_item => $record->items->[$i-1], record => $record);
596 my $best_price = $price_source->best_price;
597 my $best_discount = $price_source->best_discount;
600 $::form->{"sellprice_$i"} = $best_price->price;
601 $::form->{"active_price_source_$i"} = $best_price->source;
603 if ($best_discount) {
604 $::form->{"discount_$i"} = $best_discount->discount;
605 $::form->{"active_discount_source_$i"} = $best_discount->source;
608 # if there is an exchange rate adjust sellprice
609 $form->{"sellprice_$i"} /= $exchangerate;
612 $form->{"listprice_$i"} /= $exchangerate;
614 my $amount = $form->{"sellprice_$i"} * $form->{"qty_$i"} * (1 - $form->{"discount_$i"});
615 map { $form->{"${_}_base"} = 0 } split / /, $form->{taxaccounts};
616 map { $form->{"${_}_base"} += $amount } split / /, $form->{"taxaccounts_$i"};
617 map { $amount += ($form->{"${_}_base"} * $form->{"${_}_rate"}) } split / /, $form->{"taxaccounts_$i"} if !$form->{taxincluded};
619 $form->{creditremaining} -= $amount;
621 map { $form->{"${_}_$i"} = $form->format_amount(\%myconfig, $form->{"${_}_$i"}, $decimalplaces) } qw(sellprice lastcost);
623 $form->{"qty_$i"} = $form->format_amount(\%myconfig, $form->{"qty_$i"});
624 $form->{"discount_$i"} = $form->format_amount(\%myconfig, $form->{"discount_$i"} * 100.0);
631 # ok, so this is a new part
632 # ask if it is a part or service item
634 if ( $form->{"partsgroup_$i"}
635 && ($form->{"partsnumber_$i"} eq "")
636 && ($form->{"description_$i"} eq "")) {
638 $form->{"discount_$i"} = "";
642 $form->{"id_$i"} = 0;
647 $main::lxdebug->leave_sub();
651 $main::lxdebug->enter_sub();
653 my $form = $main::form;
654 my %myconfig = %main::myconfig;
655 my $locale = $main::locale;
657 $main::auth->assert('invoice_edit');
659 $form->mtime_ischanged('ar') ;
660 my $invdate = $form->datetonum($form->{invdate}, \%myconfig);
662 $form->{defaultcurrency} = $form->get_default_currency(\%myconfig);
663 for my $i (1 .. $form->{paidaccounts}) {
664 if ($form->{"paid_$i"}) {
665 my $datepaid = $form->datetonum($form->{"datepaid_$i"}, \%myconfig);
667 $form->isblank("datepaid_$i", $locale->text('Payment date missing!'));
670 if ($form->{currency} ne $form->{defaultcurrency}) {
671 $form->{"exchangerate_$i"} = $form->{exchangerate}
672 if ($invdate == $datepaid);
673 $form->isblank("exchangerate_$i",
674 $locale->text('Exchangerate for payment missing!'));
676 $form->error($locale->text('Cannot post transaction above the maximum future booking date!'))
677 if ($form->date_max_future($form->{"datepaid_$i"}, \%myconfig));
679 #Zusätzlich noch das Buchungsdatum in die Bücherkontrolle einbeziehen
680 # (Dient zur Prüfung ob ZE oder ZA geprüft werden soll)
681 $form->error($locale->text('Cannot post payment for a closed period!'))
682 if ($form->date_closed($form->{"datepaid_$i"}) && !$form->date_closed($form->{"gldate_$i"}, \%myconfig));
686 ($form->{AR}) = split /--/, $form->{AR};
687 ($form->{AR_paid}) = split /--/, $form->{AR_paid};
689 if ( IS->post_payment(\%myconfig, \%$form) ) {
690 $form->{snumbers} = qq|invnumber_| . $form->{invnumber};
691 $form->{what_done} = 'invoice';
692 $form->{addition} = "PAYMENT POSTED";
694 $form->redirect($locale->text('Payment posted!'))
696 $form->error($locale->text('Cannot post payment!'));
699 $main::lxdebug->leave_sub();
703 $main::lxdebug->enter_sub();
705 my $form = $main::form;
706 my %myconfig = %main::myconfig;
707 my $locale = $main::locale;
709 $main::auth->assert('invoice_edit');
710 $form->mtime_ischanged('ar');
712 $form->{defaultcurrency} = $form->get_default_currency(\%myconfig);
713 $form->isblank("invdate", $locale->text('Invoice Date missing!'));
714 $form->isblank("customer_id", $locale->text('Customer missing!'));
715 $form->error($locale->text('Cannot post invoice for a closed period!'))
716 if ($form->date_closed($form->{"invdate"}, \%myconfig));
718 $form->{invnumber} =~ s/^\s*//g;
719 $form->{invnumber} =~ s/\s*$//g;
721 # if oldcustomer ne customer redo form
722 if (($form->{previous_customer_id} || $form->{customer_id}) != $form->{customer_id}) {
724 $::dispatcher->end_request;
727 if ($myconfig{mandatory_departments} && !$form->{department_id}) {
728 $form->{saved_message} = $::locale->text('You have to specify a department.');
733 if ($form->{second_run}) {
734 $form->{print_and_post} = 0;
737 remove_emptied_rows();
740 my $closedto = $form->datetonum($form->{closedto}, \%myconfig);
741 my $invdate = $form->datetonum($form->{invdate}, \%myconfig);
743 $form->error($locale->text('Cannot post transaction above the maximum future booking date!'))
744 if ($form->date_max_future($invdate, \%myconfig));
745 $form->error($locale->text('Cannot post invoice for a closed period!'))
746 if ($invdate <= $closedto);
748 $form->isblank("exchangerate", $locale->text('Exchangerate missing!'))
749 if ($form->{currency} ne $form->{defaultcurrency});
751 for my $i (1 .. $form->{paidaccounts}) {
752 if ($form->parse_amount(\%myconfig, $form->{"paid_$i"})) {
753 my $datepaid = $form->datetonum($form->{"datepaid_$i"}, \%myconfig);
755 $form->isblank("datepaid_$i", $locale->text('Payment date missing!'));
757 $form->error($locale->text('Cannot post transaction above the maximum future booking date!'))
758 if ($form->date_max_future($form->{"datepaid_$i"}, \%myconfig));
760 #Zusätzlich noch das Buchungsdatum in die Bücherkontrolle einbeziehen
761 # (Dient zur Prüfung ob ZE oder ZA geprüft werden soll)
762 $form->error($locale->text('Cannot post payment for a closed period!'))
763 if ($form->date_closed($form->{"datepaid_$i"}) && !$form->date_closed($form->{"gldate_$i"}, \%myconfig));
765 if ($form->{currency} ne $form->{defaultcurrency}) {
766 $form->{"exchangerate_$i"} = $form->{exchangerate}
767 if ($invdate == $datepaid);
768 $form->isblank("exchangerate_$i",
769 $locale->text('Exchangerate for payment missing!'));
774 ($form->{AR}) = split /--/, $form->{AR};
775 ($form->{AR_paid}) = split /--/, $form->{AR_paid};
776 $form->{storno} ||= 0;
778 $form->{label} = $form->{type} eq 'credit_note' ? $locale->text('Credit Note') : $locale->text('Invoice');
780 $form->{id} = 0 if $form->{postasnew};
782 # get new invnumber in sequence if no invnumber is given or if posasnew was requested
783 if ($form->{postasnew}) {
784 if ($form->{type} eq "credit_note") {
785 undef($form->{cnnumber});
787 undef($form->{invnumber});
793 my $terms = get_payment_terms_for_invoice();
794 $form->{duedate} = $terms->calc_date(reference_date => $form->{invdate}, due_date => $form->{due_due})->to_kivitendo if $terms;
796 # If transfer_out is requested, get rose db handle and do post and
797 # transfer out in one transaction. Otherwise just post the invoice.
798 if ($::instance_conf->get_is_transfer_out && $form->{type} ne 'credit_note' && !$form->{storno}) {
799 require SL::DB::Inventory;
800 my $rose_db = SL::DB::Inventory->new->db;
803 if (!$rose_db->with_transaction(sub {
805 if (!IS->post_invoice(\%myconfig, \%$form, $rose_db->dbh)) {
806 push @errors, $locale->text('Cannot post invoice!');
809 my $err = IS->transfer_out(\%$form, $rose_db->dbh);
811 push @errors, @{ $err };
812 die 'transfer error';
817 push @errors, $EVAL_ERROR;
818 die 'transaction error';
823 push @errors, $rose_db->error;
824 $form->error($locale->text('Cannot post invoice and/or transfer out! Error message:') . "\n" . join("\n", @errors));
827 if (!IS->post_invoice(\%myconfig, \%$form)) {
828 $form->error($locale->text('Cannot post invoice!'));
832 if(!exists $form->{addition}) {
833 $form->{snumbers} = 'invnumber' .'_'. $form->{invnumber}; # ($form->{type} eq 'credit_note' ? 'cnnumber' : 'invnumber') .'_'. $form->{invnumber};
834 $form->{what_done} = 'invoice';
835 $form->{addition} = $form->{print_and_post} ? "PRINTED AND POSTED" :
836 $form->{storno} ? "STORNO" :
841 if (!$form->{no_redirect_after_post}) {
842 $form->{action} = 'edit';
843 $form->{script} = 'is.pl';
844 $form->{saved_message} = $form->{label} . " $form->{invnumber} " . $locale->text('posted!');
845 $form->{callback} = build_std_url(qw(action edit id callback saved_message));
849 $main::lxdebug->leave_sub();
853 $main::lxdebug->enter_sub();
855 my $form = $main::form;
857 $main::auth->assert('invoice_edit');
859 my $old_form = Form->new;
860 $form->{no_redirect_after_post} = 1;
861 $form->{print_and_post} = 1;
865 $main::lxdebug->leave_sub();
870 $main::lxdebug->enter_sub();
872 my $form = $main::form;
873 my %myconfig = %main::myconfig;
875 $main::auth->assert('invoice_edit');
877 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)};
879 $form->{paidaccounts} = 1;
880 $form->{invdate} = $form->current_date(\%myconfig);
881 my $terms = get_payment_terms_for_invoice();
882 $form->{duedate} = $terms ? $terms->calc_date(reference_date => $form->{invdate})->to_kivitendo : $form->{invdate};
883 $form->{employee_id} = SL::DB::Manager::Employee->current->id;
884 $form->{forex} = $form->check_exchangerate(\%myconfig, $form->{currency}, $form->{invdate}, 'buy');
885 $form->{exchangerate} = $form->{forex} if $form->{forex};
887 $form->{"converted_from_invoice_id_$_"} = delete $form->{"invoice_id_$_"} for 1 .. $form->{"rowcount"};
889 $form->{useasnew} = 1;
892 $main::lxdebug->leave_sub();
896 $main::lxdebug->enter_sub();
898 my $form = $main::form;
899 my %myconfig = %main::myconfig;
900 my $locale = $main::locale;
902 $main::auth->assert('invoice_edit');
904 if ($form->{storno}) {
905 $form->error($locale->text('Cannot storno storno invoice!'));
908 if (IS->has_storno(\%myconfig, $form, "ar")) {
909 $form->error($locale->text("Invoice has already been storno'd!"));
911 if ($form->datetonum($form->{invdate}, \%myconfig) <= $form->datetonum($form->{closedto}, \%myconfig)) {
912 $form->error($locale->text('Cannot storno invoice for a closed period!'));
915 # save the history of invoice being stornoed
916 $form->{snumbers} = qq|invnumber_| . $form->{invnumber};
917 $form->{what_done} = 'invoice';
918 $form->{addition} = "STORNO";
921 map({ my $key = $_; delete($form->{$key}) unless (grep({ $key eq $_ } qw(id login password type))); } keys(%{ $form }));
927 # Payments must not be recorded for the new storno invoice.
928 $form->{paidaccounts} = 0;
929 map { my $key = $_; delete $form->{$key} if grep { $key =~ /^$_/ } qw(datepaid_ gldate_ acc_trans_id_ source_ memo_ paid_ exchangerate_ AR_paid_) } keys %{ $form };
931 # record link invoice to storno
932 $form->{convert_from_ar_ids} = $form->{id};
933 $form->{storno_id} = $form->{id};
936 $form->{invnumber} = "Storno zu " . $form->{invnumber};
937 $form->{invdate} = DateTime->today->to_lxoffice;
939 # set new ids for storno invoice
940 # set new persistent ids for storno invoice items
941 $form->{"converted_from_invoice_id_$_"} = delete $form->{"invoice_id_$_"} for 1 .. $form->{"rowcount"};
944 $main::lxdebug->leave_sub();
948 $main::lxdebug->enter_sub();
950 my $form = $main::form;
952 $main::auth->assert('invoice_edit');
954 $form->{preview} = 1;
955 my $old_form = Form->new;
956 for (keys %$form) { $old_form->{$_} = $form->{$_} }
958 &print_form($old_form);
959 $main::lxdebug->leave_sub();
964 $main::lxdebug->enter_sub();
966 my $form = $main::form;
967 my %myconfig = %main::myconfig;
968 my $locale = $main::locale;
970 $main::auth->assert('invoice_edit');
972 $form->{transdate} = $form->{invdate} = $form->current_date(\%myconfig);
974 $form->current_date(\%myconfig, $form->{invdate}, $form->{terms} * 1);
976 $form->{convert_from_ar_ids} = $form->{id};
981 $form->{title} = $locale->text('Add Credit Note');
982 $form->{script} = 'is.pl';
984 # Bei Gutschriften bezug zur Rechnungsnummer
985 $form->{invnumber_for_credit_note} = $form->{invnumber};
986 # bo creates the id, reset it
987 map { delete $form->{$_} }
988 qw(id invnumber subject message cc bcc printed emailed queued);
989 $form->{ $form->{vc} } =~ s/--.*//g;
990 $form->{type} = "credit_note";
993 map { $form->{"select$_"} = "" } ($form->{vc}, 'currency');
995 # map { $form->{$_} = $form->parse_amount(\%myconfig, $form->{$_}) }
996 # qw(creditlimit creditremaining);
998 # set new persistent ids for credit note and link previous invoice id
999 $form->{"converted_from_invoice_id_$_"} = delete $form->{"invoice_id_$_"} for 1 .. $form->{"rowcount"};
1001 my $currency = $form->{currency};
1004 $form->{currency} = $currency;
1005 $form->{forex} = $form->check_exchangerate( \%myconfig, $form->{currency}, $form->{invdate}, 'buy');
1006 $form->{exchangerate} = $form->{forex} || '';
1008 $form->{creditremaining} -= ($form->{oldinvtotal} - $form->{ordtotal});
1010 # bei Gutschriften werden Zahlungseingänge aus Rechnung nicht übernommen
1011 for my $i (1 .. $form->{paidaccounts}) {
1012 delete $form->{"paid_$i"};
1013 delete $form->{"source_$i"};
1014 delete $form->{"memo_$i"};
1015 delete $form->{"datepaid_$i"};
1016 delete $form->{"gldate_$i"};
1017 delete $form->{"acc_trans_id_$i"};
1018 delete $form->{"AR_paid_$i"};
1020 $form->{paidaccounts} = 1;
1027 $main::lxdebug->leave_sub();
1031 $::lxdebug->enter_sub;
1033 $::auth->assert('invoice_edit');
1037 my $new_rowcount = $::form->{"rowcount"} * 1 + 1;
1038 $::form->{"project_id_${new_rowcount}"} = $::form->{"globalproject_id"};
1040 $::form->language_payment(\%::myconfig);
1042 Common::webdav_folder($::form);
1045 display_row(++$::form->{rowcount});
1048 $::lxdebug->leave_sub;
1052 $::auth->assert('invoice_edit');
1054 if (IS->delete_invoice(\%::myconfig, $::form)) {
1055 # saving the history
1056 if(!exists $::form->{addition}) {
1057 $::form->{snumbers} = 'invnumber' .'_'. $::form->{invnumber};
1058 $::form->{what_done} = 'invoice';
1059 $::form->{addition} = "DELETED";
1060 $::form->save_history;
1062 # /saving the history
1063 $::form->redirect($::locale->text('Invoice deleted!'));
1065 $::form->error($::locale->text('Cannot delete invoice!'));
1068 sub post_and_e_mail {
1073 $main::lxdebug->enter_sub();
1075 my $form = $main::form;
1077 $main::auth->assert('invoice_edit');
1080 $form->{no_redirect_after_post} = 1;
1082 my $saved_form = save_form();
1086 restore_form($saved_form, 0, qw(id invnumber));
1091 $main::lxdebug->leave_sub();
1096 print update ship_to e_mail storno post_payment use_as_new credit_note
1097 delete post order preview post_and_e_mail print_and_post
1100 if ($::form->{"action_$action"}) {
1106 $::form->error($::locale->text('No action defined.'));