1 #=====================================================================
4 # Based on SQL-Ledger Version 2.1.9
5 # Web http://www.lx-office.org
7 #=====================================================================
8 # SQL-Ledger Accounting
9 # Copyright (c) 1998-2002
11 # Author: Dieter Simader
12 # Email: dsimader@sql-ledger.org
13 # Web: http://www.sql-ledger.org
16 # This program is free software; you can redistribute it and/or modify
17 # it under the terms of the GNU General Public License as published by
18 # the Free Software Foundation; either version 2 of the License, or
19 # (at your option) any later version.
21 # This program is distributed in the hope that it will be useful,
22 # but WITHOUT ANY WARRANTY; without even the implied warranty of
23 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
24 # GNU General Public License for more details.
25 # You should have received a copy of the GNU General Public License
26 # along with this program; if not, write to the Free Software
27 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
29 #======================================================================
31 # Inventory invoicing module
33 #======================================================================
38 use SL::MoreCommon qw(restore_form save_form);
41 use List::MoreUtils qw(uniq);
42 use List::Util qw(max sum);
43 use List::UtilsBy qw(sort_by);
44 use English qw(-no_match_vars);
49 use SL::DB::PaymentTerm;
51 require "bin/mozilla/io.pl";
52 require "bin/mozilla/arap.pl";
61 $main::lxdebug->enter_sub();
63 my $form = $main::form;
64 my $locale = $main::locale;
66 $main::auth->assert('invoice_edit');
68 $form->{show_details} = $::myconfig{show_form_details};
70 if ($form->{type} eq "credit_note") {
71 $form->{title} = $locale->text('Add Credit Note');
73 if ($form->{storno}) {
74 $form->{title} = $locale->text('Add Storno Credit Note');
77 $form->{title} = $locale->text('Add Sales Invoice');
82 $form->{callback} = "$form->{script}?action=add&type=$form->{type}" unless $form->{callback};
88 $main::lxdebug->leave_sub();
92 $main::lxdebug->enter_sub();
94 my $form = $main::form;
95 my $locale = $main::locale;
97 $main::auth->assert('invoice_edit');
99 $form->{show_details} = $::myconfig{show_form_details};
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 "price_factors" => "ALL_PRICE_FACTORS");
308 $form->{ALL_DEPARTMENTS} = SL::DB::Manager::Department->get_all;
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 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.Draft 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 my $grossamount = $form->{invtotal};
469 $form->{invtotal} = $form->round_amount( $form->{invtotal}, 2, 1 );
470 $form->{rounding} = $form->round_amount(
471 $form->{invtotal} - $form->round_amount($grossamount, 2),
477 $form->{follow_ups} = FU->follow_ups('trans_id' => $form->{id}, 'not_done' => 1) || [];
478 $form->{follow_ups_unfinished} = ( sum map { $_->{due} * 1 } @{ $form->{follow_ups} } ) || 0;
485 $form->{paidaccounts}++ if ($form->{"paid_$form->{paidaccounts}"});
486 $form->{paid_indices} = [ 1 .. $form->{paidaccounts} ];
488 # Standard Konto für Umlaufvermögen
489 my $accno_arap = IS->get_standard_accno_current_assets(\%myconfig, \%$form);
491 for my $i (1 .. $form->{paidaccounts}) {
492 $form->{"changeable_$i"} = 1;
493 if (SL::DB::Default->get->payments_changeable == 0) {
495 $form->{"changeable_$i"} = ($form->{"acc_trans_id_$i"})? 0 : 1;
496 } elsif (SL::DB::Default->get->payments_changeable == 2) {
498 $form->{"changeable_$i"} = (($form->{"gldate_$i"} eq '') ||
499 ($form->current_date(\%myconfig) eq $form->{"gldate_$i"}));
502 #deaktivieren von gebuchten Zahlungen ausserhalb der Bücherkontrolle, vorher prüfen ob heute eingegeben
503 if ($form->date_closed($form->{"gldate_$i"})) {
504 $form->{"changeable_$i"} = 0;
507 $form->{"selectAR_paid_$i"} = $form->{selectAR_paid};
508 if (!$form->{"AR_paid_$i"}) {
509 $form->{"selectAR_paid_$i"} =~ s/option>$accno_arap--(.*?)</option selected>$accno_arap--$1</;
511 $form->{"selectAR_paid_$i"} =~ s/option>\Q$form->{"AR_paid_$i"}\E/option selected>$form->{"AR_paid_$i"}/;
514 $totalpaid += $form->{"paid_$i"};
517 $form->{oldinvtotal} = $form->{invtotal};
519 $form->{ALL_DELIVERY_TERMS} = SL::DB::Manager::DeliveryTerm->get_all_sorted();
521 print $form->parse_html_template('is/form_footer', {
522 is_type_credit_note => ($form->{type} eq "credit_note"),
523 totalpaid => $totalpaid,
524 paid_missing => $form->{invtotal} - $totalpaid,
525 print_options => print_options(inline => 1),
526 show_storno => $form->{id} && !$form->{storno} && !IS->has_storno(\%myconfig, $form, "ar") && !$totalpaid,
527 show_delete => ($::instance_conf->get_is_changeable == 2)
528 ? ($form->current_date(\%myconfig) eq $form->{gldate})
529 : ($::instance_conf->get_is_changeable == 1),
530 today => DateTime->today,
532 ##print $form->parse_html_template('is/_payments'); # parser
533 ##print $form->parse_html_template('webdav/_list'); # parser
535 $main::lxdebug->leave_sub();
539 $::auth->assert('invoice_edit');
541 SL::DB::Invoice->new(id => $::form->{id})->load->mark_as_paid;
543 $::form->redirect($::locale->text("Marked as paid"));
551 $main::lxdebug->enter_sub();
553 my $form = $main::form;
554 my %myconfig = %main::myconfig;
556 $main::auth->assert('invoice_edit');
558 my ($recursive_call) = @_;
560 $form->{print_and_post} = 0 if $form->{second_run};
561 my $taxincluded = $form->{taxincluded} ? "checked" : '';
564 &check_name("customer");
566 $form->{taxincluded} ||= $taxincluded;
568 if (!$form->{forex}) { # read exchangerate from input field (not hidden)
569 $form->{exchangerate} = $form->parse_amount(\%myconfig, $form->{exchangerate}) unless $recursive_call;
571 $form->{forex} = $form->check_exchangerate(\%myconfig, $form->{currency}, $form->{invdate}, 'buy');
572 $form->{exchangerate} = $form->{forex} if $form->{forex};
574 for my $i (1 .. $form->{paidaccounts}) {
575 next unless $form->{"paid_$i"};
576 map { $form->{"${_}_$i"} = $form->parse_amount(\%myconfig, $form->{"${_}_$i"}) } qw(paid exchangerate);
577 if (!$form->{"forex_$i"}) { #read exchangerate from input field (not hidden)
578 $form->{exchangerate} = $form->{"exchangerate_$i"};
580 $form->{"forex_$i"} = $form->check_exchangerate(\%myconfig, $form->{currency}, $form->{"datepaid_$i"}, 'buy');
581 $form->{"exchangerate_$i"} = $form->{"forex_$i"} if $form->{"forex_$i"};
584 my $i = $form->{rowcount};
585 my $exchangerate = $form->{exchangerate} || 1;
587 # if last row empty, check the form otherwise retrieve new item
588 if ( ($form->{"partnumber_$i"} eq "")
589 && ($form->{"description_$i"} eq "")
590 && ($form->{"partsgroup_$i"} eq "")) {
592 $form->{creditremaining} += ($form->{oldinvtotal} - $form->{oldtotalpaid});
597 IS->retrieve_item(\%myconfig, \%$form);
599 my $rows = scalar @{ $form->{item_list} };
601 $form->{"discount_$i"} = $form->parse_amount(\%myconfig, $form->{"discount_$i"}) / 100.0;
602 $form->{"discount_$i"} ||= $form->{customer_discount};
605 $form->{"qty_$i"} = $form->parse_amount(\%myconfig, $form->{"qty_$i"});
606 if( !$form->{"qty_$i"} ) {
607 $form->{"qty_$i"} = 1;
612 select_item(mode => 'IS', pre_entered_qty => $form->{"qty_$i"});
613 $::dispatcher->end_request;
617 my $sellprice = $form->parse_amount(\%myconfig, $form->{"sellprice_$i"});
619 map { $form->{item_list}[$i]{$_} =~ s/\"/"/g } qw(partnumber description unit);
620 map { $form->{"${_}_$i"} = $form->{item_list}[0]{$_} } keys %{ $form->{item_list}[0] };
622 $form->{payment_id} = $form->{"part_payment_id_$i"} if $form->{"part_payment_id_$i"} ne "";
623 $form->{"discount_$i"} = 0 if $form->{"not_discountable_$i"};
625 $form->{"marge_price_factor_$i"} = $form->{item_list}->[0]->{price_factor};
627 ($sellprice || $form->{"sellprice_$i"}) =~ /\.(\d+)/;
628 my $decimalplaces = max 2, length $1;
631 $form->{"sellprice_$i"} = $sellprice;
633 my $record = _make_record();
634 my $price_source = SL::PriceSource->new(record_item => $record->items->[$i-1], record => $record);
635 my $best_price = $price_source->best_price;
636 my $best_discount = $price_source->best_discount;
639 $::form->{"sellprice_$i"} = $best_price->price;
640 $::form->{"active_price_source_$i"} = $best_price->source;
642 if ($best_discount) {
643 $::form->{"discount_$i"} = $best_discount->discount;
644 $::form->{"active_discount_source_$i"} = $best_discount->source;
647 # if there is an exchange rate adjust sellprice
648 $form->{"sellprice_$i"} /= $exchangerate;
651 $form->{"listprice_$i"} /= $exchangerate;
653 my $amount = $form->{"sellprice_$i"} * $form->{"qty_$i"} * (1 - $form->{"discount_$i"});
654 map { $form->{"${_}_base"} = 0 } split / /, $form->{taxaccounts};
655 map { $form->{"${_}_base"} += $amount } split / /, $form->{"taxaccounts_$i"};
656 map { $amount += ($form->{"${_}_base"} * $form->{"${_}_rate"}) } split / /, $form->{"taxaccounts_$i"} if !$form->{taxincluded};
658 $form->{creditremaining} -= $amount;
660 map { $form->{"${_}_$i"} = $form->format_amount(\%myconfig, $form->{"${_}_$i"}, $decimalplaces) } qw(sellprice lastcost);
662 $form->{"qty_$i"} = $form->format_amount(\%myconfig, $form->{"qty_$i"});
663 $form->{"discount_$i"} = $form->format_amount(\%myconfig, $form->{"discount_$i"} * 100.0);
670 # ok, so this is a new part
671 # ask if it is a part or service item
673 if ( $form->{"partsgroup_$i"}
674 && ($form->{"partsnumber_$i"} eq "")
675 && ($form->{"description_$i"} eq "")) {
677 $form->{"discount_$i"} = "";
681 $form->{"id_$i"} = 0;
686 $main::lxdebug->leave_sub();
690 $main::lxdebug->enter_sub();
692 my $form = $main::form;
693 my %myconfig = %main::myconfig;
694 my $locale = $main::locale;
696 $main::auth->assert('invoice_edit');
698 $form->mtime_ischanged('ar') ;
699 my $invdate = $form->datetonum($form->{invdate}, \%myconfig);
701 $form->{defaultcurrency} = $form->get_default_currency(\%myconfig);
702 for my $i (1 .. $form->{paidaccounts}) {
703 if ($form->{"paid_$i"}) {
704 my $datepaid = $form->datetonum($form->{"datepaid_$i"}, \%myconfig);
706 $form->isblank("datepaid_$i", $locale->text('Payment date missing!'));
709 if ($form->{currency} ne $form->{defaultcurrency}) {
710 $form->{"exchangerate_$i"} = $form->{exchangerate}
711 if ($invdate == $datepaid);
712 $form->isblank("exchangerate_$i",
713 $locale->text('Exchangerate for payment missing!'));
715 $form->error($locale->text('Cannot post transaction above the maximum future booking date!'))
716 if ($form->date_max_future($form->{"datepaid_$i"}, \%myconfig));
718 #Zusätzlich noch das Buchungsdatum in die Bücherkontrolle einbeziehen
719 # (Dient zur Prüfung ob ZE oder ZA geprüft werden soll)
720 $form->error($locale->text('Cannot post payment for a closed period!'))
721 if ($form->date_closed($form->{"datepaid_$i"}) && !$form->date_closed($form->{"gldate_$i"}, \%myconfig));
725 ($form->{AR}) = split /--/, $form->{AR};
726 ($form->{AR_paid}) = split /--/, $form->{AR_paid};
728 if ( IS->post_payment(\%myconfig, \%$form) ) {
729 $form->{snumbers} = qq|invnumber_| . $form->{invnumber};
730 $form->{what_done} = 'invoice';
731 $form->{addition} = "PAYMENT POSTED";
733 $form->redirect($locale->text('Payment posted!'))
735 $form->error($locale->text('Cannot post payment!'));
738 $main::lxdebug->leave_sub();
742 $main::lxdebug->enter_sub();
744 my $form = $main::form;
745 my %myconfig = %main::myconfig;
746 my $locale = $main::locale;
748 $main::auth->assert('invoice_edit');
749 $form->mtime_ischanged('ar');
751 $form->{defaultcurrency} = $form->get_default_currency(\%myconfig);
752 $form->isblank("invdate", $locale->text('Invoice Date missing!'));
753 $form->isblank("customer", $locale->text('Customer missing!'));
754 $form->error($locale->text('Cannot post invoice for a closed period!'))
755 if ($form->date_closed($form->{"invdate"}, \%myconfig));
757 $form->{invnumber} =~ s/^\s*//g;
758 $form->{invnumber} =~ s/\s*$//g;
760 # if oldcustomer ne customer redo form
761 if (&check_name('customer')) {
763 $::dispatcher->end_request;
766 if ($myconfig{mandatory_departments} && !$form->{department_id}) {
767 $form->{saved_message} = $::locale->text('You have to specify a department.');
772 if ($form->{second_run}) {
773 $form->{print_and_post} = 0;
776 remove_emptied_rows();
779 my $closedto = $form->datetonum($form->{closedto}, \%myconfig);
780 my $invdate = $form->datetonum($form->{invdate}, \%myconfig);
782 $form->error($locale->text('Cannot post transaction above the maximum future booking date!'))
783 if ($form->date_max_future($invdate, \%myconfig));
784 $form->error($locale->text('Cannot post invoice for a closed period!'))
785 if ($invdate <= $closedto);
787 $form->isblank("exchangerate", $locale->text('Exchangerate missing!'))
788 if ($form->{currency} ne $form->{defaultcurrency});
790 for my $i (1 .. $form->{paidaccounts}) {
791 if ($form->parse_amount(\%myconfig, $form->{"paid_$i"})) {
792 my $datepaid = $form->datetonum($form->{"datepaid_$i"}, \%myconfig);
794 $form->isblank("datepaid_$i", $locale->text('Payment date missing!'));
796 $form->error($locale->text('Cannot post transaction above the maximum future booking date!'))
797 if ($form->date_max_future($form->{"datepaid_$i"}, \%myconfig));
799 #Zusätzlich noch das Buchungsdatum in die Bücherkontrolle einbeziehen
800 # (Dient zur Prüfung ob ZE oder ZA geprüft werden soll)
801 $form->error($locale->text('Cannot post payment for a closed period!'))
802 if ($form->date_closed($form->{"datepaid_$i"}) && !$form->date_closed($form->{"gldate_$i"}, \%myconfig));
804 if ($form->{currency} ne $form->{defaultcurrency}) {
805 $form->{"exchangerate_$i"} = $form->{exchangerate}
806 if ($invdate == $datepaid);
807 $form->isblank("exchangerate_$i",
808 $locale->text('Exchangerate for payment missing!'));
813 ($form->{AR}) = split /--/, $form->{AR};
814 ($form->{AR_paid}) = split /--/, $form->{AR_paid};
815 $form->{storno} ||= 0;
817 $form->{label} = $form->{type} eq 'credit_note' ? $locale->text('Credit Note') : $locale->text('Invoice');
819 $form->{id} = 0 if $form->{postasnew};
821 # get new invnumber in sequence if no invnumber is given or if posasnew was requested
822 if ($form->{postasnew}) {
823 if ($form->{type} eq "credit_note") {
824 undef($form->{cnnumber});
826 undef($form->{invnumber});
832 my $terms = get_payment_terms_for_invoice();
833 $form->{duedate} = $terms->calc_date(reference_date => $form->{invdate}, due_date => $form->{due_due})->to_kivitendo if $terms;
835 # If transfer_out is requested, get rose db handle and do post and
836 # transfer out in one transaction. Otherwise just post the invoice.
837 if ($::instance_conf->get_is_transfer_out && $form->{type} ne 'credit_note' && !$form->{storno}) {
838 require SL::DB::Inventory;
839 my $rose_db = SL::DB::Inventory->new->db;
842 if (!$rose_db->with_transaction(sub {
844 if (!IS->post_invoice(\%myconfig, \%$form, $rose_db->dbh)) {
845 push @errors, $locale->text('Cannot post invoice!');
848 my $err = IS->transfer_out(\%$form, $rose_db->dbh);
850 push @errors, @{ $err };
851 die 'transfer error';
856 push @errors, $EVAL_ERROR;
857 die 'transaction error';
862 push @errors, $rose_db->error;
863 $form->error($locale->text('Cannot post invoice and/or transfer out! Error message:') . "\n" . join("\n", @errors));
866 if (!IS->post_invoice(\%myconfig, \%$form)) {
867 $form->error($locale->text('Cannot post invoice!'));
871 if(!exists $form->{addition}) {
872 $form->{snumbers} = 'invnumber' .'_'. $form->{invnumber}; # ($form->{type} eq 'credit_note' ? 'cnnumber' : 'invnumber') .'_'. $form->{invnumber};
873 $form->{what_done} = 'invoice';
874 $form->{addition} = $form->{print_and_post} ? "PRINTED AND POSTED" :
875 $form->{storno} ? "STORNO" :
880 if (!$form->{no_redirect_after_post}) {
881 $form->{action} = 'edit';
882 $form->{script} = 'is.pl';
883 $form->{saved_message} = $form->{label} . " $form->{invnumber} " . $locale->text('posted!');
884 $form->{callback} = build_std_url(qw(action edit id callback saved_message));
888 $main::lxdebug->leave_sub();
892 $main::lxdebug->enter_sub();
894 my $form = $main::form;
896 $main::auth->assert('invoice_edit');
898 my $old_form = Form->new;
899 $form->{no_redirect_after_post} = 1;
900 $form->{print_and_post} = 1;
904 $main::lxdebug->leave_sub();
909 $main::lxdebug->enter_sub();
911 my $form = $main::form;
912 my %myconfig = %main::myconfig;
914 $main::auth->assert('invoice_edit');
916 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)};
918 $form->{paidaccounts} = 1;
919 $form->{invdate} = $form->current_date(\%myconfig);
920 my $terms = get_payment_terms_for_invoice();
921 $form->{duedate} = $terms ? $terms->calc_date(reference_date => $form->{invdate})->to_kivitendo : $form->{invdate};
922 $form->{employee_id} = SL::DB::Manager::Employee->current->id;
923 $form->{forex} = $form->check_exchangerate(\%myconfig, $form->{currency}, $form->{invdate}, 'buy');
924 $form->{exchangerate} = $form->{forex} if $form->{forex};
926 $form->{"converted_from_invoice_id_$_"} = delete $form->{"invoice_id_$_"} for 1 .. $form->{"rowcount"};
928 $form->{useasnew} = 1;
931 $main::lxdebug->leave_sub();
935 $main::lxdebug->enter_sub();
937 my $form = $main::form;
938 my %myconfig = %main::myconfig;
939 my $locale = $main::locale;
941 $main::auth->assert('invoice_edit');
943 if ($form->{storno}) {
944 $form->error($locale->text('Cannot storno storno invoice!'));
947 if (IS->has_storno(\%myconfig, $form, "ar")) {
948 $form->error($locale->text("Invoice has already been storno'd!"));
950 if ($form->datetonum($form->{invdate}, \%myconfig) <= $form->datetonum($form->{closedto}, \%myconfig)) {
951 $form->error($locale->text('Cannot storno invoice for a closed period!'));
954 # save the history of invoice being stornoed
955 $form->{snumbers} = qq|invnumber_| . $form->{invnumber};
956 $form->{what_done} = 'invoice';
957 $form->{addition} = "STORNO";
960 map({ my $key = $_; delete($form->{$key}) unless (grep({ $key eq $_ } qw(id login password type))); } keys(%{ $form }));
966 # Payments must not be recorded for the new storno invoice.
967 $form->{paidaccounts} = 0;
968 map { my $key = $_; delete $form->{$key} if grep { $key =~ /^$_/ } qw(datepaid_ gldate_ acc_trans_id_ source_ memo_ paid_ exchangerate_ AR_paid_) } keys %{ $form };
970 # record link invoice to storno
971 $form->{convert_from_ar_ids} = $form->{id};
972 $form->{storno_id} = $form->{id};
975 $form->{invnumber} = "Storno zu " . $form->{invnumber};
976 $form->{invdate} = DateTime->today->to_lxoffice;
978 # set new ids for storno invoice
979 # set new persistent ids for storno invoice items
980 $form->{"converted_from_invoice_id_$_"} = delete $form->{"invoice_id_$_"} for 1 .. $form->{"rowcount"};
983 $main::lxdebug->leave_sub();
987 $main::lxdebug->enter_sub();
989 my $form = $main::form;
991 $main::auth->assert('invoice_edit');
993 $form->{preview} = 1;
994 my $old_form = Form->new;
995 for (keys %$form) { $old_form->{$_} = $form->{$_} }
997 &print_form($old_form);
998 $main::lxdebug->leave_sub();
1003 $main::lxdebug->enter_sub();
1005 my $form = $main::form;
1006 my %myconfig = %main::myconfig;
1007 my $locale = $main::locale;
1009 $main::auth->assert('invoice_edit');
1011 $form->{transdate} = $form->{invdate} = $form->current_date(\%myconfig);
1013 $form->current_date(\%myconfig, $form->{invdate}, $form->{terms} * 1);
1015 $form->{convert_from_ar_ids} = $form->{id};
1017 $form->{rowcount}--;
1020 $form->{title} = $locale->text('Add Credit Note');
1021 $form->{script} = 'is.pl';
1023 # Bei Gutschriften bezug zur Rechnungsnummer
1024 $form->{invnumber_for_credit_note} = $form->{invnumber};
1025 # bo creates the id, reset it
1026 map { delete $form->{$_} }
1027 qw(id invnumber subject message cc bcc printed emailed queued);
1028 $form->{ $form->{vc} } =~ s/--.*//g;
1029 $form->{type} = "credit_note";
1032 map { $form->{"select$_"} = "" } ($form->{vc}, 'currency');
1034 # map { $form->{$_} = $form->parse_amount(\%myconfig, $form->{$_}) }
1035 # qw(creditlimit creditremaining);
1037 # set new persistent ids for credit note and link previous invoice id
1038 $form->{"converted_from_invoice_id_$_"} = delete $form->{"invoice_id_$_"} for 1 .. $form->{"rowcount"};
1040 my $currency = $form->{currency};
1043 $form->{currency} = $currency;
1044 $form->{forex} = $form->check_exchangerate( \%myconfig, $form->{currency}, $form->{invdate}, 'buy');
1045 $form->{exchangerate} = $form->{forex} || '';
1047 $form->{creditremaining} -= ($form->{oldinvtotal} - $form->{ordtotal});
1049 # bei Gutschriften werden Zahlungseingänge aus Rechnung nicht übernommen
1050 for my $i (1 .. $form->{paidaccounts}) {
1051 delete $form->{"paid_$i"};
1052 delete $form->{"source_$i"};
1053 delete $form->{"memo_$i"};
1054 delete $form->{"datepaid_$i"};
1055 delete $form->{"gldate_$i"};
1056 delete $form->{"acc_trans_id_$i"};
1057 delete $form->{"AR_paid_$i"};
1059 $form->{paidaccounts} = 1;
1066 $main::lxdebug->leave_sub();
1070 $::lxdebug->enter_sub;
1072 $::auth->assert('invoice_edit');
1076 my $new_rowcount = $::form->{"rowcount"} * 1 + 1;
1077 $::form->{"project_id_${new_rowcount}"} = $::form->{"globalproject_id"};
1079 $::form->language_payment(\%::myconfig);
1081 Common::webdav_folder($::form);
1084 display_row(++$::form->{rowcount});
1087 $::lxdebug->leave_sub;
1091 $::auth->assert('invoice_edit');
1093 if (IS->delete_invoice(\%::myconfig, $::form)) {
1094 # saving the history
1095 if(!exists $::form->{addition}) {
1096 $::form->{snumbers} = 'invnumber' .'_'. $::form->{invnumber};
1097 $::form->{what_done} = 'invoice';
1098 $::form->{addition} = "DELETED";
1099 $::form->save_history;
1101 # /saving the history
1102 $::form->redirect($::locale->text('Invoice deleted!'));
1104 $::form->error($::locale->text('Cannot delete invoice!'));
1107 sub post_and_e_mail {
1112 $main::lxdebug->enter_sub();
1114 my $form = $main::form;
1116 $main::auth->assert('invoice_edit');
1119 $form->{no_redirect_after_post} = 1;
1121 my $saved_form = save_form();
1125 restore_form($saved_form, 0, qw(id invnumber));
1130 $main::lxdebug->leave_sub();
1135 print update ship_to e_mail storno post_payment use_as_new credit_note
1136 delete post order preview post_and_e_mail print_and_post
1139 if ($::form->{"action_$action"}) {
1145 $::form->error($::locale->text('No action defined.'));