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 #======================================================================
 
  39 use SL::DB::Department;
 
  40 use SL::DB::PurchaseInvoice;
 
  42 use List::Util qw(max sum);
 
  43 use List::UtilsBy qw(sort_by);
 
  45 require "bin/mozilla/io.pl";
 
  46 require "bin/mozilla/common.pl";
 
  55   $main::lxdebug->enter_sub();
 
  57   my $form     = $main::form;
 
  58   my $locale   = $main::locale;
 
  60   $main::auth->assert('vendor_invoice_edit');
 
  62   if (!$::instance_conf->get_allow_new_purchase_invoice) {
 
  63     $::form->show_generic_error($::locale->text("You do not have the permissions to access this function."));
 
  66   $form->{show_details} = $::myconfig{show_form_details};
 
  68   $form->{title} = $locale->text('Record Vendor Invoice');
 
  74   $main::lxdebug->leave_sub();
 
  78   $main::lxdebug->enter_sub();
 
  80   my $form     = $main::form;
 
  81   my $locale   = $main::locale;
 
  83   $main::auth->assert('vendor_invoice_edit');
 
  85   $form->{show_details} = $::myconfig{show_form_details};
 
  88   $form->{javascript} = qq|<script type=text/javascript src=js/show_history.js></script>|;
 
  89   #/show hhistory button
 
  91   $form->{title} = $locale->text('Edit Vendor Invoice');
 
  97   $main::lxdebug->leave_sub();
 
 101   $main::lxdebug->enter_sub();
 
 103   my $form     = $main::form;
 
 104   my %myconfig = %main::myconfig;
 
 106   $main::auth->assert('vendor_invoice_edit');
 
 108   $form->{vc} = 'vendor';
 
 111   $form->create_links("AP", \%myconfig, "vendor");
 
 113   $form->backup_vars(qw(payment_id language_id taxzone_id
 
 114                         currency delivery_term_id intnotes cp_id));
 
 116   IR->get_vendor(\%myconfig, \%$form);
 
 117   IR->retrieve_invoice(\%myconfig, \%$form);
 
 119   $form->restore_vars(qw(payment_id language_id taxzone_id
 
 120                          currency delivery_term_id intnotes cp_id));
 
 122   my @curr = $form->get_all_currencies();
 
 123   map { $form->{selectcurrency} .= "<option>$_\n" } @curr;
 
 126   $form->{forex} = $form->{exchangerate};
 
 127   my $exchangerate = ($form->{exchangerate}) ? $form->{exchangerate} : 1;
 
 129   foreach my $key (keys %{ $form->{AP_links} }) {
 
 131     foreach my $ref (@{ $form->{AP_links}{$key} }) {
 
 132       $form->{"select$key"} .= "<option>$ref->{accno}--$ref->{description}</option>";
 
 135     next unless $form->{acc_trans}{$key};
 
 137     if ($key eq "AP_paid") {
 
 138       for my $i (1 .. scalar @{ $form->{acc_trans}{$key} }) {
 
 139         $form->{"AP_paid_$i"} =
 
 140           "$form->{acc_trans}{$key}->[$i-1]->{accno}--$form->{acc_trans}{$key}->[$i-1]->{description}";
 
 142         $form->{"acc_trans_id_$i"} = $form->{acc_trans}{$key}->[$i - 1]->{acc_trans_id};
 
 144         $form->{"paid_$i"}     = $form->{acc_trans}{$key}->[$i - 1]->{amount};
 
 145         $form->{"datepaid_$i"} =
 
 146           $form->{acc_trans}{$key}->[$i - 1]->{transdate};
 
 147         $form->{"gldate_$i"}   = $form->{acc_trans}{$key}->[$i - 1]->{gldate};
 
 148         $form->{"forex_$i"} = $form->{"exchangerate_$i"} =
 
 149           $form->{acc_trans}{$key}->[$i - 1]->{exchangerate};
 
 150         $form->{"source_$i"} = $form->{acc_trans}{$key}->[$i - 1]->{source};
 
 151         $form->{"memo_$i"}   = $form->{acc_trans}{$key}->[$i - 1]->{memo};
 
 153         $form->{paidaccounts} = $i;
 
 157         "$form->{acc_trans}{$key}->[0]->{accno}--$form->{acc_trans}{$key}->[0]->{description}";
 
 162   $form->{paidaccounts} = 1 unless (exists $form->{paidaccounts});
 
 164   $form->{AP} = $form->{AP_1} unless $form->{id};
 
 167     ($form->datetonum($form->{invdate}, \%myconfig) <=
 
 168      $form->datetonum($form->{closedto}, \%myconfig));
 
 170   $main::lxdebug->leave_sub();
 
 173 sub prepare_invoice {
 
 174   $main::lxdebug->enter_sub();
 
 176   my $form     = $main::form;
 
 177   my %myconfig = %main::myconfig;
 
 179   $main::auth->assert('vendor_invoice_edit');
 
 181   $form->{type}     = "purchase_invoice";
 
 185     map { $form->{$_} =~ s/\"/"/g } qw(invnumber ordnumber quonumber);
 
 188     foreach my $ref (@{ $form->{invoice_details} }) {
 
 190       map { $form->{"${_}_$i"} = $ref->{$_} } keys %{$ref};
 
 191       # übernommen aus is.pl Fix für Bug 1642. Nebenwirkungen? jb 12.5.2011
 
 192       # getestet: Lieferantenauftrag -> Rechnung i.O.
 
 193       #           Lieferantenauftrag -> Lieferschein -> Rechnung i.O.
 
 194       # Werte: 20% (Lieferantenrabatt), 12,4% individuell und 0,4 individuell s.a.
 
 195       # Screenshot zu Bug 1642
 
 196       $form->{"discount_$i"}   = $form->format_amount(\%myconfig, $form->{"discount_$i"} * 100);
 
 198       my ($dec) = ($form->{"sellprice_$i"} =~ /\.(\d+)/);
 
 200       my $decimalplaces = ($dec > 2) ? $dec : 2;
 
 202       $form->{"sellprice_$i"} =
 
 203         $form->format_amount(\%myconfig, $form->{"sellprice_$i"},
 
 206       (my $dec_qty) = ($form->{"qty_$i"} =~ /\.(\d+)/);
 
 207       $dec_qty = length $dec_qty;
 
 210         $form->format_amount(\%myconfig, ($form->{"qty_$i"} * -1), $dec_qty);
 
 212       $form->{rowcount} = $i;
 
 216   $main::lxdebug->leave_sub();
 
 219 sub setup_ir_action_bar {
 
 221   my $change_never            = $::instance_conf->get_ir_changeable == 0;
 
 222   my $change_on_same_day_only = $::instance_conf->get_ir_changeable == 2 && ($form->current_date(\%::myconfig) ne $form->{gldate});
 
 224   for my $bar ($::request->layout->get('actionbar')) {
 
 228         submit    => [ '#form', { action => "update" } ],
 
 229         id        => 'update_button',
 
 230         accesskey => 'enter',
 
 236           submit   => [ '#form', { action => "post" } ],
 
 237           disabled => $form->{locked}                           ? t8('The billing period has already been locked.')
 
 238                     : $form->{storno}                           ? t8('A canceled invoice cannot be posted.')
 
 239                     : ($form->{id} && $change_never)            ? t8('Changing invoices has been disabled in the configuration.')
 
 240                     : ($form->{id} && $change_on_same_day_only) ? t8('Invoices can only be changed on the day they are posted.')
 
 245           submit   => [ '#form', { action => "post_payment" } ],
 
 246           disabled => !$form->{id} ? t8('This invoice has not been posted yet.') : undef,
 
 250           submit   => [ '#form', { action => "mark_as_paid" } ],
 
 251           confirm  => t8('This will remove the invoice from showing as unpaid even if the unpaid amount does not match the amount. Proceed?'),
 
 252           disabled => !$form->{id} ? t8('This invoice has not been posted yet.') : undef,
 
 253           only_if  => $::instance_conf->get_ir_show_mark_as_paid,
 
 255       ], # end of combobox "Post"
 
 258         action => [ t8('Storno'),
 
 259           submit   => [ '#form', { action => "storno" } ],
 
 260           confirm  => t8('Do you really want to cancel this invoice?'),
 
 261           disabled => !$form->{id} ? t8('This invoice has not been posted yet.') : undef,
 
 263         action => [ t8('Delete'),
 
 264           submit   => [ '#form', { action => "delete" } ],
 
 265           confirm  => t8('Do you really want to delete this object?'),
 
 266           disabled => !$form->{id}             ? t8('This invoice has not been posted yet.')
 
 267                     : $form->{locked}          ? t8('The billing period has already been locked.')
 
 268                     : $change_never            ? t8('Changing invoices has been disabled in the configuration.')
 
 269                     : $change_on_same_day_only ? t8('Invoices can only be changed on the day they are posted.')
 
 272       ], # end of combobox "Storno"
 
 277         action => [ t8('more') ],
 
 280           call     => [ 'set_history_window', $::form->{id} * 1, 'id', 'glid' ],
 
 281           disabled => !$form->{id} ? t8('This invoice has not been posted yet.') : undef,
 
 285           call     => [ 'follow_up_window' ],
 
 286           disabled => !$form->{id} ? t8('This invoice has not been posted yet.') : undef,
 
 290           call     => [ 'kivi.Draft.popup', 'ir', 'invoice', $::form->{draft_id}, $::form->{draft_description} ],
 
 291           disabled => $form->{id}     ? t8('This invoice has already been posted.')
 
 292                     : $form->{locked} ? t8('The billing period has already been locked.')
 
 295       ], # end of combobox "more"
 
 301   $main::lxdebug->enter_sub();
 
 303   my $form     = $main::form;
 
 304   my %myconfig = %main::myconfig;
 
 305   my $locale   = $main::locale;
 
 306   my $cgi      = $::request->{cgi};
 
 308   $main::auth->assert('vendor_invoice_edit');
 
 313   $TMPL_VAR{invoice_obj} = SL::DB::PurchaseInvoice->load_cached($form->{id}) if $form->{id};
 
 314   $TMPL_VAR{vendor_obj}  = SL::DB::Vendor->load_cached($form->{vendor_id})   if $form->{vendor_id};
 
 315   $form->{employee_id} = $form->{old_employee_id} if $form->{old_employee_id};
 
 316   $form->{salesman_id} = $form->{old_salesman_id} if $form->{old_salesman_id};
 
 318   $form->{defaultcurrency} = $form->get_default_currency(\%myconfig);
 
 320   my @old_project_ids = ($form->{"globalproject_id"});
 
 321   map { push @old_project_ids, $form->{"project_id_$_"} if $form->{"project_id_$_"}; } 1..$form->{"rowcount"};
 
 323   $form->get_lists("taxzones"      => ($form->{id} ? "ALL_TAXZONES" : "ALL_ACTIVE_TAXZONES"),
 
 324                    "currencies"    => "ALL_CURRENCIES",
 
 325                    "price_factors" => "ALL_PRICE_FACTORS");
 
 327   $TMPL_VAR{ALL_DEPARTMENTS}       = SL::DB::Manager::Department->get_all_sorted;
 
 328   $TMPL_VAR{ALL_EMPLOYEES}         = SL::DB::Manager::Employee->get_all_sorted(query => [ or => [ id => $::form->{employee_id},  deleted => 0 ] ]);
 
 329   $TMPL_VAR{ALL_CONTACTS}          = SL::DB::Manager::Contact->get_all_sorted(query => [
 
 331       cp_cv_id => $::form->{"$::form->{vc}_id"} * 1,
 
 334         cp_id    => $::form->{cp_id} * 1
 
 339   # currencies and exchangerate
 
 340   my @values = map { $_       } @{ $form->{ALL_CURRENCIES} };
 
 341   my %labels = map { $_ => $_ } @{ $form->{ALL_CURRENCIES} };
 
 342   $form->{currency}            = $form->{defaultcurrency} unless $form->{currency};
 
 343   # show_exchangerate is also later needed in another template
 
 344   $form->{show_exchangerate} = $form->{currency} ne $form->{defaultcurrency};
 
 345   $TMPL_VAR{currencies}        = NTI($cgi->popup_menu('-name' => 'currency', '-default' => $form->{"currency"},
 
 346                                                       '-values' => \@values, '-labels' => \%labels,
 
 347                                                       '-onchange' => "document.getElementById('update_button').click();"
 
 348                                      )) if scalar @values;
 
 349   push @custom_hiddens, "forex";
 
 350   push @custom_hiddens, "exchangerate" if $form->{forex};
 
 352   $TMPL_VAR{creditwarning} = ($form->{creditlimit} != 0) && ($form->{creditremaining} < 0) && !$form->{update};
 
 353   $TMPL_VAR{is_credit_remaining_negativ} = $form->{creditremaining} =~ /-/;
 
 355 # set option selected
 
 356   foreach my $item (qw(AP)) {
 
 357     $form->{"select$item"} =~ s/ selected//;
 
 358     $form->{"select$item"} =~ s/option>\Q$form->{$item}\E/option selected>$form->{$item}/;
 
 361   $TMPL_VAR{is_type_credit_note} = $form->{type}   eq "credit_note";
 
 362   $TMPL_VAR{is_format_html}      = $form->{format} eq 'html';
 
 363   $TMPL_VAR{dateformat}          = $myconfig{dateformat};
 
 364   $TMPL_VAR{numberformat}        = $myconfig{numberformat};
 
 367   $TMPL_VAR{HIDDENS} = [qw(
 
 368     id type queued printed emailed title vc discount
 
 369     title creditlimit creditremaining tradediscount business closedto locked shipped storno storno_id
 
 370     max_dunning_level dunning_amount
 
 371     shiptoname shiptostreet shiptozipcode shiptocity shiptocountry shiptogln shiptocontact shiptophone shiptofax
 
 372     shiptoemail shiptodepartment_1 shiptodepartment_2 message email subject cc bcc taxaccounts cursor_fokus
 
 373     convert_from_do_ids convert_from_oe_ids convert_from_ap_ids show_details gldate useasnew
 
 375   map { $_.'_rate', $_.'_description', $_.'_taxnumber' } split / /, $form->{taxaccounts}];
 
 377   $TMPL_VAR{payment_terms_obj} = get_payment_terms_for_invoice();
 
 378   $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};
 
 380   $::request->{layout}->use_javascript(map { "${_}.js" } qw(kivi.Draft kivi.File  kivi.SalesPurchase kivi.Part ckeditor/ckeditor ckeditor/adapters/jquery kivi.io autocomplete_customer autocomplete_project client_js));
 
 382   setup_ir_action_bar();
 
 386   print $form->parse_html_template("ir/form_header", \%TMPL_VAR);
 
 388   $main::lxdebug->leave_sub();
 
 392   my @fields   = qw(acc_trans_id gldate datepaid source memo paid AP_paid);
 
 394     grep { $_->{paid} != 0 }
 
 397       +{ map { ($_ => delete($::form->{"${_}_${idx}"})) } @fields }
 
 398     } (1..$::form->{paidaccounts});
 
 400   @payments = sort_by { DateTime->from_kivitendo($_->{datepaid}) } @payments;
 
 402   $::form->{paidaccounts} = max scalar(@payments), 1;
 
 404   foreach my $idx (1 .. scalar(@payments)) {
 
 405     my $payment = $payments[$idx - 1];
 
 406     $::form->{"${_}_${idx}"} = $payment->{$_} for @fields;
 
 411   $main::lxdebug->enter_sub();
 
 413   my $form     = $main::form;
 
 414   my %myconfig = %main::myconfig;
 
 415   my $locale   = $main::locale;
 
 417   $main::auth->assert('vendor_invoice_edit');
 
 419   $form->{invtotal}    = $form->{invsubtotal};
 
 420   $form->{oldinvtotal} = $form->{invtotal};
 
 423   $form->{rows} = max 2,
 
 424     $form->numtextrows($form->{notes},    26, 8),
 
 425     $form->numtextrows($form->{intnotes}, 35, 8);
 
 428   # tax, total and subtotal calculations
 
 429   my ($tax, $subtotal);
 
 430   $form->{taxaccounts_array} = [ split / /, $form->{taxaccounts} ];
 
 432   foreach my $item (@{ $form->{taxaccounts_array} }) {
 
 433     if ($form->{"${item}_base"}) {
 
 434       if ($form->{taxincluded}) {
 
 435         $form->{"${item}_total"} = $form->round_amount( ($form->{"${item}_base"} * $form->{"${item}_rate"}
 
 436                                                                                  / (1 + $form->{"${item}_rate"})), 2);
 
 437         $form->{"${item}_netto"} = $form->round_amount( ($form->{"${item}_base"} - $form->{"${item}_total"}), 2);
 
 439         $form->{"${item}_total"} = $form->round_amount( $form->{"${item}_base"} * $form->{"${item}_rate"}, 2);
 
 440         $form->{invtotal} += $form->{"${item}_total"};
 
 447     $form->{follow_ups}            = FU->follow_ups('trans_id' => $form->{id}, 'not_done' => 1) || [];
 
 448     $form->{follow_ups_unfinished} = ( sum map { $_->{due} * 1 } @{ $form->{follow_ups} } ) || 0;
 
 455   $form->{paidaccounts}++ if ($form->{"paid_$form->{paidaccounts}"});
 
 456   $form->{paid_indices} = [ 1 .. $form->{paidaccounts} ];
 
 458   # Standard Konto für Umlaufvermögen
 
 459   my $accno_arap = IS->get_standard_accno_current_assets(\%myconfig, \%$form);
 
 461   for my $i (1 .. $form->{paidaccounts}) {
 
 462     $form->{"changeable_$i"} = 1;
 
 463     if (SL::DB::Default->get->payments_changeable == 0) {
 
 465       $form->{"changeable_$i"} = ($form->{"acc_trans_id_$i"})? 0 : 1;
 
 466     } elsif (SL::DB::Default->get->payments_changeable == 2) {
 
 468       $form->{"changeable_$i"} = (($form->{"gldate_$i"} eq '') ||
 
 469                                   ($form->current_date(\%myconfig) eq $form->{"gldate_$i"}));
 
 472     $form->error($locale->text('Cannot post transaction above the maximum future booking date!'))
 
 473       if ($form->date_max_future($form->{"datepaid_$i"}, \%myconfig));
 
 475     #deaktivieren von Zahlungen ausserhalb der Bücherkontrolle
 
 476     if ($form->date_closed($form->{"gldate_$i"})) {
 
 477       $form->{"changeable_$i"} = 0;
 
 480     $form->{"selectAP_paid_$i"} = $form->{selectAP_paid};
 
 481     if (!$form->{"AP_paid_$i"}) {
 
 482       $form->{"selectAP_paid_$i"} =~ s/option>$accno_arap--(.*?)>/option selected>$accno_arap--$1>/;
 
 484       $form->{"selectAP_paid_$i"} =~ s/option>\Q$form->{"AP_paid_$i"}\E/option selected>$form->{"AP_paid_$i"}/;
 
 487     $totalpaid += $form->{"paid_$i"};
 
 490   $form->{ALL_DELIVERY_TERMS} = SL::DB::Manager::DeliveryTerm->get_all_sorted();
 
 492   print $form->parse_html_template('ir/form_footer', {
 
 493     is_type_credit_note => ($form->{type} eq "credit_note"),
 
 494     totalpaid           => $totalpaid,
 
 495     paid_missing        => $form->{invtotal} - $totalpaid,
 
 496     show_storno         => $form->{id} && !$form->{storno} && !IS->has_storno(\%myconfig, $form, "ap") && !$totalpaid,
 
 497     show_delete         => ($::instance_conf->get_ir_changeable == 2)
 
 498                              ? ($form->current_date(\%myconfig) eq $form->{gldate})
 
 499                              : ($::instance_conf->get_ir_changeable == 1),
 
 500     today               => DateTime->today,
 
 502 ##print $form->parse_html_template('ir/_payments'); # parser
 
 503 ##print $form->parse_html_template('webdav/_list'); # parser
 
 505   $main::lxdebug->leave_sub();
 
 509   $::auth->assert('vendor_invoice_edit');
 
 511   SL::DB::PurchaseInvoice->new(id => $::form->{id})->load->mark_as_paid;
 
 513   $::form->redirect($::locale->text("Marked as paid"));
 
 521   $main::lxdebug->enter_sub();
 
 523   my $form     = $main::form;
 
 524   my %myconfig = %main::myconfig;
 
 526   $main::auth->assert('vendor_invoice_edit');
 
 528   if (($form->{previous_vendor_id} || $form->{vendor_id}) != $form->{vendor_id}) {
 
 529     IR->get_vendor(\%myconfig, $form);
 
 532   if (!$form->{forex}) {        # read exchangerate from input field (not hidden)
 
 533     $form->{exchangerate} = $form->parse_amount(\%myconfig, $form->{exchangerate});
 
 535   $form->{forex}        = $form->check_exchangerate(\%myconfig, $form->{currency}, $form->{invdate}, 'sell');
 
 536   $form->{exchangerate} = $form->{forex} if $form->{forex};
 
 538   for my $i (1 .. $form->{paidaccounts}) {
 
 539     next unless $form->{"paid_$i"};
 
 540     map { $form->{"${_}_$i"} = $form->parse_amount(\%myconfig, $form->{"${_}_$i"}) } qw(paid exchangerate);
 
 541     $form->{"forex_$i"}        = $form->check_exchangerate(\%myconfig, $form->{currency}, $form->{"datepaid_$i"}, 'sell');
 
 542     $form->{"exchangerate_$i"} = $form->{"forex_$i"} if $form->{"forex_$i"};
 
 545   my $i            = $form->{rowcount};
 
 546   my $exchangerate = ($form->{exchangerate} * 1) || 1;
 
 548   if (   ($form->{"partnumber_$i"} eq "")
 
 549       && ($form->{"description_$i"} eq "")
 
 550       && ($form->{"partsgroup_$i"} eq "")) {
 
 551     $form->{creditremaining} += ($form->{oldinvtotal} - $form->{oldtotalpaid});
 
 556     IR->retrieve_item(\%myconfig, \%$form);
 
 558     my $rows = scalar @{ $form->{item_list} };
 
 560     $form->{"discount_$i"}   = $form->parse_amount(\%myconfig, $form->{"discount_$i"}) / 100.0;
 
 561     $form->{"discount_$i"} ||= $form->{vendor_discount};
 
 564       $form->{"qty_$i"} = $form->parse_amount(\%myconfig, $form->{"qty_$i"});
 
 565       if( !$form->{"qty_$i"} ) {
 
 566         $form->{"qty_$i"} = 1;
 
 571         select_item(mode => 'IR', pre_entered_qty => $form->{"qty_$i"});
 
 572         $::dispatcher->end_request;
 
 576         # override sellprice if there is one entered
 
 577         my $sellprice = $form->parse_amount(\%myconfig, $form->{"sellprice_$i"});
 
 579         map { $form->{item_list}[$i]{$_} =~ s/\"/"/g } qw(partnumber description unit);
 
 580         map { $form->{"${_}_$i"} = $form->{item_list}[0]{$_} } keys %{ $form->{item_list}[0] };
 
 582         $form->{"marge_price_factor_$i"} = $form->{item_list}->[0]->{price_factor};
 
 584         ($sellprice || $form->{"sellprice_$i"}) =~ /\.(\d+)/;
 
 585         my $dec_qty       = length $1;
 
 586         my $decimalplaces = max 2, $dec_qty;
 
 589           $form->{"sellprice_$i"} = $sellprice;
 
 591           my $record        = _make_record();
 
 592           my $price_source  = SL::PriceSource->new(record_item => $record->items->[$i-1], record => $record);
 
 593           my $best_price    = $price_source->best_price;
 
 594           my $best_discount = $price_source->best_discount;
 
 597             $::form->{"sellprice_$i"}           = $best_price->price;
 
 598             $::form->{"active_price_source_$i"} = $best_price->source;
 
 600           if ($best_discount) {
 
 601             $::form->{"discount_$i"}               = $best_discount->discount;
 
 602             $::form->{"active_discount_source_$i"} = $best_discount->source;
 
 605           # if there is an exchange rate adjust sellprice
 
 606           $form->{"sellprice_$i"} /= $exchangerate;
 
 609         my $amount                = $form->{"sellprice_$i"} * $form->{"qty_$i"} * (1 - $form->{"discount_$i"});
 
 610         $form->{creditremaining} -= $amount;
 
 611         $form->{"sellprice_$i"}   = $form->format_amount(\%myconfig, $form->{"sellprice_$i"}, $decimalplaces);
 
 612         $form->{"qty_$i"}         = $form->format_amount(\%myconfig, $form->{"qty_$i"},       $dec_qty);
 
 613         $form->{"discount_$i"}    = $form->format_amount(\%myconfig, $form->{"discount_$i"} * 100.0);
 
 620       # ok, so this is a new part
 
 621       # ask if it is a part or service item
 
 623       if (   $form->{"partsgroup_$i"}
 
 624           && ($form->{"partsnumber_$i"} eq "")
 
 625           && ($form->{"description_$i"} eq "")) {
 
 627         $form->{"discount_$i"} = "";
 
 631         $form->{"id_$i"}   = 0;
 
 636   $main::lxdebug->leave_sub();
 
 640   $main::lxdebug->enter_sub();
 
 642   my $form     = $main::form;
 
 643   my %myconfig = %main::myconfig;
 
 644   my $locale   = $main::locale;
 
 646   $main::auth->assert('vendor_invoice_edit');
 
 648   if ($form->{storno}) {
 
 649     $form->error($locale->text('Cannot storno storno invoice!'));
 
 652   if (IS->has_storno(\%myconfig, $form, "ap")) {
 
 653     $form->error($locale->text("Invoice has already been storno'd!"));
 
 656   $form->error($locale->text('Cannot post storno for a closed period!'))
 
 657     if ( $form->date_closed($form->{invdate}, \%myconfig));
 
 659   my $employee_id = $form->{employee_id};
 
 664   # Payments must not be recorded for the new storno invoice.
 
 665   $form->{paidaccounts} = 0;
 
 666   map { my $key = $_; delete $form->{$key} if grep { $key =~ /^$_/ } qw(datepaid_ gldate_ acc_trans_id_ source_ memo_ paid_ exchangerate_ AR_paid_) } keys %{ $form };
 
 667   # set new ids for storno invoice
 
 668   # set new persistent ids for storno invoice items
 
 669   $form->{"converted_from_invoice_id_$_"} = delete $form->{"invoice_id_$_"} for 1 .. $form->{"rowcount"};
 
 672   if(!exists $form->{addition} && $form->{id} ne "") {
 
 673     $form->{snumbers}  = qq|invnumber_| . $form->{invnumber};
 
 674     $form->{what_done} = "invoice";
 
 675     $form->{addition}  = "CANCELED";
 
 678   # /saving the history
 
 680   # record link invoice to storno
 
 681   $form->{convert_from_ap_ids} = $form->{id};
 
 682   $form->{storno_id} = $form->{id};
 
 685   $form->{invnumber} = "Storno zu " . $form->{invnumber};
 
 687   $form->{employee_id} = $employee_id;
 
 689   $main::lxdebug->leave_sub();
 
 694   $main::lxdebug->enter_sub();
 
 696   my $form     = $main::form;
 
 697   my %myconfig = %main::myconfig;
 
 699   $main::auth->assert('vendor_invoice_edit');
 
 701   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);
 
 702   $form->{paidaccounts} = 1;
 
 704   $form->{invdate} = $form->current_date(\%myconfig);
 
 706   $form->{"converted_from_invoice_id_$_"} = delete $form->{"invoice_id_$_"} for 1 .. $form->{"rowcount"};
 
 708   $form->{useasnew} = 1;
 
 711   $main::lxdebug->leave_sub();
 
 715   $main::lxdebug->enter_sub();
 
 717   my $form     = $main::form;
 
 718   my %myconfig = %main::myconfig;
 
 719   my $locale   = $main::locale;
 
 721   $main::auth->assert('vendor_invoice_edit');
 
 723   $form->mtime_ischanged('ap') ;
 
 724   $form->{defaultcurrency} = $form->get_default_currency(\%myconfig);
 
 725   for my $i (1 .. $form->{paidaccounts}) {
 
 726     if ($form->{"paid_$i"}) {
 
 727       my $datepaid = $form->datetonum($form->{"datepaid_$i"}, \%myconfig);
 
 729       $form->isblank("datepaid_$i", $locale->text('Payment date missing!'));
 
 731       $form->error($locale->text('Cannot post transaction above the maximum future booking date!'))
 
 732         if ($form->date_max_future($form->{"datepaid_$i"}, \%myconfig));
 
 734       #Zusätzlich noch das Buchungsdatum in die Bücherkontrolle einbeziehen
 
 735       # (Dient zur Prüfung ob ZE oder ZA geprüft werden soll)
 
 736       $form->error($locale->text('Cannot post payment for a closed period!'))
 
 737         if ($form->date_closed($form->{"datepaid_$i"})  && !$form->date_closed($form->{"gldate_$i"}, \%myconfig));
 
 739       if ($form->{currency} ne $form->{defaultcurrency}) {
 
 740 #        $form->{"exchangerate_$i"} = $form->{exchangerate} if ($invdate == $datepaid); # invdate isn't set here
 
 741         $form->isblank("exchangerate_$i", $locale->text('Exchangerate for payment missing!'));
 
 746   ($form->{AP})      = split /--/, $form->{AP};
 
 747   ($form->{AP_paid}) = split /--/, $form->{AP_paid};
 
 748   if (IR->post_payment(\%myconfig, \%$form)){
 
 749     if (!exists $form->{addition} && $form->{id} ne "") {
 
 751       $form->{snumbers}  = qq|invnumber_| . $form->{invnumber};
 
 752       $form->{addition}  = "PAYMENT POSTED";
 
 753       $form->{what_done} = "invoice";
 
 755       # /saving the history
 
 758     $form->redirect($locale->text('Payment posted!'));
 
 761   $form->error($locale->text('Cannot post payment!'));
 
 763   $main::lxdebug->leave_sub();
 
 767   my $form  =  $main::form;
 
 769   my @dates = sort { $b->[1] cmp $a->[1] }
 
 770               map  { [ $_, $main::locale->reformat_date(\%main::myconfig, $_, 'yyyy-mm-dd') ] }
 
 772               map  { $form->{"datepaid_${_}"} }
 
 773               (1..$form->{rowcount});
 
 775   return @dates ? $dates[0]->[0] : undef;
 
 780   $main::lxdebug->enter_sub();
 
 782   my $form     = $main::form;
 
 783   my %myconfig = %main::myconfig;
 
 784   my $locale   = $main::locale;
 
 786   $main::auth->assert('vendor_invoice_edit');
 
 788   $form->mtime_ischanged('ap');
 
 789   $form->{defaultcurrency} = $form->get_default_currency(\%myconfig);
 
 791   $form->isblank("invdate",   $locale->text('Invoice Date missing!'));
 
 792   $form->isblank("vendor_id", $locale->text('Vendor missing!'));
 
 793   $form->isblank("invnumber", $locale->text('Invnumber missing!'));
 
 795   $form->{invnumber} =~ s/^\s*//g;
 
 796   $form->{invnumber} =~ s/\s*$//g;
 
 798   # if the vendor changed get new values
 
 799   if (($form->{previous_vendor_id} || $form->{vendor_id}) != $form->{vendor_id}) {
 
 801     $::dispatcher->end_request;
 
 804   if ($myconfig{mandatory_departments} && !$form->{department_id}) {
 
 805     $form->{saved_message} = $::locale->text('You have to specify a department.');
 
 810   remove_emptied_rows();
 
 813   my $closedto     = $form->datetonum($form->{closedto}, \%myconfig);
 
 814   my $invdate      = $form->datetonum($form->{invdate},  \%myconfig);
 
 815   my $max_datepaid = _max_datepaid();
 
 817   $form->error($locale->text('Cannot post transaction above the maximum future booking date!'))
 
 818     if ($form->date_max_future($invdate, \%myconfig));
 
 819   $form->error($locale->text('Cannot post invoice for a closed period!'))
 
 820     if ($invdate <= $closedto);
 
 822   $form->isblank("exchangerate", $locale->text('Exchangerate missing!'))
 
 823     if ($form->{currency} ne $form->{defaultcurrency});
 
 826   for $i (1 .. $form->{paidaccounts}) {
 
 827     if ($form->parse_amount(\%myconfig, $form->{"paid_$i"})) {
 
 828       my $datepaid = $form->datetonum($form->{"datepaid_$i"}, \%myconfig);
 
 830       $form->isblank("datepaid_$i", $locale->text('Payment date missing!'));
 
 832       $form->error($locale->text('Cannot post transaction above the maximum future booking date!'))
 
 833         if ($form->date_max_future($form->{"datepaid_$i"}, \%myconfig));
 
 835       #Zusätzlich noch das Buchungsdatum in die Bücherkontrolle einbeziehen
 
 836       # (Dient zur Prüfung ob ZE oder ZA geprüft werden soll)
 
 837       $form->error($locale->text('Cannot post payment for a closed period!'))
 
 838         if ($form->date_closed($form->{"datepaid_$i"})  && !$form->date_closed($form->{"gldate_$i"}, \%myconfig));
 
 840       if ($form->{currency} ne $form->{defaultcurrency}) {
 
 841         $form->{"exchangerate_$i"} = $form->{exchangerate}
 
 842           if ($invdate == $datepaid);
 
 843         $form->isblank("exchangerate_$i",
 
 844                        $locale->text('Exchangerate for payment missing!'));
 
 849   ($form->{AP})      = split /--/, $form->{AP};
 
 850   ($form->{AP_paid}) = split /--/, $form->{AP_paid};
 
 851   $form->{storno}  ||= 0;
 
 853   $form->{id} = 0 if $form->{postasnew};
 
 857   if (IR->post_invoice(\%myconfig, \%$form)){
 
 859     if(!exists $form->{addition} && $form->{id} ne "") {
 
 860       $form->{snumbers}  = qq|invnumber_| . $form->{invnumber};
 
 861       $form->{addition}  = "POSTED";
 
 862       $form->{what_done} = 'invoice';
 
 865     # /saving the history
 
 866     $form->{callback} = 'ir.pl?action=add';
 
 867     $form->redirect(  $locale->text('Invoice')
 
 868                   . " $form->{invnumber} "
 
 869                   . $locale->text('posted!'));
 
 871   $form->error($locale->text('Cannot post invoice!'));
 
 873   $main::lxdebug->leave_sub();
 
 877   $main::lxdebug->enter_sub();
 
 879   my $form     = $main::form;
 
 880   my $locale   = $main::locale;
 
 882   $main::auth->assert('vendor_invoice_edit');
 
 886 <form method=post action=$form->{script}>
 
 889   # delete action variable
 
 890   map { delete $form->{$_} } qw(action header);
 
 892   foreach my $key (keys %$form) {
 
 893     next if (($key eq 'login') || ($key eq 'password') || ('' ne ref $form->{$key}));
 
 894     $form->{$key} =~ s/\"/"/g;
 
 895     print qq|<input type=hidden name=$key value="$form->{$key}">\n|;
 
 899 <h2 class=confirm>| . $locale->text('Confirm!') . qq|</h2>
 
 902     . $locale->text('Are you sure you want to delete Invoice Number')
 
 903     . qq| $form->{invnumber}</h4>
 
 905 <input name=action class=submit type=submit value="|
 
 906     . $locale->text('Yes') . qq|">
 
 910   $main::lxdebug->leave_sub();
 
 914   $::lxdebug->enter_sub;
 
 916   $::auth->assert('vendor_invoice_edit');
 
 920   my $new_rowcount = $::form->{"rowcount"} * 1 + 1;
 
 921   $::form->{"project_id_${new_rowcount}"} = $::form->{"globalproject_id"};
 
 923   $::form->language_payment(\%::myconfig);
 
 925   Common::webdav_folder($::form);
 
 928   display_row(++$::form->{rowcount});
 
 931   $::lxdebug->leave_sub;
 
 935   $main::lxdebug->enter_sub();
 
 937   my $form     = $main::form;
 
 938   my %myconfig = %main::myconfig;
 
 939   my $locale   = $main::locale;
 
 941   $main::auth->assert('vendor_invoice_edit');
 
 943   if (IR->delete_invoice(\%myconfig, \%$form)) {
 
 945     if(!exists $form->{addition}) {
 
 946       $form->{snumbers} = qq|invnumber_| . $form->{invnumber};
 
 947       $form->{addition} = "DELETED";
 
 950     # /saving the history
 
 951     $form->redirect($locale->text('Invoice deleted!'));
 
 953   $form->error($locale->text('Cannot delete invoice!'));
 
 955   $main::lxdebug->leave_sub();
 
 958 sub get_duedate_vendor {
 
 959   $::lxdebug->enter_sub;
 
 961   my $result = IR->get_duedate(
 
 962     vendor_id => $::form->{vendor_id},
 
 963     invdate   => $::form->{invdate},
 
 964     default   => $::form->{old_duedate},
 
 967   print $::form->ajax_response_header, $result;
 
 968   $::lxdebug->leave_sub;