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 received module
33 #======================================================================
36 use SL::Helper::Flash qw(flash_later);
37 use SL::Helper::UserPreferences::DisplayPreferences;
40 use SL::DB::BankTransactionAccTrans;
42 use SL::DB::Department;
44 use SL::DB::PurchaseInvoice;
46 use List::MoreUtils qw(uniq);
47 use List::Util qw(max sum);
48 use List::UtilsBy qw(sort_by);
50 require "bin/mozilla/io.pl";
51 require "bin/mozilla/common.pl";
59 sub _may_view_or_edit_this_invoice {
60 return 1 if $::auth->assert('ap_transactions', 1); # may edit all invoices
61 return 0 if !$::form->{id}; # creating new invoices isn't allowed without invoice_edit
62 return 1 if $::auth->assert('purchase_invoice_view', 1); # viewing is allowed with this right
63 return 0 if !$::form->{globalproject_id}; # existing records without a project ID are not allowed
64 return SL::DB::Project->new(id => $::form->{globalproject_id})->load->may_employee_view_project_invoices(SL::DB::Manager::Employee->current);
68 my $cache = $::request->cache('ap.pl::_assert_access');
70 $cache->{_may_view_or_edit_this_invoice} = _may_view_or_edit_this_invoice() if !exists $cache->{_may_view_or_edit_this_invoice};
71 $::form->show_generic_error($::locale->text("You do not have the permissions to access this function.")) if ! $cache->{_may_view_or_edit_this_invoice};
75 $main::lxdebug->enter_sub();
77 my $form = $main::form;
78 my $locale = $main::locale;
80 $main::auth->assert('vendor_invoice_edit');
82 if (!$::instance_conf->get_allow_new_purchase_invoice) {
83 $::form->show_generic_error($::locale->text("You do not have the permissions to access this function."));
86 $form->{show_details} = $::myconfig{show_form_details};
88 $form->{title} = $locale->text('Record Vendor Invoice');
94 $main::lxdebug->leave_sub();
98 $main::lxdebug->enter_sub();
100 # Delay access check to after the invoice's been loaded in
101 # "create_links" so that project-specific invoice rights can be
104 my $form = $main::form;
105 my $locale = $main::locale;
107 $form->{show_details} = $::myconfig{show_form_details};
109 # show history button
110 $form->{javascript} = qq|<script type=text/javascript src=js/show_history.js></script>|;
111 #/show hhistory button
113 $form->{title} = $locale->text('Edit Vendor Invoice');
119 $main::lxdebug->leave_sub();
123 $main::lxdebug->enter_sub();
125 # Delay access check to after the invoice's been loaded so that
126 # project-specific invoice rights can be evaluated.
128 my $form = $main::form;
129 my %myconfig = %main::myconfig;
131 $form->{vc} = 'vendor';
134 $form->create_links("AP", \%myconfig, "vendor");
138 $form->backup_vars(qw(payment_id language_id taxzone_id
139 currency delivery_term_id intnotes cp_id));
141 IR->get_vendor(\%myconfig, \%$form);
142 IR->retrieve_invoice(\%myconfig, \%$form);
144 $form->restore_vars(qw(payment_id language_id taxzone_id
145 currency delivery_term_id intnotes cp_id));
147 my @curr = $form->get_all_currencies();
148 map { $form->{selectcurrency} .= "<option>$_\n" } @curr;
151 $form->{forex} = $form->{exchangerate};
152 my $exchangerate = ($form->{exchangerate}) ? $form->{exchangerate} : 1;
154 foreach my $key (keys %{ $form->{AP_links} }) {
156 foreach my $ref (@{ $form->{AP_links}{$key} }) {
157 $form->{"select$key"} .= "<option>$ref->{accno}--$ref->{description}</option>";
160 next unless $form->{acc_trans}{$key};
162 if ($key eq "AP_paid") {
163 for my $i (1 .. scalar @{ $form->{acc_trans}{$key} }) {
164 $form->{"AP_paid_$i"} =
165 "$form->{acc_trans}{$key}->[$i-1]->{accno}--$form->{acc_trans}{$key}->[$i-1]->{description}";
167 $form->{"acc_trans_id_$i"} = $form->{acc_trans}{$key}->[$i - 1]->{acc_trans_id};
169 $form->{"paid_$i"} = $form->{acc_trans}{$key}->[$i - 1]->{amount};
170 $form->{"datepaid_$i"} =
171 $form->{acc_trans}{$key}->[$i - 1]->{transdate};
172 $form->{"gldate_$i"} = $form->{acc_trans}{$key}->[$i - 1]->{gldate};
173 $form->{"forex_$i"} = $form->{"exchangerate_$i"} =
174 $form->{acc_trans}{$key}->[$i - 1]->{exchangerate};
175 $form->{"source_$i"} = $form->{acc_trans}{$key}->[$i - 1]->{source};
176 $form->{"memo_$i"} = $form->{acc_trans}{$key}->[$i - 1]->{memo};
178 $form->{paidaccounts} = $i;
182 "$form->{acc_trans}{$key}->[0]->{accno}--$form->{acc_trans}{$key}->[0]->{description}";
187 $form->{paidaccounts} = 1 unless (exists $form->{paidaccounts});
189 $form->{AP} = $form->{AP_1} unless $form->{id};
192 ($form->datetonum($form->{invdate}, \%myconfig) <=
193 $form->datetonum($form->{closedto}, \%myconfig));
195 $main::lxdebug->leave_sub();
198 sub prepare_invoice {
199 $main::lxdebug->enter_sub();
203 my $form = $main::form;
204 my %myconfig = %main::myconfig;
206 $form->{type} = "purchase_invoice";
210 map { $form->{$_} =~ s/\"/"/g } qw(invnumber ordnumber quonumber);
213 foreach my $ref (@{ $form->{invoice_details} }) {
215 map { $form->{"${_}_$i"} = $ref->{$_} } keys %{$ref};
216 # übernommen aus is.pl Fix für Bug 1642. Nebenwirkungen? jb 12.5.2011
217 # getestet: Lieferantenauftrag -> Rechnung i.O.
218 # Lieferantenauftrag -> Lieferschein -> Rechnung i.O.
219 # Werte: 20% (Lieferantenrabatt), 12,4% individuell und 0,4 individuell s.a.
220 # Screenshot zu Bug 1642
221 $form->{"discount_$i"} = $form->format_amount(\%myconfig, $form->{"discount_$i"} * 100);
223 my ($dec) = ($form->{"sellprice_$i"} =~ /\.(\d+)/);
225 my $decimalplaces = ($dec > 2) ? $dec : 2;
227 $form->{"sellprice_$i"} =
228 $form->format_amount(\%myconfig, $form->{"sellprice_$i"},
231 (my $dec_qty) = ($form->{"qty_$i"} =~ /\.(\d+)/);
232 $dec_qty = length $dec_qty;
235 $form->format_amount(\%myconfig, ($form->{"qty_$i"} * -1), $dec_qty);
237 $form->{rowcount} = $i;
241 $main::lxdebug->leave_sub();
244 sub setup_ir_action_bar {
246 my $change_never = $::instance_conf->get_ir_changeable == 0;
247 my $change_on_same_day_only = $::instance_conf->get_ir_changeable == 2 && ($form->current_date(\%::myconfig) ne $form->{gldate});
248 my $has_storno = ($::form->{storno} && !$::form->{storno_id});
249 my $payments_balanced = ($::form->{oldtotalpaid} == 0);
250 my $may_edit_create = $::auth->assert('vendor_invoice_edit', 1);
252 my $has_sepa_exports;
254 my $invoice = SL::DB::Manager::PurchaseInvoice->find_by(id => $form->{id});
255 $has_sepa_exports = 1 if ($invoice->find_sepa_export_items()->[0]);
258 my $is_linked_bank_transaction;
260 && SL::DB::Default->get->payments_changeable != 0
261 && SL::DB::Manager::BankTransactionAccTrans->find_by(ap_id => $::form->{id})) {
263 $is_linked_bank_transaction = 1;
266 my $create_post_action = sub {
268 # $_[1]: after_action
271 submit => [ '#form', { action => "post", after_action => $_[1] } ],
272 checks => [ 'kivi.validate_form' ],
273 checks => [ 'kivi.validate_form', 'kivi.AP.check_fields_before_posting', 'kivi.AP.check_duplicate_invnumber' ],
274 disabled => !$may_edit_create ? t8('You must not change this invoice.')
275 : $form->{locked} ? t8('The billing period has already been locked.')
276 : $form->{storno} ? t8('A canceled invoice cannot be posted.')
277 : ($form->{id} && $change_never) ? t8('Changing invoices has been disabled in the configuration.')
278 : ($form->{id} && $change_on_same_day_only) ? t8('Invoices can only be changed on the day they are posted.')
279 : $is_linked_bank_transaction ? t8('This transaction is linked with a bank transaction. Please undo and redo the bank transaction booking if needed.')
285 if ($::instance_conf->get_ir_add_doc && $::instance_conf->get_doc_storage) {
286 @post_entries = ( $create_post_action->(t8('Post'), 'doc-tab') );
287 } elsif ($::instance_conf->get_doc_storage) {
288 @post_entries = ( $create_post_action->(t8('Post')),
289 $create_post_action->(t8('Post and upload document'), 'doc-tab') );
291 @post_entries = ( $create_post_action->(t8('Post')) );
294 for my $bar ($::request->layout->get('actionbar')) {
298 submit => [ '#form', { action => "update" } ],
299 id => 'update_button',
300 accesskey => 'enter',
301 disabled => !$may_edit_create ? t8('You must not change this invoice.') : undef,
307 submit => [ '#form', { action => "post_payment" } ],
308 checks => [ 'kivi.validate_form' ],
309 disabled => !$may_edit_create ? t8('You must not change this invoice.')
310 : !$form->{id} ? t8('This invoice has not been posted yet.')
311 : $is_linked_bank_transaction ? t8('This transaction is linked with a bank transaction. Please undo and redo the bank transaction booking if needed.')
316 submit => [ '#form', { action => "mark_as_paid" } ],
317 checks => [ 'kivi.validate_form' ],
318 confirm => t8('This will remove the invoice from showing as unpaid even if the unpaid amount does not match the amount. Proceed?'),
319 disabled => !$may_edit_create ? t8('You must not change this invoice.')
320 : !$form->{id} ? t8('This invoice has not been posted yet.')
322 only_if => $::instance_conf->get_ir_show_mark_as_paid,
324 ], # end of combobox "Post"
327 action => [ t8('Storno'),
328 submit => [ '#form', { action => "storno" } ],
329 checks => [ 'kivi.validate_form' ],
330 confirm => t8('Do you really want to cancel this invoice?'),
331 disabled => !$may_edit_create ? t8('You must not change this invoice.')
332 : !$form->{id} ? t8('This invoice has not been posted yet.')
333 : $has_sepa_exports ? t8('This invoice has been linked with a sepa export, undo this first.')
334 : !$payments_balanced ? t8('Cancelling is disallowed. Either undo or balance the current payments until the open amount matches the invoice amount')
337 action => [ t8('Delete'),
338 submit => [ '#form', { action => "delete" } ],
339 checks => [ 'kivi.validate_form' ],
340 confirm => t8('Do you really want to delete this object?'),
341 disabled => !$may_edit_create ? t8('You must not change this invoice.')
342 : !$form->{id} ? t8('This invoice has not been posted yet.')
343 : $form->{locked} ? t8('The billing period has already been locked.')
344 : $change_never ? t8('Changing invoices has been disabled in the configuration.')
345 : $change_on_same_day_only ? t8('Invoices can only be changed on the day they are posted.')
346 : $has_sepa_exports ? t8('This invoice has been linked with a sepa export, undo this first.')
347 : $has_storno ? t8('Can only delete the "Storno zu" part of the cancellation pair.')
348 : $is_linked_bank_transaction ? t8('This transaction is linked with a bank transaction. Please undo and redo the bank transaction booking if needed.')
351 ], # end of combobox "Storno"
356 action => [ t8('Workflow') ],
359 submit => [ '#form', { action => "use_as_new" } ],
360 checks => [ 'kivi.validate_form' ],
361 disabled => !$may_edit_create ? t8('You must not change this invoice.')
362 : !$form->{id} ? t8('This invoice has not been posted yet.')
365 ], # end of combobox "Workflow"
368 action => [ t8('more') ],
371 call => [ 'set_history_window', $::form->{id} * 1, 'glid' ],
372 disabled => !$form->{id} ? t8('This invoice has not been posted yet.') : undef,
376 call => [ 'follow_up_window' ],
377 disabled => !$form->{id} ? t8('This invoice has not been posted yet.') : undef,
381 call => [ 'kivi.Draft.popup', 'ir', 'invoice', $::form->{draft_id}, $::form->{draft_description} ],
382 disabled => !$may_edit_create ? t8('You must not change this invoice.')
383 : $form->{id} ? t8('This invoice has already been posted.')
384 : $form->{locked} ? t8('The billing period has already been locked.')
387 ], # end of combobox "more"
390 $::request->layout->add_javascripts('kivi.Validator.js', 'kivi.AP.js');
395 $main::lxdebug->enter_sub();
399 my $form = $main::form;
400 my %myconfig = %main::myconfig;
401 my $locale = $main::locale;
402 my $cgi = $::request->{cgi};
407 $TMPL_VAR{invoice_obj} = SL::DB::PurchaseInvoice->load_cached($form->{id}) if $form->{id};
408 $TMPL_VAR{vendor_obj} = SL::DB::Vendor->load_cached($form->{vendor_id}) if $form->{vendor_id};
409 my $current_employee = SL::DB::Manager::Employee->current;
410 $form->{employee_id} = $form->{old_employee_id} if $form->{old_employee_id};
411 $form->{salesman_id} = $form->{old_salesman_id} if $form->{old_salesman_id};
412 $form->{employee_id} ||= $current_employee->id;
413 $form->{salesman_id} ||= $current_employee->id;
415 $form->{defaultcurrency} = $form->get_default_currency(\%myconfig);
417 my @old_project_ids = uniq grep { $_ } map { $_ * 1 } ($form->{"globalproject_id"}, map { $form->{"project_id_$_"} } 1..$form->{"rowcount"});
418 my @conditions = @old_project_ids ? (id => \@old_project_ids) : ();
419 $TMPL_VAR{ALL_PROJECTS} = SL::DB::Manager::Project->get_all_sorted(query => [ or => [ active => 1, @conditions ]]);
420 $form->{ALL_PROJECTS} = $TMPL_VAR{ALL_PROJECTS}; # make projects available for second row drop-down in io.pl
422 $form->get_lists("taxzones" => ($form->{id} ? "ALL_TAXZONES" : "ALL_ACTIVE_TAXZONES"),
423 "currencies" => "ALL_CURRENCIES",
424 "price_factors" => "ALL_PRICE_FACTORS");
426 $TMPL_VAR{ALL_DEPARTMENTS} = SL::DB::Manager::Department->get_all_sorted;
427 $TMPL_VAR{ALL_EMPLOYEES} = SL::DB::Manager::Employee->get_all_sorted(query => [ or => [ id => $::form->{employee_id}, deleted => 0 ] ]);
428 $TMPL_VAR{ALL_CONTACTS} = SL::DB::Manager::Contact->get_all_sorted(query => [
430 cp_cv_id => $::form->{"$::form->{vc}_id"} * 1,
433 cp_id => $::form->{cp_id} * 1
438 # currencies and exchangerate
439 my @values = map { $_ } @{ $form->{ALL_CURRENCIES} };
440 my %labels = map { $_ => $_ } @{ $form->{ALL_CURRENCIES} };
441 $form->{currency} = $form->{defaultcurrency} unless $form->{currency};
442 # show_exchangerate is also later needed in another template
443 $form->{show_exchangerate} = $form->{currency} ne $form->{defaultcurrency};
444 $TMPL_VAR{currencies} = NTI($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(AP)) {
456 $form->{"select$item"} =~ s/ selected//;
457 $form->{"select$item"} =~ s/option>\Q$form->{$item}\E/option selected>$form->{$item}/;
460 $TMPL_VAR{is_format_html} = $form->{format} eq 'html';
461 $TMPL_VAR{dateformat} = $myconfig{dateformat};
462 $TMPL_VAR{numberformat} = $myconfig{numberformat};
463 $TMPL_VAR{longdescription_dialog_size_percentage} = SL::Helper::UserPreferences::DisplayPreferences->new()->get_longdescription_dialog_size_percentage();
466 $TMPL_VAR{HIDDENS} = [qw(
467 id type queued printed emailed title vc discount
468 title creditlimit creditremaining tradediscount business closedto locked shipped storno storno_id
469 max_dunning_level dunning_amount
470 shiptoname shiptostreet shiptozipcode shiptocity shiptocountry shiptogln shiptocontact shiptophone shiptofax
471 shiptoemail shiptodepartment_1 shiptodepartment_2 message email subject cc bcc taxaccounts cursor_fokus
472 convert_from_do_ids convert_from_oe_ids convert_from_ap_ids show_details gldate useasnew
474 map { $_.'_rate', $_.'_description', $_.'_taxnumber', $_.'_tax_id' } split / /, $form->{taxaccounts}];
476 $TMPL_VAR{payment_terms_obj} = get_payment_terms_for_invoice();
477 $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};
479 $::request->{layout}->use_javascript(map { "${_}.js" } qw(kivi.Draft kivi.File kivi.SalesPurchase kivi.Part kivi.CustomerVendor kivi.Validator ckeditor/ckeditor ckeditor/adapters/jquery kivi.io autocomplete_project client_js));
481 setup_ir_action_bar();
485 print $form->parse_html_template("ir/form_header", \%TMPL_VAR);
487 $main::lxdebug->leave_sub();
491 my @fields = qw(acc_trans_id gldate datepaid source memo paid AP_paid);
493 grep { $_->{paid} != 0 }
496 +{ map { ($_ => delete($::form->{"${_}_${idx}"})) } @fields }
497 } (1..$::form->{paidaccounts});
499 @payments = sort_by { DateTime->from_kivitendo($_->{datepaid}) } @payments;
501 $::form->{paidaccounts} = max scalar(@payments), 1;
503 foreach my $idx (1 .. scalar(@payments)) {
504 my $payment = $payments[$idx - 1];
505 $::form->{"${_}_${idx}"} = $payment->{$_} for @fields;
510 $main::lxdebug->enter_sub();
514 my $form = $main::form;
515 my %myconfig = %main::myconfig;
516 my $locale = $main::locale;
518 $form->{invtotal} = $form->{invsubtotal};
519 $form->{oldinvtotal} = $form->{invtotal};
521 # tax, total and subtotal calculations
522 my ($tax, $subtotal);
523 $form->{taxaccounts_array} = [ split / /, $form->{taxaccounts} ];
525 foreach my $item (@{ $form->{taxaccounts_array} }) {
526 if ($form->{"${item}_base"}) {
527 if ($form->{taxincluded}) {
528 $form->{"${item}_total"} = $form->round_amount( ($form->{"${item}_base"} * $form->{"${item}_rate"}
529 / (1 + $form->{"${item}_rate"})), 2);
530 $form->{"${item}_netto"} = $form->round_amount( ($form->{"${item}_base"} - $form->{"${item}_total"}), 2);
532 $form->{"${item}_total"} = $form->round_amount( $form->{"${item}_base"} * $form->{"${item}_rate"}, 2);
533 $form->{invtotal} += $form->{"${item}_total"};
540 $form->{follow_ups} = FU->follow_ups('trans_id' => $form->{id}, 'not_done' => 1) || [];
541 $form->{follow_ups_unfinished} = ( sum map { $_->{due} * 1 } @{ $form->{follow_ups} } ) || 0;
548 $form->{paidaccounts}++ if ($form->{"paid_$form->{paidaccounts}"});
549 $form->{paid_indices} = [ 1 .. $form->{paidaccounts} ];
551 # Standard Konto für Umlaufvermögen
552 my $accno_arap = IS->get_standard_accno_current_assets(\%myconfig, \%$form);
554 for my $i (1 .. $form->{paidaccounts}) {
555 $form->{"changeable_$i"} = 1;
556 if (SL::DB::Default->get->payments_changeable == 0) {
558 $form->{"changeable_$i"} = ($form->{"acc_trans_id_$i"})? 0 : 1;
559 } elsif (SL::DB::Default->get->payments_changeable == 2) {
561 $form->{"changeable_$i"} = (($form->{"gldate_$i"} eq '') ||
562 ($form->current_date(\%myconfig) eq $form->{"gldate_$i"}));
565 $form->error($locale->text('Cannot post transaction above the maximum future booking date!'))
566 if ($form->date_max_future($form->{"datepaid_$i"}, \%myconfig));
568 #deaktivieren von Zahlungen ausserhalb der Bücherkontrolle
569 if ($form->date_closed($form->{"gldate_$i"})) {
570 $form->{"changeable_$i"} = 0;
573 $form->{"selectAP_paid_$i"} = $form->{selectAP_paid};
574 if (!$form->{"AP_paid_$i"}) {
575 $form->{"selectAP_paid_$i"} =~ s/option>$accno_arap--(.*?)>/option selected>$accno_arap--$1>/;
577 $form->{"selectAP_paid_$i"} =~ s/option>\Q$form->{"AP_paid_$i"}\E/option selected>$form->{"AP_paid_$i"}/;
580 $totalpaid += $form->{"paid_$i"};
583 $form->{ALL_DELIVERY_TERMS} = SL::DB::Manager::DeliveryTerm->get_all_sorted();
585 print $form->parse_html_template('ir/form_footer', {
586 totalpaid => $totalpaid,
587 paid_missing => $form->{invtotal} - $totalpaid,
588 show_storno => $form->{id} && !$form->{storno} && !IS->has_storno(\%myconfig, $form, "ap") && !$totalpaid,
589 show_delete => ($::instance_conf->get_ir_changeable == 2)
590 ? ($form->current_date(\%myconfig) eq $form->{gldate})
591 : ($::instance_conf->get_ir_changeable == 1),
592 today => DateTime->today,
594 ##print $form->parse_html_template('ir/_payments'); # parser
595 ##print $form->parse_html_template('webdav/_list'); # parser
597 $main::lxdebug->leave_sub();
601 $::auth->assert('vendor_invoice_edit');
603 SL::DB::PurchaseInvoice->new(id => $::form->{id})->load->mark_as_paid;
605 $::form->redirect($::locale->text("Marked as paid"));
613 $main::lxdebug->enter_sub();
615 my $form = $main::form;
616 my %myconfig = %main::myconfig;
618 $main::auth->assert('vendor_invoice_edit');
620 if (($form->{previous_vendor_id} || $form->{vendor_id}) != $form->{vendor_id}) {
621 IR->get_vendor(\%myconfig, $form);
624 if (!$form->{forex}) { # read exchangerate from input field (not hidden)
625 $form->{exchangerate} = $form->parse_amount(\%myconfig, $form->{exchangerate});
627 $form->{forex} = $form->check_exchangerate(\%myconfig, $form->{currency}, $form->{invdate}, 'sell');
628 $form->{exchangerate} = $form->{forex} if $form->{forex};
630 for my $i (1 .. $form->{paidaccounts}) {
631 next unless $form->{"paid_$i"};
632 map { $form->{"${_}_$i"} = $form->parse_amount(\%myconfig, $form->{"${_}_$i"}) } qw(paid exchangerate);
633 $form->{"forex_$i"} = $form->check_exchangerate(\%myconfig, $form->{currency}, $form->{"datepaid_$i"}, 'sell');
634 $form->{"exchangerate_$i"} = $form->{"forex_$i"} if $form->{"forex_$i"};
637 my $i = $form->{rowcount};
638 my $exchangerate = ($form->{exchangerate} * 1) || 1;
640 if ( ($form->{"partnumber_$i"} eq "")
641 && ($form->{"description_$i"} eq "")
642 && ($form->{"partsgroup_$i"} eq "")) {
643 $form->{creditremaining} += ($form->{oldinvtotal} - $form->{oldtotalpaid});
648 IR->retrieve_item(\%myconfig, \%$form);
650 my $rows = scalar @{ $form->{item_list} };
652 $form->{"discount_$i"} = $form->parse_amount(\%myconfig, $form->{"discount_$i"}) / 100.0;
653 $form->{"discount_$i"} ||= $form->{vendor_discount};
656 $form->{"qty_$i"} = $form->parse_amount(\%myconfig, $form->{"qty_$i"});
657 if( !$form->{"qty_$i"} ) {
658 $form->{"qty_$i"} = 1;
663 select_item(mode => 'IR', pre_entered_qty => $form->{"qty_$i"});
664 $::dispatcher->end_request;
668 # override sellprice if there is one entered
669 my $sellprice = $form->parse_amount(\%myconfig, $form->{"sellprice_$i"});
671 map { $form->{item_list}[$i]{$_} =~ s/\"/"/g } qw(partnumber description unit);
672 map { $form->{"${_}_$i"} = $form->{item_list}[0]{$_} } keys %{ $form->{item_list}[0] };
674 $form->{"marge_price_factor_$i"} = $form->{item_list}->[0]->{price_factor};
676 ($sellprice || $form->{"sellprice_$i"}) =~ /\.(\d+)/;
677 my $dec_qty = length $1;
678 my $decimalplaces = max 2, $dec_qty;
681 $form->{"sellprice_$i"} = $sellprice;
683 my $record = _make_record();
684 my $price_source = SL::PriceSource->new(record_item => $record->items->[$i-1], record => $record);
685 my $best_price = $price_source->best_price;
686 my $best_discount = $price_source->best_discount;
689 $::form->{"sellprice_$i"} = $best_price->price;
690 $::form->{"active_price_source_$i"} = $best_price->source;
692 if ($best_discount) {
693 $::form->{"discount_$i"} = $best_discount->discount;
694 $::form->{"active_discount_source_$i"} = $best_discount->source;
697 # if there is an exchange rate adjust sellprice
698 $form->{"sellprice_$i"} /= $exchangerate;
701 my $amount = $form->{"sellprice_$i"} * $form->{"qty_$i"} * (1 - $form->{"discount_$i"});
702 $form->{creditremaining} -= $amount;
703 $form->{"sellprice_$i"} = $form->format_amount(\%myconfig, $form->{"sellprice_$i"}, $decimalplaces);
704 $form->{"qty_$i"} = $form->format_amount(\%myconfig, $form->{"qty_$i"}, $dec_qty);
705 $form->{"discount_$i"} = $form->format_amount(\%myconfig, $form->{"discount_$i"} * 100.0);
712 # ok, so this is a new part
713 # ask if it is a part or service item
715 if ( $form->{"partsgroup_$i"}
716 && ($form->{"partsnumber_$i"} eq "")
717 && ($form->{"description_$i"} eq "")) {
719 $form->{"discount_$i"} = "";
723 $form->{"id_$i"} = 0;
728 $main::lxdebug->leave_sub();
732 $main::lxdebug->enter_sub();
734 my $form = $main::form;
735 my %myconfig = %main::myconfig;
736 my $locale = $main::locale;
738 $main::auth->assert('vendor_invoice_edit');
740 if ($form->{storno}) {
741 $form->error($locale->text('Cannot storno storno invoice!'));
744 if (IS->has_storno(\%myconfig, $form, "ap")) {
745 $form->error($locale->text("Invoice has already been storno'd!"));
748 $form->error($locale->text('Cannot post storno for a closed period!'))
749 if ( $form->date_closed($form->{invdate}, \%myconfig));
751 my $employee_id = $form->{employee_id};
756 # Payments must not be recorded for the new storno invoice.
757 $form->{paidaccounts} = 0;
758 map { my $key = $_; delete $form->{$key} if grep { $key =~ /^$_/ } qw(datepaid_ gldate_ acc_trans_id_ source_ memo_ paid_ exchangerate_ AR_paid_) } keys %{ $form };
759 # set new ids for storno invoice
760 # set new persistent ids for storno invoice items
761 $form->{"converted_from_invoice_id_$_"} = delete $form->{"invoice_id_$_"} for 1 .. $form->{"rowcount"};
764 if(!exists $form->{addition} && $form->{id} ne "") {
765 $form->{snumbers} = qq|invnumber_| . $form->{invnumber};
766 $form->{what_done} = "invoice";
767 $form->{addition} = "CANCELED";
770 # /saving the history
772 # record link invoice to storno
773 $form->{convert_from_ap_ids} = $form->{id};
774 $form->{storno_id} = $form->{id};
777 $form->{invnumber} = "Storno zu " . $form->{invnumber};
779 $form->{employee_id} = $employee_id;
781 $main::lxdebug->leave_sub();
786 $main::lxdebug->enter_sub();
788 my $form = $main::form;
789 my %myconfig = %main::myconfig;
791 $main::auth->assert('vendor_invoice_edit');
793 map { delete $form->{$_} } qw(printed emailed queued invnumber invdate deliverydate id datepaid_1 gldate_1 acc_trans_id_1 source_1 memo_1 paid_1 exchangerate_1 AP_paid_1 storno);
794 $form->{paidaccounts} = 1;
796 $form->{invdate} = $form->current_date(\%myconfig);
798 $form->{"converted_from_invoice_id_$_"} = delete $form->{"invoice_id_$_"} for 1 .. $form->{"rowcount"};
800 $form->{useasnew} = 1;
803 $main::lxdebug->leave_sub();
807 $main::lxdebug->enter_sub();
809 my $form = $main::form;
810 my %myconfig = %main::myconfig;
811 my $locale = $main::locale;
813 $main::auth->assert('vendor_invoice_edit');
815 $form->mtime_ischanged('ap') ;
816 $form->{defaultcurrency} = $form->get_default_currency(\%myconfig);
817 for my $i (1 .. $form->{paidaccounts}) {
818 if ($form->{"paid_$i"}) {
819 my $datepaid = $form->datetonum($form->{"datepaid_$i"}, \%myconfig);
821 $form->isblank("datepaid_$i", $locale->text('Payment date missing!'));
823 $form->error($locale->text('Cannot post transaction above the maximum future booking date!'))
824 if ($form->date_max_future($form->{"datepaid_$i"}, \%myconfig));
826 #Zusätzlich noch das Buchungsdatum in die Bücherkontrolle einbeziehen
827 # (Dient zur Prüfung ob ZE oder ZA geprüft werden soll)
828 $form->error($locale->text('Cannot post payment for a closed period!'))
829 if ($form->date_closed($form->{"datepaid_$i"}) && !$form->date_closed($form->{"gldate_$i"}, \%myconfig));
831 if ($form->{currency} ne $form->{defaultcurrency}) {
832 # $form->{"exchangerate_$i"} = $form->{exchangerate} if ($invdate == $datepaid); # invdate isn't set here
833 $form->isblank("exchangerate_$i", $locale->text('Exchangerate for payment missing!'));
838 ($form->{AP}) = split /--/, $form->{AP};
839 ($form->{AP_paid}) = split /--/, $form->{AP_paid};
840 if (IR->post_payment(\%myconfig, \%$form)){
841 if (!exists $form->{addition} && $form->{id} ne "") {
843 $form->{snumbers} = qq|invnumber_| . $form->{invnumber};
844 $form->{addition} = "PAYMENT POSTED";
845 $form->{what_done} = "invoice";
847 # /saving the history
850 $form->redirect($locale->text('Payment posted!'));
853 $form->error($locale->text('Cannot post payment!'));
855 $main::lxdebug->leave_sub();
859 my $form = $main::form;
861 my @dates = sort { $b->[1] cmp $a->[1] }
862 map { [ $_, $main::locale->reformat_date(\%main::myconfig, $_, 'yyyy-mm-dd') ] }
864 map { $form->{"datepaid_${_}"} }
865 (1..$form->{rowcount});
867 return @dates ? $dates[0]->[0] : undef;
872 $main::lxdebug->enter_sub();
874 my $form = $main::form;
875 my %myconfig = %main::myconfig;
876 my $locale = $main::locale;
878 $main::auth->assert('vendor_invoice_edit');
880 $form->mtime_ischanged('ap');
881 $form->{defaultcurrency} = $form->get_default_currency(\%myconfig);
883 $form->isblank("invdate", $locale->text('Invoice Date missing!'));
884 $form->isblank("vendor_id", $locale->text('Vendor missing!'));
885 $form->isblank("invnumber", $locale->text('Invnumber missing!'));
887 $form->{invnumber} =~ s/^\s*//g;
888 $form->{invnumber} =~ s/\s*$//g;
890 # if the vendor changed get new values
891 if (($form->{previous_vendor_id} || $form->{vendor_id}) != $form->{vendor_id}) {
893 $::dispatcher->end_request;
896 if ($myconfig{mandatory_departments} && !$form->{department_id}) {
897 $form->{saved_message} = $::locale->text('You have to specify a department.');
902 remove_emptied_rows();
905 my $closedto = $form->datetonum($form->{closedto}, \%myconfig);
906 my $invdate = $form->datetonum($form->{invdate}, \%myconfig);
907 my $max_datepaid = _max_datepaid();
909 $form->error($locale->text('Cannot post transaction above the maximum future booking date!'))
910 if ($form->date_max_future($invdate, \%myconfig));
911 $form->error($locale->text('Cannot post invoice for a closed period!'))
912 if ($invdate <= $closedto);
914 $form->isblank("exchangerate", $locale->text('Exchangerate missing!'))
915 if ($form->{currency} ne $form->{defaultcurrency});
918 for $i (1 .. $form->{paidaccounts}) {
919 if ($form->parse_amount(\%myconfig, $form->{"paid_$i"})) {
920 my $datepaid = $form->datetonum($form->{"datepaid_$i"}, \%myconfig);
922 $form->isblank("datepaid_$i", $locale->text('Payment date missing!'));
924 $form->error($locale->text('Cannot post transaction above the maximum future booking date!'))
925 if ($form->date_max_future($form->{"datepaid_$i"}, \%myconfig));
927 #Zusätzlich noch das Buchungsdatum in die Bücherkontrolle einbeziehen
928 # (Dient zur Prüfung ob ZE oder ZA geprüft werden soll)
929 $form->error($locale->text('Cannot post payment for a closed period!'))
930 if ($form->date_closed($form->{"datepaid_$i"}) && !$form->date_closed($form->{"gldate_$i"}, \%myconfig));
932 if ($form->{currency} ne $form->{defaultcurrency}) {
933 $form->{"exchangerate_$i"} = $form->{exchangerate}
934 if ($invdate == $datepaid);
935 $form->isblank("exchangerate_$i",
936 $locale->text('Exchangerate for payment missing!'));
941 ($form->{AP}) = split /--/, $form->{AP};
942 ($form->{AP_paid}) = split /--/, $form->{AP_paid};
943 $form->{storno} ||= 0;
945 $form->{id} = 0 if $form->{postasnew};
949 if (IR->post_invoice(\%myconfig, \%$form)){
951 if(!exists $form->{addition} && $form->{id} ne "") {
952 $form->{snumbers} = qq|invnumber_| . $form->{invnumber};
953 $form->{addition} = "POSTED";
954 $form->{what_done} = 'invoice';
957 # /saving the history
960 if ('doc-tab' eq $form->{after_action}) {
961 $redirect_url = build_std_url("script=ir.pl", 'action=edit', 'id=' . E($form->{id}), 'fragment=ui-tabs-docs');
963 $redirect_url = build_std_url("script=ir.pl", 'action=edit', 'id=' . E($form->{id}));
965 SL::Helper::Flash::flash_later('info',
966 $locale->text('Invoice')
967 . " $form->{invnumber} "
968 . ", " . $locale->text('ID')
969 . ': ' . $form->{id} . ' '
970 . $locale->text('posted!'));
971 print $form->redirect_header($redirect_url);
972 $::dispatcher->end_request;
974 $form->error($locale->text('Cannot post invoice!'));
976 $main::lxdebug->leave_sub();
980 $main::lxdebug->enter_sub();
982 my $form = $main::form;
983 my $locale = $main::locale;
985 $main::auth->assert('vendor_invoice_edit');
989 <form method=post action=$form->{script}>
992 # delete action variable
993 map { delete $form->{$_} } qw(action header);
995 foreach my $key (keys %$form) {
996 next if (($key eq 'login') || ($key eq 'password') || ('' ne ref $form->{$key}));
997 $form->{$key} =~ s/\"/"/g;
998 print qq|<input type=hidden name=$key value="$form->{$key}">\n|;
1002 <h2 class=confirm>| . $locale->text('Confirm!') . qq|</h2>
1005 . $locale->text('Are you sure you want to delete Invoice Number')
1006 . qq| $form->{invnumber}</h4>
1008 <input name=action class=submit type=submit value="|
1009 . $locale->text('Yes') . qq|">
1013 $main::lxdebug->leave_sub();
1017 $::lxdebug->enter_sub;
1023 my $new_rowcount = $::form->{"rowcount"} * 1 + 1;
1024 $::form->{"project_id_${new_rowcount}"} = $::form->{"globalproject_id"};
1026 $::form->language_payment(\%::myconfig);
1028 Common::webdav_folder($::form);
1031 display_row(++$::form->{rowcount});
1034 $::lxdebug->leave_sub;
1038 $main::lxdebug->enter_sub();
1040 my $form = $main::form;
1041 my %myconfig = %main::myconfig;
1042 my $locale = $main::locale;
1044 $main::auth->assert('vendor_invoice_edit');
1046 if (IR->delete_invoice(\%myconfig, \%$form)) {
1047 # saving the history
1048 if(!exists $form->{addition}) {
1049 $form->{snumbers} = qq|invnumber_| . $form->{invnumber};
1050 $form->{addition} = "DELETED";
1051 $form->save_history;
1053 # /saving the history
1054 $form->redirect($locale->text('Invoice deleted!'));
1056 $form->error($locale->text('Cannot delete invoice!'));
1058 $main::lxdebug->leave_sub();
1061 sub get_duedate_vendor {
1062 $::lxdebug->enter_sub;
1064 my $result = IR->get_duedate(
1065 vendor_id => $::form->{vendor_id},
1066 invdate => $::form->{invdate},
1067 default => $::form->{old_duedate},
1070 print $::form->ajax_response_header, $result;
1071 $::lxdebug->leave_sub;