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('E Mail'),
348 call => [ 'kivi.SalesPurchase.show_email_dialog' ],
349 checks => [ @req_trans_desc ],
350 disabled => !$form->{id} ? t8('This invoice has not been posted yet.') : undef,
352 ], # end of combobox "Export"
355 action => [ t8('more') ],
358 call => [ 'set_history_window', $form->{id} * 1, 'glid' ],
359 disabled => !$form->{id} ? t8('This invoice has not been posted yet.') : undef,
363 call => [ 'follow_up_window' ],
364 disabled => !$form->{id} ? t8('This invoice has not been posted yet.') : undef,
368 call => [ 'kivi.Draft.popup', 'is', 'invoice', $form->{draft_id}, $form->{draft_description} ],
369 disabled => $form->{id} ? t8('This invoice has already been posted.')
370 : $form->{locked} ? t8('The billing period has already been locked.')
373 ], # end of combobox "more"
379 $main::lxdebug->enter_sub();
381 my $form = $main::form;
382 my %myconfig = %main::myconfig;
383 my $locale = $main::locale;
384 my $cgi = $::request->{cgi};
386 $main::auth->assert('invoice_edit');
391 $TMPL_VAR{customer_obj} = SL::DB::Customer->load_cached($form->{customer_id}) if $form->{customer_id};
392 $TMPL_VAR{invoice_obj} = SL::DB::Invoice->load_cached($form->{id}) if $form->{id};
394 my $current_employee = SL::DB::Manager::Employee->current;
395 $form->{employee_id} = $form->{old_employee_id} if $form->{old_employee_id};
396 $form->{salesman_id} = $form->{old_salesman_id} if $form->{old_salesman_id};
397 $form->{employee_id} ||= $current_employee->id;
398 $form->{salesman_id} ||= $current_employee->id;
400 $form->{defaultcurrency} = $form->get_default_currency(\%myconfig);
402 $form->get_lists("taxzones" => ($form->{id} ? "ALL_TAXZONES" : "ALL_ACTIVE_TAXZONES"),
403 "currencies" => "ALL_CURRENCIES",
404 "price_factors" => "ALL_PRICE_FACTORS");
406 $form->{ALL_DEPARTMENTS} = SL::DB::Manager::Department->get_all_sorted;
409 my @old_project_ids = uniq grep { $_ } map { $_ * 1 } ($form->{"globalproject_id"}, map { $form->{"project_id_$_"} } 1..$form->{"rowcount"});
410 my @old_ids_cond = @old_project_ids ? (id => \@old_project_ids) : ();
412 if ($::instance_conf->get_customer_projects_only_in_sales) {
415 customer_id => $::form->{customer_id},
416 billable_customer_id => $::form->{customer_id},
421 and => [ active => 1, @customer_cond ],
425 $TMPL_VAR{ALL_PROJECTS} = SL::DB::Manager::Project->get_all_sorted(query => \@conditions);
426 $form->{ALL_PROJECTS} = $TMPL_VAR{ALL_PROJECTS}; # make projects available for second row drop-down in io.pl
427 $TMPL_VAR{ALL_EMPLOYEES} = SL::DB::Manager::Employee->get_all_sorted(query => [ or => [ id => $::form->{employee_id}, deleted => 0 ] ]);
428 $TMPL_VAR{ALL_SALESMEN} = SL::DB::Manager::Employee->get_all_sorted(query => [ or => [ id => $::form->{salesman_id}, deleted => 0 ] ]);
429 $TMPL_VAR{ALL_SHIPTO} = SL::DB::Manager::Shipto->get_all_sorted(query => [
430 or => [ trans_id => $::form->{"$::form->{vc}_id"} * 1, and => [ shipto_id => $::form->{shipto_id} * 1, trans_id => undef ] ]
432 $TMPL_VAR{ALL_CONTACTS} = SL::DB::Manager::Contact->get_all_sorted(query => [
434 cp_cv_id => $::form->{"$::form->{vc}_id"} * 1,
437 cp_id => $::form->{cp_id} * 1
442 # currencies and exchangerate
443 my @values = map { $_ } @{ $form->{ALL_CURRENCIES} };
444 my %labels = map { $_ => $_ } @{ $form->{ALL_CURRENCIES} };
445 $form->{currency} = $form->{defaultcurrency} unless $form->{currency};
446 $form->{show_exchangerate} = $form->{currency} ne $form->{defaultcurrency};
447 $TMPL_VAR{currencies} = NTI($::request->{cgi}->popup_menu('-name' => 'currency', '-default' => $form->{"currency"},
448 '-values' => \@values, '-labels' => \%labels,
449 '-onchange' => "document.getElementById('update_button').click();"
450 )) if scalar @values;
451 push @custom_hiddens, "forex";
452 push @custom_hiddens, "exchangerate" if $form->{forex};
454 $TMPL_VAR{creditwarning} = ($form->{creditlimit} != 0) && ($form->{creditremaining} < 0) && !$form->{update};
455 $TMPL_VAR{is_credit_remaining_negativ} = $form->{creditremaining} =~ /-/;
457 # set option selected
458 foreach my $item (qw(AR)) {
459 $form->{"select$item"} =~ s/ selected//;
460 $form->{"select$item"} =~ s/option>\Q$form->{$item}\E/option selected>$form->{$item}/;
463 $TMPL_VAR{is_type_credit_note} = $form->{type} eq "credit_note";
464 $TMPL_VAR{is_format_html} = $form->{format} eq 'html';
465 $TMPL_VAR{dateformat} = $myconfig{dateformat};
466 $TMPL_VAR{numberformat} = $myconfig{numberformat};
469 $TMPL_VAR{HIDDENS} = [qw(
470 id type queued printed emailed vc discount
471 title creditlimit creditremaining tradediscount business closedto locked shipped storno storno_id
472 max_dunning_level dunning_amount dunning_description
473 taxaccounts cursor_fokus
474 convert_from_do_ids convert_from_oe_ids convert_from_ar_ids useasnew
478 map { $_.'_rate', $_.'_description', $_.'_taxnumber' } split / /, $form->{taxaccounts}];
480 $::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));
482 $TMPL_VAR{payment_terms_obj} = get_payment_terms_for_invoice();
483 $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};
485 setup_is_action_bar();
489 print $form->parse_html_template("is/form_header", \%TMPL_VAR);
491 $main::lxdebug->leave_sub();
495 my @fields = qw(acc_trans_id gldate datepaid source memo paid AR_paid);
497 grep { $_->{paid} != 0 }
500 +{ map { ($_ => delete($::form->{"${_}_${idx}"})) } @fields }
501 } (1..$::form->{paidaccounts});
503 @payments = sort_by { DateTime->from_kivitendo($_->{datepaid}) } @payments;
505 $::form->{paidaccounts} = max scalar(@payments), 1;
507 foreach my $idx (1 .. scalar(@payments)) {
508 my $payment = $payments[$idx - 1];
509 $::form->{"${_}_${idx}"} = $payment->{$_} for @fields;
514 $main::lxdebug->enter_sub();
516 my $form = $main::form;
517 my %myconfig = %main::myconfig;
518 my $locale = $main::locale;
520 $main::auth->assert('invoice_edit');
522 $form->{invtotal} = $form->{invsubtotal};
525 $form->{rows} = max 2,
526 $form->numtextrows($form->{notes}, 26, 8),
527 $form->numtextrows($form->{intnotes}, 35, 8);
530 # tax, total and subtotal calculations
531 my ($tax, $subtotal);
532 $form->{taxaccounts_array} = [ split(/ /, $form->{taxaccounts}) ];
534 if( $form->{customer_id} && !$form->{taxincluded_changed_by_user} ) {
535 my $customer = SL::DB::Customer->load_cached($form->{customer_id});
536 $form->{taxincluded} = defined($customer->taxincluded_checked) ? $customer->taxincluded_checked : $myconfig{taxincluded_checked};
539 foreach my $item (@{ $form->{taxaccounts_array} }) {
540 if ($form->{"${item}_base"}) {
541 if ($form->{taxincluded}) {
542 $form->{"${item}_total"} = $form->round_amount( ($form->{"${item}_base"} * $form->{"${item}_rate"}
543 / (1 + $form->{"${item}_rate"})), 2);
544 $form->{"${item}_netto"} = $form->round_amount( ($form->{"${item}_base"} - $form->{"${item}_total"}), 2);
546 $form->{"${item}_total"} = $form->round_amount( $form->{"${item}_base"} * $form->{"${item}_rate"}, 2);
547 $form->{invtotal} += $form->{"${item}_total"};
552 my $grossamount = $form->{invtotal};
553 $form->{invtotal} = $form->round_amount( $form->{invtotal}, 2, 1 );
554 $form->{rounding} = $form->round_amount(
555 $form->{invtotal} - $form->round_amount($grossamount, 2),
561 $form->{follow_ups} = FU->follow_ups('trans_id' => $form->{id}, 'not_done' => 1) || [];
562 $form->{follow_ups_unfinished} = ( sum map { $_->{due} * 1 } @{ $form->{follow_ups} } ) || 0;
569 $form->{paidaccounts}++ if ($form->{"paid_$form->{paidaccounts}"});
570 $form->{paid_indices} = [ 1 .. $form->{paidaccounts} ];
572 # Standard Konto für Umlaufvermögen
573 my $accno_arap = IS->get_standard_accno_current_assets(\%myconfig, \%$form);
575 for my $i (1 .. $form->{paidaccounts}) {
576 $form->{"changeable_$i"} = 1;
577 if (SL::DB::Default->get->payments_changeable == 0) {
579 $form->{"changeable_$i"} = ($form->{"acc_trans_id_$i"})? 0 : 1;
580 } elsif (SL::DB::Default->get->payments_changeable == 2) {
582 $form->{"changeable_$i"} = (($form->{"gldate_$i"} eq '') ||
583 ($form->current_date(\%myconfig) eq $form->{"gldate_$i"}));
586 #deaktivieren von gebuchten Zahlungen ausserhalb der Bücherkontrolle, vorher prüfen ob heute eingegeben
587 if ($form->date_closed($form->{"gldate_$i"})) {
588 $form->{"changeable_$i"} = 0;
591 $form->{"selectAR_paid_$i"} = $form->{selectAR_paid};
592 if (!$form->{"AR_paid_$i"}) {
593 $form->{"selectAR_paid_$i"} =~ s/option>$accno_arap--(.*?)</option selected>$accno_arap--$1</;
595 $form->{"selectAR_paid_$i"} =~ s/option>\Q$form->{"AR_paid_$i"}\E/option selected>$form->{"AR_paid_$i"}/;
598 $totalpaid += $form->{"paid_$i"};
601 $form->{oldinvtotal} = $form->{invtotal};
603 $form->{ALL_DELIVERY_TERMS} = SL::DB::Manager::DeliveryTerm->get_all_sorted();
605 print $form->parse_html_template('is/form_footer', {
606 is_type_credit_note => ($form->{type} eq "credit_note"),
607 totalpaid => $totalpaid,
608 paid_missing => $form->{invtotal} - $totalpaid,
609 print_options => setup_sales_purchase_print_options(),
610 show_storno => $form->{id} && !$form->{storno} && !IS->has_storno(\%myconfig, $form, "ar") && !$totalpaid,
611 show_delete => ($::instance_conf->get_is_changeable == 2)
612 ? ($form->current_date(\%myconfig) eq $form->{gldate})
613 : ($::instance_conf->get_is_changeable == 1),
614 today => DateTime->today,
615 vc_obj => $form->{customer_id} ? SL::DB::Customer->load_cached($form->{customer_id}) : undef,
617 ##print $form->parse_html_template('is/_payments'); # parser
618 ##print $form->parse_html_template('webdav/_list'); # parser
620 $main::lxdebug->leave_sub();
624 $::auth->assert('invoice_edit');
626 SL::DB::Invoice->new(id => $::form->{id})->load->mark_as_paid;
628 $::form->redirect($::locale->text("Marked as paid"));
632 # unless no lazy implementation of save draft without invdate
633 # set the current date like in version <= 3.4.1
634 $::form->{invdate} = DateTime->today->to_lxoffice;
639 $main::lxdebug->enter_sub();
641 my $form = $main::form;
642 my %myconfig = %main::myconfig;
644 $main::auth->assert('invoice_edit');
646 my ($recursive_call) = @_;
648 $form->{print_and_post} = 0 if $form->{second_run};
649 my $taxincluded = $form->{taxincluded} ? "checked" : '';
652 if (($form->{previous_customer_id} || $form->{customer_id}) != $form->{customer_id}) {
653 $::form->{salesman_id} = SL::DB::Manager::Employee->current->id if exists $::form->{salesman_id};
655 IS->get_customer(\%myconfig, $form);
658 $form->{taxincluded} ||= $taxincluded;
660 if (!$form->{forex}) { # read exchangerate from input field (not hidden)
661 $form->{exchangerate} = $form->parse_amount(\%myconfig, $form->{exchangerate}) unless $recursive_call;
663 $form->{forex} = $form->check_exchangerate(\%myconfig, $form->{currency}, $form->{invdate}, 'buy');
664 $form->{exchangerate} = $form->{forex} if $form->{forex};
666 for my $i (1 .. $form->{paidaccounts}) {
667 next unless $form->{"paid_$i"};
668 map { $form->{"${_}_$i"} = $form->parse_amount(\%myconfig, $form->{"${_}_$i"}) } qw(paid exchangerate);
669 if (!$form->{"forex_$i"}) { #read exchangerate from input field (not hidden)
670 $form->{exchangerate} = $form->{"exchangerate_$i"};
672 $form->{"forex_$i"} = $form->check_exchangerate(\%myconfig, $form->{currency}, $form->{"datepaid_$i"}, 'buy');
673 $form->{"exchangerate_$i"} = $form->{"forex_$i"} if $form->{"forex_$i"};
676 my $i = $form->{rowcount};
677 my $exchangerate = $form->{exchangerate} || 1;
679 # if last row empty, check the form otherwise retrieve new item
680 if ( ($form->{"partnumber_$i"} eq "")
681 && ($form->{"description_$i"} eq "")
682 && ($form->{"partsgroup_$i"} eq "")) {
684 $form->{creditremaining} += ($form->{oldinvtotal} - $form->{oldtotalpaid});
689 IS->retrieve_item(\%myconfig, \%$form);
691 my $rows = scalar @{ $form->{item_list} };
693 $form->{"discount_$i"} = $form->parse_amount(\%myconfig, $form->{"discount_$i"}) / 100.0;
694 $form->{"discount_$i"} ||= $form->{customer_discount};
697 $form->{"qty_$i"} = $form->parse_amount(\%myconfig, $form->{"qty_$i"});
698 if( !$form->{"qty_$i"} ) {
699 $form->{"qty_$i"} = 1;
704 select_item(mode => 'IS', pre_entered_qty => $form->{"qty_$i"});
705 $::dispatcher->end_request;
709 my $sellprice = $form->parse_amount(\%myconfig, $form->{"sellprice_$i"});
711 map { $form->{item_list}[$i]{$_} =~ s/\"/"/g } qw(partnumber description unit);
712 map { $form->{"${_}_$i"} = $form->{item_list}[0]{$_} } keys %{ $form->{item_list}[0] };
714 $form->{payment_id} = $form->{"part_payment_id_$i"} if $form->{"part_payment_id_$i"} ne "";
715 $form->{"discount_$i"} = 0 if $form->{"not_discountable_$i"};
717 $form->{"marge_price_factor_$i"} = $form->{item_list}->[0]->{price_factor};
719 ($sellprice || $form->{"sellprice_$i"}) =~ /\.(\d+)/;
720 my $decimalplaces = max 2, length $1;
723 $form->{"sellprice_$i"} = $sellprice;
725 my $record = _make_record();
726 my $price_source = SL::PriceSource->new(record_item => $record->items->[$i-1], record => $record);
727 my $best_price = $price_source->best_price;
728 my $best_discount = $price_source->best_discount;
731 $::form->{"sellprice_$i"} = $best_price->price;
732 $::form->{"active_price_source_$i"} = $best_price->source;
734 if ($best_discount) {
735 $::form->{"discount_$i"} = $best_discount->discount;
736 $::form->{"active_discount_source_$i"} = $best_discount->source;
739 # if there is an exchange rate adjust sellprice
740 $form->{"sellprice_$i"} /= $exchangerate;
743 $form->{"listprice_$i"} /= $exchangerate;
745 my $amount = $form->{"sellprice_$i"} * $form->{"qty_$i"} * (1 - $form->{"discount_$i"});
746 map { $form->{"${_}_base"} = 0 } split / /, $form->{taxaccounts};
747 map { $form->{"${_}_base"} += $amount } split / /, $form->{"taxaccounts_$i"};
748 map { $amount += ($form->{"${_}_base"} * $form->{"${_}_rate"}) } split / /, $form->{"taxaccounts_$i"} if !$form->{taxincluded};
750 $form->{creditremaining} -= $amount;
752 map { $form->{"${_}_$i"} = $form->format_amount(\%myconfig, $form->{"${_}_$i"}, $decimalplaces) } qw(sellprice lastcost);
754 $form->{"qty_$i"} = $form->format_amount(\%myconfig, $form->{"qty_$i"});
755 $form->{"discount_$i"} = $form->format_amount(\%myconfig, $form->{"discount_$i"} * 100.0);
762 # ok, so this is a new part
763 # ask if it is a part or service item
765 if ( $form->{"partsgroup_$i"}
766 && ($form->{"partsnumber_$i"} eq "")
767 && ($form->{"description_$i"} eq "")) {
769 $form->{"discount_$i"} = "";
773 $form->{"id_$i"} = 0;
778 $main::lxdebug->leave_sub();
782 $main::lxdebug->enter_sub();
784 my $form = $main::form;
785 my %myconfig = %main::myconfig;
786 my $locale = $main::locale;
788 $main::auth->assert('invoice_edit');
790 $form->mtime_ischanged('ar') ;
791 my $invdate = $form->datetonum($form->{invdate}, \%myconfig);
793 $form->{defaultcurrency} = $form->get_default_currency(\%myconfig);
794 for my $i (1 .. $form->{paidaccounts}) {
795 if ($form->{"paid_$i"}) {
796 my $datepaid = $form->datetonum($form->{"datepaid_$i"}, \%myconfig);
798 $form->isblank("datepaid_$i", $locale->text('Payment date missing!'));
801 if ($form->{currency} ne $form->{defaultcurrency}) {
802 $form->{"exchangerate_$i"} = $form->{exchangerate}
803 if ($invdate == $datepaid);
804 $form->isblank("exchangerate_$i",
805 $locale->text('Exchangerate for payment missing!'));
807 $form->error($locale->text('Cannot post transaction above the maximum future booking date!'))
808 if ($form->date_max_future($form->{"datepaid_$i"}, \%myconfig));
810 #Zusätzlich noch das Buchungsdatum in die Bücherkontrolle einbeziehen
811 # (Dient zur Prüfung ob ZE oder ZA geprüft werden soll)
812 $form->error($locale->text('Cannot post payment for a closed period!'))
813 if ($form->date_closed($form->{"datepaid_$i"}) && !$form->date_closed($form->{"gldate_$i"}, \%myconfig));
817 ($form->{AR}) = split /--/, $form->{AR};
818 ($form->{AR_paid}) = split /--/, $form->{AR_paid};
820 if ( IS->post_payment(\%myconfig, \%$form) ) {
821 $form->{snumbers} = qq|invnumber_| . $form->{invnumber};
822 $form->{what_done} = 'invoice';
823 $form->{addition} = "PAYMENT POSTED";
825 $form->redirect($locale->text('Payment posted!'))
827 $form->error($locale->text('Cannot post payment!'));
830 $main::lxdebug->leave_sub();
834 $main::lxdebug->enter_sub();
836 my $form = $main::form;
837 my %myconfig = %main::myconfig;
838 my $locale = $main::locale;
840 $main::auth->assert('invoice_edit');
841 $form->mtime_ischanged('ar');
843 $form->{defaultcurrency} = $form->get_default_currency(\%myconfig);
844 $form->isblank("invdate", $locale->text('Invoice Date missing!'));
845 $form->isblank("customer_id", $locale->text('Customer missing!'));
846 $form->error($locale->text('Cannot post invoice for a closed period!'))
847 if ($form->date_closed($form->{"invdate"}, \%myconfig));
849 $form->{invnumber} =~ s/^\s*//g;
850 $form->{invnumber} =~ s/\s*$//g;
852 # if oldcustomer ne customer redo form
853 if (($form->{previous_customer_id} || $form->{customer_id}) != $form->{customer_id}) {
855 $::dispatcher->end_request;
858 if ($myconfig{mandatory_departments} && !$form->{department_id}) {
859 $form->{saved_message} = $::locale->text('You have to specify a department.');
864 if ($form->{second_run}) {
865 $form->{print_and_post} = 0;
868 remove_emptied_rows();
871 my $closedto = $form->datetonum($form->{closedto}, \%myconfig);
872 my $invdate = $form->datetonum($form->{invdate}, \%myconfig);
874 $form->error($locale->text('Cannot post transaction above the maximum future booking date!'))
875 if ($form->date_max_future($invdate, \%myconfig));
876 $form->error($locale->text('Cannot post invoice for a closed period!'))
877 if ($invdate <= $closedto);
879 $form->isblank("exchangerate", $locale->text('Exchangerate missing!'))
880 if ($form->{currency} ne $form->{defaultcurrency});
882 for my $i (1 .. $form->{paidaccounts}) {
883 if ($form->parse_amount(\%myconfig, $form->{"paid_$i"})) {
884 my $datepaid = $form->datetonum($form->{"datepaid_$i"}, \%myconfig);
886 $form->isblank("datepaid_$i", $locale->text('Payment date missing!'));
888 $form->error($locale->text('Cannot post transaction above the maximum future booking date!'))
889 if ($form->date_max_future($form->{"datepaid_$i"}, \%myconfig));
891 #Zusätzlich noch das Buchungsdatum in die Bücherkontrolle einbeziehen
892 # (Dient zur Prüfung ob ZE oder ZA geprüft werden soll)
893 $form->error($locale->text('Cannot post payment for a closed period!'))
894 if ($form->date_closed($form->{"datepaid_$i"}) && !$form->date_closed($form->{"gldate_$i"}, \%myconfig));
896 if ($form->{currency} ne $form->{defaultcurrency}) {
897 $form->{"exchangerate_$i"} = $form->{exchangerate}
898 if ($invdate == $datepaid);
899 $form->isblank("exchangerate_$i",
900 $locale->text('Exchangerate for payment missing!'));
905 ($form->{AR}) = split /--/, $form->{AR};
906 ($form->{AR_paid}) = split /--/, $form->{AR_paid};
907 $form->{storno} ||= 0;
909 $form->{label} = $form->{type} eq 'credit_note' ? $locale->text('Credit Note') : $locale->text('Invoice');
911 $form->{id} = 0 if $form->{postasnew};
913 # get new invnumber in sequence if no invnumber is given or if posasnew was requested
914 if ($form->{postasnew}) {
915 if ($form->{type} eq "credit_note") {
916 undef($form->{cnnumber});
918 undef($form->{invnumber});
924 my $terms = get_payment_terms_for_invoice();
925 $form->{duedate} = $terms->calc_date(reference_date => $form->{invdate}, due_date => $form->{duedate})->to_kivitendo if $terms;
927 # If transfer_out is requested, get rose db handle and do post and
928 # transfer out in one transaction. Otherwise just post the invoice.
929 if ($::instance_conf->get_is_transfer_out && $form->{type} ne 'credit_note' && !$form->{storno}) {
930 require SL::DB::Inventory;
931 my $rose_db = SL::DB::Inventory->new->db;
934 if (!$rose_db->with_transaction(sub {
936 if (!IS->post_invoice(\%myconfig, \%$form, $rose_db->dbh)) {
937 push @errors, $locale->text('Cannot post invoice!');
940 my $err = IS->transfer_out(\%$form, $rose_db->dbh);
942 push @errors, @{ $err };
943 die 'transfer error';
948 push @errors, $EVAL_ERROR;
949 $form->error($locale->text('Cannot post invoice and/or transfer out! Error message:') . "\n" . join("\n", @errors));
954 push @errors, $rose_db->error;
955 $form->error($locale->text('Cannot post invoice and/or transfer out! Error message:') . "\n" . join("\n", @errors));
958 if (!IS->post_invoice(\%myconfig, \%$form)) {
959 $form->error($locale->text('Cannot post invoice!'));
963 if(!exists $form->{addition}) {
964 $form->{snumbers} = 'invnumber' .'_'. $form->{invnumber}; # ($form->{type} eq 'credit_note' ? 'cnnumber' : 'invnumber') .'_'. $form->{invnumber};
965 $form->{what_done} = 'invoice';
966 $form->{addition} = $form->{print_and_post} ? "PRINTED AND POSTED" :
967 $form->{storno} ? "STORNO" :
972 if (!$form->{no_redirect_after_post}) {
973 $form->{action} = 'edit';
974 $form->{script} = 'is.pl';
975 $form->{callback} = build_std_url(qw(action edit id callback saved_message));
976 $form->redirect($form->{label} . " $form->{invnumber} " . $locale->text('posted!'));
979 $main::lxdebug->leave_sub();
983 $main::lxdebug->enter_sub();
985 my $form = $main::form;
987 $main::auth->assert('invoice_edit');
989 my $old_form = Form->new;
990 $form->{no_redirect_after_post} = 1;
991 $form->{print_and_post} = 1;
995 $main::lxdebug->leave_sub();
1000 $main::lxdebug->enter_sub();
1002 my $form = $main::form;
1003 my %myconfig = %main::myconfig;
1005 $main::auth->assert('invoice_edit');
1007 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)};
1008 $form->{rowcount}--;
1009 $form->{paidaccounts} = 1;
1010 $form->{invdate} = $form->current_date(\%myconfig);
1011 my $terms = get_payment_terms_for_invoice();
1012 $form->{duedate} = $terms ? $terms->calc_date(reference_date => $form->{invdate})->to_kivitendo : $form->{invdate};
1013 $form->{employee_id} = SL::DB::Manager::Employee->current->id;
1014 $form->{forex} = $form->check_exchangerate(\%myconfig, $form->{currency}, $form->{invdate}, 'buy');
1015 $form->{exchangerate} = $form->{forex} if $form->{forex};
1017 $form->{"converted_from_invoice_id_$_"} = delete $form->{"invoice_id_$_"} for 1 .. $form->{"rowcount"};
1019 $form->{useasnew} = 1;
1022 $main::lxdebug->leave_sub();
1026 $main::lxdebug->enter_sub();
1028 my $form = $main::form;
1029 my %myconfig = %main::myconfig;
1030 my $locale = $main::locale;
1032 $main::auth->assert('invoice_edit');
1034 if ($form->{storno}) {
1035 $form->error($locale->text('Cannot storno storno invoice!'));
1038 if (IS->has_storno(\%myconfig, $form, "ar")) {
1039 $form->error($locale->text("Invoice has already been storno'd!"));
1041 if ($form->datetonum($form->{invdate}, \%myconfig) <= $form->datetonum($form->{closedto}, \%myconfig)) {
1042 $form->error($locale->text('Cannot storno invoice for a closed period!'));
1045 # save the history of invoice being stornoed
1046 $form->{snumbers} = qq|invnumber_| . $form->{invnumber};
1047 $form->{what_done} = 'invoice';
1048 $form->{addition} = "STORNO";
1049 $form->save_history;
1051 map({ my $key = $_; delete($form->{$key}) unless (grep({ $key eq $_ } qw(id login password type))); } keys(%{ $form }));
1057 # Payments must not be recorded for the new storno invoice.
1058 $form->{paidaccounts} = 0;
1059 map { my $key = $_; delete $form->{$key} if grep { $key =~ /^$_/ } qw(datepaid_ gldate_ acc_trans_id_ source_ memo_ paid_ exchangerate_ AR_paid_) } keys %{ $form };
1061 # record link invoice to storno
1062 $form->{convert_from_ar_ids} = $form->{id};
1063 $form->{storno_id} = $form->{id};
1064 $form->{storno} = 1;
1066 $form->{invnumber} = "Storno zu " . $form->{invnumber};
1067 $form->{invdate} = DateTime->today->to_lxoffice;
1068 $form->{rowcount}++;
1069 # set new ids for storno invoice
1070 # set new persistent ids for storno invoice items
1071 $form->{"converted_from_invoice_id_$_"} = delete $form->{"invoice_id_$_"} for 1 .. $form->{"rowcount"};
1074 $main::lxdebug->leave_sub();
1078 $main::lxdebug->enter_sub();
1080 my $form = $main::form;
1082 $main::auth->assert('invoice_edit');
1084 $form->{preview} = 1;
1085 my $old_form = Form->new;
1086 for (keys %$form) { $old_form->{$_} = $form->{$_} }
1088 &print_form($old_form);
1089 $main::lxdebug->leave_sub();
1094 $main::lxdebug->enter_sub();
1096 my $form = $main::form;
1097 my %myconfig = %main::myconfig;
1098 my $locale = $main::locale;
1100 $main::auth->assert('invoice_edit');
1102 $form->{transdate} = $form->{invdate} = $form->current_date(\%myconfig);
1104 $form->current_date(\%myconfig, $form->{invdate}, $form->{terms} * 1);
1106 $form->{convert_from_ar_ids} = $form->{id};
1108 $form->{rowcount}--;
1111 $form->{title} = $locale->text('Add Credit Note');
1112 $form->{script} = 'is.pl';
1114 # Bei Gutschriften bezug zur Rechnungsnummer
1115 $form->{invnumber_for_credit_note} = $form->{invnumber};
1116 # bo creates the id, reset it
1117 map { delete $form->{$_} }
1118 qw(id invnumber subject message cc bcc printed emailed queued);
1119 $form->{ $form->{vc} } =~ s/--.*//g;
1120 $form->{type} = "credit_note";
1123 map { $form->{"select$_"} = "" } ($form->{vc}, 'currency');
1125 # map { $form->{$_} = $form->parse_amount(\%myconfig, $form->{$_}) }
1126 # qw(creditlimit creditremaining);
1128 # set new persistent ids for credit note and link previous invoice id
1129 $form->{"converted_from_invoice_id_$_"} = delete $form->{"invoice_id_$_"} for 1 .. $form->{"rowcount"};
1131 my $currency = $form->{currency};
1134 $form->{currency} = $currency;
1135 $form->{forex} = $form->check_exchangerate( \%myconfig, $form->{currency}, $form->{invdate}, 'buy');
1136 $form->{exchangerate} = $form->{forex} || '';
1138 $form->{creditremaining} -= ($form->{oldinvtotal} - $form->{ordtotal});
1140 # bei Gutschriften werden Zahlungseingänge aus Rechnung nicht übernommen
1141 for my $i (1 .. $form->{paidaccounts}) {
1142 delete $form->{"paid_$i"};
1143 delete $form->{"source_$i"};
1144 delete $form->{"memo_$i"};
1145 delete $form->{"datepaid_$i"};
1146 delete $form->{"gldate_$i"};
1147 delete $form->{"acc_trans_id_$i"};
1148 delete $form->{"AR_paid_$i"};
1150 $form->{paidaccounts} = 1;
1157 $main::lxdebug->leave_sub();
1161 $::lxdebug->enter_sub;
1163 $::auth->assert('invoice_edit');
1167 my $new_rowcount = $::form->{"rowcount"} * 1 + 1;
1168 $::form->{"project_id_${new_rowcount}"} = $::form->{"globalproject_id"};
1170 $::form->language_payment(\%::myconfig);
1172 Common::webdav_folder($::form);
1175 display_row(++$::form->{rowcount});
1178 $::lxdebug->leave_sub;
1182 $::auth->assert('invoice_edit');
1184 if (IS->delete_invoice(\%::myconfig, $::form)) {
1185 # saving the history
1186 if(!exists $::form->{addition}) {
1187 $::form->{snumbers} = 'invnumber' .'_'. $::form->{invnumber};
1188 $::form->{what_done} = 'invoice';
1189 $::form->{addition} = "DELETED";
1190 $::form->save_history;
1192 # /saving the history
1193 $::form->redirect($::locale->text('Invoice deleted!'));
1195 $::form->error($::locale->text('Cannot delete invoice!'));
1200 print update ship_to storno post_payment use_as_new credit_note
1201 delete post order preview post_and_e_mail print_and_post
1204 if ($::form->{"action_$action"}) {
1210 $::form->error($::locale->text('No action defined.'));