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->{taxincluded_changed_by_user} = 1;
100 # show history button
101 $form->{javascript} = qq|<script type="text/javascript" src="js/show_history.js"></script>|;
103 my ($language_id, $printer_id);
104 if ($form->{print_and_post}) {
105 $form->{action} = "print";
106 $form->{resubmit} = 1;
107 $language_id = $form->{language_id};
108 $printer_id = $form->{printer_id};
112 if ($form->{type} eq "credit_note") {
113 $form->{title} = $locale->text('Edit Credit Note');
114 $form->{title} = $locale->text('Edit Storno Credit Note') if $form->{storno};
116 $form->{title} = $locale->text('Edit Sales Invoice');
117 $form->{title} = $locale->text('Edit Storno Invoice') if $form->{storno};
121 if ($form->{print_and_post}) {
122 $form->{language_id} = $language_id;
123 $form->{printer_id} = $printer_id;
128 $main::lxdebug->leave_sub();
132 $main::lxdebug->enter_sub();
134 my $form = $main::form;
135 my %myconfig = %main::myconfig;
137 $main::auth->assert('invoice_edit');
139 $form->{vc} = 'customer';
142 $form->create_links("AR", \%myconfig, "customer");
144 if ($form->{all_customer}) {
145 unless ($form->{customer_id}) {
146 $form->{customer_id} = $form->{all_customer}->[0]->{id};
147 $form->{salesman_id} = $form->{all_customer}->[0]->{salesman_id};
151 my $editing = $form->{id};
153 $form->backup_vars(qw(payment_id language_id taxzone_id salesman_id
154 taxincluded currency cp_id intnotes id shipto_id
157 IS->get_customer(\%myconfig, \%$form);
159 #quote all_customer Bug 133
160 foreach my $ref (@{ $form->{all_customer} }) {
161 $ref->{name} = $form->quote($ref->{name});
164 $form->restore_vars(qw(id));
166 IS->retrieve_invoice(\%myconfig, \%$form);
167 $form->restore_vars(qw(payment_id language_id taxzone_id currency intnotes
168 cp_id shipto_id delivery_term_id));
169 $form->restore_vars(qw(taxincluded)) if $form->{id};
170 $form->restore_vars(qw(salesman_id)) if $editing;
173 # build vendor/customer drop down compatibility... don't ask
174 if (@{ $form->{"all_customer"} }) {
175 $form->{"selectcustomer"} = 1;
176 $form->{customer} = qq|$form->{customer}--$form->{"customer_id"}|;
179 $form->{"oldcustomer"} = $form->{customer};
181 if ($form->{"oldcustomer"} !~ m/--\d+$/ && $form->{"customer_id"}) {
182 $form->{"oldcustomer"} .= qq|--$form->{"customer_id"}|
186 # $form->{oldcustomer} = "$form->{customer}--$form->{customer_id}";
187 # $form->{selectcustomer} = 1;
189 $form->{employee} = "$form->{employee}--$form->{employee_id}";
192 $form->{forex} = $form->{exchangerate};
193 my $exchangerate = ($form->{exchangerate}) ? $form->{exchangerate} : 1;
195 foreach my $key (keys %{ $form->{AR_links} }) {
196 foreach my $ref (@{ $form->{AR_links}{$key} }) {
197 $form->{"select$key"} .= "<option>$ref->{accno}--$ref->{description}</option>\n";
200 if ($key eq "AR_paid") {
201 next unless $form->{acc_trans}{$key};
202 for my $i (1 .. scalar @{ $form->{acc_trans}{$key} }) {
203 $form->{"AR_paid_$i"} = "$form->{acc_trans}{$key}->[$i-1]->{accno}--$form->{acc_trans}{$key}->[$i-1]->{description}";
205 $form->{"acc_trans_id_$i"} = $form->{acc_trans}{$key}->[$i - 1]->{acc_trans_id};
207 $form->{"paid_$i"} = $form->{acc_trans}{$key}->[$i - 1]->{amount} * -1;
208 $form->{"datepaid_$i"} = $form->{acc_trans}{$key}->[$i - 1]->{transdate};
209 $form->{"gldate_$i"} = $form->{acc_trans}{$key}->[$i - 1]->{gldate};
210 $form->{"exchangerate_$i"} = $form->{acc_trans}{$key}->[$i - 1]->{exchangerate};
211 $form->{"forex_$i"} = $form->{"exchangerate_$i"};
212 $form->{"source_$i"} = $form->{acc_trans}{$key}->[$i - 1]->{source};
213 $form->{"memo_$i"} = $form->{acc_trans}{$key}->[$i - 1]->{memo};
215 $form->{paidaccounts} = $i;
218 $form->{$key} = "$form->{acc_trans}{$key}->[0]->{accno}--$form->{acc_trans}{$key}->[0]->{description}";
222 $form->{paidaccounts} = 1 unless (exists $form->{paidaccounts});
224 $form->{AR} = $form->{AR_1} unless $form->{id};
226 $form->{locked} = ($form->datetonum($form->{invdate}, \%myconfig)
227 <= $form->datetonum($form->{closedto}, \%myconfig));
229 $main::lxdebug->leave_sub();
232 sub prepare_invoice {
233 $main::lxdebug->enter_sub();
235 my $form = $main::form;
236 my %myconfig = %main::myconfig;
238 $main::auth->assert('invoice_edit');
240 if ($form->{type} eq "credit_note") {
241 $form->{type} = "credit_note";
242 $form->{formname} = "credit_note";
244 $form->{type} = "invoice";
245 $form->{formname} = "invoice";
252 foreach my $ref (@{ $form->{invoice_details} }) {
255 map { $form->{"${_}_$i"} = $ref->{$_} } keys %{$ref};
257 $form->{"discount_$i"} = $form->format_amount(\%myconfig, $form->{"discount_$i"} * 100);
258 my ($dec) = ($form->{"sellprice_$i"} =~ /\.(\d+)/);
260 my $decimalplaces = ($dec > 2) ? $dec : 2;
262 $form->{"sellprice_$i"} = $form->format_amount(\%myconfig, $form->{"sellprice_$i"}, $decimalplaces);
263 (my $dec_qty) = ($form->{"qty_$i"} =~ /\.(\d+)/);
264 $dec_qty = length $dec_qty;
266 $form->{"lastcost_$i"} = $form->format_amount(\%myconfig, $form->{"lastcost_$i"}, $decimalplaces);
268 $form->{"qty_$i"} = $form->format_amount(\%myconfig, $form->{"qty_$i"}, $dec_qty);
270 $form->{"sellprice_pg_$i"} = join ('--', $form->{"sellprice_$i"}, $form->{"pricegroup_id_$i"});
272 $form->{rowcount} = $i;
276 $main::lxdebug->leave_sub();
280 $main::lxdebug->enter_sub();
282 my $form = $main::form;
283 my %myconfig = %main::myconfig;
284 my $locale = $main::locale;
285 my $cgi = $::request->{cgi};
287 $main::auth->assert('invoice_edit');
293 require SL::DB::Invoice;
294 $TMPL_VAR{invoice_obj} = SL::DB::Invoice->new(id => $form->{id})->load;
296 $form->{employee_id} = $form->{old_employee_id} if $form->{old_employee_id};
297 $form->{salesman_id} = $form->{old_salesman_id} if $form->{old_salesman_id};
299 $form->{defaultcurrency} = $form->get_default_currency(\%myconfig);
301 $form->get_lists("taxzones" => ($form->{id} ? "ALL_TAXZONES" : "ALL_ACTIVE_TAXZONES"),
302 "currencies" => "ALL_CURRENCIES",
303 "customers" => "ALL_CUSTOMERS",
304 "departments" => "all_departments",
305 "price_factors" => "ALL_PRICE_FACTORS");
308 my @old_project_ids = uniq grep { $_ } map { $_ * 1 } ($form->{"globalproject_id"}, map { $form->{"project_id_$_"} } 1..$form->{"rowcount"});
309 my @old_ids_cond = @old_project_ids ? (id => \@old_project_ids) : ();
311 if ($::instance_conf->get_customer_projects_only_in_sales) {
314 customer_id => $::form->{customer_id},
315 billable_customer_id => $::form->{customer_id},
320 and => [ active => 1, @customer_cond ],
324 $TMPL_VAR{ALL_PROJECTS} = SL::DB::Manager::Project->get_all_sorted(query => \@conditions);
325 $form->{ALL_PROJECTS} = $TMPL_VAR{ALL_PROJECTS}; # make projects available for second row drop-down in io.pl
326 $TMPL_VAR{ALL_EMPLOYEES} = SL::DB::Manager::Employee->get_all_sorted(query => [ or => [ id => $::form->{employee_id}, deleted => 0 ] ]);
327 $TMPL_VAR{ALL_SALESMEN} = SL::DB::Manager::Employee->get_all_sorted(query => [ or => [ id => $::form->{salesman_id}, deleted => 0 ] ]);
328 $TMPL_VAR{ALL_SHIPTO} = SL::DB::Manager::Shipto->get_all_sorted(query => [
329 or => [ trans_id => $::form->{"$::form->{vc}_id"} * 1, and => [ shipto_id => $::form->{shipto_id} * 1, trans_id => undef ] ]
331 $TMPL_VAR{ALL_CONTACTS} = SL::DB::Manager::Contact->get_all_sorted(query => [
333 cp_cv_id => $::form->{"$::form->{vc}_id"} * 1,
336 cp_id => $::form->{cp_id} * 1
340 $TMPL_VAR{department_labels} = sub { "$_[0]->{description}--$_[0]->{id}" };
343 $TMPL_VAR{vc_keys} = sub { "$_[0]->{name}--$_[0]->{id}" };
344 $TMPL_VAR{vclimit} = $myconfig{vclimit};
345 $TMPL_VAR{vc_select} = "customer_or_vendor_selection_window('customer', '', 0, 0)";
346 push @custom_hiddens, "customer_id";
347 push @custom_hiddens, "oldcustomer";
348 push @custom_hiddens, "selectcustomer";
350 # currencies and exchangerate
351 my @values = map { $_ } @{ $form->{ALL_CURRENCIES} };
352 my %labels = map { $_ => $_ } @{ $form->{ALL_CURRENCIES} };
353 $form->{currency} = $form->{defaultcurrency} unless $form->{currency};
354 $form->{show_exchangerate} = $form->{currency} ne $form->{defaultcurrency};
355 $TMPL_VAR{currencies} = NTI($::request->{cgi}->popup_menu('-name' => 'currency', '-default' => $form->{"currency"},
356 '-values' => \@values, '-labels' => \%labels,
357 '-onchange' => "document.getElementById('update_button').click();"
358 )) if scalar @values;
359 push @custom_hiddens, "forex";
360 push @custom_hiddens, "exchangerate" if $form->{forex};
362 $TMPL_VAR{creditwarning} = ($form->{creditlimit} != 0) && ($form->{creditremaining} < 0) && !$form->{update};
363 $TMPL_VAR{is_credit_remaining_negativ} = $form->{creditremaining} =~ /-/;
365 my $follow_up_vc = $form->{customer};
366 $follow_up_vc =~ s/--\d*\s*$//;
367 $TMPL_VAR{customer_name} = $follow_up_vc;
369 # set option selected
370 foreach my $item (qw(AR)) {
371 $form->{"select$item"} =~ s/ selected//;
372 $form->{"select$item"} =~ s/option>\Q$form->{$item}\E/option selected>$form->{$item}/;
375 $TMPL_VAR{is_type_credit_note} = $form->{type} eq "credit_note";
376 $TMPL_VAR{is_format_html} = $form->{format} eq 'html';
377 $TMPL_VAR{dateformat} = $myconfig{dateformat};
378 $TMPL_VAR{numberformat} = $myconfig{numberformat};
381 $TMPL_VAR{HIDDENS} = [qw(
382 id action type media format queued printed emailed title vc discount
383 title creditlimit creditremaining tradediscount business closedto locked shipped storno storno_id
384 max_dunning_level dunning_amount dunning_description
385 shiptoname shiptostreet shiptozipcode shiptocity shiptocountry shiptocontact shiptophone shiptofax
386 shiptoemail shiptodepartment_1 shiptodepartment_2 shiptocp_gender message email subject cc bcc taxaccounts cursor_fokus
387 convert_from_do_ids convert_from_oe_ids convert_from_ar_ids useasnew
391 map { $_.'_rate', $_.'_description', $_.'_taxnumber' } split / /, $form->{taxaccounts}];
393 $::request->{layout}->use_javascript(map { "${_}.js" } qw(kivi.SalesPurchase ckeditor/ckeditor ckeditor/adapters/jquery kivi.io autocomplete_customer autocomplete_part client_js));
395 $TMPL_VAR{payment_terms_obj} = get_payment_terms_for_invoice();
396 $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};
400 print $form->parse_html_template("is/form_header", \%TMPL_VAR);
402 $main::lxdebug->leave_sub();
406 my @fields = qw(acc_trans_id gldate datepaid source memo paid AR_paid);
408 grep { $_->{paid} != 0 }
411 +{ map { ($_ => delete($::form->{"${_}_${idx}"})) } @fields }
412 } (1..$::form->{paidaccounts});
414 @payments = sort_by { DateTime->from_kivitendo($_->{datepaid}) } @payments;
416 $::form->{paidaccounts} = max scalar(@payments), 1;
418 foreach my $idx (1 .. scalar(@payments)) {
419 my $payment = $payments[$idx - 1];
420 $::form->{"${_}_${idx}"} = $payment->{$_} for @fields;
425 $main::lxdebug->enter_sub();
427 my $form = $main::form;
428 my %myconfig = %main::myconfig;
429 my $locale = $main::locale;
431 $main::auth->assert('invoice_edit');
433 $form->{invtotal} = $form->{invsubtotal};
436 $form->{rows} = max 2,
437 $form->numtextrows($form->{notes}, 26, 8),
438 $form->numtextrows($form->{intnotes}, 35, 8);
441 # tax, total and subtotal calculations
442 my ($tax, $subtotal);
443 $form->{taxaccounts_array} = [ split(/ /, $form->{taxaccounts}) ];
445 if( $form->{customer_id} && !$form->{taxincluded_changed_by_user} ) {
446 my $customer = SL::DB::Customer->new(id => $form->{customer_id})->load();
447 $form->{taxincluded} = defined($customer->taxincluded_checked) ? $customer->taxincluded_checked : $myconfig{taxincluded_checked};
450 foreach my $item (@{ $form->{taxaccounts_array} }) {
451 if ($form->{"${item}_base"}) {
452 if ($form->{taxincluded}) {
453 $form->{"${item}_total"} = $form->round_amount( ($form->{"${item}_base"} * $form->{"${item}_rate"}
454 / (1 + $form->{"${item}_rate"})), 2);
455 $form->{"${item}_netto"} = $form->round_amount( ($form->{"${item}_base"} - $form->{"${item}_total"}), 2);
457 $form->{"${item}_total"} = $form->round_amount( $form->{"${item}_base"} * $form->{"${item}_rate"}, 2);
458 $form->{invtotal} += $form->{"${item}_total"};
463 $form->{rounding} = $form->round_amount(
464 $form->round_amount($form->{invtotal}, 2, 1) - $form->round_amount($form->{invtotal}, 2), 2
466 $form->{invtotal} = $form->round_amount( $form->{invtotal}, 2, 1 );
470 $form->{follow_ups} = FU->follow_ups('trans_id' => $form->{id}) || [];
471 $form->{follow_ups_unfinished} = ( sum map { $_->{due} * 1 } @{ $form->{follow_ups} } ) || 0;
478 $form->{paidaccounts}++ if ($form->{"paid_$form->{paidaccounts}"});
479 $form->{paid_indices} = [ 1 .. $form->{paidaccounts} ];
481 # Standard Konto für Umlaufvermögen
482 my $accno_arap = IS->get_standard_accno_current_assets(\%myconfig, \%$form);
484 for my $i (1 .. $form->{paidaccounts}) {
485 $form->{"changeable_$i"} = 1;
486 if (SL::DB::Default->get->payments_changeable == 0) {
488 $form->{"changeable_$i"} = ($form->{"acc_trans_id_$i"})? 0 : 1;
489 } elsif (SL::DB::Default->get->payments_changeable == 2) {
491 $form->{"changeable_$i"} = (($form->{"gldate_$i"} eq '') ||
492 ($form->current_date(\%myconfig) eq $form->{"gldate_$i"}));
495 $form->{"selectAR_paid_$i"} = $form->{selectAR_paid};
496 if (!$form->{"AR_paid_$i"}) {
497 $form->{"selectAR_paid_$i"} =~ s/option>$accno_arap--(.*?)</option selected>$accno_arap--$1</;
499 $form->{"selectAR_paid_$i"} =~ s/option>\Q$form->{"AR_paid_$i"}\E/option selected>$form->{"AR_paid_$i"}/;
502 $totalpaid += $form->{"paid_$i"};
505 $form->{oldinvtotal} = $form->{invtotal};
507 $form->{ALL_DELIVERY_TERMS} = SL::DB::Manager::DeliveryTerm->get_all_sorted();
509 print $form->parse_html_template('is/form_footer', {
510 is_type_credit_note => ($form->{type} eq "credit_note"),
511 totalpaid => $totalpaid,
512 paid_missing => $form->{invtotal} - $totalpaid,
513 print_options => print_options(inline => 1),
514 show_storno => $form->{id} && !$form->{storno} && !IS->has_storno(\%myconfig, $form, "ar") && !$totalpaid,
515 show_delete => ($::instance_conf->get_is_changeable == 2)
516 ? ($form->current_date(\%myconfig) eq $form->{gldate})
517 : ($::instance_conf->get_is_changeable == 1),
518 today => DateTime->today,
520 ##print $form->parse_html_template('is/_payments'); # parser
521 ##print $form->parse_html_template('webdav/_list'); # parser
523 $main::lxdebug->leave_sub();
527 $main::lxdebug->enter_sub();
529 my $form = $main::form;
530 my %myconfig = %main::myconfig;
532 $main::auth->assert('invoice_edit');
534 &mark_as_paid_common(\%myconfig,"ar");
536 $main::lxdebug->leave_sub();
540 $main::lxdebug->enter_sub();
542 my $form = $main::form;
543 my %myconfig = %main::myconfig;
545 $main::auth->assert('invoice_edit');
547 my ($recursive_call) = @_;
549 $form->{print_and_post} = 0 if $form->{second_run};
550 my $taxincluded = $form->{taxincluded} ? "checked" : '';
553 &check_name("customer");
555 $form->{taxincluded} ||= $taxincluded;
557 if (!$form->{forex}) { # read exchangerate from input field (not hidden)
558 $form->{exchangerate} = $form->parse_amount(\%myconfig, $form->{exchangerate}) unless $recursive_call;
560 $form->{forex} = $form->check_exchangerate(\%myconfig, $form->{currency}, $form->{invdate}, 'buy');
561 $form->{exchangerate} = $form->{forex} if $form->{forex};
563 for my $i (1 .. $form->{paidaccounts}) {
564 next unless $form->{"paid_$i"};
565 map { $form->{"${_}_$i"} = $form->parse_amount(\%myconfig, $form->{"${_}_$i"}) } qw(paid exchangerate);
566 if (!$form->{"forex_$i"}) { #read exchangerate from input field (not hidden)
567 $form->{exchangerate} = $form->{"exchangerate_$i"};
569 $form->{"forex_$i"} = $form->check_exchangerate(\%myconfig, $form->{currency}, $form->{"datepaid_$i"}, 'buy');
570 $form->{"exchangerate_$i"} = $form->{"forex_$i"} if $form->{"forex_$i"};
573 my $i = $form->{rowcount};
574 my $exchangerate = $form->{exchangerate} || 1;
576 # if last row empty, check the form otherwise retrieve new item
577 if ( ($form->{"partnumber_$i"} eq "")
578 && ($form->{"description_$i"} eq "")
579 && ($form->{"partsgroup_$i"} eq "")) {
581 $form->{creditremaining} += ($form->{oldinvtotal} - $form->{oldtotalpaid});
586 IS->retrieve_item(\%myconfig, \%$form);
588 my $rows = scalar @{ $form->{item_list} };
590 $form->{"discount_$i"} = $form->parse_amount(\%myconfig, $form->{"discount_$i"}) / 100.0;
591 $form->{"discount_$i"} ||= $form->{customer_discount};
594 $form->{"qty_$i"} = $form->parse_amount(\%myconfig, $form->{"qty_$i"});
595 if( !$form->{"qty_$i"} ) {
596 $form->{"qty_$i"} = 1;
601 select_item(mode => 'IS', pre_entered_qty => $form->{"qty_$i"});
606 my $sellprice = $form->parse_amount(\%myconfig, $form->{"sellprice_$i"});
608 map { $form->{item_list}[$i]{$_} =~ s/\"/"/g } qw(partnumber description unit);
609 map { $form->{"${_}_$i"} = $form->{item_list}[0]{$_} } keys %{ $form->{item_list}[0] };
611 $form->{payment_id} = $form->{"part_payment_id_$i"} if $form->{"part_payment_id_$i"} ne "";
612 $form->{"discount_$i"} = 0 if $form->{"not_discountable_$i"};
614 $form->{"marge_price_factor_$i"} = $form->{item_list}->[0]->{price_factor};
616 ($sellprice || $form->{"sellprice_$i"}) =~ /\.(\d+)/;
617 my $decimalplaces = max 2, length $1;
620 $form->{"sellprice_$i"} = $sellprice;
622 my $record = _make_record();
623 my $price_source = SL::PriceSource->new(record_item => $record->items->[$i-1], record => $record);
624 my $best_price = $price_source->best_price;
625 my $best_discount = $price_source->best_discount;
628 $::form->{"sellprice_$i"} = $best_price->price;
629 $::form->{"active_price_source_$i"} = $best_price->source;
631 if ($best_discount) {
632 $::form->{"discount_$i"} = $best_discount->discount;
633 $::form->{"active_discount_source_$i"} = $best_discount->source;
636 # if there is an exchange rate adjust sellprice
637 $form->{"sellprice_$i"} /= $exchangerate;
640 $form->{"listprice_$i"} /= $exchangerate;
642 my $amount = $form->{"sellprice_$i"} * $form->{"qty_$i"} * (1 - $form->{"discount_$i"});
643 map { $form->{"${_}_base"} = 0 } split / /, $form->{taxaccounts};
644 map { $form->{"${_}_base"} += $amount } split / /, $form->{"taxaccounts_$i"};
645 map { $amount += ($form->{"${_}_base"} * $form->{"${_}_rate"}) } split / /, $form->{"taxaccounts_$i"} if !$form->{taxincluded};
647 $form->{creditremaining} -= $amount;
649 map { $form->{"${_}_$i"} = $form->format_amount(\%myconfig, $form->{"${_}_$i"}, $decimalplaces) } qw(sellprice lastcost);
651 $form->{"qty_$i"} = $form->format_amount(\%myconfig, $form->{"qty_$i"});
652 $form->{"discount_$i"} = $form->format_amount(\%myconfig, $form->{"discount_$i"} * 100.0);
659 # ok, so this is a new part
660 # ask if it is a part or service item
662 if ( $form->{"partsgroup_$i"}
663 && ($form->{"partsnumber_$i"} eq "")
664 && ($form->{"description_$i"} eq "")) {
666 $form->{"discount_$i"} = "";
670 $form->{"id_$i"} = 0;
675 $main::lxdebug->leave_sub();
679 $main::lxdebug->enter_sub();
681 my $form = $main::form;
682 my %myconfig = %main::myconfig;
683 my $locale = $main::locale;
685 $main::auth->assert('invoice_edit');
687 $form->mtime_ischanged('ar') ;
688 my $invdate = $form->datetonum($form->{invdate}, \%myconfig);
690 $form->{defaultcurrency} = $form->get_default_currency(\%myconfig);
691 for my $i (1 .. $form->{paidaccounts}) {
692 if ($form->{"paid_$i"}) {
693 my $datepaid = $form->datetonum($form->{"datepaid_$i"}, \%myconfig);
695 $form->isblank("datepaid_$i", $locale->text('Payment date missing!'));
698 if ($form->{currency} ne $form->{defaultcurrency}) {
699 $form->{"exchangerate_$i"} = $form->{exchangerate}
700 if ($invdate == $datepaid);
701 $form->isblank("exchangerate_$i",
702 $locale->text('Exchangerate for payment missing!'));
706 # Abgeschlossene Zeiträume nur für den letzten (aktuellen) Zahlungseingang prüfen
707 # Details s.a. Bug 1502
708 # Das Problem ist jetzt, dass man Zahlungseingänge nachträglich ändern kann
709 # Wobei dies für Installationen die sowieso nicht mit Bücherkontrolle arbeiten keinen
710 # keinen Unterschied macht.
711 # Optimal wäre, wenn gegen einen Zeitstempel des Zahlungsfelds geprüft würde ...
712 # Das Problem hierbei ist, dass in IS.pm post_invoice IMMER alle Zahlungseingänge aus $form
713 # erneut gespeichert werden. Prinzipiell wäre es besser NUR die Änderungen des Rechnungs-
714 # belegs (neue Zahlung aber nichts anderes) zu speichern ...
715 # Vielleicht könnte man ähnlich wie bei Rechnung löschen verfahren
716 $form->error($locale->text('Cannot post payment for a closed period!'))
717 if ($form->date_closed($form->{"datepaid_$form->{paidaccounts}"}, \%myconfig));
719 ($form->{AR}) = split /--/, $form->{AR};
720 ($form->{AR_paid}) = split /--/, $form->{AR_paid};
722 if ( IS->post_payment(\%myconfig, \%$form) ) {
723 $form->{snumbers} = qq|invnumber_| . $form->{invnumber};
724 $form->{what_done} = 'invoice';
725 $form->{addition} = "PAYMENT POSTED";
727 $form->redirect($locale->text('Payment posted!'))
729 $form->error($locale->text('Cannot post payment!'));
732 $main::lxdebug->leave_sub();
736 $main::lxdebug->enter_sub();
738 my $form = $main::form;
739 my %myconfig = %main::myconfig;
740 my $locale = $main::locale;
742 $main::auth->assert('invoice_edit');
743 $form->mtime_ischanged('ar');
745 $form->{defaultcurrency} = $form->get_default_currency(\%myconfig);
746 $form->isblank("invdate", $locale->text('Invoice Date missing!'));
747 $form->isblank("customer", $locale->text('Customer missing!'));
748 $form->error($locale->text('Cannot post invoice for a closed period!'))
749 if ($form->date_closed($form->{"invdate"}, \%myconfig));
751 $form->{invnumber} =~ s/^\s*//g;
752 $form->{invnumber} =~ s/\s*$//g;
754 # if oldcustomer ne customer redo form
755 if (&check_name('customer')) {
760 if ($myconfig{mandatory_departments} && !$form->{department_id}) {
761 $form->{saved_message} = $::locale->text('You have to specify a department.');
766 if ($form->{second_run}) {
767 $form->{print_and_post} = 0;
770 remove_emptied_rows();
773 my $closedto = $form->datetonum($form->{closedto}, \%myconfig);
774 my $invdate = $form->datetonum($form->{invdate}, \%myconfig);
776 $form->error($locale->text('Cannot post transaction above the maximum future booking date!'))
777 if ($form->date_max_future($invdate, \%myconfig));
778 $form->error($locale->text('Cannot post invoice for a closed period!'))
779 if ($invdate <= $closedto);
781 $form->isblank("exchangerate", $locale->text('Exchangerate missing!'))
782 if ($form->{currency} ne $form->{defaultcurrency});
784 for my $i (1 .. $form->{paidaccounts}) {
785 if ($form->parse_amount(\%myconfig, $form->{"paid_$i"})) {
786 my $datepaid = $form->datetonum($form->{"datepaid_$i"}, \%myconfig);
788 $form->isblank("datepaid_$i", $locale->text('Payment date missing!'));
790 $form->error($locale->text('Cannot post payment for a closed period!'))
791 if ($form->date_closed($form->{"datepaid_$i"}, \%myconfig));
793 if ($form->{currency} ne $form->{defaultcurrency}) {
794 $form->{"exchangerate_$i"} = $form->{exchangerate}
795 if ($invdate == $datepaid);
796 $form->isblank("exchangerate_$i",
797 $locale->text('Exchangerate for payment missing!'));
802 ($form->{AR}) = split /--/, $form->{AR};
803 ($form->{AR_paid}) = split /--/, $form->{AR_paid};
804 $form->{storno} ||= 0;
806 $form->{label} = $form->{type} eq 'credit_note' ? $locale->text('Credit Note') : $locale->text('Invoice');
808 $form->{id} = 0 if $form->{postasnew};
810 # get new invnumber in sequence if no invnumber is given or if posasnew was requested
811 if ($form->{postasnew}) {
812 if ($form->{type} eq "credit_note") {
813 undef($form->{cnnumber});
815 undef($form->{invnumber});
821 my $terms = get_payment_terms_for_invoice();
822 $form->{duedate} = $terms->calc_date(reference_date => $form->{invdate}, due_date => $form->{due_due})->to_kivitendo if $terms;
824 # If transfer_out is requested, get rose db handle and do post and
825 # transfer out in one transaction. Otherwise just post the invoice.
826 if ($::instance_conf->get_is_transfer_out && $form->{type} ne 'credit_note' && !$form->{storno}) {
827 require SL::DB::Inventory;
828 my $rose_db = SL::DB::Inventory->new->db;
831 if (!$rose_db->with_transaction(sub {
833 if (!IS->post_invoice(\%myconfig, \%$form, $rose_db->dbh)) {
834 push @errors, $locale->text('Cannot post invoice!');
837 my $err = IS->transfer_out(\%$form, $rose_db->dbh);
839 push @errors, @{ $err };
840 die 'transfer error';
845 push @errors, $EVAL_ERROR;
846 die 'transaction error';
851 push @errors, $rose_db->error;
852 $form->error($locale->text('Cannot post invoice and/or transfer out! Error message:') . "\n" . join("\n", @errors));
855 if (!IS->post_invoice(\%myconfig, \%$form)) {
856 $form->error($locale->text('Cannot post invoice!'));
860 remove_draft() if $form->{remove_draft};
862 if(!exists $form->{addition}) {
863 $form->{snumbers} = 'invnumber' .'_'. $form->{invnumber}; # ($form->{type} eq 'credit_note' ? 'cnnumber' : 'invnumber') .'_'. $form->{invnumber};
864 $form->{what_done} = 'invoice';
865 $form->{addition} = $form->{print_and_post} ? "PRINTED AND POSTED" :
866 $form->{storno} ? "STORNO" :
871 if (!$form->{no_redirect_after_post}) {
872 $form->{action} = 'edit';
873 $form->{script} = 'is.pl';
874 $form->{saved_message} = $form->{label} . " $form->{invnumber} " . $locale->text('posted!');
875 $form->{callback} = build_std_url(qw(action edit id callback saved_message));
879 $main::lxdebug->leave_sub();
883 $main::lxdebug->enter_sub();
885 my $form = $main::form;
887 $main::auth->assert('invoice_edit');
889 my $old_form = Form->new;
890 $form->{no_redirect_after_post} = 1;
891 $form->{print_and_post} = 1;
895 $main::lxdebug->leave_sub();
900 $main::lxdebug->enter_sub();
902 my $form = $main::form;
903 my %myconfig = %main::myconfig;
905 $main::auth->assert('invoice_edit');
907 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)};
909 $form->{paidaccounts} = 1;
910 $form->{invdate} = $form->current_date(\%myconfig);
911 my $terms = get_payment_terms_for_invoice();
912 $form->{duedate} = $terms ? $terms->calc_date(reference_date => $form->{invdate})->to_kivitendo : $form->{invdate};
913 $form->{employee_id} = SL::DB::Manager::Employee->current->id;
914 $form->{forex} = $form->check_exchangerate(\%myconfig, $form->{currency}, $form->{invdate}, 'buy');
915 $form->{exchangerate} = $form->{forex} if $form->{forex};
917 $form->{"converted_from_invoice_id_$_"} = delete $form->{"invoice_id_$_"} for 1 .. $form->{"rowcount"};
919 $form->{useasnew} = 1;
922 $main::lxdebug->leave_sub();
926 $main::lxdebug->enter_sub();
928 my $form = $main::form;
929 my %myconfig = %main::myconfig;
930 my $locale = $main::locale;
932 $main::auth->assert('invoice_edit');
934 if ($form->{storno}) {
935 $form->error($locale->text('Cannot storno storno invoice!'));
938 if (IS->has_storno(\%myconfig, $form, "ar")) {
939 $form->error($locale->text("Invoice has already been storno'd!"));
941 if ($form->datetonum($form->{invdate}, \%myconfig) <= $form->datetonum($form->{closedto}, \%myconfig)) {
942 $form->error($locale->text('Cannot storno invoice for a closed period!'));
945 # save the history of invoice being stornoed
946 $form->{snumbers} = qq|invnumber_| . $form->{invnumber};
947 $form->{what_done} = 'invoice';
948 $form->{addition} = "STORNO";
951 map({ my $key = $_; delete($form->{$key}) unless (grep({ $key eq $_ } qw(id login password type))); } keys(%{ $form }));
957 # Payments must not be recorded for the new storno invoice.
958 $form->{paidaccounts} = 0;
959 map { my $key = $_; delete $form->{$key} if grep { $key =~ /^$_/ } qw(datepaid_ gldate_ acc_trans_id_ source_ memo_ paid_ exchangerate_ AR_paid_) } keys %{ $form };
961 $form->{storno_id} = $form->{id};
964 $form->{invnumber} = "Storno zu " . $form->{invnumber};
965 $form->{invdate} = DateTime->today->to_lxoffice;
967 # set new ids for storno invoice
968 delete $form->{"invoice_id_$_"} for 1 .. $form->{"rowcount"};
971 $main::lxdebug->leave_sub();
975 $main::lxdebug->enter_sub();
977 my $form = $main::form;
979 $main::auth->assert('invoice_edit');
981 $form->{preview} = 1;
982 my $old_form = Form->new;
983 for (keys %$form) { $old_form->{$_} = $form->{$_} }
985 &print_form($old_form);
986 $main::lxdebug->leave_sub();
991 $main::lxdebug->enter_sub();
993 my $form = $main::form;
994 my $locale = $main::locale;
996 $main::auth->assert('invoice_edit');
998 if ($form->{second_run}) {
999 $form->{print_and_post} = 0;
1004 <form method="post" action="$form->{script}">
1007 # delete action variable
1008 map { delete $form->{$_} } qw(action header);
1010 foreach my $key (keys %$form) {
1011 next if (($key eq 'login') || ($key eq 'password') || ('' ne ref $form->{$key}));
1012 $form->{$key} =~ s/\"/"/g;
1013 print qq|<input type="hidden" name="$key" value="$form->{$key}">\n|;
1017 <h2 class="confirm">| . $locale->text('Confirm!') . qq|</h2>
1020 . $locale->text('Are you sure you want to delete Invoice Number')
1021 . qq| $form->{invnumber}
1025 <input name="action" class="submit" type="submit" value="|
1026 . $locale->text('Yes') . qq|">
1030 $main::lxdebug->leave_sub();
1034 $main::lxdebug->enter_sub();
1036 my $form = $main::form;
1037 my %myconfig = %main::myconfig;
1038 my $locale = $main::locale;
1040 $main::auth->assert('invoice_edit');
1042 $form->{transdate} = $form->{invdate} = $form->current_date(\%myconfig);
1044 $form->current_date(\%myconfig, $form->{invdate}, $form->{terms} * 1);
1046 $form->{convert_from_ar_ids} = $form->{id};
1048 $form->{rowcount}--;
1051 $form->{title} = $locale->text('Add Credit Note');
1052 $form->{script} = 'is.pl';
1054 # Bei Gutschriften bezug zur Rechnungsnummer
1055 $form->{invnumber_for_credit_note} = $form->{invnumber};
1056 # bo creates the id, reset it
1057 map { delete $form->{$_} }
1058 qw(id invnumber subject message cc bcc printed emailed queued);
1059 $form->{ $form->{vc} } =~ s/--.*//g;
1060 $form->{type} = "credit_note";
1063 map { $form->{"select$_"} = "" } ($form->{vc}, 'currency');
1065 # map { $form->{$_} = $form->parse_amount(\%myconfig, $form->{$_}) }
1066 # qw(creditlimit creditremaining);
1068 # set new persistent ids for credit note and link previous invoice id
1069 $form->{"converted_from_invoice_id_$_"} = delete $form->{"invoice_id_$_"} for 1 .. $form->{"rowcount"};
1071 my $currency = $form->{currency};
1074 $form->{currency} = $currency;
1075 $form->{forex} = $form->check_exchangerate( \%myconfig, $form->{currency}, $form->{invdate}, 'buy');
1076 $form->{exchangerate} = $form->{forex} || '';
1078 $form->{creditremaining} -= ($form->{oldinvtotal} - $form->{ordtotal});
1080 # bei Gutschriften werden Zahlungseingänge aus Rechnung nicht übernommen
1081 for my $i (1 .. $form->{paidaccounts}) {
1082 delete $form->{"paid_$i"};
1083 delete $form->{"source_$i"};
1084 delete $form->{"memo_$i"};
1085 delete $form->{"datepaid_$i"};
1086 delete $form->{"gldate_$i"};
1087 delete $form->{"acc_trans_id_$i"};
1088 delete $form->{"AR_paid_$i"};
1090 $form->{paidaccounts} = 1;
1097 $main::lxdebug->leave_sub();
1101 $::lxdebug->enter_sub;
1103 $::auth->assert('invoice_edit');
1107 my $new_rowcount = $::form->{"rowcount"} * 1 + 1;
1108 $::form->{"project_id_${new_rowcount}"} = $::form->{"globalproject_id"};
1110 $::form->language_payment(\%::myconfig);
1112 Common::webdav_folder($::form);
1115 display_row(++$::form->{rowcount});
1118 $::lxdebug->leave_sub;
1122 $main::lxdebug->enter_sub();
1124 my $form = $main::form;
1125 my %myconfig = %main::myconfig;
1126 my $locale = $main::locale;
1128 $main::auth->assert('invoice_edit');
1130 if (IS->delete_invoice(\%myconfig, \%$form)) {
1131 # saving the history
1132 if(!exists $form->{addition}) {
1133 $form->{snumbers} = 'invnumber' .'_'. $form->{invnumber}; # ($form->{type} eq 'credit_note' ? 'cnnumber' : 'invnumber') .'_'. $form->{invnumber};
1134 $form->{what_done} = 'invoice';
1135 $form->{addition} = "DELETED";
1136 $form->save_history;
1138 # /saving the history
1139 $form->redirect($locale->text('Invoice deleted!'));
1141 $form->error($locale->text('Cannot delete invoice!'));
1143 $main::lxdebug->leave_sub();
1146 sub post_and_e_mail {
1151 $main::lxdebug->enter_sub();
1153 my $form = $main::form;
1155 $main::auth->assert('invoice_edit');
1158 $form->{no_redirect_after_post} = 1;
1160 my $saved_form = save_form();
1164 restore_form($saved_form, 0, qw(id invnumber));
1169 $main::lxdebug->leave_sub();