1 #=====================================================================
4 # Based on SQL-Ledger Version 2.1.9
5 # Web http://www.lx-office.org
7 #=====================================================================
8 # SQL-Ledger Accounting
9 # Copyright (c) 1998-2002
11 # Author: Dieter Simader
12 # Email: dsimader@sql-ledger.org
13 # Web: http://www.sql-ledger.org
16 # This program is free software; you can redistribute it and/or modify
17 # it under the terms of the GNU General Public License as published by
18 # the Free Software Foundation; either version 2 of the License, or
19 # (at your option) any later version.
21 # This program is distributed in the hope that it will be useful,
22 # but WITHOUT ANY WARRANTY; without even the implied warranty of
23 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
24 # GNU General Public License for more details.
25 # You should have received a copy of the GNU General Public License
26 # along with this program; if not, write to the Free Software
27 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
29 #======================================================================
31 # Inventory invoicing module
33 #======================================================================
38 use SL::MoreCommon qw(restore_form save_form);
41 use List::MoreUtils qw(uniq);
42 use List::Util qw(max sum);
43 use List::UtilsBy qw(sort_by);
44 use English qw(-no_match_vars);
48 use SL::DB::Department;
50 use SL::DB::PaymentTerm;
52 require "bin/mozilla/common.pl";
53 require "bin/mozilla/io.pl";
62 $main::lxdebug->enter_sub();
64 my $form = $main::form;
65 my $locale = $main::locale;
67 $main::auth->assert('invoice_edit');
69 $form->{show_details} = $::myconfig{show_form_details};
71 if ($form->{type} eq "credit_note") {
72 $form->{title} = $locale->text('Add Credit Note');
74 if ($form->{storno}) {
75 $form->{title} = $locale->text('Add Storno Credit Note');
78 $form->{title} = $locale->text('Add Sales Invoice');
83 $form->{callback} = "$form->{script}?action=add&type=$form->{type}" unless $form->{callback};
89 $main::lxdebug->leave_sub();
93 $main::lxdebug->enter_sub();
95 my $form = $main::form;
96 my $locale = $main::locale;
98 $main::auth->assert('invoice_edit');
100 $form->{show_details} = $::myconfig{show_form_details};
101 $form->{taxincluded_changed_by_user} = 1;
103 # show history button
104 $form->{javascript} = qq|<script type="text/javascript" src="js/show_history.js"></script>|;
106 my ($language_id, $printer_id);
107 if ($form->{print_and_post}) {
108 $form->{action} = "print";
109 $form->{resubmit} = 1;
110 $language_id = $form->{language_id};
111 $printer_id = $form->{printer_id};
115 if ($form->{type} eq "credit_note") {
116 $form->{title} = $locale->text('Edit Credit Note');
117 $form->{title} = $locale->text('Edit Storno Credit Note') if $form->{storno};
119 $form->{title} = $locale->text('Edit Sales Invoice');
120 $form->{title} = $locale->text('Edit Storno Invoice') if $form->{storno};
124 if ($form->{print_and_post}) {
125 $form->{language_id} = $language_id;
126 $form->{printer_id} = $printer_id;
131 $main::lxdebug->leave_sub();
135 $main::lxdebug->enter_sub();
137 my $form = $main::form;
138 my %myconfig = %main::myconfig;
140 $main::auth->assert('invoice_edit');
142 $form->{vc} = 'customer';
145 $form->create_links("AR", \%myconfig, "customer");
147 my $editing = $form->{id};
149 $form->backup_vars(qw(payment_id language_id taxzone_id salesman_id
150 taxincluded currency cp_id intnotes id shipto_id
153 IS->get_customer(\%myconfig, \%$form);
155 $form->restore_vars(qw(id));
157 IS->retrieve_invoice(\%myconfig, \%$form);
158 $form->restore_vars(qw(payment_id language_id taxzone_id currency intnotes
159 cp_id shipto_id delivery_term_id));
160 $form->restore_vars(qw(taxincluded)) if $form->{id};
161 $form->restore_vars(qw(salesman_id)) if $editing;
163 $form->{employee} = "$form->{employee}--$form->{employee_id}";
166 $form->{forex} = $form->{exchangerate};
167 my $exchangerate = ($form->{exchangerate}) ? $form->{exchangerate} : 1;
169 foreach my $key (keys %{ $form->{AR_links} }) {
170 foreach my $ref (@{ $form->{AR_links}{$key} }) {
171 $form->{"select$key"} .= "<option>$ref->{accno}--$ref->{description}</option>\n";
174 if ($key eq "AR_paid") {
175 next unless $form->{acc_trans}{$key};
176 for my $i (1 .. scalar @{ $form->{acc_trans}{$key} }) {
177 $form->{"AR_paid_$i"} = "$form->{acc_trans}{$key}->[$i-1]->{accno}--$form->{acc_trans}{$key}->[$i-1]->{description}";
179 $form->{"acc_trans_id_$i"} = $form->{acc_trans}{$key}->[$i - 1]->{acc_trans_id};
181 $form->{"paid_$i"} = $form->{acc_trans}{$key}->[$i - 1]->{amount} * -1;
182 $form->{"datepaid_$i"} = $form->{acc_trans}{$key}->[$i - 1]->{transdate};
183 $form->{"gldate_$i"} = $form->{acc_trans}{$key}->[$i - 1]->{gldate};
184 $form->{"exchangerate_$i"} = $form->{acc_trans}{$key}->[$i - 1]->{exchangerate};
185 $form->{"forex_$i"} = $form->{"exchangerate_$i"};
186 $form->{"source_$i"} = $form->{acc_trans}{$key}->[$i - 1]->{source};
187 $form->{"memo_$i"} = $form->{acc_trans}{$key}->[$i - 1]->{memo};
189 $form->{paidaccounts} = $i;
192 $form->{$key} = "$form->{acc_trans}{$key}->[0]->{accno}--$form->{acc_trans}{$key}->[0]->{description}";
196 $form->{paidaccounts} = 1 unless (exists $form->{paidaccounts});
198 $form->{AR} = $form->{AR_1} unless $form->{id};
200 $form->{locked} = ($form->datetonum($form->{invdate}, \%myconfig)
201 <= $form->datetonum($form->{closedto}, \%myconfig));
203 $main::lxdebug->leave_sub();
206 sub prepare_invoice {
207 $main::lxdebug->enter_sub();
209 my $form = $main::form;
210 my %myconfig = %main::myconfig;
212 $main::auth->assert('invoice_edit');
214 if ($form->{type} eq "credit_note") {
215 $form->{type} = "credit_note";
216 $form->{formname} = "credit_note";
217 } elsif ($form->{formname} eq "proforma" ) {
218 $form->{type} = "invoice";
220 $form->{type} = "invoice";
221 $form->{formname} = "invoice";
228 foreach my $ref (@{ $form->{invoice_details} }) {
231 map { $form->{"${_}_$i"} = $ref->{$_} } keys %{$ref};
233 $form->{"discount_$i"} = $form->format_amount(\%myconfig, $form->{"discount_$i"} * 100);
234 my ($dec) = ($form->{"sellprice_$i"} =~ /\.(\d+)/);
236 my $decimalplaces = ($dec > 2) ? $dec : 2;
238 $form->{"sellprice_$i"} = $form->format_amount(\%myconfig, $form->{"sellprice_$i"}, $decimalplaces);
239 (my $dec_qty) = ($form->{"qty_$i"} =~ /\.(\d+)/);
240 $dec_qty = length $dec_qty;
242 $form->{"lastcost_$i"} = $form->format_amount(\%myconfig, $form->{"lastcost_$i"}, $decimalplaces);
244 $form->{"qty_$i"} = $form->format_amount(\%myconfig, $form->{"qty_$i"}, $dec_qty);
246 $form->{"sellprice_pg_$i"} = join ('--', $form->{"sellprice_$i"}, $form->{"pricegroup_id_$i"});
248 $form->{rowcount} = $i;
252 $main::lxdebug->leave_sub();
256 $main::lxdebug->enter_sub();
258 my $form = $main::form;
259 my %myconfig = %main::myconfig;
260 my $locale = $main::locale;
261 my $cgi = $::request->{cgi};
263 $main::auth->assert('invoice_edit');
268 $TMPL_VAR{customer_obj} = SL::DB::Customer->load_cached($form->{customer_id}) if $form->{customer_id};
269 $TMPL_VAR{invoice_obj} = SL::DB::Invoice->load_cached($form->{id}) if $form->{id};
271 $form->{employee_id} = $form->{old_employee_id} if $form->{old_employee_id};
272 $form->{salesman_id} = $form->{old_salesman_id} if $form->{old_salesman_id};
274 $form->{defaultcurrency} = $form->get_default_currency(\%myconfig);
276 $form->get_lists("taxzones" => ($form->{id} ? "ALL_TAXZONES" : "ALL_ACTIVE_TAXZONES"),
277 "currencies" => "ALL_CURRENCIES",
278 "price_factors" => "ALL_PRICE_FACTORS");
280 $form->{ALL_DEPARTMENTS} = SL::DB::Manager::Department->get_all_sorted;
283 my @old_project_ids = uniq grep { $_ } map { $_ * 1 } ($form->{"globalproject_id"}, map { $form->{"project_id_$_"} } 1..$form->{"rowcount"});
284 my @old_ids_cond = @old_project_ids ? (id => \@old_project_ids) : ();
286 if ($::instance_conf->get_customer_projects_only_in_sales) {
289 customer_id => $::form->{customer_id},
290 billable_customer_id => $::form->{customer_id},
295 and => [ active => 1, @customer_cond ],
299 $TMPL_VAR{ALL_PROJECTS} = SL::DB::Manager::Project->get_all_sorted(query => \@conditions);
300 $form->{ALL_PROJECTS} = $TMPL_VAR{ALL_PROJECTS}; # make projects available for second row drop-down in io.pl
301 $TMPL_VAR{ALL_EMPLOYEES} = SL::DB::Manager::Employee->get_all_sorted(query => [ or => [ id => $::form->{employee_id}, deleted => 0 ] ]);
302 $TMPL_VAR{ALL_SALESMEN} = SL::DB::Manager::Employee->get_all_sorted(query => [ or => [ id => $::form->{salesman_id}, deleted => 0 ] ]);
303 $TMPL_VAR{ALL_SHIPTO} = SL::DB::Manager::Shipto->get_all_sorted(query => [
304 or => [ trans_id => $::form->{"$::form->{vc}_id"} * 1, and => [ shipto_id => $::form->{shipto_id} * 1, trans_id => undef ] ]
306 $TMPL_VAR{ALL_CONTACTS} = SL::DB::Manager::Contact->get_all_sorted(query => [
308 cp_cv_id => $::form->{"$::form->{vc}_id"} * 1,
311 cp_id => $::form->{cp_id} * 1
316 # currencies and exchangerate
317 my @values = map { $_ } @{ $form->{ALL_CURRENCIES} };
318 my %labels = map { $_ => $_ } @{ $form->{ALL_CURRENCIES} };
319 $form->{currency} = $form->{defaultcurrency} unless $form->{currency};
320 $form->{show_exchangerate} = $form->{currency} ne $form->{defaultcurrency};
321 $TMPL_VAR{currencies} = NTI($::request->{cgi}->popup_menu('-name' => 'currency', '-default' => $form->{"currency"},
322 '-values' => \@values, '-labels' => \%labels,
323 '-onchange' => "document.getElementById('update_button').click();"
324 )) if scalar @values;
325 push @custom_hiddens, "forex";
326 push @custom_hiddens, "exchangerate" if $form->{forex};
328 $TMPL_VAR{creditwarning} = ($form->{creditlimit} != 0) && ($form->{creditremaining} < 0) && !$form->{update};
329 $TMPL_VAR{is_credit_remaining_negativ} = $form->{creditremaining} =~ /-/;
331 # set option selected
332 foreach my $item (qw(AR)) {
333 $form->{"select$item"} =~ s/ selected//;
334 $form->{"select$item"} =~ s/option>\Q$form->{$item}\E/option selected>$form->{$item}/;
337 $TMPL_VAR{is_type_credit_note} = $form->{type} eq "credit_note";
338 $TMPL_VAR{is_format_html} = $form->{format} eq 'html';
339 $TMPL_VAR{dateformat} = $myconfig{dateformat};
340 $TMPL_VAR{numberformat} = $myconfig{numberformat};
342 push @custom_hiddens, map { "shiptocvar_" . $_->name } @{ SL::DB::Manager::CustomVariableConfig->get_all(where => [ module => 'ShipTo' ]) };
345 $TMPL_VAR{HIDDENS} = [qw(
346 id type media format queued printed emailed title vc discount
347 title creditlimit creditremaining tradediscount business closedto locked shipped storno storno_id
348 max_dunning_level dunning_amount dunning_description
349 shiptoname shiptostreet shiptozipcode shiptocity shiptocountry shiptogln shiptocontact shiptophone shiptofax
350 shiptoemail shiptodepartment_1 shiptodepartment_2 shiptocp_gender message email subject cc bcc taxaccounts cursor_fokus
351 convert_from_do_ids convert_from_oe_ids convert_from_ar_ids useasnew
355 map { $_.'_rate', $_.'_description', $_.'_taxnumber' } split / /, $form->{taxaccounts}];
357 $::request->{layout}->use_javascript(map { "${_}.js" } qw(kivi.Draft kivi.File kivi.SalesPurchase kivi.Part ckeditor/ckeditor ckeditor/adapters/jquery kivi.io autocomplete_customer client_js));
359 $TMPL_VAR{payment_terms_obj} = get_payment_terms_for_invoice();
360 $form->{duedate} = $TMPL_VAR{payment_terms_obj}->calc_date(reference_date => $form->{invdate}, due_date => $form->{duedate})->to_kivitendo if $TMPL_VAR{payment_terms_obj};
362 my @req_trans_desc = qw(kivi.SalesPurchase.check_transaction_description) x!!$::instance_conf->get_require_transaction_description_ps;
363 my $show_delete = ($::instance_conf->get_is_changeable == 2 && $form->current_date(\%myconfig) eq $form->{gldate})
364 || $::instance_conf->get_is_changeable == 1;
366 for my $bar ($::request->layout->get('actionbar')) {
367 $bar->add_actions([ t8('Update'),
368 submit => [ '#form', { action_update => 1 } ],
369 disabled => !$::form->{id} && $::form->{locked},
371 $bar->add_actions("combobox");
372 $bar->actions->[-1]->add_actions([ t8('Post'),
373 submit => [ '#form', { action_post => 1 } ],
374 checks => [ @req_trans_desc ],
375 disabled => (!$::form->{id} && $::form->{locked}) || !$show_delete || $::form->{storno},
377 $bar->actions->[-1]->add_actions([ t8('Post Payment'),
378 submit => [ '#form', { action_post_payment => 1 } ],
379 checks => [ @req_trans_desc ],
380 disabled => !$::form->{id},
382 $bar->actions->[-1]->add_actions([ t8('mark as paid'),
383 submit => [ '#form', { action_mark_as_paid => 1 } ],
384 confirm => t8('This will remove the invoice from showing as unpaid even if the unpaid amount does not match the amount. Proceed?'),
385 disabled => !$::form->{id},
386 ]) if $::instance_conf->get_is_show_mark_as_paid;
388 $bar->add_actions("combobox");
389 $bar->actions->[-1]->add_actions([ t8('Storno'),
390 submit => [ '#form', { action_storno => 1 } ],
391 confirm => t8('Do you really want to cancel this invoice?'),
392 checks => [ @req_trans_desc ],
393 disabled => !$::form->{id},
395 $bar->actions->[-1]->add_actions([ t8('Delete'),
396 submit => [ '#form', { action_delete => 1 } ],
397 confirm => t8('Do you really want to delete this object?'),
398 checks => [ @req_trans_desc ],
399 disabled => !$::form->{id},
401 $bar->add_actions('separator');
403 $bar->add_actions('combobox');
404 $bar->actions->[-1]->add_actions([ t8('Workflow'),
407 $bar->actions->[-1]->add_actions([ t8('Use As New'),
408 submit => [ '#form', { action_use_as_new => 1 } ],
409 disabled => !$::form->{id},
411 $bar->actions->[-1]->add_actions([ t8('Credit Note'),
412 submit => [ '#form', { action_credit_note => 1 } ],
413 checks => [ @req_trans_desc ],
414 disabled => !$::form->{id} || $form->{type} eq "credit_note",
416 $bar->actions->[-1]->add_actions([ t8('Sales Order'),
417 submit => [ '#form', { action_sales_order => 1 } ],
418 disabled => !$::form->{id},
421 $bar->add_actions('combobox');
422 $bar->actions->[-1]->add_actions([ t8('Export'),
425 $bar->actions->[-1]->add_actions([ ($::form->{id} ? t8('Print') : t8('Preview')),
426 submit => [ '#form', { action_print => 1 } ],
427 checks => [ @req_trans_desc ],
428 disabled => !$::form->{id} && $::form->{locked},
430 $bar->actions->[-1]->add_actions([ t8('E Mail'),
431 submit => [ '#form', { action_print => 1 } ],
432 checks => [ @req_trans_desc ],
433 disabled => !$::form->{id},
435 $bar->add_actions('combobox');
436 $bar->actions->[-1]->add_actions([ t8('more'),
439 $bar->actions->[-1]->add_actions([ t8('History'),
440 call => [ 'set_history_window', $::form->{id} * 1, 'id' ],
441 disabled => !$::form->{id},
443 $bar->actions->[-1]->add_actions([ t8('Follow-Up'),
444 call => [ 'follow_up_window' ],
445 disabled => !$::form->{id},
447 $bar->actions->[-1]->add_actions([ t8('Drafts'),
448 call => [ 'kivi.Draft.popup', 'is', 'invoice', $::form->{draft_id}, $::form->{draft_description} ],
449 disabled => $::form->{id} || $::form->{locked},
456 print $form->parse_html_template("is/form_header", \%TMPL_VAR);
458 $main::lxdebug->leave_sub();
462 my @fields = qw(acc_trans_id gldate datepaid source memo paid AR_paid);
464 grep { $_->{paid} != 0 }
467 +{ map { ($_ => delete($::form->{"${_}_${idx}"})) } @fields }
468 } (1..$::form->{paidaccounts});
470 @payments = sort_by { DateTime->from_kivitendo($_->{datepaid}) } @payments;
472 $::form->{paidaccounts} = max scalar(@payments), 1;
474 foreach my $idx (1 .. scalar(@payments)) {
475 my $payment = $payments[$idx - 1];
476 $::form->{"${_}_${idx}"} = $payment->{$_} for @fields;
481 $main::lxdebug->enter_sub();
483 my $form = $main::form;
484 my %myconfig = %main::myconfig;
485 my $locale = $main::locale;
487 $main::auth->assert('invoice_edit');
489 $form->{invtotal} = $form->{invsubtotal};
492 $form->{rows} = max 2,
493 $form->numtextrows($form->{notes}, 26, 8),
494 $form->numtextrows($form->{intnotes}, 35, 8);
497 # tax, total and subtotal calculations
498 my ($tax, $subtotal);
499 $form->{taxaccounts_array} = [ split(/ /, $form->{taxaccounts}) ];
501 if( $form->{customer_id} && !$form->{taxincluded_changed_by_user} ) {
502 my $customer = SL::DB::Customer->load_cached($form->{customer_id});
503 $form->{taxincluded} = defined($customer->taxincluded_checked) ? $customer->taxincluded_checked : $myconfig{taxincluded_checked};
506 foreach my $item (@{ $form->{taxaccounts_array} }) {
507 if ($form->{"${item}_base"}) {
508 if ($form->{taxincluded}) {
509 $form->{"${item}_total"} = $form->round_amount( ($form->{"${item}_base"} * $form->{"${item}_rate"}
510 / (1 + $form->{"${item}_rate"})), 2);
511 $form->{"${item}_netto"} = $form->round_amount( ($form->{"${item}_base"} - $form->{"${item}_total"}), 2);
513 $form->{"${item}_total"} = $form->round_amount( $form->{"${item}_base"} * $form->{"${item}_rate"}, 2);
514 $form->{invtotal} += $form->{"${item}_total"};
519 my $grossamount = $form->{invtotal};
520 $form->{invtotal} = $form->round_amount( $form->{invtotal}, 2, 1 );
521 $form->{rounding} = $form->round_amount(
522 $form->{invtotal} - $form->round_amount($grossamount, 2),
528 $form->{follow_ups} = FU->follow_ups('trans_id' => $form->{id}, 'not_done' => 1) || [];
529 $form->{follow_ups_unfinished} = ( sum map { $_->{due} * 1 } @{ $form->{follow_ups} } ) || 0;
536 $form->{paidaccounts}++ if ($form->{"paid_$form->{paidaccounts}"});
537 $form->{paid_indices} = [ 1 .. $form->{paidaccounts} ];
539 # Standard Konto für Umlaufvermögen
540 my $accno_arap = IS->get_standard_accno_current_assets(\%myconfig, \%$form);
542 for my $i (1 .. $form->{paidaccounts}) {
543 $form->{"changeable_$i"} = 1;
544 if (SL::DB::Default->get->payments_changeable == 0) {
546 $form->{"changeable_$i"} = ($form->{"acc_trans_id_$i"})? 0 : 1;
547 } elsif (SL::DB::Default->get->payments_changeable == 2) {
549 $form->{"changeable_$i"} = (($form->{"gldate_$i"} eq '') ||
550 ($form->current_date(\%myconfig) eq $form->{"gldate_$i"}));
553 #deaktivieren von gebuchten Zahlungen ausserhalb der Bücherkontrolle, vorher prüfen ob heute eingegeben
554 if ($form->date_closed($form->{"gldate_$i"})) {
555 $form->{"changeable_$i"} = 0;
558 $form->{"selectAR_paid_$i"} = $form->{selectAR_paid};
559 if (!$form->{"AR_paid_$i"}) {
560 $form->{"selectAR_paid_$i"} =~ s/option>$accno_arap--(.*?)</option selected>$accno_arap--$1</;
562 $form->{"selectAR_paid_$i"} =~ s/option>\Q$form->{"AR_paid_$i"}\E/option selected>$form->{"AR_paid_$i"}/;
565 $totalpaid += $form->{"paid_$i"};
568 $form->{oldinvtotal} = $form->{invtotal};
570 $form->{ALL_DELIVERY_TERMS} = SL::DB::Manager::DeliveryTerm->get_all_sorted();
572 print $form->parse_html_template('is/form_footer', {
573 is_type_credit_note => ($form->{type} eq "credit_note"),
574 totalpaid => $totalpaid,
575 paid_missing => $form->{invtotal} - $totalpaid,
576 print_options => print_options(inline => 1),
577 show_storno => $form->{id} && !$form->{storno} && !IS->has_storno(\%myconfig, $form, "ar") && !$totalpaid,
578 show_delete => ($::instance_conf->get_is_changeable == 2)
579 ? ($form->current_date(\%myconfig) eq $form->{gldate})
580 : ($::instance_conf->get_is_changeable == 1),
581 today => DateTime->today,
583 ##print $form->parse_html_template('is/_payments'); # parser
584 ##print $form->parse_html_template('webdav/_list'); # parser
586 $main::lxdebug->leave_sub();
590 $::auth->assert('invoice_edit');
592 SL::DB::Invoice->new(id => $::form->{id})->load->mark_as_paid;
594 $::form->redirect($::locale->text("Marked as paid"));
602 $main::lxdebug->enter_sub();
604 my $form = $main::form;
605 my %myconfig = %main::myconfig;
607 $main::auth->assert('invoice_edit');
609 my ($recursive_call) = @_;
611 $form->{print_and_post} = 0 if $form->{second_run};
612 my $taxincluded = $form->{taxincluded} ? "checked" : '';
615 if (($form->{previous_customer_id} || $form->{customer_id}) != $form->{customer_id}) {
616 $::form->{salesman_id} = SL::DB::Manager::Employee->current->id if exists $::form->{salesman_id};
618 IS->get_customer(\%myconfig, $form);
621 $form->{taxincluded} ||= $taxincluded;
623 if (!$form->{forex}) { # read exchangerate from input field (not hidden)
624 $form->{exchangerate} = $form->parse_amount(\%myconfig, $form->{exchangerate}) unless $recursive_call;
626 $form->{forex} = $form->check_exchangerate(\%myconfig, $form->{currency}, $form->{invdate}, 'buy');
627 $form->{exchangerate} = $form->{forex} if $form->{forex};
629 for my $i (1 .. $form->{paidaccounts}) {
630 next unless $form->{"paid_$i"};
631 map { $form->{"${_}_$i"} = $form->parse_amount(\%myconfig, $form->{"${_}_$i"}) } qw(paid exchangerate);
632 if (!$form->{"forex_$i"}) { #read exchangerate from input field (not hidden)
633 $form->{exchangerate} = $form->{"exchangerate_$i"};
635 $form->{"forex_$i"} = $form->check_exchangerate(\%myconfig, $form->{currency}, $form->{"datepaid_$i"}, 'buy');
636 $form->{"exchangerate_$i"} = $form->{"forex_$i"} if $form->{"forex_$i"};
639 my $i = $form->{rowcount};
640 my $exchangerate = $form->{exchangerate} || 1;
642 # if last row empty, check the form otherwise retrieve new item
643 if ( ($form->{"partnumber_$i"} eq "")
644 && ($form->{"description_$i"} eq "")
645 && ($form->{"partsgroup_$i"} eq "")) {
647 $form->{creditremaining} += ($form->{oldinvtotal} - $form->{oldtotalpaid});
652 IS->retrieve_item(\%myconfig, \%$form);
654 my $rows = scalar @{ $form->{item_list} };
656 $form->{"discount_$i"} = $form->parse_amount(\%myconfig, $form->{"discount_$i"}) / 100.0;
657 $form->{"discount_$i"} ||= $form->{customer_discount};
660 $form->{"qty_$i"} = $form->parse_amount(\%myconfig, $form->{"qty_$i"});
661 if( !$form->{"qty_$i"} ) {
662 $form->{"qty_$i"} = 1;
667 select_item(mode => 'IS', pre_entered_qty => $form->{"qty_$i"});
668 $::dispatcher->end_request;
672 my $sellprice = $form->parse_amount(\%myconfig, $form->{"sellprice_$i"});
674 map { $form->{item_list}[$i]{$_} =~ s/\"/"/g } qw(partnumber description unit);
675 map { $form->{"${_}_$i"} = $form->{item_list}[0]{$_} } keys %{ $form->{item_list}[0] };
677 $form->{payment_id} = $form->{"part_payment_id_$i"} if $form->{"part_payment_id_$i"} ne "";
678 $form->{"discount_$i"} = 0 if $form->{"not_discountable_$i"};
680 $form->{"marge_price_factor_$i"} = $form->{item_list}->[0]->{price_factor};
682 ($sellprice || $form->{"sellprice_$i"}) =~ /\.(\d+)/;
683 my $decimalplaces = max 2, length $1;
686 $form->{"sellprice_$i"} = $sellprice;
688 my $record = _make_record();
689 my $price_source = SL::PriceSource->new(record_item => $record->items->[$i-1], record => $record);
690 my $best_price = $price_source->best_price;
691 my $best_discount = $price_source->best_discount;
694 $::form->{"sellprice_$i"} = $best_price->price;
695 $::form->{"active_price_source_$i"} = $best_price->source;
697 if ($best_discount) {
698 $::form->{"discount_$i"} = $best_discount->discount;
699 $::form->{"active_discount_source_$i"} = $best_discount->source;
702 # if there is an exchange rate adjust sellprice
703 $form->{"sellprice_$i"} /= $exchangerate;
706 $form->{"listprice_$i"} /= $exchangerate;
708 my $amount = $form->{"sellprice_$i"} * $form->{"qty_$i"} * (1 - $form->{"discount_$i"});
709 map { $form->{"${_}_base"} = 0 } split / /, $form->{taxaccounts};
710 map { $form->{"${_}_base"} += $amount } split / /, $form->{"taxaccounts_$i"};
711 map { $amount += ($form->{"${_}_base"} * $form->{"${_}_rate"}) } split / /, $form->{"taxaccounts_$i"} if !$form->{taxincluded};
713 $form->{creditremaining} -= $amount;
715 map { $form->{"${_}_$i"} = $form->format_amount(\%myconfig, $form->{"${_}_$i"}, $decimalplaces) } qw(sellprice lastcost);
717 $form->{"qty_$i"} = $form->format_amount(\%myconfig, $form->{"qty_$i"});
718 $form->{"discount_$i"} = $form->format_amount(\%myconfig, $form->{"discount_$i"} * 100.0);
725 # ok, so this is a new part
726 # ask if it is a part or service item
728 if ( $form->{"partsgroup_$i"}
729 && ($form->{"partsnumber_$i"} eq "")
730 && ($form->{"description_$i"} eq "")) {
732 $form->{"discount_$i"} = "";
736 $form->{"id_$i"} = 0;
741 $main::lxdebug->leave_sub();
745 $main::lxdebug->enter_sub();
747 my $form = $main::form;
748 my %myconfig = %main::myconfig;
749 my $locale = $main::locale;
751 $main::auth->assert('invoice_edit');
753 $form->mtime_ischanged('ar') ;
754 my $invdate = $form->datetonum($form->{invdate}, \%myconfig);
756 $form->{defaultcurrency} = $form->get_default_currency(\%myconfig);
757 for my $i (1 .. $form->{paidaccounts}) {
758 if ($form->{"paid_$i"}) {
759 my $datepaid = $form->datetonum($form->{"datepaid_$i"}, \%myconfig);
761 $form->isblank("datepaid_$i", $locale->text('Payment date missing!'));
764 if ($form->{currency} ne $form->{defaultcurrency}) {
765 $form->{"exchangerate_$i"} = $form->{exchangerate}
766 if ($invdate == $datepaid);
767 $form->isblank("exchangerate_$i",
768 $locale->text('Exchangerate for payment missing!'));
770 $form->error($locale->text('Cannot post transaction above the maximum future booking date!'))
771 if ($form->date_max_future($form->{"datepaid_$i"}, \%myconfig));
773 #Zusätzlich noch das Buchungsdatum in die Bücherkontrolle einbeziehen
774 # (Dient zur Prüfung ob ZE oder ZA geprüft werden soll)
775 $form->error($locale->text('Cannot post payment for a closed period!'))
776 if ($form->date_closed($form->{"datepaid_$i"}) && !$form->date_closed($form->{"gldate_$i"}, \%myconfig));
780 ($form->{AR}) = split /--/, $form->{AR};
781 ($form->{AR_paid}) = split /--/, $form->{AR_paid};
783 if ( IS->post_payment(\%myconfig, \%$form) ) {
784 $form->{snumbers} = qq|invnumber_| . $form->{invnumber};
785 $form->{what_done} = 'invoice';
786 $form->{addition} = "PAYMENT POSTED";
788 $form->redirect($locale->text('Payment posted!'))
790 $form->error($locale->text('Cannot post payment!'));
793 $main::lxdebug->leave_sub();
797 $main::lxdebug->enter_sub();
799 my $form = $main::form;
800 my %myconfig = %main::myconfig;
801 my $locale = $main::locale;
803 $main::auth->assert('invoice_edit');
804 $form->mtime_ischanged('ar');
806 $form->{defaultcurrency} = $form->get_default_currency(\%myconfig);
807 $form->isblank("invdate", $locale->text('Invoice Date missing!'));
808 $form->isblank("customer_id", $locale->text('Customer missing!'));
809 $form->error($locale->text('Cannot post invoice for a closed period!'))
810 if ($form->date_closed($form->{"invdate"}, \%myconfig));
812 $form->{invnumber} =~ s/^\s*//g;
813 $form->{invnumber} =~ s/\s*$//g;
815 # if oldcustomer ne customer redo form
816 if (($form->{previous_customer_id} || $form->{customer_id}) != $form->{customer_id}) {
818 $::dispatcher->end_request;
821 if ($myconfig{mandatory_departments} && !$form->{department_id}) {
822 $form->{saved_message} = $::locale->text('You have to specify a department.');
827 if ($form->{second_run}) {
828 $form->{print_and_post} = 0;
831 remove_emptied_rows();
834 my $closedto = $form->datetonum($form->{closedto}, \%myconfig);
835 my $invdate = $form->datetonum($form->{invdate}, \%myconfig);
837 $form->error($locale->text('Cannot post transaction above the maximum future booking date!'))
838 if ($form->date_max_future($invdate, \%myconfig));
839 $form->error($locale->text('Cannot post invoice for a closed period!'))
840 if ($invdate <= $closedto);
842 $form->isblank("exchangerate", $locale->text('Exchangerate missing!'))
843 if ($form->{currency} ne $form->{defaultcurrency});
845 for my $i (1 .. $form->{paidaccounts}) {
846 if ($form->parse_amount(\%myconfig, $form->{"paid_$i"})) {
847 my $datepaid = $form->datetonum($form->{"datepaid_$i"}, \%myconfig);
849 $form->isblank("datepaid_$i", $locale->text('Payment date missing!'));
851 $form->error($locale->text('Cannot post transaction above the maximum future booking date!'))
852 if ($form->date_max_future($form->{"datepaid_$i"}, \%myconfig));
854 #Zusätzlich noch das Buchungsdatum in die Bücherkontrolle einbeziehen
855 # (Dient zur Prüfung ob ZE oder ZA geprüft werden soll)
856 $form->error($locale->text('Cannot post payment for a closed period!'))
857 if ($form->date_closed($form->{"datepaid_$i"}) && !$form->date_closed($form->{"gldate_$i"}, \%myconfig));
859 if ($form->{currency} ne $form->{defaultcurrency}) {
860 $form->{"exchangerate_$i"} = $form->{exchangerate}
861 if ($invdate == $datepaid);
862 $form->isblank("exchangerate_$i",
863 $locale->text('Exchangerate for payment missing!'));
868 ($form->{AR}) = split /--/, $form->{AR};
869 ($form->{AR_paid}) = split /--/, $form->{AR_paid};
870 $form->{storno} ||= 0;
872 $form->{label} = $form->{type} eq 'credit_note' ? $locale->text('Credit Note') : $locale->text('Invoice');
874 $form->{id} = 0 if $form->{postasnew};
876 # get new invnumber in sequence if no invnumber is given or if posasnew was requested
877 if ($form->{postasnew}) {
878 if ($form->{type} eq "credit_note") {
879 undef($form->{cnnumber});
881 undef($form->{invnumber});
887 my $terms = get_payment_terms_for_invoice();
888 $form->{duedate} = $terms->calc_date(reference_date => $form->{invdate}, due_date => $form->{duedate})->to_kivitendo if $terms;
890 # If transfer_out is requested, get rose db handle and do post and
891 # transfer out in one transaction. Otherwise just post the invoice.
892 if ($::instance_conf->get_is_transfer_out && $form->{type} ne 'credit_note' && !$form->{storno}) {
893 require SL::DB::Inventory;
894 my $rose_db = SL::DB::Inventory->new->db;
897 if (!$rose_db->with_transaction(sub {
899 if (!IS->post_invoice(\%myconfig, \%$form, $rose_db->dbh)) {
900 push @errors, $locale->text('Cannot post invoice!');
903 my $err = IS->transfer_out(\%$form, $rose_db->dbh);
905 push @errors, @{ $err };
906 die 'transfer error';
911 push @errors, $EVAL_ERROR;
912 die 'transaction error';
917 push @errors, $rose_db->error;
918 $form->error($locale->text('Cannot post invoice and/or transfer out! Error message:') . "\n" . join("\n", @errors));
921 if (!IS->post_invoice(\%myconfig, \%$form)) {
922 $form->error($locale->text('Cannot post invoice!'));
926 if(!exists $form->{addition}) {
927 $form->{snumbers} = 'invnumber' .'_'. $form->{invnumber}; # ($form->{type} eq 'credit_note' ? 'cnnumber' : 'invnumber') .'_'. $form->{invnumber};
928 $form->{what_done} = 'invoice';
929 $form->{addition} = $form->{print_and_post} ? "PRINTED AND POSTED" :
930 $form->{storno} ? "STORNO" :
935 if (!$form->{no_redirect_after_post}) {
936 $form->{action} = 'edit';
937 $form->{script} = 'is.pl';
938 $form->{callback} = build_std_url(qw(action edit id callback saved_message));
939 $form->redirect($form->{label} . " $form->{invnumber} " . $locale->text('posted!'));
942 $main::lxdebug->leave_sub();
946 $main::lxdebug->enter_sub();
948 my $form = $main::form;
950 $main::auth->assert('invoice_edit');
952 my $old_form = Form->new;
953 $form->{no_redirect_after_post} = 1;
954 $form->{print_and_post} = 1;
958 $main::lxdebug->leave_sub();
963 $main::lxdebug->enter_sub();
965 my $form = $main::form;
966 my %myconfig = %main::myconfig;
968 $main::auth->assert('invoice_edit');
970 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)};
972 $form->{paidaccounts} = 1;
973 $form->{invdate} = $form->current_date(\%myconfig);
974 my $terms = get_payment_terms_for_invoice();
975 $form->{duedate} = $terms ? $terms->calc_date(reference_date => $form->{invdate})->to_kivitendo : $form->{invdate};
976 $form->{employee_id} = SL::DB::Manager::Employee->current->id;
977 $form->{forex} = $form->check_exchangerate(\%myconfig, $form->{currency}, $form->{invdate}, 'buy');
978 $form->{exchangerate} = $form->{forex} if $form->{forex};
980 $form->{"converted_from_invoice_id_$_"} = delete $form->{"invoice_id_$_"} for 1 .. $form->{"rowcount"};
982 $form->{useasnew} = 1;
985 $main::lxdebug->leave_sub();
989 $main::lxdebug->enter_sub();
991 my $form = $main::form;
992 my %myconfig = %main::myconfig;
993 my $locale = $main::locale;
995 $main::auth->assert('invoice_edit');
997 if ($form->{storno}) {
998 $form->error($locale->text('Cannot storno storno invoice!'));
1001 if (IS->has_storno(\%myconfig, $form, "ar")) {
1002 $form->error($locale->text("Invoice has already been storno'd!"));
1004 if ($form->datetonum($form->{invdate}, \%myconfig) <= $form->datetonum($form->{closedto}, \%myconfig)) {
1005 $form->error($locale->text('Cannot storno invoice for a closed period!'));
1008 # save the history of invoice being stornoed
1009 $form->{snumbers} = qq|invnumber_| . $form->{invnumber};
1010 $form->{what_done} = 'invoice';
1011 $form->{addition} = "STORNO";
1012 $form->save_history;
1014 map({ my $key = $_; delete($form->{$key}) unless (grep({ $key eq $_ } qw(id login password type))); } keys(%{ $form }));
1020 # Payments must not be recorded for the new storno invoice.
1021 $form->{paidaccounts} = 0;
1022 map { my $key = $_; delete $form->{$key} if grep { $key =~ /^$_/ } qw(datepaid_ gldate_ acc_trans_id_ source_ memo_ paid_ exchangerate_ AR_paid_) } keys %{ $form };
1024 # record link invoice to storno
1025 $form->{convert_from_ar_ids} = $form->{id};
1026 $form->{storno_id} = $form->{id};
1027 $form->{storno} = 1;
1029 $form->{invnumber} = "Storno zu " . $form->{invnumber};
1030 $form->{invdate} = DateTime->today->to_lxoffice;
1031 $form->{rowcount}++;
1032 # set new ids for storno invoice
1033 # set new persistent ids for storno invoice items
1034 $form->{"converted_from_invoice_id_$_"} = delete $form->{"invoice_id_$_"} for 1 .. $form->{"rowcount"};
1037 $main::lxdebug->leave_sub();
1041 $main::lxdebug->enter_sub();
1043 my $form = $main::form;
1045 $main::auth->assert('invoice_edit');
1047 $form->{preview} = 1;
1048 my $old_form = Form->new;
1049 for (keys %$form) { $old_form->{$_} = $form->{$_} }
1051 &print_form($old_form);
1052 $main::lxdebug->leave_sub();
1057 $main::lxdebug->enter_sub();
1059 my $form = $main::form;
1060 my %myconfig = %main::myconfig;
1061 my $locale = $main::locale;
1063 $main::auth->assert('invoice_edit');
1065 $form->{transdate} = $form->{invdate} = $form->current_date(\%myconfig);
1067 $form->current_date(\%myconfig, $form->{invdate}, $form->{terms} * 1);
1069 $form->{convert_from_ar_ids} = $form->{id};
1071 $form->{rowcount}--;
1074 $form->{title} = $locale->text('Add Credit Note');
1075 $form->{script} = 'is.pl';
1077 # Bei Gutschriften bezug zur Rechnungsnummer
1078 $form->{invnumber_for_credit_note} = $form->{invnumber};
1079 # bo creates the id, reset it
1080 map { delete $form->{$_} }
1081 qw(id invnumber subject message cc bcc printed emailed queued);
1082 $form->{ $form->{vc} } =~ s/--.*//g;
1083 $form->{type} = "credit_note";
1086 map { $form->{"select$_"} = "" } ($form->{vc}, 'currency');
1088 # map { $form->{$_} = $form->parse_amount(\%myconfig, $form->{$_}) }
1089 # qw(creditlimit creditremaining);
1091 # set new persistent ids for credit note and link previous invoice id
1092 $form->{"converted_from_invoice_id_$_"} = delete $form->{"invoice_id_$_"} for 1 .. $form->{"rowcount"};
1094 my $currency = $form->{currency};
1097 $form->{currency} = $currency;
1098 $form->{forex} = $form->check_exchangerate( \%myconfig, $form->{currency}, $form->{invdate}, 'buy');
1099 $form->{exchangerate} = $form->{forex} || '';
1101 $form->{creditremaining} -= ($form->{oldinvtotal} - $form->{ordtotal});
1103 # bei Gutschriften werden Zahlungseingänge aus Rechnung nicht übernommen
1104 for my $i (1 .. $form->{paidaccounts}) {
1105 delete $form->{"paid_$i"};
1106 delete $form->{"source_$i"};
1107 delete $form->{"memo_$i"};
1108 delete $form->{"datepaid_$i"};
1109 delete $form->{"gldate_$i"};
1110 delete $form->{"acc_trans_id_$i"};
1111 delete $form->{"AR_paid_$i"};
1113 $form->{paidaccounts} = 1;
1120 $main::lxdebug->leave_sub();
1124 $::lxdebug->enter_sub;
1126 $::auth->assert('invoice_edit');
1130 my $new_rowcount = $::form->{"rowcount"} * 1 + 1;
1131 $::form->{"project_id_${new_rowcount}"} = $::form->{"globalproject_id"};
1133 $::form->language_payment(\%::myconfig);
1135 Common::webdav_folder($::form);
1138 display_row(++$::form->{rowcount});
1141 $::lxdebug->leave_sub;
1145 $::auth->assert('invoice_edit');
1147 if (IS->delete_invoice(\%::myconfig, $::form)) {
1148 # saving the history
1149 if(!exists $::form->{addition}) {
1150 $::form->{snumbers} = 'invnumber' .'_'. $::form->{invnumber};
1151 $::form->{what_done} = 'invoice';
1152 $::form->{addition} = "DELETED";
1153 $::form->save_history;
1155 # /saving the history
1156 $::form->redirect($::locale->text('Invoice deleted!'));
1158 $::form->error($::locale->text('Cannot delete invoice!'));
1161 sub post_and_e_mail {
1166 $main::lxdebug->enter_sub();
1168 my $form = $main::form;
1170 $main::auth->assert('invoice_edit');
1173 $form->{no_redirect_after_post} = 1;
1175 my $saved_form = save_form();
1179 restore_form($saved_form, 0, qw(id invnumber));
1184 $main::lxdebug->leave_sub();
1189 print update ship_to e_mail storno post_payment use_as_new credit_note
1190 delete post order preview post_and_e_mail print_and_post
1193 if ($::form->{"action_$action"}) {
1199 $::form->error($::locale->text('No action defined.'));