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();
255 sub setup_is_action_bar {
257 my $change_never = $::instance_conf->get_is_changeable == 0;
258 my $change_on_same_day_only = $::instance_conf->get_is_changeable == 2 && ($form->current_date(\%::myconfig) ne $form->{gldate});
259 my @req_trans_desc = qw(kivi.SalesPurchase.check_transaction_description) x!!$::instance_conf->get_require_transaction_description_ps;
261 for my $bar ($::request->layout->get('actionbar')) {
265 submit => [ '#form', { action => "update" } ],
266 disabled => $form->{locked} ? t8('The billing period has already been locked.') : undef,
267 id => 'update_button',
268 accesskey => 'enter',
274 submit => [ '#form', { action => "post" } ],
275 checks => [ @req_trans_desc ],
276 disabled => $form->{locked} ? t8('The billing period has already been locked.')
277 : $form->{storno} ? t8('A canceled invoice cannot be posted.')
278 : ($form->{id} && $change_never) ? t8('Changing invoices has been disabled in the configuration.')
279 : ($form->{id} && $change_on_same_day_only) ? t8('Invoices can only be changed on the day they are posted.')
284 submit => [ '#form', { action => "post_payment" } ],
285 checks => [ @req_trans_desc ],
286 disabled => !$form->{id} ? t8('This invoice has not been posted yet.') : undef,
288 action => [ t8('Mark as paid'),
289 submit => [ '#form', { action => "mark_as_paid" } ],
290 confirm => t8('This will remove the invoice from showing as unpaid even if the unpaid amount does not match the amount. Proceed?'),
291 disabled => !$form->{id} ? t8('This invoice has not been posted yet.') : undef,
292 only_if => $::instance_conf->get_is_show_mark_as_paid,
294 ], # end of combobox "Post"
297 action => [ t8('Storno'),
298 submit => [ '#form', { action => "storno" } ],
299 confirm => t8('Do you really want to cancel this invoice?'),
300 checks => [ @req_trans_desc ],
301 disabled => !$form->{id} ? t8('This invoice has not been posted yet.') : undef,
303 action => [ t8('Delete'),
304 submit => [ '#form', { action => "delete" } ],
305 confirm => t8('Do you really want to delete this object?'),
306 checks => [ @req_trans_desc ],
307 disabled => !$form->{id} ? t8('This invoice has not been posted yet.')
308 : $form->{locked} ? t8('The billing period has already been locked.')
309 : $change_never ? t8('Changing invoices has been disabled in the configuration.')
310 : $change_on_same_day_only ? t8('Invoices can only be changed on the day they are posted.')
313 ], # end of combobox "Storno"
318 action => [ t8('Workflow') ],
321 submit => [ '#form', { action => "use_as_new" } ],
322 disabled => !$form->{id} ? t8('This invoice has not been posted yet.') : undef,
326 submit => [ '#form', { action => "credit_note" } ],
327 checks => [ @req_trans_desc ],
328 disabled => $form->{type} eq "credit_note" ? t8('Credit notes cannot be converted into other credit notes.')
329 : !$form->{id} ? t8('This invoice has not been posted yet.')
334 submit => [ '#form', { action => "order" } ],
335 disabled => !$form->{id} ? t8('This invoice has not been posted yet.') : undef,
337 ], # end of combobox "Workflow"
340 action => [ t8('Export') ],
342 ($form->{id} ? t8('Print') : t8('Preview')),
343 call => [ 'kivi.SalesPurchase.show_print_dialog', $form->{id} ? 'print' : 'preview' ],
344 checks => [ @req_trans_desc ],
345 disabled => !$form->{id} && $form->{locked} ? t8('The billing period has already been locked.') : undef,
347 action => [ t8('Print and Post'),
348 call => [ 'kivi.SalesPurchase.show_print_dialog', $form->{id} ? 'print' : 'print_and_post' ],
349 checks => [ @req_trans_desc ],
350 disabled => $form->{id} ? t8('This invoice has already been posted.') : undef,,
352 action => [ t8('E Mail'),
353 call => [ 'kivi.SalesPurchase.show_email_dialog' ],
354 checks => [ @req_trans_desc ],
355 disabled => !$form->{id} ? t8('This invoice has not been posted yet.') : undef,
357 ], # end of combobox "Export"
360 action => [ t8('more') ],
363 call => [ 'set_history_window', $form->{id} * 1, 'glid' ],
364 disabled => !$form->{id} ? t8('This invoice has not been posted yet.') : undef,
368 call => [ 'follow_up_window' ],
369 disabled => !$form->{id} ? t8('This invoice has not been posted yet.') : undef,
373 call => [ 'kivi.Draft.popup', 'is', 'invoice', $form->{draft_id}, $form->{draft_description} ],
374 disabled => $form->{id} ? t8('This invoice has already been posted.')
375 : $form->{locked} ? t8('The billing period has already been locked.')
378 ], # end of combobox "more"
384 $main::lxdebug->enter_sub();
386 my $form = $main::form;
387 my %myconfig = %main::myconfig;
388 my $locale = $main::locale;
389 my $cgi = $::request->{cgi};
391 $main::auth->assert('invoice_edit');
396 $TMPL_VAR{customer_obj} = SL::DB::Customer->load_cached($form->{customer_id}) if $form->{customer_id};
397 $TMPL_VAR{invoice_obj} = SL::DB::Invoice->load_cached($form->{id}) if $form->{id};
399 my $current_employee = SL::DB::Manager::Employee->current;
400 $form->{employee_id} = $form->{old_employee_id} if $form->{old_employee_id};
401 $form->{salesman_id} = $form->{old_salesman_id} if $form->{old_salesman_id};
402 $form->{employee_id} ||= $current_employee->id;
403 $form->{salesman_id} ||= $current_employee->id;
405 $form->{defaultcurrency} = $form->get_default_currency(\%myconfig);
407 $form->get_lists("taxzones" => ($form->{id} ? "ALL_TAXZONES" : "ALL_ACTIVE_TAXZONES"),
408 "currencies" => "ALL_CURRENCIES",
409 "price_factors" => "ALL_PRICE_FACTORS");
411 $form->{ALL_DEPARTMENTS} = SL::DB::Manager::Department->get_all_sorted;
414 my @old_project_ids = uniq grep { $_ } map { $_ * 1 } ($form->{"globalproject_id"}, map { $form->{"project_id_$_"} } 1..$form->{"rowcount"});
415 my @old_ids_cond = @old_project_ids ? (id => \@old_project_ids) : ();
417 if ($::instance_conf->get_customer_projects_only_in_sales) {
420 customer_id => $::form->{customer_id},
421 billable_customer_id => $::form->{customer_id},
426 and => [ active => 1, @customer_cond ],
430 $TMPL_VAR{ALL_PROJECTS} = SL::DB::Manager::Project->get_all_sorted(query => \@conditions);
431 $form->{ALL_PROJECTS} = $TMPL_VAR{ALL_PROJECTS}; # make projects available for second row drop-down in io.pl
432 $TMPL_VAR{ALL_EMPLOYEES} = SL::DB::Manager::Employee->get_all_sorted(query => [ or => [ id => $::form->{employee_id}, deleted => 0 ] ]);
433 $TMPL_VAR{ALL_SALESMEN} = SL::DB::Manager::Employee->get_all_sorted(query => [ or => [ id => $::form->{salesman_id}, deleted => 0 ] ]);
434 $TMPL_VAR{ALL_SHIPTO} = SL::DB::Manager::Shipto->get_all_sorted(query => [
435 or => [ trans_id => $::form->{"$::form->{vc}_id"} * 1, and => [ shipto_id => $::form->{shipto_id} * 1, trans_id => undef ] ]
437 $TMPL_VAR{ALL_CONTACTS} = SL::DB::Manager::Contact->get_all_sorted(query => [
439 cp_cv_id => $::form->{"$::form->{vc}_id"} * 1,
442 cp_id => $::form->{cp_id} * 1
447 # currencies and exchangerate
448 my @values = map { $_ } @{ $form->{ALL_CURRENCIES} };
449 my %labels = map { $_ => $_ } @{ $form->{ALL_CURRENCIES} };
450 $form->{currency} = $form->{defaultcurrency} unless $form->{currency};
451 $form->{show_exchangerate} = $form->{currency} ne $form->{defaultcurrency};
452 $TMPL_VAR{currencies} = NTI($::request->{cgi}->popup_menu('-name' => 'currency', '-default' => $form->{"currency"},
453 '-values' => \@values, '-labels' => \%labels,
454 '-onchange' => "document.getElementById('update_button').click();"
455 )) if scalar @values;
456 push @custom_hiddens, "forex";
457 push @custom_hiddens, "exchangerate" if $form->{forex};
459 $TMPL_VAR{creditwarning} = ($form->{creditlimit} != 0) && ($form->{creditremaining} < 0) && !$form->{update};
460 $TMPL_VAR{is_credit_remaining_negativ} = $form->{creditremaining} =~ /-/;
462 # set option selected
463 foreach my $item (qw(AR)) {
464 $form->{"select$item"} =~ s/ selected//;
465 $form->{"select$item"} =~ s/option>\Q$form->{$item}\E/option selected>$form->{$item}/;
468 $TMPL_VAR{is_type_credit_note} = $form->{type} eq "credit_note";
469 $TMPL_VAR{is_format_html} = $form->{format} eq 'html';
470 $TMPL_VAR{dateformat} = $myconfig{dateformat};
471 $TMPL_VAR{numberformat} = $myconfig{numberformat};
474 $TMPL_VAR{HIDDENS} = [qw(
475 id type queued printed emailed vc discount
476 title creditlimit creditremaining tradediscount business closedto locked shipped storno storno_id
477 max_dunning_level dunning_amount dunning_description
478 taxaccounts cursor_fokus
479 convert_from_do_ids convert_from_oe_ids convert_from_ar_ids useasnew
483 map { $_.'_rate', $_.'_description', $_.'_taxnumber' } split / /, $form->{taxaccounts}];
485 $::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));
487 $TMPL_VAR{payment_terms_obj} = get_payment_terms_for_invoice();
488 $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};
490 setup_is_action_bar();
494 print $form->parse_html_template("is/form_header", \%TMPL_VAR);
496 $main::lxdebug->leave_sub();
500 my @fields = qw(acc_trans_id gldate datepaid source memo paid AR_paid);
502 grep { $_->{paid} != 0 }
505 +{ map { ($_ => delete($::form->{"${_}_${idx}"})) } @fields }
506 } (1..$::form->{paidaccounts});
508 @payments = sort_by { DateTime->from_kivitendo($_->{datepaid}) } @payments;
510 $::form->{paidaccounts} = max scalar(@payments), 1;
512 foreach my $idx (1 .. scalar(@payments)) {
513 my $payment = $payments[$idx - 1];
514 $::form->{"${_}_${idx}"} = $payment->{$_} for @fields;
519 $main::lxdebug->enter_sub();
521 my $form = $main::form;
522 my %myconfig = %main::myconfig;
523 my $locale = $main::locale;
525 $main::auth->assert('invoice_edit');
527 $form->{invtotal} = $form->{invsubtotal};
530 $form->{rows} = max 2,
531 $form->numtextrows($form->{notes}, 26, 8),
532 $form->numtextrows($form->{intnotes}, 35, 8);
535 # tax, total and subtotal calculations
536 my ($tax, $subtotal);
537 $form->{taxaccounts_array} = [ split(/ /, $form->{taxaccounts}) ];
539 if( $form->{customer_id} && !$form->{taxincluded_changed_by_user} ) {
540 my $customer = SL::DB::Customer->load_cached($form->{customer_id});
541 $form->{taxincluded} = defined($customer->taxincluded_checked) ? $customer->taxincluded_checked : $myconfig{taxincluded_checked};
544 foreach my $item (@{ $form->{taxaccounts_array} }) {
545 if ($form->{"${item}_base"}) {
546 if ($form->{taxincluded}) {
547 $form->{"${item}_total"} = $form->round_amount( ($form->{"${item}_base"} * $form->{"${item}_rate"}
548 / (1 + $form->{"${item}_rate"})), 2);
549 $form->{"${item}_netto"} = $form->round_amount( ($form->{"${item}_base"} - $form->{"${item}_total"}), 2);
551 $form->{"${item}_total"} = $form->round_amount( $form->{"${item}_base"} * $form->{"${item}_rate"}, 2);
552 $form->{invtotal} += $form->{"${item}_total"};
557 my $grossamount = $form->{invtotal};
558 $form->{invtotal} = $form->round_amount( $form->{invtotal}, 2, 1 );
559 $form->{rounding} = $form->round_amount(
560 $form->{invtotal} - $form->round_amount($grossamount, 2),
566 $form->{follow_ups} = FU->follow_ups('trans_id' => $form->{id}, 'not_done' => 1) || [];
567 $form->{follow_ups_unfinished} = ( sum map { $_->{due} * 1 } @{ $form->{follow_ups} } ) || 0;
574 $form->{paidaccounts}++ if ($form->{"paid_$form->{paidaccounts}"});
575 $form->{paid_indices} = [ 1 .. $form->{paidaccounts} ];
577 # Standard Konto für Umlaufvermögen
578 my $accno_arap = IS->get_standard_accno_current_assets(\%myconfig, \%$form);
580 for my $i (1 .. $form->{paidaccounts}) {
581 $form->{"changeable_$i"} = 1;
582 if (SL::DB::Default->get->payments_changeable == 0) {
584 $form->{"changeable_$i"} = ($form->{"acc_trans_id_$i"})? 0 : 1;
585 } elsif (SL::DB::Default->get->payments_changeable == 2) {
587 $form->{"changeable_$i"} = (($form->{"gldate_$i"} eq '') ||
588 ($form->current_date(\%myconfig) eq $form->{"gldate_$i"}));
591 #deaktivieren von gebuchten Zahlungen ausserhalb der Bücherkontrolle, vorher prüfen ob heute eingegeben
592 if ($form->date_closed($form->{"gldate_$i"})) {
593 $form->{"changeable_$i"} = 0;
596 $form->{"selectAR_paid_$i"} = $form->{selectAR_paid};
597 if (!$form->{"AR_paid_$i"}) {
598 $form->{"selectAR_paid_$i"} =~ s/option>$accno_arap--(.*?)</option selected>$accno_arap--$1</;
600 $form->{"selectAR_paid_$i"} =~ s/option>\Q$form->{"AR_paid_$i"}\E/option selected>$form->{"AR_paid_$i"}/;
603 $totalpaid += $form->{"paid_$i"};
606 $form->{oldinvtotal} = $form->{invtotal};
608 $form->{ALL_DELIVERY_TERMS} = SL::DB::Manager::DeliveryTerm->get_all_sorted();
610 print $form->parse_html_template('is/form_footer', {
611 is_type_credit_note => ($form->{type} eq "credit_note"),
612 totalpaid => $totalpaid,
613 paid_missing => $form->{invtotal} - $totalpaid,
614 print_options => setup_sales_purchase_print_options(),
615 show_storno => $form->{id} && !$form->{storno} && !IS->has_storno(\%myconfig, $form, "ar") && !$totalpaid,
616 show_delete => ($::instance_conf->get_is_changeable == 2)
617 ? ($form->current_date(\%myconfig) eq $form->{gldate})
618 : ($::instance_conf->get_is_changeable == 1),
619 today => DateTime->today,
620 vc_obj => $form->{customer_id} ? SL::DB::Customer->load_cached($form->{customer_id}) : undef,
622 ##print $form->parse_html_template('is/_payments'); # parser
623 ##print $form->parse_html_template('webdav/_list'); # parser
625 $main::lxdebug->leave_sub();
629 $::auth->assert('invoice_edit');
631 SL::DB::Invoice->new(id => $::form->{id})->load->mark_as_paid;
633 $::form->redirect($::locale->text("Marked as paid"));
637 # unless no lazy implementation of save draft without invdate
638 # set the current date like in version <= 3.4.1
639 $::form->{invdate} = DateTime->today->to_lxoffice;
644 $main::lxdebug->enter_sub();
646 my $form = $main::form;
647 my %myconfig = %main::myconfig;
649 $main::auth->assert('invoice_edit');
651 my ($recursive_call) = @_;
653 $form->{print_and_post} = 0 if $form->{second_run};
654 my $taxincluded = $form->{taxincluded} ? "checked" : '';
657 if (($form->{previous_customer_id} || $form->{customer_id}) != $form->{customer_id}) {
658 $::form->{salesman_id} = SL::DB::Manager::Employee->current->id if exists $::form->{salesman_id};
660 IS->get_customer(\%myconfig, $form);
663 $form->{taxincluded} ||= $taxincluded;
665 if (!$form->{forex}) { # read exchangerate from input field (not hidden)
666 $form->{exchangerate} = $form->parse_amount(\%myconfig, $form->{exchangerate}) unless $recursive_call;
668 $form->{forex} = $form->check_exchangerate(\%myconfig, $form->{currency}, $form->{invdate}, 'buy');
669 $form->{exchangerate} = $form->{forex} if $form->{forex};
671 for my $i (1 .. $form->{paidaccounts}) {
672 next unless $form->{"paid_$i"};
673 map { $form->{"${_}_$i"} = $form->parse_amount(\%myconfig, $form->{"${_}_$i"}) } qw(paid exchangerate);
674 if (!$form->{"forex_$i"}) { #read exchangerate from input field (not hidden)
675 $form->{exchangerate} = $form->{"exchangerate_$i"};
677 $form->{"forex_$i"} = $form->check_exchangerate(\%myconfig, $form->{currency}, $form->{"datepaid_$i"}, 'buy');
678 $form->{"exchangerate_$i"} = $form->{"forex_$i"} if $form->{"forex_$i"};
681 my $i = $form->{rowcount};
682 my $exchangerate = $form->{exchangerate} || 1;
684 # if last row empty, check the form otherwise retrieve new item
685 if ( ($form->{"partnumber_$i"} eq "")
686 && ($form->{"description_$i"} eq "")
687 && ($form->{"partsgroup_$i"} eq "")) {
689 $form->{creditremaining} += ($form->{oldinvtotal} - $form->{oldtotalpaid});
694 IS->retrieve_item(\%myconfig, \%$form);
696 my $rows = scalar @{ $form->{item_list} };
698 $form->{"discount_$i"} = $form->parse_amount(\%myconfig, $form->{"discount_$i"}) / 100.0;
699 $form->{"discount_$i"} ||= $form->{customer_discount};
702 $form->{"qty_$i"} = $form->parse_amount(\%myconfig, $form->{"qty_$i"});
703 if( !$form->{"qty_$i"} ) {
704 $form->{"qty_$i"} = 1;
709 select_item(mode => 'IS', pre_entered_qty => $form->{"qty_$i"});
710 $::dispatcher->end_request;
714 my $sellprice = $form->parse_amount(\%myconfig, $form->{"sellprice_$i"});
716 map { $form->{item_list}[$i]{$_} =~ s/\"/"/g } qw(partnumber description unit);
717 map { $form->{"${_}_$i"} = $form->{item_list}[0]{$_} } keys %{ $form->{item_list}[0] };
719 $form->{payment_id} = $form->{"part_payment_id_$i"} if $form->{"part_payment_id_$i"} ne "";
720 $form->{"discount_$i"} = 0 if $form->{"not_discountable_$i"};
722 $form->{"marge_price_factor_$i"} = $form->{item_list}->[0]->{price_factor};
724 ($sellprice || $form->{"sellprice_$i"}) =~ /\.(\d+)/;
725 my $decimalplaces = max 2, length $1;
728 $form->{"sellprice_$i"} = $sellprice;
730 my $record = _make_record();
731 my $price_source = SL::PriceSource->new(record_item => $record->items->[$i-1], record => $record);
732 my $best_price = $price_source->best_price;
733 my $best_discount = $price_source->best_discount;
736 $::form->{"sellprice_$i"} = $best_price->price;
737 $::form->{"active_price_source_$i"} = $best_price->source;
739 if ($best_discount) {
740 $::form->{"discount_$i"} = $best_discount->discount;
741 $::form->{"active_discount_source_$i"} = $best_discount->source;
744 # if there is an exchange rate adjust sellprice
745 $form->{"sellprice_$i"} /= $exchangerate;
748 $form->{"listprice_$i"} /= $exchangerate;
750 my $amount = $form->{"sellprice_$i"} * $form->{"qty_$i"} * (1 - $form->{"discount_$i"});
751 map { $form->{"${_}_base"} = 0 } split / /, $form->{taxaccounts};
752 map { $form->{"${_}_base"} += $amount } split / /, $form->{"taxaccounts_$i"};
753 map { $amount += ($form->{"${_}_base"} * $form->{"${_}_rate"}) } split / /, $form->{"taxaccounts_$i"} if !$form->{taxincluded};
755 $form->{creditremaining} -= $amount;
757 map { $form->{"${_}_$i"} = $form->format_amount(\%myconfig, $form->{"${_}_$i"}, $decimalplaces) } qw(sellprice lastcost);
759 $form->{"qty_$i"} = $form->format_amount(\%myconfig, $form->{"qty_$i"});
760 $form->{"discount_$i"} = $form->format_amount(\%myconfig, $form->{"discount_$i"} * 100.0);
767 # ok, so this is a new part
768 # ask if it is a part or service item
770 if ( $form->{"partsgroup_$i"}
771 && ($form->{"partsnumber_$i"} eq "")
772 && ($form->{"description_$i"} eq "")) {
774 $form->{"discount_$i"} = "";
778 $form->{"id_$i"} = 0;
783 $main::lxdebug->leave_sub();
787 $main::lxdebug->enter_sub();
789 my $form = $main::form;
790 my %myconfig = %main::myconfig;
791 my $locale = $main::locale;
793 $main::auth->assert('invoice_edit');
795 $form->mtime_ischanged('ar') ;
796 my $invdate = $form->datetonum($form->{invdate}, \%myconfig);
798 $form->{defaultcurrency} = $form->get_default_currency(\%myconfig);
799 for my $i (1 .. $form->{paidaccounts}) {
800 if ($form->{"paid_$i"}) {
801 my $datepaid = $form->datetonum($form->{"datepaid_$i"}, \%myconfig);
803 $form->isblank("datepaid_$i", $locale->text('Payment date missing!'));
806 if ($form->{currency} ne $form->{defaultcurrency}) {
807 $form->{"exchangerate_$i"} = $form->{exchangerate}
808 if ($invdate == $datepaid);
809 $form->isblank("exchangerate_$i",
810 $locale->text('Exchangerate for payment missing!'));
812 $form->error($locale->text('Cannot post transaction above the maximum future booking date!'))
813 if ($form->date_max_future($form->{"datepaid_$i"}, \%myconfig));
815 #Zusätzlich noch das Buchungsdatum in die Bücherkontrolle einbeziehen
816 # (Dient zur Prüfung ob ZE oder ZA geprüft werden soll)
817 $form->error($locale->text('Cannot post payment for a closed period!'))
818 if ($form->date_closed($form->{"datepaid_$i"}) && !$form->date_closed($form->{"gldate_$i"}, \%myconfig));
822 ($form->{AR}) = split /--/, $form->{AR};
823 ($form->{AR_paid}) = split /--/, $form->{AR_paid};
825 if ( IS->post_payment(\%myconfig, \%$form) ) {
826 $form->{snumbers} = qq|invnumber_| . $form->{invnumber};
827 $form->{what_done} = 'invoice';
828 $form->{addition} = "PAYMENT POSTED";
830 $form->redirect($locale->text('Payment posted!'))
832 $form->error($locale->text('Cannot post payment!'));
835 $main::lxdebug->leave_sub();
839 $main::lxdebug->enter_sub();
841 my $form = $main::form;
842 my %myconfig = %main::myconfig;
843 my $locale = $main::locale;
845 $main::auth->assert('invoice_edit');
846 $form->mtime_ischanged('ar');
848 $form->{defaultcurrency} = $form->get_default_currency(\%myconfig);
849 $form->isblank("invdate", $locale->text('Invoice Date missing!'));
850 $form->isblank("customer_id", $locale->text('Customer missing!'));
851 $form->error($locale->text('Cannot post invoice for a closed period!'))
852 if ($form->date_closed($form->{"invdate"}, \%myconfig));
854 $form->{invnumber} =~ s/^\s*//g;
855 $form->{invnumber} =~ s/\s*$//g;
857 # if oldcustomer ne customer redo form
858 if (($form->{previous_customer_id} || $form->{customer_id}) != $form->{customer_id}) {
860 $::dispatcher->end_request;
863 if ($myconfig{mandatory_departments} && !$form->{department_id}) {
864 $form->{saved_message} = $::locale->text('You have to specify a department.');
869 if ($form->{second_run}) {
870 $form->{print_and_post} = 0;
873 remove_emptied_rows();
876 my $closedto = $form->datetonum($form->{closedto}, \%myconfig);
877 my $invdate = $form->datetonum($form->{invdate}, \%myconfig);
879 $form->error($locale->text('Cannot post transaction above the maximum future booking date!'))
880 if ($form->date_max_future($invdate, \%myconfig));
881 $form->error($locale->text('Cannot post invoice for a closed period!'))
882 if ($invdate <= $closedto);
884 $form->isblank("exchangerate", $locale->text('Exchangerate missing!'))
885 if ($form->{currency} ne $form->{defaultcurrency});
887 for my $i (1 .. $form->{paidaccounts}) {
888 if ($form->parse_amount(\%myconfig, $form->{"paid_$i"})) {
889 my $datepaid = $form->datetonum($form->{"datepaid_$i"}, \%myconfig);
891 $form->isblank("datepaid_$i", $locale->text('Payment date missing!'));
893 $form->error($locale->text('Cannot post transaction above the maximum future booking date!'))
894 if ($form->date_max_future($form->{"datepaid_$i"}, \%myconfig));
896 #Zusätzlich noch das Buchungsdatum in die Bücherkontrolle einbeziehen
897 # (Dient zur Prüfung ob ZE oder ZA geprüft werden soll)
898 $form->error($locale->text('Cannot post payment for a closed period!'))
899 if ($form->date_closed($form->{"datepaid_$i"}) && !$form->date_closed($form->{"gldate_$i"}, \%myconfig));
901 if ($form->{currency} ne $form->{defaultcurrency}) {
902 $form->{"exchangerate_$i"} = $form->{exchangerate}
903 if ($invdate == $datepaid);
904 $form->isblank("exchangerate_$i",
905 $locale->text('Exchangerate for payment missing!'));
910 ($form->{AR}) = split /--/, $form->{AR};
911 ($form->{AR_paid}) = split /--/, $form->{AR_paid};
912 $form->{storno} ||= 0;
914 $form->{label} = $form->{type} eq 'credit_note' ? $locale->text('Credit Note') : $locale->text('Invoice');
916 $form->{id} = 0 if $form->{postasnew};
918 # get new invnumber in sequence if no invnumber is given or if posasnew was requested
919 if ($form->{postasnew}) {
920 if ($form->{type} eq "credit_note") {
921 undef($form->{cnnumber});
923 undef($form->{invnumber});
929 my $terms = get_payment_terms_for_invoice();
930 $form->{duedate} = $terms->calc_date(reference_date => $form->{invdate}, due_date => $form->{duedate})->to_kivitendo if $terms;
932 # If transfer_out is requested, get rose db handle and do post and
933 # transfer out in one transaction. Otherwise just post the invoice.
934 if ($::instance_conf->get_is_transfer_out && $form->{type} ne 'credit_note' && !$form->{storno}) {
935 require SL::DB::Inventory;
936 my $rose_db = SL::DB::Inventory->new->db;
939 if (!$rose_db->with_transaction(sub {
941 if (!IS->post_invoice(\%myconfig, \%$form, $rose_db->dbh)) {
942 push @errors, $locale->text('Cannot post invoice!');
945 my $err = IS->transfer_out(\%$form, $rose_db->dbh);
947 push @errors, @{ $err };
948 die 'transfer error';
953 push @errors, $EVAL_ERROR;
954 $form->error($locale->text('Cannot post invoice and/or transfer out! Error message:') . "\n" . join("\n", @errors));
959 push @errors, $rose_db->error;
960 $form->error($locale->text('Cannot post invoice and/or transfer out! Error message:') . "\n" . join("\n", @errors));
963 if (!IS->post_invoice(\%myconfig, \%$form)) {
964 $form->error($locale->text('Cannot post invoice!'));
968 if(!exists $form->{addition}) {
969 $form->{snumbers} = 'invnumber' .'_'. $form->{invnumber}; # ($form->{type} eq 'credit_note' ? 'cnnumber' : 'invnumber') .'_'. $form->{invnumber};
970 $form->{what_done} = 'invoice';
971 $form->{addition} = $form->{print_and_post} ? "PRINTED AND POSTED" :
972 $form->{storno} ? "STORNO" :
977 if (!$form->{no_redirect_after_post}) {
978 $form->{action} = 'edit';
979 $form->{script} = 'is.pl';
980 $form->{callback} = build_std_url(qw(action edit id callback saved_message));
981 $form->redirect($form->{label} . " $form->{invnumber} " . $locale->text('posted!'));
984 $main::lxdebug->leave_sub();
988 $main::lxdebug->enter_sub();
990 my $form = $main::form;
992 $main::auth->assert('invoice_edit');
994 my $old_form = Form->new;
995 $form->{no_redirect_after_post} = 1;
996 $form->{print_and_post} = 1;
1000 $main::lxdebug->leave_sub();
1005 $main::lxdebug->enter_sub();
1007 my $form = $main::form;
1008 my %myconfig = %main::myconfig;
1010 $main::auth->assert('invoice_edit');
1012 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)};
1013 $form->{rowcount}--;
1014 $form->{paidaccounts} = 1;
1015 $form->{invdate} = $form->current_date(\%myconfig);
1016 my $terms = get_payment_terms_for_invoice();
1017 $form->{duedate} = $terms ? $terms->calc_date(reference_date => $form->{invdate})->to_kivitendo : $form->{invdate};
1018 $form->{employee_id} = SL::DB::Manager::Employee->current->id;
1019 $form->{forex} = $form->check_exchangerate(\%myconfig, $form->{currency}, $form->{invdate}, 'buy');
1020 $form->{exchangerate} = $form->{forex} if $form->{forex};
1022 $form->{"converted_from_invoice_id_$_"} = delete $form->{"invoice_id_$_"} for 1 .. $form->{"rowcount"};
1024 $form->{useasnew} = 1;
1027 $main::lxdebug->leave_sub();
1031 $main::lxdebug->enter_sub();
1033 my $form = $main::form;
1034 my %myconfig = %main::myconfig;
1035 my $locale = $main::locale;
1037 $main::auth->assert('invoice_edit');
1039 if ($form->{storno}) {
1040 $form->error($locale->text('Cannot storno storno invoice!'));
1043 if (IS->has_storno(\%myconfig, $form, "ar")) {
1044 $form->error($locale->text("Invoice has already been storno'd!"));
1046 if ($form->datetonum($form->{invdate}, \%myconfig) <= $form->datetonum($form->{closedto}, \%myconfig)) {
1047 $form->error($locale->text('Cannot storno invoice for a closed period!'));
1050 # save the history of invoice being stornoed
1051 $form->{snumbers} = qq|invnumber_| . $form->{invnumber};
1052 $form->{what_done} = 'invoice';
1053 $form->{addition} = "STORNO";
1054 $form->save_history;
1056 map({ my $key = $_; delete($form->{$key}) unless (grep({ $key eq $_ } qw(id login password type))); } keys(%{ $form }));
1062 # Payments must not be recorded for the new storno invoice.
1063 $form->{paidaccounts} = 0;
1064 map { my $key = $_; delete $form->{$key} if grep { $key =~ /^$_/ } qw(datepaid_ gldate_ acc_trans_id_ source_ memo_ paid_ exchangerate_ AR_paid_) } keys %{ $form };
1066 # record link invoice to storno
1067 $form->{convert_from_ar_ids} = $form->{id};
1068 $form->{storno_id} = $form->{id};
1069 $form->{storno} = 1;
1071 $form->{invnumber} = "Storno zu " . $form->{invnumber};
1072 $form->{invdate} = DateTime->today->to_lxoffice;
1073 $form->{rowcount}++;
1074 # set new ids for storno invoice
1075 # set new persistent ids for storno invoice items
1076 $form->{"converted_from_invoice_id_$_"} = delete $form->{"invoice_id_$_"} for 1 .. $form->{"rowcount"};
1079 $main::lxdebug->leave_sub();
1083 $main::lxdebug->enter_sub();
1085 my $form = $main::form;
1087 $main::auth->assert('invoice_edit');
1089 $form->{preview} = 1;
1090 my $old_form = Form->new;
1091 for (keys %$form) { $old_form->{$_} = $form->{$_} }
1093 &print_form($old_form);
1094 $main::lxdebug->leave_sub();
1099 $main::lxdebug->enter_sub();
1101 my $form = $main::form;
1102 my %myconfig = %main::myconfig;
1103 my $locale = $main::locale;
1105 $main::auth->assert('invoice_edit');
1107 $form->{transdate} = $form->{invdate} = $form->current_date(\%myconfig);
1109 $form->current_date(\%myconfig, $form->{invdate}, $form->{terms} * 1);
1111 $form->{convert_from_ar_ids} = $form->{id};
1113 $form->{rowcount}--;
1116 $form->{title} = $locale->text('Add Credit Note');
1117 $form->{script} = 'is.pl';
1119 # Bei Gutschriften bezug zur Rechnungsnummer
1120 $form->{invnumber_for_credit_note} = $form->{invnumber};
1121 # bo creates the id, reset it
1122 map { delete $form->{$_} }
1123 qw(id invnumber subject message cc bcc printed emailed queued);
1124 $form->{ $form->{vc} } =~ s/--.*//g;
1125 $form->{type} = "credit_note";
1128 map { $form->{"select$_"} = "" } ($form->{vc}, 'currency');
1130 # map { $form->{$_} = $form->parse_amount(\%myconfig, $form->{$_}) }
1131 # qw(creditlimit creditremaining);
1133 # set new persistent ids for credit note and link previous invoice id
1134 $form->{"converted_from_invoice_id_$_"} = delete $form->{"invoice_id_$_"} for 1 .. $form->{"rowcount"};
1136 my $currency = $form->{currency};
1139 $form->{currency} = $currency;
1140 $form->{forex} = $form->check_exchangerate( \%myconfig, $form->{currency}, $form->{invdate}, 'buy');
1141 $form->{exchangerate} = $form->{forex} || '';
1143 $form->{creditremaining} -= ($form->{oldinvtotal} - $form->{ordtotal});
1145 # bei Gutschriften werden Zahlungseingänge aus Rechnung nicht übernommen
1146 for my $i (1 .. $form->{paidaccounts}) {
1147 delete $form->{"paid_$i"};
1148 delete $form->{"source_$i"};
1149 delete $form->{"memo_$i"};
1150 delete $form->{"datepaid_$i"};
1151 delete $form->{"gldate_$i"};
1152 delete $form->{"acc_trans_id_$i"};
1153 delete $form->{"AR_paid_$i"};
1155 $form->{paidaccounts} = 1;
1162 $main::lxdebug->leave_sub();
1166 $::lxdebug->enter_sub;
1168 $::auth->assert('invoice_edit');
1172 my $new_rowcount = $::form->{"rowcount"} * 1 + 1;
1173 $::form->{"project_id_${new_rowcount}"} = $::form->{"globalproject_id"};
1175 $::form->language_payment(\%::myconfig);
1177 Common::webdav_folder($::form);
1180 display_row(++$::form->{rowcount});
1183 $::lxdebug->leave_sub;
1187 $::auth->assert('invoice_edit');
1189 if (IS->delete_invoice(\%::myconfig, $::form)) {
1190 # saving the history
1191 if(!exists $::form->{addition}) {
1192 $::form->{snumbers} = 'invnumber' .'_'. $::form->{invnumber};
1193 $::form->{what_done} = 'invoice';
1194 $::form->{addition} = "DELETED";
1195 $::form->save_history;
1197 # /saving the history
1198 $::form->redirect($::locale->text('Invoice deleted!'));
1200 $::form->error($::locale->text('Cannot delete invoice!'));
1205 print update ship_to storno post_payment use_as_new credit_note
1206 delete post order preview post_and_e_mail print_and_post
1209 if ($::form->{"action_$action"}) {
1215 $::form->error($::locale->text('No action defined.'));