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 $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 if ($form->{all_customer}) {
148 unless ($form->{customer_id}) {
149 $form->{customer_id} = $form->{all_customer}->[0]->{id};
150 $form->{salesman_id} = $form->{all_customer}->[0]->{salesman_id};
154 my $editing = $form->{id};
156 $form->backup_vars(qw(payment_id language_id taxzone_id salesman_id
157 taxincluded currency cp_id intnotes id shipto_id
160 IS->get_customer(\%myconfig, \%$form);
162 #quote all_customer Bug 133
163 foreach my $ref (@{ $form->{all_customer} }) {
164 $ref->{name} = $form->quote($ref->{name});
167 $form->restore_vars(qw(id));
169 IS->retrieve_invoice(\%myconfig, \%$form);
170 $form->restore_vars(qw(payment_id language_id taxzone_id currency intnotes
171 cp_id shipto_id delivery_term_id));
172 $form->restore_vars(qw(taxincluded)) if $form->{id};
173 $form->restore_vars(qw(salesman_id)) if $editing;
176 # build vendor/customer drop down compatibility... don't ask
177 if (@{ $form->{"all_customer"} }) {
178 $form->{"selectcustomer"} = 1;
179 $form->{customer} = qq|$form->{customer}--$form->{"customer_id"}|;
182 $form->{"oldcustomer"} = $form->{customer};
184 if ($form->{"oldcustomer"} !~ m/--\d+$/ && $form->{"customer_id"}) {
185 $form->{"oldcustomer"} .= qq|--$form->{"customer_id"}|
189 # $form->{oldcustomer} = "$form->{customer}--$form->{customer_id}";
190 # $form->{selectcustomer} = 1;
192 $form->{employee} = "$form->{employee}--$form->{employee_id}";
195 $form->{forex} = $form->{exchangerate};
196 my $exchangerate = ($form->{exchangerate}) ? $form->{exchangerate} : 1;
198 foreach my $key (keys %{ $form->{AR_links} }) {
199 foreach my $ref (@{ $form->{AR_links}{$key} }) {
200 $form->{"select$key"} .= "<option>$ref->{accno}--$ref->{description}</option>\n";
203 if ($key eq "AR_paid") {
204 next unless $form->{acc_trans}{$key};
205 for my $i (1 .. scalar @{ $form->{acc_trans}{$key} }) {
206 $form->{"AR_paid_$i"} = "$form->{acc_trans}{$key}->[$i-1]->{accno}--$form->{acc_trans}{$key}->[$i-1]->{description}";
208 $form->{"acc_trans_id_$i"} = $form->{acc_trans}{$key}->[$i - 1]->{acc_trans_id};
210 $form->{"paid_$i"} = $form->{acc_trans}{$key}->[$i - 1]->{amount} * -1;
211 $form->{"datepaid_$i"} = $form->{acc_trans}{$key}->[$i - 1]->{transdate};
212 $form->{"gldate_$i"} = $form->{acc_trans}{$key}->[$i - 1]->{gldate};
213 $form->{"exchangerate_$i"} = $form->{acc_trans}{$key}->[$i - 1]->{exchangerate};
214 $form->{"forex_$i"} = $form->{"exchangerate_$i"};
215 $form->{"source_$i"} = $form->{acc_trans}{$key}->[$i - 1]->{source};
216 $form->{"memo_$i"} = $form->{acc_trans}{$key}->[$i - 1]->{memo};
218 $form->{paidaccounts} = $i;
221 $form->{$key} = "$form->{acc_trans}{$key}->[0]->{accno}--$form->{acc_trans}{$key}->[0]->{description}";
225 $form->{paidaccounts} = 1 unless (exists $form->{paidaccounts});
227 $form->{AR} = $form->{AR_1} unless $form->{id};
229 $form->{locked} = ($form->datetonum($form->{invdate}, \%myconfig)
230 <= $form->datetonum($form->{closedto}, \%myconfig));
232 $main::lxdebug->leave_sub();
235 sub prepare_invoice {
236 $main::lxdebug->enter_sub();
238 my $form = $main::form;
239 my %myconfig = %main::myconfig;
241 $main::auth->assert('invoice_edit');
243 if ($form->{type} eq "credit_note") {
244 $form->{type} = "credit_note";
245 $form->{formname} = "credit_note";
247 $form->{type} = "invoice";
248 $form->{formname} = "invoice";
255 foreach my $ref (@{ $form->{invoice_details} }) {
258 map { $form->{"${_}_$i"} = $ref->{$_} } keys %{$ref};
260 $form->{"discount_$i"} = $form->format_amount(\%myconfig, $form->{"discount_$i"} * 100);
261 my ($dec) = ($form->{"sellprice_$i"} =~ /\.(\d+)/);
263 my $decimalplaces = ($dec > 2) ? $dec : 2;
265 $form->{"sellprice_$i"} = $form->format_amount(\%myconfig, $form->{"sellprice_$i"}, $decimalplaces);
266 (my $dec_qty) = ($form->{"qty_$i"} =~ /\.(\d+)/);
267 $dec_qty = length $dec_qty;
269 $form->{"lastcost_$i"} = $form->format_amount(\%myconfig, $form->{"lastcost_$i"}, $decimalplaces);
271 $form->{"qty_$i"} = $form->format_amount(\%myconfig, $form->{"qty_$i"}, $dec_qty);
273 $form->{"sellprice_pg_$i"} = join ('--', $form->{"sellprice_$i"}, $form->{"pricegroup_id_$i"});
275 $form->{rowcount} = $i;
279 $main::lxdebug->leave_sub();
283 $main::lxdebug->enter_sub();
285 my $form = $main::form;
286 my %myconfig = %main::myconfig;
287 my $locale = $main::locale;
288 my $cgi = $::request->{cgi};
290 $main::auth->assert('invoice_edit');
296 require SL::DB::Invoice;
297 $TMPL_VAR{invoice_obj} = SL::DB::Invoice->new(id => $form->{id})->load;
299 $form->{employee_id} = $form->{old_employee_id} if $form->{old_employee_id};
300 $form->{salesman_id} = $form->{old_salesman_id} if $form->{old_salesman_id};
302 $form->{defaultcurrency} = $form->get_default_currency(\%myconfig);
304 $form->get_lists("taxzones" => ($form->{id} ? "ALL_TAXZONES" : "ALL_ACTIVE_TAXZONES"),
305 "currencies" => "ALL_CURRENCIES",
306 "customers" => "ALL_CUSTOMERS",
307 "departments" => "all_departments",
308 "price_factors" => "ALL_PRICE_FACTORS");
311 my @old_project_ids = uniq grep { $_ } map { $_ * 1 } ($form->{"globalproject_id"}, map { $form->{"project_id_$_"} } 1..$form->{"rowcount"});
312 my @old_ids_cond = @old_project_ids ? (id => \@old_project_ids) : ();
314 if ($::instance_conf->get_customer_projects_only_in_sales) {
317 customer_id => $::form->{customer_id},
318 billable_customer_id => $::form->{customer_id},
323 and => [ active => 1, @customer_cond ],
327 $TMPL_VAR{ALL_PROJECTS} = SL::DB::Manager::Project->get_all_sorted(query => \@conditions);
328 $form->{ALL_PROJECTS} = $TMPL_VAR{ALL_PROJECTS}; # make projects available for second row drop-down in io.pl
329 $TMPL_VAR{ALL_EMPLOYEES} = SL::DB::Manager::Employee->get_all_sorted(query => [ or => [ id => $::form->{employee_id}, deleted => 0 ] ]);
330 $TMPL_VAR{ALL_SALESMEN} = SL::DB::Manager::Employee->get_all_sorted(query => [ or => [ id => $::form->{salesman_id}, deleted => 0 ] ]);
331 $TMPL_VAR{ALL_SHIPTO} = SL::DB::Manager::Shipto->get_all_sorted(query => [
332 or => [ trans_id => $::form->{"$::form->{vc}_id"} * 1, and => [ shipto_id => $::form->{shipto_id} * 1, trans_id => undef ] ]
334 $TMPL_VAR{ALL_CONTACTS} = SL::DB::Manager::Contact->get_all_sorted(query => [
336 cp_cv_id => $::form->{"$::form->{vc}_id"} * 1,
339 cp_id => $::form->{cp_id} * 1
343 $TMPL_VAR{department_labels} = sub { "$_[0]->{description}--$_[0]->{id}" };
346 $TMPL_VAR{vc_keys} = sub { "$_[0]->{name}--$_[0]->{id}" };
347 $TMPL_VAR{vclimit} = $myconfig{vclimit};
348 $TMPL_VAR{vc_select} = "customer_or_vendor_selection_window('customer', '', 0, 0)";
349 push @custom_hiddens, "customer_id";
350 push @custom_hiddens, "oldcustomer";
351 push @custom_hiddens, "selectcustomer";
353 # currencies and exchangerate
354 my @values = map { $_ } @{ $form->{ALL_CURRENCIES} };
355 my %labels = map { $_ => $_ } @{ $form->{ALL_CURRENCIES} };
356 $form->{currency} = $form->{defaultcurrency} unless $form->{currency};
357 $form->{show_exchangerate} = $form->{currency} ne $form->{defaultcurrency};
358 $TMPL_VAR{currencies} = NTI($::request->{cgi}->popup_menu('-name' => 'currency', '-default' => $form->{"currency"},
359 '-values' => \@values, '-labels' => \%labels,
360 '-onchange' => "document.getElementById('update_button').click();"
361 )) if scalar @values;
362 push @custom_hiddens, "forex";
363 push @custom_hiddens, "exchangerate" if $form->{forex};
365 $TMPL_VAR{creditwarning} = ($form->{creditlimit} != 0) && ($form->{creditremaining} < 0) && !$form->{update};
366 $TMPL_VAR{is_credit_remaining_negativ} = $form->{creditremaining} =~ /-/;
368 my $follow_up_vc = $form->{customer};
369 $follow_up_vc =~ s/--\d*\s*$//;
370 $TMPL_VAR{customer_name} = $follow_up_vc;
372 # set option selected
373 foreach my $item (qw(AR)) {
374 $form->{"select$item"} =~ s/ selected//;
375 $form->{"select$item"} =~ s/option>\Q$form->{$item}\E/option selected>$form->{$item}/;
378 $TMPL_VAR{is_type_credit_note} = $form->{type} eq "credit_note";
379 $TMPL_VAR{is_format_html} = $form->{format} eq 'html';
380 $TMPL_VAR{dateformat} = $myconfig{dateformat};
381 $TMPL_VAR{numberformat} = $myconfig{numberformat};
383 push @custom_hiddens, map { "shiptocvar_" . $_->name } @{ SL::DB::Manager::CustomVariableConfig->get_all(where => [ module => 'ShipTo' ]) };
386 $TMPL_VAR{HIDDENS} = [qw(
387 id action type media format queued printed emailed title vc discount
388 title creditlimit creditremaining tradediscount business closedto locked shipped storno storno_id
389 max_dunning_level dunning_amount dunning_description
390 shiptoname shiptostreet shiptozipcode shiptocity shiptocountry shiptogln shiptocontact shiptophone shiptofax
391 shiptoemail shiptodepartment_1 shiptodepartment_2 shiptocp_gender message email subject cc bcc taxaccounts cursor_fokus
392 convert_from_do_ids convert_from_oe_ids convert_from_ar_ids useasnew
396 map { $_.'_rate', $_.'_description', $_.'_taxnumber' } split / /, $form->{taxaccounts}];
398 $::request->{layout}->use_javascript(map { "${_}.js" } qw(kivi.SalesPurchase ckeditor/ckeditor ckeditor/adapters/jquery kivi.io autocomplete_customer autocomplete_part client_js));
400 $TMPL_VAR{payment_terms_obj} = get_payment_terms_for_invoice();
401 $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};
405 print $form->parse_html_template("is/form_header", \%TMPL_VAR);
407 $main::lxdebug->leave_sub();
411 my @fields = qw(acc_trans_id gldate datepaid source memo paid AR_paid);
413 grep { $_->{paid} != 0 }
416 +{ map { ($_ => delete($::form->{"${_}_${idx}"})) } @fields }
417 } (1..$::form->{paidaccounts});
419 @payments = sort_by { DateTime->from_kivitendo($_->{datepaid}) } @payments;
421 $::form->{paidaccounts} = max scalar(@payments), 1;
423 foreach my $idx (1 .. scalar(@payments)) {
424 my $payment = $payments[$idx - 1];
425 $::form->{"${_}_${idx}"} = $payment->{$_} for @fields;
430 $main::lxdebug->enter_sub();
432 my $form = $main::form;
433 my %myconfig = %main::myconfig;
434 my $locale = $main::locale;
436 $main::auth->assert('invoice_edit');
438 $form->{invtotal} = $form->{invsubtotal};
441 $form->{rows} = max 2,
442 $form->numtextrows($form->{notes}, 26, 8),
443 $form->numtextrows($form->{intnotes}, 35, 8);
446 # tax, total and subtotal calculations
447 my ($tax, $subtotal);
448 $form->{taxaccounts_array} = [ split(/ /, $form->{taxaccounts}) ];
450 if( $form->{customer_id} && !$form->{taxincluded_changed_by_user} ) {
451 my $customer = SL::DB::Customer->new(id => $form->{customer_id})->load();
452 $form->{taxincluded} = defined($customer->taxincluded_checked) ? $customer->taxincluded_checked : $myconfig{taxincluded_checked};
455 foreach my $item (@{ $form->{taxaccounts_array} }) {
456 if ($form->{"${item}_base"}) {
457 if ($form->{taxincluded}) {
458 $form->{"${item}_total"} = $form->round_amount( ($form->{"${item}_base"} * $form->{"${item}_rate"}
459 / (1 + $form->{"${item}_rate"})), 2);
460 $form->{"${item}_netto"} = $form->round_amount( ($form->{"${item}_base"} - $form->{"${item}_total"}), 2);
462 $form->{"${item}_total"} = $form->round_amount( $form->{"${item}_base"} * $form->{"${item}_rate"}, 2);
463 $form->{invtotal} += $form->{"${item}_total"};
468 $form->{rounding} = $form->round_amount(
469 $form->round_amount($form->{invtotal}, 2, 1) - $form->round_amount($form->{invtotal}, 2), 2
471 $form->{invtotal} = $form->round_amount( $form->{invtotal}, 2, 1 );
475 $form->{follow_ups} = FU->follow_ups('trans_id' => $form->{id}) || [];
476 $form->{follow_ups_unfinished} = ( sum map { $_->{due} * 1 } @{ $form->{follow_ups} } ) || 0;
483 $form->{paidaccounts}++ if ($form->{"paid_$form->{paidaccounts}"});
484 $form->{paid_indices} = [ 1 .. $form->{paidaccounts} ];
486 # Standard Konto für Umlaufvermögen
487 my $accno_arap = IS->get_standard_accno_current_assets(\%myconfig, \%$form);
489 for my $i (1 .. $form->{paidaccounts}) {
490 $form->{"changeable_$i"} = 1;
491 if (SL::DB::Default->get->payments_changeable == 0) {
493 $form->{"changeable_$i"} = ($form->{"acc_trans_id_$i"})? 0 : 1;
494 } elsif (SL::DB::Default->get->payments_changeable == 2) {
496 $form->{"changeable_$i"} = (($form->{"gldate_$i"} eq '') ||
497 ($form->current_date(\%myconfig) eq $form->{"gldate_$i"}));
500 $form->{"selectAR_paid_$i"} = $form->{selectAR_paid};
501 if (!$form->{"AR_paid_$i"}) {
502 $form->{"selectAR_paid_$i"} =~ s/option>$accno_arap--(.*?)</option selected>$accno_arap--$1</;
504 $form->{"selectAR_paid_$i"} =~ s/option>\Q$form->{"AR_paid_$i"}\E/option selected>$form->{"AR_paid_$i"}/;
507 $totalpaid += $form->{"paid_$i"};
510 $form->{oldinvtotal} = $form->{invtotal};
512 $form->{ALL_DELIVERY_TERMS} = SL::DB::Manager::DeliveryTerm->get_all_sorted();
514 print $form->parse_html_template('is/form_footer', {
515 is_type_credit_note => ($form->{type} eq "credit_note"),
516 totalpaid => $totalpaid,
517 paid_missing => $form->{invtotal} - $totalpaid,
518 print_options => print_options(inline => 1),
519 show_storno => $form->{id} && !$form->{storno} && !IS->has_storno(\%myconfig, $form, "ar") && !$totalpaid,
520 show_delete => ($::instance_conf->get_is_changeable == 2)
521 ? ($form->current_date(\%myconfig) eq $form->{gldate})
522 : ($::instance_conf->get_is_changeable == 1),
523 today => DateTime->today,
525 ##print $form->parse_html_template('is/_payments'); # parser
526 ##print $form->parse_html_template('webdav/_list'); # parser
528 $main::lxdebug->leave_sub();
532 $main::lxdebug->enter_sub();
534 my $form = $main::form;
535 my %myconfig = %main::myconfig;
537 $main::auth->assert('invoice_edit');
539 &mark_as_paid_common(\%myconfig,"ar");
541 $main::lxdebug->leave_sub();
545 $main::lxdebug->enter_sub();
547 my $form = $main::form;
548 my %myconfig = %main::myconfig;
550 $main::auth->assert('invoice_edit');
552 my ($recursive_call) = @_;
554 $form->{print_and_post} = 0 if $form->{second_run};
555 my $taxincluded = $form->{taxincluded} ? "checked" : '';
558 &check_name("customer");
560 $form->{taxincluded} ||= $taxincluded;
562 if (!$form->{forex}) { # read exchangerate from input field (not hidden)
563 $form->{exchangerate} = $form->parse_amount(\%myconfig, $form->{exchangerate}) unless $recursive_call;
565 $form->{forex} = $form->check_exchangerate(\%myconfig, $form->{currency}, $form->{invdate}, 'buy');
566 $form->{exchangerate} = $form->{forex} if $form->{forex};
568 for my $i (1 .. $form->{paidaccounts}) {
569 next unless $form->{"paid_$i"};
570 map { $form->{"${_}_$i"} = $form->parse_amount(\%myconfig, $form->{"${_}_$i"}) } qw(paid exchangerate);
571 if (!$form->{"forex_$i"}) { #read exchangerate from input field (not hidden)
572 $form->{exchangerate} = $form->{"exchangerate_$i"};
574 $form->{"forex_$i"} = $form->check_exchangerate(\%myconfig, $form->{currency}, $form->{"datepaid_$i"}, 'buy');
575 $form->{"exchangerate_$i"} = $form->{"forex_$i"} if $form->{"forex_$i"};
578 my $i = $form->{rowcount};
579 my $exchangerate = $form->{exchangerate} || 1;
581 # if last row empty, check the form otherwise retrieve new item
582 if ( ($form->{"partnumber_$i"} eq "")
583 && ($form->{"description_$i"} eq "")
584 && ($form->{"partsgroup_$i"} eq "")) {
586 $form->{creditremaining} += ($form->{oldinvtotal} - $form->{oldtotalpaid});
591 IS->retrieve_item(\%myconfig, \%$form);
593 my $rows = scalar @{ $form->{item_list} };
595 $form->{"discount_$i"} = $form->parse_amount(\%myconfig, $form->{"discount_$i"}) / 100.0;
596 $form->{"discount_$i"} ||= $form->{customer_discount};
599 $form->{"qty_$i"} = $form->parse_amount(\%myconfig, $form->{"qty_$i"});
600 if( !$form->{"qty_$i"} ) {
601 $form->{"qty_$i"} = 1;
606 select_item(mode => 'IS', pre_entered_qty => $form->{"qty_$i"});
611 my $sellprice = $form->parse_amount(\%myconfig, $form->{"sellprice_$i"});
613 map { $form->{item_list}[$i]{$_} =~ s/\"/"/g } qw(partnumber description unit);
614 map { $form->{"${_}_$i"} = $form->{item_list}[0]{$_} } keys %{ $form->{item_list}[0] };
616 $form->{payment_id} = $form->{"part_payment_id_$i"} if $form->{"part_payment_id_$i"} ne "";
617 $form->{"discount_$i"} = 0 if $form->{"not_discountable_$i"};
619 $form->{"marge_price_factor_$i"} = $form->{item_list}->[0]->{price_factor};
621 ($sellprice || $form->{"sellprice_$i"}) =~ /\.(\d+)/;
622 my $decimalplaces = max 2, length $1;
625 $form->{"sellprice_$i"} = $sellprice;
627 my $record = _make_record();
628 my $price_source = SL::PriceSource->new(record_item => $record->items->[$i-1], record => $record);
629 my $best_price = $price_source->best_price;
630 my $best_discount = $price_source->best_discount;
633 $::form->{"sellprice_$i"} = $best_price->price;
634 $::form->{"active_price_source_$i"} = $best_price->source;
636 if ($best_discount) {
637 $::form->{"discount_$i"} = $best_discount->discount;
638 $::form->{"active_discount_source_$i"} = $best_discount->source;
641 # if there is an exchange rate adjust sellprice
642 $form->{"sellprice_$i"} /= $exchangerate;
645 $form->{"listprice_$i"} /= $exchangerate;
647 my $amount = $form->{"sellprice_$i"} * $form->{"qty_$i"} * (1 - $form->{"discount_$i"});
648 map { $form->{"${_}_base"} = 0 } split / /, $form->{taxaccounts};
649 map { $form->{"${_}_base"} += $amount } split / /, $form->{"taxaccounts_$i"};
650 map { $amount += ($form->{"${_}_base"} * $form->{"${_}_rate"}) } split / /, $form->{"taxaccounts_$i"} if !$form->{taxincluded};
652 $form->{creditremaining} -= $amount;
654 map { $form->{"${_}_$i"} = $form->format_amount(\%myconfig, $form->{"${_}_$i"}, $decimalplaces) } qw(sellprice lastcost);
656 $form->{"qty_$i"} = $form->format_amount(\%myconfig, $form->{"qty_$i"});
657 $form->{"discount_$i"} = $form->format_amount(\%myconfig, $form->{"discount_$i"} * 100.0);
664 # ok, so this is a new part
665 # ask if it is a part or service item
667 if ( $form->{"partsgroup_$i"}
668 && ($form->{"partsnumber_$i"} eq "")
669 && ($form->{"description_$i"} eq "")) {
671 $form->{"discount_$i"} = "";
675 $form->{"id_$i"} = 0;
680 $main::lxdebug->leave_sub();
684 $main::lxdebug->enter_sub();
686 my $form = $main::form;
687 my %myconfig = %main::myconfig;
688 my $locale = $main::locale;
690 $main::auth->assert('invoice_edit');
692 $form->mtime_ischanged('ar') ;
693 my $invdate = $form->datetonum($form->{invdate}, \%myconfig);
695 $form->{defaultcurrency} = $form->get_default_currency(\%myconfig);
696 for my $i (1 .. $form->{paidaccounts}) {
697 if ($form->{"paid_$i"}) {
698 my $datepaid = $form->datetonum($form->{"datepaid_$i"}, \%myconfig);
700 $form->isblank("datepaid_$i", $locale->text('Payment date missing!'));
703 if ($form->{currency} ne $form->{defaultcurrency}) {
704 $form->{"exchangerate_$i"} = $form->{exchangerate}
705 if ($invdate == $datepaid);
706 $form->isblank("exchangerate_$i",
707 $locale->text('Exchangerate for payment missing!'));
711 # Abgeschlossene Zeiträume nur für den letzten (aktuellen) Zahlungseingang prüfen
712 # Details s.a. Bug 1502
713 # Das Problem ist jetzt, dass man Zahlungseingänge nachträglich ändern kann
714 # Wobei dies für Installationen die sowieso nicht mit Bücherkontrolle arbeiten keinen
715 # keinen Unterschied macht.
716 # Optimal wäre, wenn gegen einen Zeitstempel des Zahlungsfelds geprüft würde ...
717 # Das Problem hierbei ist, dass in IS.pm post_invoice IMMER alle Zahlungseingänge aus $form
718 # erneut gespeichert werden. Prinzipiell wäre es besser NUR die Änderungen des Rechnungs-
719 # belegs (neue Zahlung aber nichts anderes) zu speichern ...
720 # Vielleicht könnte man ähnlich wie bei Rechnung löschen verfahren
721 $form->error($locale->text('Cannot post payment for a closed period!'))
722 if ($form->date_closed($form->{"datepaid_$form->{paidaccounts}"}, \%myconfig));
724 ($form->{AR}) = split /--/, $form->{AR};
725 ($form->{AR_paid}) = split /--/, $form->{AR_paid};
727 if ( IS->post_payment(\%myconfig, \%$form) ) {
728 $form->{snumbers} = qq|invnumber_| . $form->{invnumber};
729 $form->{what_done} = 'invoice';
730 $form->{addition} = "PAYMENT POSTED";
732 $form->redirect($locale->text('Payment posted!'))
734 $form->error($locale->text('Cannot post payment!'));
737 $main::lxdebug->leave_sub();
741 $main::lxdebug->enter_sub();
743 my $form = $main::form;
744 my %myconfig = %main::myconfig;
745 my $locale = $main::locale;
747 $main::auth->assert('invoice_edit');
748 $form->mtime_ischanged('ar');
750 $form->{defaultcurrency} = $form->get_default_currency(\%myconfig);
751 $form->isblank("invdate", $locale->text('Invoice Date missing!'));
752 $form->isblank("customer", $locale->text('Customer missing!'));
753 $form->error($locale->text('Cannot post invoice for a closed period!'))
754 if ($form->date_closed($form->{"invdate"}, \%myconfig));
756 $form->{invnumber} =~ s/^\s*//g;
757 $form->{invnumber} =~ s/\s*$//g;
759 # if oldcustomer ne customer redo form
760 if (&check_name('customer')) {
765 if ($myconfig{mandatory_departments} && !$form->{department_id}) {
766 $form->{saved_message} = $::locale->text('You have to specify a department.');
771 if ($form->{second_run}) {
772 $form->{print_and_post} = 0;
775 remove_emptied_rows();
778 my $closedto = $form->datetonum($form->{closedto}, \%myconfig);
779 my $invdate = $form->datetonum($form->{invdate}, \%myconfig);
781 $form->error($locale->text('Cannot post transaction above the maximum future booking date!'))
782 if ($form->date_max_future($invdate, \%myconfig));
783 $form->error($locale->text('Cannot post invoice for a closed period!'))
784 if ($invdate <= $closedto);
786 $form->isblank("exchangerate", $locale->text('Exchangerate missing!'))
787 if ($form->{currency} ne $form->{defaultcurrency});
789 for my $i (1 .. $form->{paidaccounts}) {
790 if ($form->parse_amount(\%myconfig, $form->{"paid_$i"})) {
791 my $datepaid = $form->datetonum($form->{"datepaid_$i"}, \%myconfig);
793 $form->isblank("datepaid_$i", $locale->text('Payment date missing!'));
795 $form->error($locale->text('Cannot post payment for a closed period!'))
796 if ($form->date_closed($form->{"datepaid_$i"}, \%myconfig));
798 if ($form->{currency} ne $form->{defaultcurrency}) {
799 $form->{"exchangerate_$i"} = $form->{exchangerate}
800 if ($invdate == $datepaid);
801 $form->isblank("exchangerate_$i",
802 $locale->text('Exchangerate for payment missing!'));
807 ($form->{AR}) = split /--/, $form->{AR};
808 ($form->{AR_paid}) = split /--/, $form->{AR_paid};
809 $form->{storno} ||= 0;
811 $form->{label} = $form->{type} eq 'credit_note' ? $locale->text('Credit Note') : $locale->text('Invoice');
813 $form->{id} = 0 if $form->{postasnew};
815 # get new invnumber in sequence if no invnumber is given or if posasnew was requested
816 if ($form->{postasnew}) {
817 if ($form->{type} eq "credit_note") {
818 undef($form->{cnnumber});
820 undef($form->{invnumber});
826 my $terms = get_payment_terms_for_invoice();
827 $form->{duedate} = $terms->calc_date(reference_date => $form->{invdate}, due_date => $form->{due_due})->to_kivitendo if $terms;
829 # If transfer_out is requested, get rose db handle and do post and
830 # transfer out in one transaction. Otherwise just post the invoice.
831 if ($::instance_conf->get_is_transfer_out && $form->{type} ne 'credit_note' && !$form->{storno}) {
832 require SL::DB::Inventory;
833 my $rose_db = SL::DB::Inventory->new->db;
836 if (!$rose_db->with_transaction(sub {
838 if (!IS->post_invoice(\%myconfig, \%$form, $rose_db->dbh)) {
839 push @errors, $locale->text('Cannot post invoice!');
842 my $err = IS->transfer_out(\%$form, $rose_db->dbh);
844 push @errors, @{ $err };
845 die 'transfer error';
850 push @errors, $EVAL_ERROR;
851 die 'transaction error';
856 push @errors, $rose_db->error;
857 $form->error($locale->text('Cannot post invoice and/or transfer out! Error message:') . "\n" . join("\n", @errors));
860 if (!IS->post_invoice(\%myconfig, \%$form)) {
861 $form->error($locale->text('Cannot post invoice!'));
865 remove_draft() if $form->{remove_draft};
867 if(!exists $form->{addition}) {
868 $form->{snumbers} = 'invnumber' .'_'. $form->{invnumber}; # ($form->{type} eq 'credit_note' ? 'cnnumber' : 'invnumber') .'_'. $form->{invnumber};
869 $form->{what_done} = 'invoice';
870 $form->{addition} = $form->{print_and_post} ? "PRINTED AND POSTED" :
871 $form->{storno} ? "STORNO" :
876 if (!$form->{no_redirect_after_post}) {
877 $form->{action} = 'edit';
878 $form->{script} = 'is.pl';
879 $form->{saved_message} = $form->{label} . " $form->{invnumber} " . $locale->text('posted!');
880 $form->{callback} = build_std_url(qw(action edit id callback saved_message));
884 $main::lxdebug->leave_sub();
888 $main::lxdebug->enter_sub();
890 my $form = $main::form;
892 $main::auth->assert('invoice_edit');
894 my $old_form = Form->new;
895 $form->{no_redirect_after_post} = 1;
896 $form->{print_and_post} = 1;
900 $main::lxdebug->leave_sub();
905 $main::lxdebug->enter_sub();
907 my $form = $main::form;
908 my %myconfig = %main::myconfig;
910 $main::auth->assert('invoice_edit');
912 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)};
914 $form->{paidaccounts} = 1;
915 $form->{invdate} = $form->current_date(\%myconfig);
916 my $terms = get_payment_terms_for_invoice();
917 $form->{duedate} = $terms ? $terms->calc_date(reference_date => $form->{invdate})->to_kivitendo : $form->{invdate};
918 $form->{employee_id} = SL::DB::Manager::Employee->current->id;
919 $form->{forex} = $form->check_exchangerate(\%myconfig, $form->{currency}, $form->{invdate}, 'buy');
920 $form->{exchangerate} = $form->{forex} if $form->{forex};
922 $form->{"converted_from_invoice_id_$_"} = delete $form->{"invoice_id_$_"} for 1 .. $form->{"rowcount"};
924 $form->{useasnew} = 1;
927 $main::lxdebug->leave_sub();
931 $main::lxdebug->enter_sub();
933 my $form = $main::form;
934 my %myconfig = %main::myconfig;
935 my $locale = $main::locale;
937 $main::auth->assert('invoice_edit');
939 if ($form->{storno}) {
940 $form->error($locale->text('Cannot storno storno invoice!'));
943 if (IS->has_storno(\%myconfig, $form, "ar")) {
944 $form->error($locale->text("Invoice has already been storno'd!"));
946 if ($form->datetonum($form->{invdate}, \%myconfig) <= $form->datetonum($form->{closedto}, \%myconfig)) {
947 $form->error($locale->text('Cannot storno invoice for a closed period!'));
950 # save the history of invoice being stornoed
951 $form->{snumbers} = qq|invnumber_| . $form->{invnumber};
952 $form->{what_done} = 'invoice';
953 $form->{addition} = "STORNO";
956 map({ my $key = $_; delete($form->{$key}) unless (grep({ $key eq $_ } qw(id login password type))); } keys(%{ $form }));
962 # Payments must not be recorded for the new storno invoice.
963 $form->{paidaccounts} = 0;
964 map { my $key = $_; delete $form->{$key} if grep { $key =~ /^$_/ } qw(datepaid_ gldate_ acc_trans_id_ source_ memo_ paid_ exchangerate_ AR_paid_) } keys %{ $form };
966 $form->{storno_id} = $form->{id};
969 $form->{invnumber} = "Storno zu " . $form->{invnumber};
970 $form->{invdate} = DateTime->today->to_lxoffice;
972 # set new ids for storno invoice
973 delete $form->{"invoice_id_$_"} for 1 .. $form->{"rowcount"};
976 $main::lxdebug->leave_sub();
980 $main::lxdebug->enter_sub();
982 my $form = $main::form;
984 $main::auth->assert('invoice_edit');
986 $form->{preview} = 1;
987 my $old_form = Form->new;
988 for (keys %$form) { $old_form->{$_} = $form->{$_} }
990 &print_form($old_form);
991 $main::lxdebug->leave_sub();
996 $main::lxdebug->enter_sub();
998 my $form = $main::form;
999 my $locale = $main::locale;
1001 $main::auth->assert('invoice_edit');
1003 if ($form->{second_run}) {
1004 $form->{print_and_post} = 0;
1009 <form method="post" action="$form->{script}">
1012 # delete action variable
1013 map { delete $form->{$_} } qw(action header);
1015 foreach my $key (keys %$form) {
1016 next if (($key eq 'login') || ($key eq 'password') || ('' ne ref $form->{$key}));
1017 $form->{$key} =~ s/\"/"/g;
1018 print qq|<input type="hidden" name="$key" value="$form->{$key}">\n|;
1022 <h2 class="confirm">| . $locale->text('Confirm!') . qq|</h2>
1025 . $locale->text('Are you sure you want to delete Invoice Number')
1026 . qq| $form->{invnumber}
1030 <input name="action" class="submit" type="submit" value="|
1031 . $locale->text('Yes') . qq|">
1035 $main::lxdebug->leave_sub();
1039 $main::lxdebug->enter_sub();
1041 my $form = $main::form;
1042 my %myconfig = %main::myconfig;
1043 my $locale = $main::locale;
1045 $main::auth->assert('invoice_edit');
1047 $form->{transdate} = $form->{invdate} = $form->current_date(\%myconfig);
1049 $form->current_date(\%myconfig, $form->{invdate}, $form->{terms} * 1);
1051 $form->{convert_from_ar_ids} = $form->{id};
1053 $form->{rowcount}--;
1056 $form->{title} = $locale->text('Add Credit Note');
1057 $form->{script} = 'is.pl';
1059 # Bei Gutschriften bezug zur Rechnungsnummer
1060 $form->{invnumber_for_credit_note} = $form->{invnumber};
1061 # bo creates the id, reset it
1062 map { delete $form->{$_} }
1063 qw(id invnumber subject message cc bcc printed emailed queued);
1064 $form->{ $form->{vc} } =~ s/--.*//g;
1065 $form->{type} = "credit_note";
1068 map { $form->{"select$_"} = "" } ($form->{vc}, 'currency');
1070 # map { $form->{$_} = $form->parse_amount(\%myconfig, $form->{$_}) }
1071 # qw(creditlimit creditremaining);
1073 # set new persistent ids for credit note and link previous invoice id
1074 $form->{"converted_from_invoice_id_$_"} = delete $form->{"invoice_id_$_"} for 1 .. $form->{"rowcount"};
1076 my $currency = $form->{currency};
1079 $form->{currency} = $currency;
1080 $form->{forex} = $form->check_exchangerate( \%myconfig, $form->{currency}, $form->{invdate}, 'buy');
1081 $form->{exchangerate} = $form->{forex} || '';
1083 $form->{creditremaining} -= ($form->{oldinvtotal} - $form->{ordtotal});
1085 # bei Gutschriften werden Zahlungseingänge aus Rechnung nicht übernommen
1086 for my $i (1 .. $form->{paidaccounts}) {
1087 delete $form->{"paid_$i"};
1088 delete $form->{"source_$i"};
1089 delete $form->{"memo_$i"};
1090 delete $form->{"datepaid_$i"};
1091 delete $form->{"gldate_$i"};
1092 delete $form->{"acc_trans_id_$i"};
1093 delete $form->{"AR_paid_$i"};
1095 $form->{paidaccounts} = 1;
1102 $main::lxdebug->leave_sub();
1106 $::lxdebug->enter_sub;
1108 $::auth->assert('invoice_edit');
1112 my $new_rowcount = $::form->{"rowcount"} * 1 + 1;
1113 $::form->{"project_id_${new_rowcount}"} = $::form->{"globalproject_id"};
1115 $::form->language_payment(\%::myconfig);
1117 Common::webdav_folder($::form);
1120 display_row(++$::form->{rowcount});
1123 $::lxdebug->leave_sub;
1127 $main::lxdebug->enter_sub();
1129 my $form = $main::form;
1130 my %myconfig = %main::myconfig;
1131 my $locale = $main::locale;
1133 $main::auth->assert('invoice_edit');
1135 if (IS->delete_invoice(\%myconfig, \%$form)) {
1136 # saving the history
1137 if(!exists $form->{addition}) {
1138 $form->{snumbers} = 'invnumber' .'_'. $form->{invnumber}; # ($form->{type} eq 'credit_note' ? 'cnnumber' : 'invnumber') .'_'. $form->{invnumber};
1139 $form->{what_done} = 'invoice';
1140 $form->{addition} = "DELETED";
1141 $form->save_history;
1143 # /saving the history
1144 $form->redirect($locale->text('Invoice deleted!'));
1146 $form->error($locale->text('Cannot delete invoice!'));
1148 $main::lxdebug->leave_sub();
1151 sub post_and_e_mail {
1156 $main::lxdebug->enter_sub();
1158 my $form = $main::form;
1160 $main::auth->assert('invoice_edit');
1163 $form->{no_redirect_after_post} = 1;
1165 my $saved_form = save_form();
1169 restore_form($saved_form, 0, qw(id invnumber));
1174 $main::lxdebug->leave_sub();