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 => "sales_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 $form->{employee_id} = $form->{old_employee_id} if $form->{old_employee_id};
395 $form->{salesman_id} = $form->{old_salesman_id} if $form->{old_salesman_id};
397 $form->{defaultcurrency} = $form->get_default_currency(\%myconfig);
399 $form->get_lists("taxzones" => ($form->{id} ? "ALL_TAXZONES" : "ALL_ACTIVE_TAXZONES"),
400 "currencies" => "ALL_CURRENCIES",
401 "price_factors" => "ALL_PRICE_FACTORS");
403 $form->{ALL_DEPARTMENTS} = SL::DB::Manager::Department->get_all_sorted;
406 my @old_project_ids = uniq grep { $_ } map { $_ * 1 } ($form->{"globalproject_id"}, map { $form->{"project_id_$_"} } 1..$form->{"rowcount"});
407 my @old_ids_cond = @old_project_ids ? (id => \@old_project_ids) : ();
409 if ($::instance_conf->get_customer_projects_only_in_sales) {
412 customer_id => $::form->{customer_id},
413 billable_customer_id => $::form->{customer_id},
418 and => [ active => 1, @customer_cond ],
422 $TMPL_VAR{ALL_PROJECTS} = SL::DB::Manager::Project->get_all_sorted(query => \@conditions);
423 $form->{ALL_PROJECTS} = $TMPL_VAR{ALL_PROJECTS}; # make projects available for second row drop-down in io.pl
424 $TMPL_VAR{ALL_EMPLOYEES} = SL::DB::Manager::Employee->get_all_sorted(query => [ or => [ id => $::form->{employee_id}, deleted => 0 ] ]);
425 $TMPL_VAR{ALL_SALESMEN} = SL::DB::Manager::Employee->get_all_sorted(query => [ or => [ id => $::form->{salesman_id}, deleted => 0 ] ]);
426 $TMPL_VAR{ALL_SHIPTO} = SL::DB::Manager::Shipto->get_all_sorted(query => [
427 or => [ trans_id => $::form->{"$::form->{vc}_id"} * 1, and => [ shipto_id => $::form->{shipto_id} * 1, trans_id => undef ] ]
429 $TMPL_VAR{ALL_CONTACTS} = SL::DB::Manager::Contact->get_all_sorted(query => [
431 cp_cv_id => $::form->{"$::form->{vc}_id"} * 1,
434 cp_id => $::form->{cp_id} * 1
439 # currencies and exchangerate
440 my @values = map { $_ } @{ $form->{ALL_CURRENCIES} };
441 my %labels = map { $_ => $_ } @{ $form->{ALL_CURRENCIES} };
442 $form->{currency} = $form->{defaultcurrency} unless $form->{currency};
443 $form->{show_exchangerate} = $form->{currency} ne $form->{defaultcurrency};
444 $TMPL_VAR{currencies} = NTI($::request->{cgi}->popup_menu('-name' => 'currency', '-default' => $form->{"currency"},
445 '-values' => \@values, '-labels' => \%labels,
446 '-onchange' => "document.getElementById('update_button').click();"
447 )) if scalar @values;
448 push @custom_hiddens, "forex";
449 push @custom_hiddens, "exchangerate" if $form->{forex};
451 $TMPL_VAR{creditwarning} = ($form->{creditlimit} != 0) && ($form->{creditremaining} < 0) && !$form->{update};
452 $TMPL_VAR{is_credit_remaining_negativ} = $form->{creditremaining} =~ /-/;
454 # set option selected
455 foreach my $item (qw(AR)) {
456 $form->{"select$item"} =~ s/ selected//;
457 $form->{"select$item"} =~ s/option>\Q$form->{$item}\E/option selected>$form->{$item}/;
460 $TMPL_VAR{is_type_credit_note} = $form->{type} eq "credit_note";
461 $TMPL_VAR{is_format_html} = $form->{format} eq 'html';
462 $TMPL_VAR{dateformat} = $myconfig{dateformat};
463 $TMPL_VAR{numberformat} = $myconfig{numberformat};
466 $TMPL_VAR{HIDDENS} = [qw(
467 id type queued printed emailed vc discount
468 title creditlimit creditremaining tradediscount business closedto locked shipped storno storno_id
469 max_dunning_level dunning_amount dunning_description
470 taxaccounts cursor_fokus
471 convert_from_do_ids convert_from_oe_ids convert_from_ar_ids useasnew
475 map { $_.'_rate', $_.'_description', $_.'_taxnumber' } split / /, $form->{taxaccounts}];
477 $::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));
479 $TMPL_VAR{payment_terms_obj} = get_payment_terms_for_invoice();
480 $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};
482 setup_is_action_bar();
486 print $form->parse_html_template("is/form_header", \%TMPL_VAR);
488 $main::lxdebug->leave_sub();
492 my @fields = qw(acc_trans_id gldate datepaid source memo paid AR_paid);
494 grep { $_->{paid} != 0 }
497 +{ map { ($_ => delete($::form->{"${_}_${idx}"})) } @fields }
498 } (1..$::form->{paidaccounts});
500 @payments = sort_by { DateTime->from_kivitendo($_->{datepaid}) } @payments;
502 $::form->{paidaccounts} = max scalar(@payments), 1;
504 foreach my $idx (1 .. scalar(@payments)) {
505 my $payment = $payments[$idx - 1];
506 $::form->{"${_}_${idx}"} = $payment->{$_} for @fields;
511 $main::lxdebug->enter_sub();
513 my $form = $main::form;
514 my %myconfig = %main::myconfig;
515 my $locale = $main::locale;
517 $main::auth->assert('invoice_edit');
519 $form->{invtotal} = $form->{invsubtotal};
522 $form->{rows} = max 2,
523 $form->numtextrows($form->{notes}, 26, 8),
524 $form->numtextrows($form->{intnotes}, 35, 8);
527 # tax, total and subtotal calculations
528 my ($tax, $subtotal);
529 $form->{taxaccounts_array} = [ split(/ /, $form->{taxaccounts}) ];
531 if( $form->{customer_id} && !$form->{taxincluded_changed_by_user} ) {
532 my $customer = SL::DB::Customer->load_cached($form->{customer_id});
533 $form->{taxincluded} = defined($customer->taxincluded_checked) ? $customer->taxincluded_checked : $myconfig{taxincluded_checked};
536 foreach my $item (@{ $form->{taxaccounts_array} }) {
537 if ($form->{"${item}_base"}) {
538 if ($form->{taxincluded}) {
539 $form->{"${item}_total"} = $form->round_amount( ($form->{"${item}_base"} * $form->{"${item}_rate"}
540 / (1 + $form->{"${item}_rate"})), 2);
541 $form->{"${item}_netto"} = $form->round_amount( ($form->{"${item}_base"} - $form->{"${item}_total"}), 2);
543 $form->{"${item}_total"} = $form->round_amount( $form->{"${item}_base"} * $form->{"${item}_rate"}, 2);
544 $form->{invtotal} += $form->{"${item}_total"};
549 my $grossamount = $form->{invtotal};
550 $form->{invtotal} = $form->round_amount( $form->{invtotal}, 2, 1 );
551 $form->{rounding} = $form->round_amount(
552 $form->{invtotal} - $form->round_amount($grossamount, 2),
558 $form->{follow_ups} = FU->follow_ups('trans_id' => $form->{id}, 'not_done' => 1) || [];
559 $form->{follow_ups_unfinished} = ( sum map { $_->{due} * 1 } @{ $form->{follow_ups} } ) || 0;
566 $form->{paidaccounts}++ if ($form->{"paid_$form->{paidaccounts}"});
567 $form->{paid_indices} = [ 1 .. $form->{paidaccounts} ];
569 # Standard Konto für Umlaufvermögen
570 my $accno_arap = IS->get_standard_accno_current_assets(\%myconfig, \%$form);
572 for my $i (1 .. $form->{paidaccounts}) {
573 $form->{"changeable_$i"} = 1;
574 if (SL::DB::Default->get->payments_changeable == 0) {
576 $form->{"changeable_$i"} = ($form->{"acc_trans_id_$i"})? 0 : 1;
577 } elsif (SL::DB::Default->get->payments_changeable == 2) {
579 $form->{"changeable_$i"} = (($form->{"gldate_$i"} eq '') ||
580 ($form->current_date(\%myconfig) eq $form->{"gldate_$i"}));
583 #deaktivieren von gebuchten Zahlungen ausserhalb der Bücherkontrolle, vorher prüfen ob heute eingegeben
584 if ($form->date_closed($form->{"gldate_$i"})) {
585 $form->{"changeable_$i"} = 0;
588 $form->{"selectAR_paid_$i"} = $form->{selectAR_paid};
589 if (!$form->{"AR_paid_$i"}) {
590 $form->{"selectAR_paid_$i"} =~ s/option>$accno_arap--(.*?)</option selected>$accno_arap--$1</;
592 $form->{"selectAR_paid_$i"} =~ s/option>\Q$form->{"AR_paid_$i"}\E/option selected>$form->{"AR_paid_$i"}/;
595 $totalpaid += $form->{"paid_$i"};
598 $form->{oldinvtotal} = $form->{invtotal};
600 $form->{ALL_DELIVERY_TERMS} = SL::DB::Manager::DeliveryTerm->get_all_sorted();
602 print $form->parse_html_template('is/form_footer', {
603 is_type_credit_note => ($form->{type} eq "credit_note"),
604 totalpaid => $totalpaid,
605 paid_missing => $form->{invtotal} - $totalpaid,
606 print_options => setup_sales_purchase_print_options(),
607 show_storno => $form->{id} && !$form->{storno} && !IS->has_storno(\%myconfig, $form, "ar") && !$totalpaid,
608 show_delete => ($::instance_conf->get_is_changeable == 2)
609 ? ($form->current_date(\%myconfig) eq $form->{gldate})
610 : ($::instance_conf->get_is_changeable == 1),
611 today => DateTime->today,
612 vc_obj => $form->{customer_id} ? SL::DB::Customer->load_cached($form->{customer_id}) : undef,
614 ##print $form->parse_html_template('is/_payments'); # parser
615 ##print $form->parse_html_template('webdav/_list'); # parser
617 $main::lxdebug->leave_sub();
621 $::auth->assert('invoice_edit');
623 SL::DB::Invoice->new(id => $::form->{id})->load->mark_as_paid;
625 $::form->redirect($::locale->text("Marked as paid"));
633 $main::lxdebug->enter_sub();
635 my $form = $main::form;
636 my %myconfig = %main::myconfig;
638 $main::auth->assert('invoice_edit');
640 my ($recursive_call) = @_;
642 $form->{print_and_post} = 0 if $form->{second_run};
643 my $taxincluded = $form->{taxincluded} ? "checked" : '';
646 if (($form->{previous_customer_id} || $form->{customer_id}) != $form->{customer_id}) {
647 $::form->{salesman_id} = SL::DB::Manager::Employee->current->id if exists $::form->{salesman_id};
649 IS->get_customer(\%myconfig, $form);
652 $form->{taxincluded} ||= $taxincluded;
654 if (!$form->{forex}) { # read exchangerate from input field (not hidden)
655 $form->{exchangerate} = $form->parse_amount(\%myconfig, $form->{exchangerate}) unless $recursive_call;
657 $form->{forex} = $form->check_exchangerate(\%myconfig, $form->{currency}, $form->{invdate}, 'buy');
658 $form->{exchangerate} = $form->{forex} if $form->{forex};
660 for my $i (1 .. $form->{paidaccounts}) {
661 next unless $form->{"paid_$i"};
662 map { $form->{"${_}_$i"} = $form->parse_amount(\%myconfig, $form->{"${_}_$i"}) } qw(paid exchangerate);
663 if (!$form->{"forex_$i"}) { #read exchangerate from input field (not hidden)
664 $form->{exchangerate} = $form->{"exchangerate_$i"};
666 $form->{"forex_$i"} = $form->check_exchangerate(\%myconfig, $form->{currency}, $form->{"datepaid_$i"}, 'buy');
667 $form->{"exchangerate_$i"} = $form->{"forex_$i"} if $form->{"forex_$i"};
670 my $i = $form->{rowcount};
671 my $exchangerate = $form->{exchangerate} || 1;
673 # if last row empty, check the form otherwise retrieve new item
674 if ( ($form->{"partnumber_$i"} eq "")
675 && ($form->{"description_$i"} eq "")
676 && ($form->{"partsgroup_$i"} eq "")) {
678 $form->{creditremaining} += ($form->{oldinvtotal} - $form->{oldtotalpaid});
683 IS->retrieve_item(\%myconfig, \%$form);
685 my $rows = scalar @{ $form->{item_list} };
687 $form->{"discount_$i"} = $form->parse_amount(\%myconfig, $form->{"discount_$i"}) / 100.0;
688 $form->{"discount_$i"} ||= $form->{customer_discount};
691 $form->{"qty_$i"} = $form->parse_amount(\%myconfig, $form->{"qty_$i"});
692 if( !$form->{"qty_$i"} ) {
693 $form->{"qty_$i"} = 1;
698 select_item(mode => 'IS', pre_entered_qty => $form->{"qty_$i"});
699 $::dispatcher->end_request;
703 my $sellprice = $form->parse_amount(\%myconfig, $form->{"sellprice_$i"});
705 map { $form->{item_list}[$i]{$_} =~ s/\"/"/g } qw(partnumber description unit);
706 map { $form->{"${_}_$i"} = $form->{item_list}[0]{$_} } keys %{ $form->{item_list}[0] };
708 $form->{payment_id} = $form->{"part_payment_id_$i"} if $form->{"part_payment_id_$i"} ne "";
709 $form->{"discount_$i"} = 0 if $form->{"not_discountable_$i"};
711 $form->{"marge_price_factor_$i"} = $form->{item_list}->[0]->{price_factor};
713 ($sellprice || $form->{"sellprice_$i"}) =~ /\.(\d+)/;
714 my $decimalplaces = max 2, length $1;
717 $form->{"sellprice_$i"} = $sellprice;
719 my $record = _make_record();
720 my $price_source = SL::PriceSource->new(record_item => $record->items->[$i-1], record => $record);
721 my $best_price = $price_source->best_price;
722 my $best_discount = $price_source->best_discount;
725 $::form->{"sellprice_$i"} = $best_price->price;
726 $::form->{"active_price_source_$i"} = $best_price->source;
728 if ($best_discount) {
729 $::form->{"discount_$i"} = $best_discount->discount;
730 $::form->{"active_discount_source_$i"} = $best_discount->source;
733 # if there is an exchange rate adjust sellprice
734 $form->{"sellprice_$i"} /= $exchangerate;
737 $form->{"listprice_$i"} /= $exchangerate;
739 my $amount = $form->{"sellprice_$i"} * $form->{"qty_$i"} * (1 - $form->{"discount_$i"});
740 map { $form->{"${_}_base"} = 0 } split / /, $form->{taxaccounts};
741 map { $form->{"${_}_base"} += $amount } split / /, $form->{"taxaccounts_$i"};
742 map { $amount += ($form->{"${_}_base"} * $form->{"${_}_rate"}) } split / /, $form->{"taxaccounts_$i"} if !$form->{taxincluded};
744 $form->{creditremaining} -= $amount;
746 map { $form->{"${_}_$i"} = $form->format_amount(\%myconfig, $form->{"${_}_$i"}, $decimalplaces) } qw(sellprice lastcost);
748 $form->{"qty_$i"} = $form->format_amount(\%myconfig, $form->{"qty_$i"});
749 $form->{"discount_$i"} = $form->format_amount(\%myconfig, $form->{"discount_$i"} * 100.0);
756 # ok, so this is a new part
757 # ask if it is a part or service item
759 if ( $form->{"partsgroup_$i"}
760 && ($form->{"partsnumber_$i"} eq "")
761 && ($form->{"description_$i"} eq "")) {
763 $form->{"discount_$i"} = "";
767 $form->{"id_$i"} = 0;
772 $main::lxdebug->leave_sub();
776 $main::lxdebug->enter_sub();
778 my $form = $main::form;
779 my %myconfig = %main::myconfig;
780 my $locale = $main::locale;
782 $main::auth->assert('invoice_edit');
784 $form->mtime_ischanged('ar') ;
785 my $invdate = $form->datetonum($form->{invdate}, \%myconfig);
787 $form->{defaultcurrency} = $form->get_default_currency(\%myconfig);
788 for my $i (1 .. $form->{paidaccounts}) {
789 if ($form->{"paid_$i"}) {
790 my $datepaid = $form->datetonum($form->{"datepaid_$i"}, \%myconfig);
792 $form->isblank("datepaid_$i", $locale->text('Payment date missing!'));
795 if ($form->{currency} ne $form->{defaultcurrency}) {
796 $form->{"exchangerate_$i"} = $form->{exchangerate}
797 if ($invdate == $datepaid);
798 $form->isblank("exchangerate_$i",
799 $locale->text('Exchangerate for payment missing!'));
801 $form->error($locale->text('Cannot post transaction above the maximum future booking date!'))
802 if ($form->date_max_future($form->{"datepaid_$i"}, \%myconfig));
804 #Zusätzlich noch das Buchungsdatum in die Bücherkontrolle einbeziehen
805 # (Dient zur Prüfung ob ZE oder ZA geprüft werden soll)
806 $form->error($locale->text('Cannot post payment for a closed period!'))
807 if ($form->date_closed($form->{"datepaid_$i"}) && !$form->date_closed($form->{"gldate_$i"}, \%myconfig));
811 ($form->{AR}) = split /--/, $form->{AR};
812 ($form->{AR_paid}) = split /--/, $form->{AR_paid};
814 if ( IS->post_payment(\%myconfig, \%$form) ) {
815 $form->{snumbers} = qq|invnumber_| . $form->{invnumber};
816 $form->{what_done} = 'invoice';
817 $form->{addition} = "PAYMENT POSTED";
819 $form->redirect($locale->text('Payment posted!'))
821 $form->error($locale->text('Cannot post payment!'));
824 $main::lxdebug->leave_sub();
828 $main::lxdebug->enter_sub();
830 my $form = $main::form;
831 my %myconfig = %main::myconfig;
832 my $locale = $main::locale;
834 $main::auth->assert('invoice_edit');
835 $form->mtime_ischanged('ar');
837 $form->{defaultcurrency} = $form->get_default_currency(\%myconfig);
838 $form->isblank("invdate", $locale->text('Invoice Date missing!'));
839 $form->isblank("customer_id", $locale->text('Customer missing!'));
840 $form->error($locale->text('Cannot post invoice for a closed period!'))
841 if ($form->date_closed($form->{"invdate"}, \%myconfig));
843 $form->{invnumber} =~ s/^\s*//g;
844 $form->{invnumber} =~ s/\s*$//g;
846 # if oldcustomer ne customer redo form
847 if (($form->{previous_customer_id} || $form->{customer_id}) != $form->{customer_id}) {
849 $::dispatcher->end_request;
852 if ($myconfig{mandatory_departments} && !$form->{department_id}) {
853 $form->{saved_message} = $::locale->text('You have to specify a department.');
858 if ($form->{second_run}) {
859 $form->{print_and_post} = 0;
862 remove_emptied_rows();
865 my $closedto = $form->datetonum($form->{closedto}, \%myconfig);
866 my $invdate = $form->datetonum($form->{invdate}, \%myconfig);
868 $form->error($locale->text('Cannot post transaction above the maximum future booking date!'))
869 if ($form->date_max_future($invdate, \%myconfig));
870 $form->error($locale->text('Cannot post invoice for a closed period!'))
871 if ($invdate <= $closedto);
873 $form->isblank("exchangerate", $locale->text('Exchangerate missing!'))
874 if ($form->{currency} ne $form->{defaultcurrency});
876 for my $i (1 .. $form->{paidaccounts}) {
877 if ($form->parse_amount(\%myconfig, $form->{"paid_$i"})) {
878 my $datepaid = $form->datetonum($form->{"datepaid_$i"}, \%myconfig);
880 $form->isblank("datepaid_$i", $locale->text('Payment date missing!'));
882 $form->error($locale->text('Cannot post transaction above the maximum future booking date!'))
883 if ($form->date_max_future($form->{"datepaid_$i"}, \%myconfig));
885 #Zusätzlich noch das Buchungsdatum in die Bücherkontrolle einbeziehen
886 # (Dient zur Prüfung ob ZE oder ZA geprüft werden soll)
887 $form->error($locale->text('Cannot post payment for a closed period!'))
888 if ($form->date_closed($form->{"datepaid_$i"}) && !$form->date_closed($form->{"gldate_$i"}, \%myconfig));
890 if ($form->{currency} ne $form->{defaultcurrency}) {
891 $form->{"exchangerate_$i"} = $form->{exchangerate}
892 if ($invdate == $datepaid);
893 $form->isblank("exchangerate_$i",
894 $locale->text('Exchangerate for payment missing!'));
899 ($form->{AR}) = split /--/, $form->{AR};
900 ($form->{AR_paid}) = split /--/, $form->{AR_paid};
901 $form->{storno} ||= 0;
903 $form->{label} = $form->{type} eq 'credit_note' ? $locale->text('Credit Note') : $locale->text('Invoice');
905 $form->{id} = 0 if $form->{postasnew};
907 # get new invnumber in sequence if no invnumber is given or if posasnew was requested
908 if ($form->{postasnew}) {
909 if ($form->{type} eq "credit_note") {
910 undef($form->{cnnumber});
912 undef($form->{invnumber});
918 my $terms = get_payment_terms_for_invoice();
919 $form->{duedate} = $terms->calc_date(reference_date => $form->{invdate}, due_date => $form->{duedate})->to_kivitendo if $terms;
921 # If transfer_out is requested, get rose db handle and do post and
922 # transfer out in one transaction. Otherwise just post the invoice.
923 if ($::instance_conf->get_is_transfer_out && $form->{type} ne 'credit_note' && !$form->{storno}) {
924 require SL::DB::Inventory;
925 my $rose_db = SL::DB::Inventory->new->db;
928 if (!$rose_db->with_transaction(sub {
930 if (!IS->post_invoice(\%myconfig, \%$form, $rose_db->dbh)) {
931 push @errors, $locale->text('Cannot post invoice!');
934 my $err = IS->transfer_out(\%$form, $rose_db->dbh);
936 push @errors, @{ $err };
937 die 'transfer error';
942 push @errors, $EVAL_ERROR;
943 die 'transaction error';
948 push @errors, $rose_db->error;
949 $form->error($locale->text('Cannot post invoice and/or transfer out! Error message:') . "\n" . join("\n", @errors));
952 if (!IS->post_invoice(\%myconfig, \%$form)) {
953 $form->error($locale->text('Cannot post invoice!'));
957 if(!exists $form->{addition}) {
958 $form->{snumbers} = 'invnumber' .'_'. $form->{invnumber}; # ($form->{type} eq 'credit_note' ? 'cnnumber' : 'invnumber') .'_'. $form->{invnumber};
959 $form->{what_done} = 'invoice';
960 $form->{addition} = $form->{print_and_post} ? "PRINTED AND POSTED" :
961 $form->{storno} ? "STORNO" :
966 if (!$form->{no_redirect_after_post}) {
967 $form->{action} = 'edit';
968 $form->{script} = 'is.pl';
969 $form->{callback} = build_std_url(qw(action edit id callback saved_message));
970 $form->redirect($form->{label} . " $form->{invnumber} " . $locale->text('posted!'));
973 $main::lxdebug->leave_sub();
977 $main::lxdebug->enter_sub();
979 my $form = $main::form;
981 $main::auth->assert('invoice_edit');
983 my $old_form = Form->new;
984 $form->{no_redirect_after_post} = 1;
985 $form->{print_and_post} = 1;
989 $main::lxdebug->leave_sub();
994 $main::lxdebug->enter_sub();
996 my $form = $main::form;
997 my %myconfig = %main::myconfig;
999 $main::auth->assert('invoice_edit');
1001 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)};
1002 $form->{rowcount}--;
1003 $form->{paidaccounts} = 1;
1004 $form->{invdate} = $form->current_date(\%myconfig);
1005 my $terms = get_payment_terms_for_invoice();
1006 $form->{duedate} = $terms ? $terms->calc_date(reference_date => $form->{invdate})->to_kivitendo : $form->{invdate};
1007 $form->{employee_id} = SL::DB::Manager::Employee->current->id;
1008 $form->{forex} = $form->check_exchangerate(\%myconfig, $form->{currency}, $form->{invdate}, 'buy');
1009 $form->{exchangerate} = $form->{forex} if $form->{forex};
1011 $form->{"converted_from_invoice_id_$_"} = delete $form->{"invoice_id_$_"} for 1 .. $form->{"rowcount"};
1013 $form->{useasnew} = 1;
1016 $main::lxdebug->leave_sub();
1020 $main::lxdebug->enter_sub();
1022 my $form = $main::form;
1023 my %myconfig = %main::myconfig;
1024 my $locale = $main::locale;
1026 $main::auth->assert('invoice_edit');
1028 if ($form->{storno}) {
1029 $form->error($locale->text('Cannot storno storno invoice!'));
1032 if (IS->has_storno(\%myconfig, $form, "ar")) {
1033 $form->error($locale->text("Invoice has already been storno'd!"));
1035 if ($form->datetonum($form->{invdate}, \%myconfig) <= $form->datetonum($form->{closedto}, \%myconfig)) {
1036 $form->error($locale->text('Cannot storno invoice for a closed period!'));
1039 # save the history of invoice being stornoed
1040 $form->{snumbers} = qq|invnumber_| . $form->{invnumber};
1041 $form->{what_done} = 'invoice';
1042 $form->{addition} = "STORNO";
1043 $form->save_history;
1045 map({ my $key = $_; delete($form->{$key}) unless (grep({ $key eq $_ } qw(id login password type))); } keys(%{ $form }));
1051 # Payments must not be recorded for the new storno invoice.
1052 $form->{paidaccounts} = 0;
1053 map { my $key = $_; delete $form->{$key} if grep { $key =~ /^$_/ } qw(datepaid_ gldate_ acc_trans_id_ source_ memo_ paid_ exchangerate_ AR_paid_) } keys %{ $form };
1055 # record link invoice to storno
1056 $form->{convert_from_ar_ids} = $form->{id};
1057 $form->{storno_id} = $form->{id};
1058 $form->{storno} = 1;
1060 $form->{invnumber} = "Storno zu " . $form->{invnumber};
1061 $form->{invdate} = DateTime->today->to_lxoffice;
1062 $form->{rowcount}++;
1063 # set new ids for storno invoice
1064 # set new persistent ids for storno invoice items
1065 $form->{"converted_from_invoice_id_$_"} = delete $form->{"invoice_id_$_"} for 1 .. $form->{"rowcount"};
1068 $main::lxdebug->leave_sub();
1072 $main::lxdebug->enter_sub();
1074 my $form = $main::form;
1076 $main::auth->assert('invoice_edit');
1078 $form->{preview} = 1;
1079 my $old_form = Form->new;
1080 for (keys %$form) { $old_form->{$_} = $form->{$_} }
1082 &print_form($old_form);
1083 $main::lxdebug->leave_sub();
1088 $main::lxdebug->enter_sub();
1090 my $form = $main::form;
1091 my %myconfig = %main::myconfig;
1092 my $locale = $main::locale;
1094 $main::auth->assert('invoice_edit');
1096 $form->{transdate} = $form->{invdate} = $form->current_date(\%myconfig);
1098 $form->current_date(\%myconfig, $form->{invdate}, $form->{terms} * 1);
1100 $form->{convert_from_ar_ids} = $form->{id};
1102 $form->{rowcount}--;
1105 $form->{title} = $locale->text('Add Credit Note');
1106 $form->{script} = 'is.pl';
1108 # Bei Gutschriften bezug zur Rechnungsnummer
1109 $form->{invnumber_for_credit_note} = $form->{invnumber};
1110 # bo creates the id, reset it
1111 map { delete $form->{$_} }
1112 qw(id invnumber subject message cc bcc printed emailed queued);
1113 $form->{ $form->{vc} } =~ s/--.*//g;
1114 $form->{type} = "credit_note";
1117 map { $form->{"select$_"} = "" } ($form->{vc}, 'currency');
1119 # map { $form->{$_} = $form->parse_amount(\%myconfig, $form->{$_}) }
1120 # qw(creditlimit creditremaining);
1122 # set new persistent ids for credit note and link previous invoice id
1123 $form->{"converted_from_invoice_id_$_"} = delete $form->{"invoice_id_$_"} for 1 .. $form->{"rowcount"};
1125 my $currency = $form->{currency};
1128 $form->{currency} = $currency;
1129 $form->{forex} = $form->check_exchangerate( \%myconfig, $form->{currency}, $form->{invdate}, 'buy');
1130 $form->{exchangerate} = $form->{forex} || '';
1132 $form->{creditremaining} -= ($form->{oldinvtotal} - $form->{ordtotal});
1134 # bei Gutschriften werden Zahlungseingänge aus Rechnung nicht übernommen
1135 for my $i (1 .. $form->{paidaccounts}) {
1136 delete $form->{"paid_$i"};
1137 delete $form->{"source_$i"};
1138 delete $form->{"memo_$i"};
1139 delete $form->{"datepaid_$i"};
1140 delete $form->{"gldate_$i"};
1141 delete $form->{"acc_trans_id_$i"};
1142 delete $form->{"AR_paid_$i"};
1144 $form->{paidaccounts} = 1;
1151 $main::lxdebug->leave_sub();
1155 $::lxdebug->enter_sub;
1157 $::auth->assert('invoice_edit');
1161 my $new_rowcount = $::form->{"rowcount"} * 1 + 1;
1162 $::form->{"project_id_${new_rowcount}"} = $::form->{"globalproject_id"};
1164 $::form->language_payment(\%::myconfig);
1166 Common::webdav_folder($::form);
1169 display_row(++$::form->{rowcount});
1172 $::lxdebug->leave_sub;
1176 $::auth->assert('invoice_edit');
1178 if (IS->delete_invoice(\%::myconfig, $::form)) {
1179 # saving the history
1180 if(!exists $::form->{addition}) {
1181 $::form->{snumbers} = 'invnumber' .'_'. $::form->{invnumber};
1182 $::form->{what_done} = 'invoice';
1183 $::form->{addition} = "DELETED";
1184 $::form->save_history;
1186 # /saving the history
1187 $::form->redirect($::locale->text('Invoice deleted!'));
1189 $::form->error($::locale->text('Cannot delete invoice!'));
1194 print update ship_to storno post_payment use_as_new credit_note
1195 delete post order preview post_and_e_mail print_and_post
1198 if ($::form->{"action_$action"}) {
1204 $::form->error($::locale->text('No action defined.'));