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., 675 Mass Ave, Cambridge, MA 02139, USA.
28 #======================================================================
30 # Inventory invoicing module
32 #======================================================================
40 use List::MoreUtils qw(uniq);
41 use List::Util qw(max sum);
42 use List::UtilsBy qw(sort_by);
43 use English qw(-no_match_vars);
47 use SL::DB::PaymentTerm;
49 require "bin/mozilla/io.pl";
50 require "bin/mozilla/arap.pl";
51 require "bin/mozilla/drafts.pl";
60 $main::lxdebug->enter_sub();
62 my $form = $main::form;
63 my $locale = $main::locale;
65 $main::auth->assert('invoice_edit');
67 return $main::lxdebug->leave_sub() if (load_draft_maybe());
69 if ($form->{type} eq "credit_note") {
70 $form->{title} = $locale->text('Add Credit Note');
72 if ($form->{storno}) {
73 $form->{title} = $locale->text('Add Storno Credit Note');
76 $form->{title} = $locale->text('Add Sales Invoice');
81 $form->{callback} = "$form->{script}?action=add&type=$form->{type}" unless $form->{callback};
87 $main::lxdebug->leave_sub();
91 $main::lxdebug->enter_sub();
93 my $form = $main::form;
94 my $locale = $main::locale;
96 $main::auth->assert('invoice_edit');
98 $form->{AUTH} = $::auth;
100 $form->{taxincluded_changed_by_user} = 1;
102 # show history button
103 $form->{javascript} = qq|<script type="text/javascript" src="js/show_history.js"></script>|;
105 my ($language_id, $printer_id);
106 if ($form->{print_and_post}) {
107 $form->{action} = "print";
108 $form->{resubmit} = 1;
109 $language_id = $form->{language_id};
110 $printer_id = $form->{printer_id};
114 if ($form->{type} eq "credit_note") {
115 $form->{title} = $locale->text('Edit Credit Note');
116 $form->{title} = $locale->text('Edit Storno Credit Note') if $form->{storno};
118 $form->{title} = $locale->text('Edit Sales Invoice');
119 $form->{title} = $locale->text('Edit Storno Invoice') if $form->{storno};
123 if ($form->{print_and_post}) {
124 $form->{language_id} = $language_id;
125 $form->{printer_id} = $printer_id;
130 $main::lxdebug->leave_sub();
134 $main::lxdebug->enter_sub();
136 my $form = $main::form;
137 my %myconfig = %main::myconfig;
139 $main::auth->assert('invoice_edit');
141 $form->{vc} = 'customer';
144 $form->create_links("AR", \%myconfig, "customer");
146 if ($form->{all_customer}) {
147 unless ($form->{customer_id}) {
148 $form->{customer_id} = $form->{all_customer}->[0]->{id};
149 $form->{salesman_id} = $form->{all_customer}->[0]->{salesman_id};
153 my $editing = $form->{id};
155 $form->backup_vars(qw(payment_id language_id taxzone_id salesman_id
156 taxincluded currency cp_id intnotes id shipto_id
159 IS->get_customer(\%myconfig, \%$form);
161 #quote all_customer Bug 133
162 foreach my $ref (@{ $form->{all_customer} }) {
163 $ref->{name} = $form->quote($ref->{name});
166 $form->restore_vars(qw(id));
168 IS->retrieve_invoice(\%myconfig, \%$form);
169 $form->restore_vars(qw(payment_id language_id taxzone_id currency intnotes
170 cp_id shipto_id delivery_term_id));
171 $form->restore_vars(qw(taxincluded)) if $form->{id};
172 $form->restore_vars(qw(salesman_id)) if $editing;
175 # build vendor/customer drop down compatibility... don't ask
176 if (@{ $form->{"all_customer"} }) {
177 $form->{"selectcustomer"} = 1;
178 $form->{customer} = qq|$form->{customer}--$form->{"customer_id"}|;
181 $form->{"oldcustomer"} = $form->{customer};
183 if ($form->{"oldcustomer"} !~ m/--\d+$/ && $form->{"customer_id"}) {
184 $form->{"oldcustomer"} .= qq|--$form->{"customer_id"}|
188 # $form->{oldcustomer} = "$form->{customer}--$form->{customer_id}";
189 # $form->{selectcustomer} = 1;
191 $form->{employee} = "$form->{employee}--$form->{employee_id}";
194 $form->{forex} = $form->{exchangerate};
195 my $exchangerate = ($form->{exchangerate}) ? $form->{exchangerate} : 1;
197 foreach my $key (keys %{ $form->{AR_links} }) {
198 foreach my $ref (@{ $form->{AR_links}{$key} }) {
199 $form->{"select$key"} .= "<option>$ref->{accno}--$ref->{description}</option>\n";
202 if ($key eq "AR_paid") {
203 next unless $form->{acc_trans}{$key};
204 for my $i (1 .. scalar @{ $form->{acc_trans}{$key} }) {
205 $form->{"AR_paid_$i"} = "$form->{acc_trans}{$key}->[$i-1]->{accno}--$form->{acc_trans}{$key}->[$i-1]->{description}";
207 $form->{"acc_trans_id_$i"} = $form->{acc_trans}{$key}->[$i - 1]->{acc_trans_id};
209 $form->{"paid_$i"} = $form->{acc_trans}{$key}->[$i - 1]->{amount} * -1;
210 $form->{"datepaid_$i"} = $form->{acc_trans}{$key}->[$i - 1]->{transdate};
211 $form->{"gldate_$i"} = $form->{acc_trans}{$key}->[$i - 1]->{gldate};
212 $form->{"exchangerate_$i"} = $form->{acc_trans}{$key}->[$i - 1]->{exchangerate};
213 $form->{"forex_$i"} = $form->{"exchangerate_$i"};
214 $form->{"source_$i"} = $form->{acc_trans}{$key}->[$i - 1]->{source};
215 $form->{"memo_$i"} = $form->{acc_trans}{$key}->[$i - 1]->{memo};
217 $form->{paidaccounts} = $i;
220 $form->{$key} = "$form->{acc_trans}{$key}->[0]->{accno}--$form->{acc_trans}{$key}->[0]->{description}";
224 $form->{paidaccounts} = 1 unless (exists $form->{paidaccounts});
226 $form->{AR} = $form->{AR_1} unless $form->{id};
228 $form->{locked} = ($form->datetonum($form->{invdate}, \%myconfig)
229 <= $form->datetonum($form->{closedto}, \%myconfig));
231 $main::lxdebug->leave_sub();
234 sub prepare_invoice {
235 $main::lxdebug->enter_sub();
237 my $form = $main::form;
238 my %myconfig = %main::myconfig;
240 $main::auth->assert('invoice_edit');
242 if ($form->{type} eq "credit_note") {
243 $form->{type} = "credit_note";
244 $form->{formname} = "credit_note";
246 $form->{type} = "invoice";
247 $form->{formname} = "invoice";
254 foreach my $ref (@{ $form->{invoice_details} }) {
257 map { $form->{"${_}_$i"} = $ref->{$_} } keys %{$ref};
259 $form->{"discount_$i"} = $form->format_amount(\%myconfig, $form->{"discount_$i"} * 100);
260 my ($dec) = ($form->{"sellprice_$i"} =~ /\.(\d+)/);
262 my $decimalplaces = ($dec > 2) ? $dec : 2;
264 $form->{"sellprice_$i"} = $form->format_amount(\%myconfig, $form->{"sellprice_$i"}, $decimalplaces);
265 (my $dec_qty) = ($form->{"qty_$i"} =~ /\.(\d+)/);
266 $dec_qty = length $dec_qty;
268 $form->{"lastcost_$i"} = $form->format_amount(\%myconfig, $form->{"lastcost_$i"}, $decimalplaces);
270 $form->{"qty_$i"} = $form->format_amount(\%myconfig, $form->{"qty_$i"}, $dec_qty);
272 $form->{"sellprice_pg_$i"} = join ('--', $form->{"sellprice_$i"}, $form->{"pricegroup_id_$i"});
274 $form->{rowcount} = $i;
278 $main::lxdebug->leave_sub();
282 $main::lxdebug->enter_sub();
284 my $form = $main::form;
285 my %myconfig = %main::myconfig;
286 my $locale = $main::locale;
287 my $cgi = $::request->{cgi};
289 $main::auth->assert('invoice_edit');
295 require SL::DB::Invoice;
296 $TMPL_VAR{invoice_obj} = SL::DB::Invoice->new(id => $form->{id})->load;
298 $form->{employee_id} = $form->{old_employee_id} if $form->{old_employee_id};
299 $form->{salesman_id} = $form->{old_salesman_id} if $form->{old_salesman_id};
301 $form->{defaultcurrency} = $form->get_default_currency(\%myconfig);
303 $form->get_lists("taxzones" => ($form->{id} ? "ALL_TAXZONES" : "ALL_ACTIVE_TAXZONES"),
304 "currencies" => "ALL_CURRENCIES",
305 "customers" => "ALL_CUSTOMERS",
306 "departments" => "all_departments",
307 "price_factors" => "ALL_PRICE_FACTORS");
310 my @old_project_ids = uniq grep { $_ } map { $_ * 1 } ($form->{"globalproject_id"}, map { $form->{"project_id_$_"} } 1..$form->{"rowcount"});
311 my @old_ids_cond = @old_project_ids ? (id => \@old_project_ids) : ();
313 if ($::instance_conf->get_customer_projects_only_in_sales) {
316 customer_id => $::form->{customer_id},
317 billable_customer_id => $::form->{customer_id},
322 and => [ active => 1, @customer_cond ],
326 $TMPL_VAR{ALL_PROJECTS} = SL::DB::Manager::Project->get_all_sorted(query => \@conditions);
327 $form->{ALL_PROJECTS} = $TMPL_VAR{ALL_PROJECTS}; # make projects available for second row drop-down in io.pl
328 $TMPL_VAR{ALL_EMPLOYEES} = SL::DB::Manager::Employee->get_all_sorted(query => [ or => [ id => $::form->{employee_id}, deleted => 0 ] ]);
329 $TMPL_VAR{ALL_SALESMEN} = SL::DB::Manager::Employee->get_all_sorted(query => [ or => [ id => $::form->{salesman_id}, deleted => 0 ] ]);
330 $TMPL_VAR{ALL_SHIPTO} = SL::DB::Manager::Shipto->get_all_sorted(query => [
331 or => [ trans_id => $::form->{"$::form->{vc}_id"} * 1, and => [ shipto_id => $::form->{shipto_id} * 1, trans_id => undef ] ]
333 $TMPL_VAR{ALL_CONTACTS} = SL::DB::Manager::Contact->get_all_sorted(query => [
335 cp_cv_id => $::form->{"$::form->{vc}_id"} * 1,
338 cp_id => $::form->{cp_id} * 1
342 $TMPL_VAR{department_labels} = sub { "$_[0]->{description}--$_[0]->{id}" };
345 $TMPL_VAR{vc_keys} = sub { "$_[0]->{name}--$_[0]->{id}" };
346 $TMPL_VAR{vclimit} = $myconfig{vclimit};
347 $TMPL_VAR{vc_select} = "customer_or_vendor_selection_window('customer', '', 0, 0)";
348 push @custom_hiddens, "customer_id";
349 push @custom_hiddens, "oldcustomer";
350 push @custom_hiddens, "selectcustomer";
352 # currencies and exchangerate
353 my @values = map { $_ } @{ $form->{ALL_CURRENCIES} };
354 my %labels = map { $_ => $_ } @{ $form->{ALL_CURRENCIES} };
355 $form->{currency} = $form->{defaultcurrency} unless $form->{currency};
356 $form->{show_exchangerate} = $form->{currency} ne $form->{defaultcurrency};
357 $TMPL_VAR{currencies} = NTI($::request->{cgi}->popup_menu('-name' => 'currency', '-default' => $form->{"currency"},
358 '-values' => \@values, '-labels' => \%labels,
359 '-onchange' => "document.getElementById('update_button').click();"
360 )) if scalar @values;
361 push @custom_hiddens, "forex";
362 push @custom_hiddens, "exchangerate" if $form->{forex};
364 $TMPL_VAR{creditwarning} = ($form->{creditlimit} != 0) && ($form->{creditremaining} < 0) && !$form->{update};
365 $TMPL_VAR{is_credit_remaining_negativ} = $form->{creditremaining} =~ /-/;
367 my $follow_up_vc = $form->{customer};
368 $follow_up_vc =~ s/--\d*\s*$//;
369 $TMPL_VAR{customer_name} = $follow_up_vc;
371 # set option selected
372 foreach my $item (qw(AR)) {
373 $form->{"select$item"} =~ s/ selected//;
374 $form->{"select$item"} =~ s/option>\Q$form->{$item}\E/option selected>$form->{$item}/;
377 $TMPL_VAR{is_type_credit_note} = $form->{type} eq "credit_note";
378 $TMPL_VAR{is_format_html} = $form->{format} eq 'html';
379 $TMPL_VAR{dateformat} = $myconfig{dateformat};
380 $TMPL_VAR{numberformat} = $myconfig{numberformat};
383 $TMPL_VAR{HIDDENS} = [qw(
384 id action type media format queued printed emailed title vc discount
385 title creditlimit creditremaining tradediscount business closedto locked shipped storno storno_id
386 max_dunning_level dunning_amount dunning_description
387 shiptoname shiptostreet shiptozipcode shiptocity shiptocountry shiptocontact shiptophone shiptofax
388 shiptoemail shiptodepartment_1 shiptodepartment_2 shiptocp_gender message email subject cc bcc taxaccounts cursor_fokus
389 convert_from_do_ids convert_from_oe_ids convert_from_ar_ids useasnew
393 map { $_.'_rate', $_.'_description', $_.'_taxnumber' } split / /, $form->{taxaccounts}];
395 $::request->{layout}->use_javascript(map { "${_}.js" } qw(kivi.SalesPurchase ckeditor/ckeditor ckeditor/adapters/jquery kivi.io autocomplete_customer autocomplete_part client_js));
397 $TMPL_VAR{payment_terms_obj} = get_payment_terms_for_invoice();
398 $form->{duedate} = $TMPL_VAR{payment_terms_obj}->calc_date(reference_date => $form->{invdate}, due_date => $form->{due_due})->to_kivitendo if $TMPL_VAR{payment_terms_obj};
402 print $form->parse_html_template("is/form_header", \%TMPL_VAR);
404 $main::lxdebug->leave_sub();
408 my @fields = qw(acc_trans_id gldate datepaid source memo paid AR_paid);
410 grep { $_->{paid} != 0 }
413 +{ map { ($_ => delete($::form->{"${_}_${idx}"})) } @fields }
414 } (1..$::form->{paidaccounts});
416 @payments = sort_by { DateTime->from_kivitendo($_->{datepaid}) } @payments;
418 $::form->{paidaccounts} = max scalar(@payments), 1;
420 foreach my $idx (1 .. scalar(@payments)) {
421 my $payment = $payments[$idx - 1];
422 $::form->{"${_}_${idx}"} = $payment->{$_} for @fields;
427 $main::lxdebug->enter_sub();
429 my $form = $main::form;
430 my %myconfig = %main::myconfig;
431 my $locale = $main::locale;
433 $main::auth->assert('invoice_edit');
435 $form->{invtotal} = $form->{invsubtotal};
438 $form->{rows} = max 2,
439 $form->numtextrows($form->{notes}, 26, 8),
440 $form->numtextrows($form->{intnotes}, 35, 8);
443 # tax, total and subtotal calculations
444 my ($tax, $subtotal);
445 $form->{taxaccounts_array} = [ split(/ /, $form->{taxaccounts}) ];
447 if( $form->{customer_id} && !$form->{taxincluded_changed_by_user} ) {
448 my $customer = SL::DB::Customer->new(id => $form->{customer_id})->load();
449 $form->{taxincluded} = defined($customer->taxincluded_checked) ? $customer->taxincluded_checked : $myconfig{taxincluded_checked};
452 foreach my $item (@{ $form->{taxaccounts_array} }) {
453 if ($form->{"${item}_base"}) {
454 if ($form->{taxincluded}) {
455 $form->{"${item}_total"} = $form->round_amount( ($form->{"${item}_base"} * $form->{"${item}_rate"}
456 / (1 + $form->{"${item}_rate"})), 2);
457 $form->{"${item}_netto"} = $form->round_amount( ($form->{"${item}_base"} - $form->{"${item}_total"}), 2);
459 $form->{"${item}_total"} = $form->round_amount( $form->{"${item}_base"} * $form->{"${item}_rate"}, 2);
460 $form->{invtotal} += $form->{"${item}_total"};
467 $form->{follow_ups} = FU->follow_ups('trans_id' => $form->{id}) || [];
468 $form->{follow_ups_unfinished} = ( sum map { $_->{due} * 1 } @{ $form->{follow_ups} } ) || 0;
475 $form->{paidaccounts}++ if ($form->{"paid_$form->{paidaccounts}"});
476 $form->{paid_indices} = [ 1 .. $form->{paidaccounts} ];
478 # Standard Konto für Umlaufvermögen
479 my $accno_arap = IS->get_standard_accno_current_assets(\%myconfig, \%$form);
481 for my $i (1 .. $form->{paidaccounts}) {
482 $form->{"changeable_$i"} = 1;
483 if (SL::DB::Default->get->payments_changeable == 0) {
485 $form->{"changeable_$i"} = ($form->{"acc_trans_id_$i"})? 0 : 1;
486 } elsif (SL::DB::Default->get->payments_changeable == 2) {
488 $form->{"changeable_$i"} = (($form->{"gldate_$i"} eq '') ||
489 ($form->current_date(\%myconfig) eq $form->{"gldate_$i"}));
492 $form->{"selectAR_paid_$i"} = $form->{selectAR_paid};
493 if (!$form->{"AR_paid_$i"}) {
494 $form->{"selectAR_paid_$i"} =~ s/option>$accno_arap--(.*?)</option selected>$accno_arap--$1</;
496 $form->{"selectAR_paid_$i"} =~ s/option>\Q$form->{"AR_paid_$i"}\E/option selected>$form->{"AR_paid_$i"}/;
499 $totalpaid += $form->{"paid_$i"};
502 $form->{oldinvtotal} = $form->{invtotal};
504 $form->{ALL_DELIVERY_TERMS} = SL::DB::Manager::DeliveryTerm->get_all_sorted();
506 print $form->parse_html_template('is/form_footer', {
507 is_type_credit_note => ($form->{type} eq "credit_note"),
508 totalpaid => $totalpaid,
509 paid_missing => $form->{invtotal} - $totalpaid,
510 print_options => print_options(inline => 1),
511 show_storno => $form->{id} && !$form->{storno} && !IS->has_storno(\%myconfig, $form, "ar") && !$totalpaid,
512 show_delete => ($::instance_conf->get_is_changeable == 2)
513 ? ($form->current_date(\%myconfig) eq $form->{gldate})
514 : ($::instance_conf->get_is_changeable == 1),
515 today => DateTime->today,
517 ##print $form->parse_html_template('is/_payments'); # parser
518 ##print $form->parse_html_template('webdav/_list'); # parser
520 $main::lxdebug->leave_sub();
524 $main::lxdebug->enter_sub();
526 my $form = $main::form;
527 my %myconfig = %main::myconfig;
529 $main::auth->assert('invoice_edit');
531 &mark_as_paid_common(\%myconfig,"ar");
533 $main::lxdebug->leave_sub();
537 $main::lxdebug->enter_sub();
539 my $form = $main::form;
540 my %myconfig = %main::myconfig;
542 $main::auth->assert('invoice_edit');
544 my ($recursive_call) = @_;
546 $form->{print_and_post} = 0 if $form->{second_run};
547 my $taxincluded = $form->{taxincluded} ? "checked" : '';
550 &check_name("customer");
552 $form->{taxincluded} ||= $taxincluded;
554 if (!$form->{forex}) { # read exchangerate from input field (not hidden)
555 $form->{exchangerate} = $form->parse_amount(\%myconfig, $form->{exchangerate}) unless $recursive_call;
557 $form->{forex} = $form->check_exchangerate(\%myconfig, $form->{currency}, $form->{invdate}, 'buy');
558 $form->{exchangerate} = $form->{forex} if $form->{forex};
560 for my $i (1 .. $form->{paidaccounts}) {
561 next unless $form->{"paid_$i"};
562 map { $form->{"${_}_$i"} = $form->parse_amount(\%myconfig, $form->{"${_}_$i"}) } qw(paid exchangerate);
563 if (!$form->{"forex_$i"}) { #read exchangerate from input field (not hidden)
564 $form->{exchangerate} = $form->{"exchangerate_$i"};
566 $form->{"forex_$i"} = $form->check_exchangerate(\%myconfig, $form->{currency}, $form->{"datepaid_$i"}, 'buy');
567 $form->{"exchangerate_$i"} = $form->{"forex_$i"} if $form->{"forex_$i"};
570 my $i = $form->{rowcount};
571 my $exchangerate = $form->{exchangerate} || 1;
573 # if last row empty, check the form otherwise retrieve new item
574 if ( ($form->{"partnumber_$i"} eq "")
575 && ($form->{"description_$i"} eq "")
576 && ($form->{"partsgroup_$i"} eq "")) {
578 $form->{creditremaining} += ($form->{oldinvtotal} - $form->{oldtotalpaid});
583 IS->retrieve_item(\%myconfig, \%$form);
585 my $rows = scalar @{ $form->{item_list} };
587 $form->{"discount_$i"} = $form->parse_amount(\%myconfig, $form->{"discount_$i"}) / 100.0;
588 $form->{"discount_$i"} ||= $form->{customer_discount};
591 $form->{"qty_$i"} = $form->parse_amount(\%myconfig, $form->{"qty_$i"});
592 if( !$form->{"qty_$i"} ) {
593 $form->{"qty_$i"} = 1;
598 select_item(mode => 'IS', pre_entered_qty => $form->{"qty_$i"});
603 my $sellprice = $form->parse_amount(\%myconfig, $form->{"sellprice_$i"});
605 map { $form->{item_list}[$i]{$_} =~ s/\"/"/g } qw(partnumber description unit);
606 map { $form->{"${_}_$i"} = $form->{item_list}[0]{$_} } keys %{ $form->{item_list}[0] };
608 $form->{payment_id} = $form->{"part_payment_id_$i"} if $form->{"part_payment_id_$i"} ne "";
609 $form->{"discount_$i"} = 0 if $form->{"not_discountable_$i"};
611 $form->{"marge_price_factor_$i"} = $form->{item_list}->[0]->{price_factor};
613 ($sellprice || $form->{"sellprice_$i"}) =~ /\.(\d+)/;
614 my $decimalplaces = max 2, length $1;
617 $form->{"sellprice_$i"} = $sellprice;
619 my $record = _make_record();
620 my $price_source = SL::PriceSource->new(record_item => $record->items->[$i-1], record => $record);
621 my $best_price = $price_source->best_price;
622 my $best_discount = $price_source->best_discount;
625 $::form->{"sellprice_$i"} = $best_price->price;
626 $::form->{"active_price_source_$i"} = $best_price->source;
628 if ($best_discount) {
629 $::form->{"discount_$i"} = $best_discount->discount;
630 $::form->{"active_discount_source_$i"} = $best_discount->source;
633 # if there is an exchange rate adjust sellprice
634 $form->{"sellprice_$i"} /= $exchangerate;
637 $form->{"listprice_$i"} /= $exchangerate;
639 my $amount = $form->{"sellprice_$i"} * $form->{"qty_$i"} * (1 - $form->{"discount_$i"});
640 map { $form->{"${_}_base"} = 0 } split / /, $form->{taxaccounts};
641 map { $form->{"${_}_base"} += $amount } split / /, $form->{"taxaccounts_$i"};
642 map { $amount += ($form->{"${_}_base"} * $form->{"${_}_rate"}) } split / /, $form->{"taxaccounts_$i"} if !$form->{taxincluded};
644 $form->{creditremaining} -= $amount;
646 map { $form->{"${_}_$i"} = $form->format_amount(\%myconfig, $form->{"${_}_$i"}, $decimalplaces) } qw(sellprice lastcost);
648 $form->{"qty_$i"} = $form->format_amount(\%myconfig, $form->{"qty_$i"});
649 $form->{"discount_$i"} = $form->format_amount(\%myconfig, $form->{"discount_$i"} * 100.0);
656 # ok, so this is a new part
657 # ask if it is a part or service item
659 if ( $form->{"partsgroup_$i"}
660 && ($form->{"partsnumber_$i"} eq "")
661 && ($form->{"description_$i"} eq "")) {
663 $form->{"discount_$i"} = "";
667 $form->{"id_$i"} = 0;
672 $main::lxdebug->leave_sub();
676 $main::lxdebug->enter_sub();
678 my $form = $main::form;
679 my %myconfig = %main::myconfig;
680 my $locale = $main::locale;
682 $main::auth->assert('invoice_edit');
684 $form->mtime_ischanged('ar') ;
685 my $invdate = $form->datetonum($form->{invdate}, \%myconfig);
687 $form->{defaultcurrency} = $form->get_default_currency(\%myconfig);
688 for my $i (1 .. $form->{paidaccounts}) {
689 if ($form->{"paid_$i"}) {
690 my $datepaid = $form->datetonum($form->{"datepaid_$i"}, \%myconfig);
692 $form->isblank("datepaid_$i", $locale->text('Payment date missing!'));
695 if ($form->{currency} ne $form->{defaultcurrency}) {
696 $form->{"exchangerate_$i"} = $form->{exchangerate}
697 if ($invdate == $datepaid);
698 $form->isblank("exchangerate_$i",
699 $locale->text('Exchangerate for payment missing!'));
703 # Abgeschlossene Zeiträume nur für den letzten (aktuellen) Zahlungseingang prüfen
704 # Details s.a. Bug 1502
705 # Das Problem ist jetzt, dass man Zahlungseingänge nachträglich ändern kann
706 # Wobei dies für Installationen die sowieso nicht mit Bücherkontrolle arbeiten keinen
707 # keinen Unterschied macht.
708 # Optimal wäre, wenn gegen einen Zeitstempel des Zahlungsfelds geprüft würde ...
709 # Das Problem hierbei ist, dass in IS.pm post_invoice IMMER alle Zahlungseingänge aus $form
710 # erneut gespeichert werden. Prinzipiell wäre es besser NUR die Änderungen des Rechnungs-
711 # belegs (neue Zahlung aber nichts anderes) zu speichern ...
712 # Vielleicht könnte man ähnlich wie bei Rechnung löschen verfahren
713 $form->error($locale->text('Cannot post payment for a closed period!'))
714 if ($form->date_closed($form->{"datepaid_$form->{paidaccounts}"}, \%myconfig));
716 ($form->{AR}) = split /--/, $form->{AR};
717 ($form->{AR_paid}) = split /--/, $form->{AR_paid};
719 if ( IS->post_payment(\%myconfig, \%$form) ) {
720 $form->{snumbers} = qq|invnumber_| . $form->{invnumber};
721 $form->{what_done} = 'invoice';
722 $form->{addition} = "PAYMENT POSTED";
724 $form->redirect($locale->text('Payment posted!'))
726 $form->error($locale->text('Cannot post payment!'));
729 $main::lxdebug->leave_sub();
733 $main::lxdebug->enter_sub();
735 my $form = $main::form;
736 my %myconfig = %main::myconfig;
737 my $locale = $main::locale;
739 $main::auth->assert('invoice_edit');
740 $form->mtime_ischanged('ar');
742 $form->{defaultcurrency} = $form->get_default_currency(\%myconfig);
743 $form->isblank("invdate", $locale->text('Invoice Date missing!'));
744 $form->isblank("customer", $locale->text('Customer missing!'));
745 $form->error($locale->text('Cannot post invoice for a closed period!'))
746 if ($form->date_closed($form->{"invdate"}, \%myconfig));
748 $form->{invnumber} =~ s/^\s*//g;
749 $form->{invnumber} =~ s/\s*$//g;
751 # if oldcustomer ne customer redo form
752 if (&check_name('customer')) {
757 if ($myconfig{mandatory_departments} && !$form->{department_id}) {
758 $form->{saved_message} = $::locale->text('You have to specify a department.');
763 if ($form->{second_run}) {
764 $form->{print_and_post} = 0;
767 remove_emptied_rows();
770 my $closedto = $form->datetonum($form->{closedto}, \%myconfig);
771 my $invdate = $form->datetonum($form->{invdate}, \%myconfig);
773 $form->error($locale->text('Cannot post transaction above the maximum future booking date!'))
774 if ($form->date_max_future($invdate, \%myconfig));
775 $form->error($locale->text('Cannot post invoice for a closed period!'))
776 if ($invdate <= $closedto);
778 $form->isblank("exchangerate", $locale->text('Exchangerate missing!'))
779 if ($form->{currency} ne $form->{defaultcurrency});
781 for my $i (1 .. $form->{paidaccounts}) {
782 if ($form->parse_amount(\%myconfig, $form->{"paid_$i"})) {
783 my $datepaid = $form->datetonum($form->{"datepaid_$i"}, \%myconfig);
785 $form->isblank("datepaid_$i", $locale->text('Payment date missing!'));
787 $form->error($locale->text('Cannot post payment for a closed period!'))
788 if ($form->date_closed($form->{"datepaid_$i"}, \%myconfig));
790 if ($form->{currency} ne $form->{defaultcurrency}) {
791 $form->{"exchangerate_$i"} = $form->{exchangerate}
792 if ($invdate == $datepaid);
793 $form->isblank("exchangerate_$i",
794 $locale->text('Exchangerate for payment missing!'));
799 ($form->{AR}) = split /--/, $form->{AR};
800 ($form->{AR_paid}) = split /--/, $form->{AR_paid};
801 $form->{storno} ||= 0;
803 $form->{label} = $form->{type} eq 'credit_note' ? $locale->text('Credit Note') : $locale->text('Invoice');
805 $form->{id} = 0 if $form->{postasnew};
807 # get new invnumber in sequence if no invnumber is given or if posasnew was requested
808 if ($form->{postasnew}) {
809 if ($form->{type} eq "credit_note") {
810 undef($form->{cnnumber});
812 undef($form->{invnumber});
818 my $terms = get_payment_terms_for_invoice();
819 $form->{duedate} = $terms->calc_date(reference_date => $form->{invdate}, due_date => $form->{due_due})->to_kivitendo if $terms;
821 # If transfer_out is requested, get rose db handle and do post and
822 # transfer out in one transaction. Otherwise just post the invoice.
823 if ($::instance_conf->get_is_transfer_out && $form->{type} ne 'credit_note' && !$form->{storno}) {
824 require SL::DB::Inventory;
825 my $rose_db = SL::DB::Inventory->new->db;
828 if (!$rose_db->with_transaction(sub {
830 if (!IS->post_invoice(\%myconfig, \%$form, $rose_db->dbh)) {
831 push @errors, $locale->text('Cannot post invoice!');
834 my $err = IS->transfer_out(\%$form, $rose_db->dbh);
836 push @errors, @{ $err };
837 die 'transfer error';
842 push @errors, $EVAL_ERROR;
843 die 'transaction error';
848 push @errors, $rose_db->error;
849 $form->error($locale->text('Cannot post invoice and/or transfer out! Error message:') . "\n" . join("\n", @errors));
852 if (!IS->post_invoice(\%myconfig, \%$form)) {
853 $form->error($locale->text('Cannot post invoice!'));
857 remove_draft() if $form->{remove_draft};
859 if(!exists $form->{addition}) {
860 $form->{snumbers} = 'invnumber' .'_'. $form->{invnumber}; # ($form->{type} eq 'credit_note' ? 'cnnumber' : 'invnumber') .'_'. $form->{invnumber};
861 $form->{what_done} = 'invoice';
862 $form->{addition} = $form->{print_and_post} ? "PRINTED AND POSTED" :
863 $form->{storno} ? "STORNO" :
868 if (!$form->{no_redirect_after_post}) {
869 $form->{action} = 'edit';
870 $form->{script} = 'is.pl';
871 $form->{saved_message} = $form->{label} . " $form->{invnumber} " . $locale->text('posted!');
872 $form->{callback} = build_std_url(qw(action edit id callback saved_message));
876 $main::lxdebug->leave_sub();
880 $main::lxdebug->enter_sub();
882 my $form = $main::form;
884 $main::auth->assert('invoice_edit');
886 my $old_form = Form->new;
887 $form->{no_redirect_after_post} = 1;
888 $form->{print_and_post} = 1;
892 $main::lxdebug->leave_sub();
897 $main::lxdebug->enter_sub();
899 my $form = $main::form;
900 my %myconfig = %main::myconfig;
902 $main::auth->assert('invoice_edit');
904 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)};
906 $form->{paidaccounts} = 1;
907 $form->{invdate} = $form->current_date(\%myconfig);
908 my $terms = get_payment_terms_for_invoice();
909 $form->{duedate} = $terms ? $terms->calc_date(reference_date => $form->{invdate})->to_kivitendo : $form->{invdate};
910 $form->{employee_id} = SL::DB::Manager::Employee->current->id;
911 $form->{forex} = $form->check_exchangerate(\%myconfig, $form->{currency}, $form->{invdate}, 'buy');
912 $form->{exchangerate} = $form->{forex} if $form->{forex};
914 $form->{"converted_from_invoice_id_$_"} = delete $form->{"invoice_id_$_"} for 1 .. $form->{"rowcount"};
916 $form->{useasnew} = 1;
919 $main::lxdebug->leave_sub();
923 $main::lxdebug->enter_sub();
925 my $form = $main::form;
926 my %myconfig = %main::myconfig;
927 my $locale = $main::locale;
929 $main::auth->assert('invoice_edit');
931 if ($form->{storno}) {
932 $form->error($locale->text('Cannot storno storno invoice!'));
935 if (IS->has_storno(\%myconfig, $form, "ar")) {
936 $form->error($locale->text("Invoice has already been storno'd!"));
938 if ($form->datetonum($form->{invdate}, \%myconfig) <= $form->datetonum($form->{closedto}, \%myconfig)) {
939 $form->error($locale->text('Cannot storno invoice for a closed period!'));
942 # save the history of invoice being stornoed
943 $form->{snumbers} = qq|invnumber_| . $form->{invnumber};
944 $form->{what_done} = 'invoice';
945 $form->{addition} = "STORNO";
948 map({ my $key = $_; delete($form->{$key}) unless (grep({ $key eq $_ } qw(id login password type))); } keys(%{ $form }));
954 # Payments must not be recorded for the new storno invoice.
955 $form->{paidaccounts} = 0;
956 map { my $key = $_; delete $form->{$key} if grep { $key =~ /^$_/ } qw(datepaid_ gldate_ acc_trans_id_ source_ memo_ paid_ exchangerate_ AR_paid_) } keys %{ $form };
958 $form->{storno_id} = $form->{id};
961 $form->{invnumber} = "Storno zu " . $form->{invnumber};
962 $form->{invdate} = DateTime->today->to_lxoffice;
964 # set new ids for storno invoice
965 delete $form->{"invoice_id_$_"} for 1 .. $form->{"rowcount"};
968 $main::lxdebug->leave_sub();
972 $main::lxdebug->enter_sub();
974 my $form = $main::form;
976 $main::auth->assert('invoice_edit');
978 $form->{preview} = 1;
979 my $old_form = Form->new;
980 for (keys %$form) { $old_form->{$_} = $form->{$_} }
982 &print_form($old_form);
983 $main::lxdebug->leave_sub();
988 $main::lxdebug->enter_sub();
990 my $form = $main::form;
991 my $locale = $main::locale;
993 $main::auth->assert('invoice_edit');
995 if ($form->{second_run}) {
996 $form->{print_and_post} = 0;
1001 <form method="post" action="$form->{script}">
1004 # delete action variable
1005 map { delete $form->{$_} } qw(action header);
1007 foreach my $key (keys %$form) {
1008 next if (($key eq 'login') || ($key eq 'password') || ('' ne ref $form->{$key}));
1009 $form->{$key} =~ s/\"/"/g;
1010 print qq|<input type="hidden" name="$key" value="$form->{$key}">\n|;
1014 <h2 class="confirm">| . $locale->text('Confirm!') . qq|</h2>
1017 . $locale->text('Are you sure you want to delete Invoice Number')
1018 . qq| $form->{invnumber}
1022 <input name="action" class="submit" type="submit" value="|
1023 . $locale->text('Yes') . qq|">
1027 $main::lxdebug->leave_sub();
1031 $main::lxdebug->enter_sub();
1033 my $form = $main::form;
1034 my %myconfig = %main::myconfig;
1035 my $locale = $main::locale;
1037 $main::auth->assert('invoice_edit');
1039 $form->{transdate} = $form->{invdate} = $form->current_date(\%myconfig);
1041 $form->current_date(\%myconfig, $form->{invdate}, $form->{terms} * 1);
1043 $form->{convert_from_ar_ids} = $form->{id};
1045 $form->{rowcount}--;
1048 $form->{title} = $locale->text('Add Credit Note');
1049 $form->{script} = 'is.pl';
1051 # Bei Gutschriften bezug zur Rechnungsnummer
1052 $form->{invnumber_for_credit_note} = $form->{invnumber};
1053 # bo creates the id, reset it
1054 map { delete $form->{$_} }
1055 qw(id invnumber subject message cc bcc printed emailed queued);
1056 $form->{ $form->{vc} } =~ s/--.*//g;
1057 $form->{type} = "credit_note";
1060 map { $form->{"select$_"} = "" } ($form->{vc}, 'currency');
1062 # map { $form->{$_} = $form->parse_amount(\%myconfig, $form->{$_}) }
1063 # qw(creditlimit creditremaining);
1065 # set new persistent ids for credit note and link previous invoice id
1066 $form->{"converted_from_invoice_id_$_"} = delete $form->{"invoice_id_$_"} for 1 .. $form->{"rowcount"};
1068 my $currency = $form->{currency};
1071 $form->{currency} = $currency;
1072 $form->{forex} = $form->check_exchangerate( \%myconfig, $form->{currency}, $form->{invdate}, 'buy');
1073 $form->{exchangerate} = $form->{forex} || '';
1075 $form->{creditremaining} -= ($form->{oldinvtotal} - $form->{ordtotal});
1077 # bei Gutschriften werden Zahlungseingänge aus Rechnung nicht übernommen
1078 for my $i (1 .. $form->{paidaccounts}) {
1079 delete $form->{"paid_$i"};
1080 delete $form->{"source_$i"};
1081 delete $form->{"memo_$i"};
1082 delete $form->{"datepaid_$i"};
1083 delete $form->{"gldate_$i"};
1084 delete $form->{"acc_trans_id_$i"};
1085 delete $form->{"AR_paid_$i"};
1087 $form->{paidaccounts} = 1;
1094 $main::lxdebug->leave_sub();
1098 $::lxdebug->enter_sub;
1100 $::auth->assert('invoice_edit');
1104 my $new_rowcount = $::form->{"rowcount"} * 1 + 1;
1105 $::form->{"project_id_${new_rowcount}"} = $::form->{"globalproject_id"};
1107 $::form->language_payment(\%::myconfig);
1109 Common::webdav_folder($::form);
1112 display_row(++$::form->{rowcount});
1115 $::lxdebug->leave_sub;
1119 $main::lxdebug->enter_sub();
1121 my $form = $main::form;
1122 my %myconfig = %main::myconfig;
1123 my $locale = $main::locale;
1125 $main::auth->assert('invoice_edit');
1127 if (IS->delete_invoice(\%myconfig, \%$form)) {
1128 # saving the history
1129 if(!exists $form->{addition}) {
1130 $form->{snumbers} = 'invnumber' .'_'. $form->{invnumber}; # ($form->{type} eq 'credit_note' ? 'cnnumber' : 'invnumber') .'_'. $form->{invnumber};
1131 $form->{what_done} = 'invoice';
1132 $form->{addition} = "DELETED";
1133 $form->save_history;
1135 # /saving the history
1136 $form->redirect($locale->text('Invoice deleted!'));
1138 $form->error($locale->text('Cannot delete invoice!'));
1140 $main::lxdebug->leave_sub();
1143 sub post_and_e_mail {
1148 $main::lxdebug->enter_sub();
1150 my $form = $main::form;
1152 $main::auth->assert('invoice_edit');
1155 $form->{no_redirect_after_post} = 1;
1157 my $saved_form = save_form();
1161 restore_form($saved_form, 0, qw(id invnumber));
1166 $main::lxdebug->leave_sub();