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., 675 Mass Ave, Cambridge, MA 02139, USA.
 
  28 #======================================================================
 
  30 # Inventory received module
 
  32 #======================================================================
 
  39 use SL::DB::PurchaseInvoice;
 
  40 use List::Util qw(max sum);
 
  41 use List::UtilsBy qw(sort_by);
 
  43 require "bin/mozilla/io.pl";
 
  44 require "bin/mozilla/invoice_io.pl";
 
  45 require "bin/mozilla/arap.pl";
 
  46 require "bin/mozilla/common.pl";
 
  47 require "bin/mozilla/drafts.pl";
 
  56   $main::lxdebug->enter_sub();
 
  58   my $form     = $main::form;
 
  59   my $locale   = $main::locale;
 
  61   $main::auth->assert('vendor_invoice_edit');
 
  63   if (!$::instance_conf->get_allow_new_purchase_invoice) {
 
  64     $::form->show_generic_error($::locale->text("You do not have the permissions to access this function."));
 
  67   return $main::lxdebug->leave_sub() if (load_draft_maybe());
 
  69   $form->{title} = $locale->text('Record Vendor Invoice');
 
  75   $main::lxdebug->leave_sub();
 
  79   $main::lxdebug->enter_sub();
 
  81   my $form     = $main::form;
 
  82   my $locale   = $main::locale;
 
  84   $main::auth->assert('vendor_invoice_edit');
 
  87   $form->{javascript} = qq|<script type=text/javascript src=js/show_history.js></script>|;
 
  88   #/show hhistory button
 
  90   $form->{title} = $locale->text('Edit Vendor Invoice');
 
  96   $main::lxdebug->leave_sub();
 
 100   $main::lxdebug->enter_sub();
 
 102   my $form     = $main::form;
 
 103   my %myconfig = %main::myconfig;
 
 105   $main::auth->assert('vendor_invoice_edit');
 
 107   $form->{vc} = 'vendor';
 
 110   $form->{webdav}   = $::instance_conf->get_webdav;
 
 112   $form->create_links("AP", \%myconfig, "vendor");
 
 114   #quote all_vendor Bug 133
 
 115   foreach my $ref (@{ $form->{all_vendor} }) {
 
 116     $ref->{name} = $form->quote($ref->{name});
 
 119   if ($form->{all_vendor}) {
 
 120     unless ($form->{vendor_id}) {
 
 121       $form->{vendor_id} = $form->{all_vendor}->[0]->{id};
 
 125   $form->backup_vars(qw(payment_id language_id taxzone_id
 
 126                         currency delivery_term_id intnotes cp_id));
 
 128   IR->get_vendor(\%myconfig, \%$form);
 
 129   IR->retrieve_invoice(\%myconfig, \%$form);
 
 131   $form->restore_vars(qw(payment_id language_id taxzone_id
 
 132                          currency delivery_term_id intnotes cp_id));
 
 134   my @curr = $form->get_all_currencies();
 
 135   map { $form->{selectcurrency} .= "<option>$_\n" } @curr;
 
 137   $form->{oldvendor} = "$form->{vendor}--$form->{vendor_id}";
 
 139   # build vendor/customer drop down comatibility... don't ask
 
 140   if (@{ $form->{"all_vendor"} || [] }) {
 
 141     $form->{"selectvendor"} = 1;
 
 142     $form->{vendor}         = qq|$form->{vendor}--$form->{vendor_id}|;
 
 146   if ($form->{all_departments}) {
 
 147     $form->{selectdepartment} = "<option>\n";
 
 148     $form->{department}       = "$form->{department}--$form->{department_id}";
 
 151       $form->{selectdepartment} .=
 
 152         "<option>$_->{description}--$_->{id}\n"
 
 153     } (@{ $form->{all_departments} || [] });
 
 157   $form->{forex} = $form->{exchangerate};
 
 158   my $exchangerate = ($form->{exchangerate}) ? $form->{exchangerate} : 1;
 
 160   foreach my $key (keys %{ $form->{AP_links} }) {
 
 162     foreach my $ref (@{ $form->{AP_links}{$key} }) {
 
 163       $form->{"select$key"} .= "<option>$ref->{accno}--$ref->{description}</option>";
 
 166     next unless $form->{acc_trans}{$key};
 
 168     if ($key eq "AP_paid") {
 
 169       for my $i (1 .. scalar @{ $form->{acc_trans}{$key} }) {
 
 170         $form->{"AP_paid_$i"} =
 
 171           "$form->{acc_trans}{$key}->[$i-1]->{accno}--$form->{acc_trans}{$key}->[$i-1]->{description}";
 
 173         $form->{"acc_trans_id_$i"} = $form->{acc_trans}{$key}->[$i - 1]->{acc_trans_id};
 
 175         $form->{"paid_$i"}     = $form->{acc_trans}{$key}->[$i - 1]->{amount};
 
 176         $form->{"datepaid_$i"} =
 
 177           $form->{acc_trans}{$key}->[$i - 1]->{transdate};
 
 178         $form->{"gldate_$i"}   = $form->{acc_trans}{$key}->[$i - 1]->{gldate};
 
 179         $form->{"forex_$i"} = $form->{"exchangerate_$i"} =
 
 180           $form->{acc_trans}{$key}->[$i - 1]->{exchangerate};
 
 181         $form->{"source_$i"} = $form->{acc_trans}{$key}->[$i - 1]->{source};
 
 182         $form->{"memo_$i"}   = $form->{acc_trans}{$key}->[$i - 1]->{memo};
 
 184         $form->{paidaccounts} = $i;
 
 188         "$form->{acc_trans}{$key}->[0]->{accno}--$form->{acc_trans}{$key}->[0]->{description}";
 
 193   $form->{paidaccounts} = 1 unless (exists $form->{paidaccounts});
 
 195   $form->{AP} = $form->{AP_1} unless $form->{id};
 
 198     ($form->datetonum($form->{invdate}, \%myconfig) <=
 
 199      $form->datetonum($form->{closedto}, \%myconfig));
 
 201   $main::lxdebug->leave_sub();
 
 204 sub prepare_invoice {
 
 205   $main::lxdebug->enter_sub();
 
 207   my $form     = $main::form;
 
 208   my %myconfig = %main::myconfig;
 
 210   $main::auth->assert('vendor_invoice_edit');
 
 212   $form->{type}     = "purchase_invoice";
 
 216     map { $form->{$_} =~ s/\"/"/g } qw(invnumber ordnumber quonumber);
 
 219     foreach my $ref (@{ $form->{invoice_details} }) {
 
 221       map { $form->{"${_}_$i"} = $ref->{$_} } keys %{$ref};
 
 222       # übernommen aus is.pl Fix für Bug 1642. Nebenwirkungen? jb 12.5.2011
 
 223       # getestet: Lieferantenauftrag -> Rechnung i.O.
 
 224       #           Lieferantenauftrag -> Lieferschein -> Rechnung i.O.
 
 225       # Werte: 20% (Lieferantenrabatt), 12,4% individuell und 0,4 individuell s.a.
 
 226       # Screenshot zu Bug 1642
 
 227       $form->{"discount_$i"}   = $form->format_amount(\%myconfig, $form->{"discount_$i"} * 100);
 
 229       my ($dec) = ($form->{"sellprice_$i"} =~ /\.(\d+)/);
 
 231       my $decimalplaces = ($dec > 2) ? $dec : 2;
 
 233       $form->{"sellprice_$i"} =
 
 234         $form->format_amount(\%myconfig, $form->{"sellprice_$i"},
 
 237       (my $dec_qty) = ($form->{"qty_$i"} =~ /\.(\d+)/);
 
 238       $dec_qty = length $dec_qty;
 
 241         $form->format_amount(\%myconfig, ($form->{"qty_$i"} * -1), $dec_qty);
 
 243       $form->{rowcount} = $i;
 
 247   $main::lxdebug->leave_sub();
 
 251   $main::lxdebug->enter_sub();
 
 253   my $form     = $main::form;
 
 254   my %myconfig = %main::myconfig;
 
 255   my $locale   = $main::locale;
 
 256   my $cgi      = $::request->{cgi};
 
 258   $main::auth->assert('vendor_invoice_edit');
 
 263   $TMPL_VAR{invoice_obj} = SL::DB::PurchaseInvoice->new(id => $form->{id})->load if $form->{id};
 
 264   $form->{employee_id} = $form->{old_employee_id} if $form->{old_employee_id};
 
 265   $form->{salesman_id} = $form->{old_salesman_id} if $form->{old_salesman_id};
 
 267   $form->{defaultcurrency} = $form->get_default_currency(\%myconfig);
 
 269   my @old_project_ids = ($form->{"globalproject_id"});
 
 270   map { push @old_project_ids, $form->{"project_id_$_"} if $form->{"project_id_$_"}; } 1..$form->{"rowcount"};
 
 272   $form->get_lists("projects"      => { "key"    => "ALL_PROJECTS",
 
 274                                         "old_id" => \@old_project_ids },
 
 275                    "taxzones"      => "ALL_TAXZONES",
 
 276                    "currencies"    => "ALL_CURRENCIES",
 
 277                    "vendors"       => "ALL_VENDORS",
 
 278                    "departments"   => "all_departments",
 
 279                    "price_factors" => "ALL_PRICE_FACTORS");
 
 281   $TMPL_VAR{ALL_EMPLOYEES}         = SL::DB::Manager::Employee->get_all_sorted(query => [ or => [ id => $::form->{employee_id},  deleted => 0 ] ]);
 
 282   $TMPL_VAR{ALL_CONTACTS}          = SL::DB::Manager::Contact->get_all_sorted(query => [
 
 284       cp_cv_id => $::form->{"$::form->{vc}_id"} * 1,
 
 287         cp_id    => $::form->{cp_id} * 1
 
 291   $TMPL_VAR{department_labels}     = sub { "$_[0]->{description}--$_[0]->{id}" };
 
 294   $TMPL_VAR{vc_keys} = sub { "$_[0]->{name}--$_[0]->{id}" };
 
 295   $TMPL_VAR{vclimit} = $myconfig{vclimit};
 
 296   $TMPL_VAR{vc_select} = "customer_or_vendor_selection_window('vendor', '', 1, 0)";
 
 297   push @custom_hiddens, "vendor_id";
 
 298   push @custom_hiddens, "oldvendor";
 
 299   push @custom_hiddens, "selectvendor";
 
 301   # currencies and exchangerate
 
 302   my @values = map { $_       } @{ $form->{ALL_CURRENCIES} };
 
 303   my %labels = map { $_ => $_ } @{ $form->{ALL_CURRENCIES} };
 
 304   $form->{currency}            = $form->{defaultcurrency} unless $form->{currency};
 
 305   # show_exchangerate is also later needed in another template
 
 306   $form->{show_exchangerate} = $form->{currency} ne $form->{defaultcurrency};
 
 307   $TMPL_VAR{currencies}        = NTI($cgi->popup_menu('-name' => 'currency', '-default' => $form->{"currency"},
 
 308                                                       '-values' => \@values, '-labels' => \%labels,
 
 309                                                       '-onchange' => "document.getElementById('update_button').click();"
 
 310                                      )) if scalar @values;
 
 311   push @custom_hiddens, "forex";
 
 312   push @custom_hiddens, "exchangerate" if $form->{forex};
 
 314   $TMPL_VAR{creditwarning} = ($form->{creditlimit} != 0) && ($form->{creditremaining} < 0) && !$form->{update};
 
 315   $TMPL_VAR{is_credit_remaining_negativ} = $form->{creditremaining} =~ /-/;
 
 317   my $follow_up_vc         =  $form->{vendor};
 
 318   $follow_up_vc            =~ s/--\d*\s*$//;
 
 319   $TMPL_VAR{vendor_name} = $follow_up_vc;
 
 321 # set option selected
 
 322   foreach my $item (qw(AP)) {
 
 323     $form->{"select$item"} =~ s/ selected//;
 
 324     $form->{"select$item"} =~ s/option>\Q$form->{$item}\E/option selected>$form->{$item}/;
 
 327   $TMPL_VAR{is_type_credit_note} = $form->{type}   eq "credit_note";
 
 328   $TMPL_VAR{is_format_html}      = $form->{format} eq 'html';
 
 329   $TMPL_VAR{dateformat}          = $myconfig{dateformat};
 
 330   $TMPL_VAR{numberformat}        = $myconfig{numberformat};
 
 333   $TMPL_VAR{HIDDENS} = [qw(
 
 334     id action type media format queued printed emailed title vc discount
 
 335     title creditlimit creditremaining tradediscount business closedto locked shipped storno storno_id
 
 336     max_dunning_level dunning_amount
 
 337     shiptoname shiptostreet shiptozipcode shiptocity shiptocountry  shiptocontact shiptophone shiptofax
 
 338     shiptoemail shiptodepartment_1 shiptodepartment_2 message email subject cc bcc taxaccounts cursor_fokus
 
 339     convert_from_do_ids convert_from_oe_ids show_details gldate useasnew
 
 341   map { $_.'_rate', $_.'_description', $_.'_taxnumber' } split / /, $form->{taxaccounts}];
 
 343   $TMPL_VAR{payment_terms_obj} = get_payment_terms_for_invoice();
 
 344   $form->{duedate}             = $TMPL_VAR{payment_terms_obj}->calc_date(reference_date => $form->{invdate}, due_date => $form->{due_due})->to_kivitendo if $TMPL_VAR{payment_terms_obj};
 
 346   $::request->{layout}->use_javascript(map { "${_}.js" } qw(kivi.SalesPurchase ckeditor/ckeditor ckeditor/adapters/jquery kivi.io autocomplete_customer autocomplete_part client_js));
 
 350   print $form->parse_html_template("ir/form_header", \%TMPL_VAR);
 
 352   $main::lxdebug->leave_sub();
 
 356   my @fields   = qw(acc_trans_id gldate datepaid source memo paid AR_paid);
 
 358     grep { $_->{paid} != 0 }
 
 361       +{ map { ($_ => delete($::form->{"${_}_${idx}"})) } @fields }
 
 362     } (1..$::form->{paidaccounts});
 
 364   @payments = sort_by { DateTime->from_kivitendo($_->{datepaid}) } @payments;
 
 366   $::form->{paidaccounts} = max scalar(@payments), 1;
 
 368   foreach my $idx (1 .. scalar(@payments)) {
 
 369     my $payment = $payments[$idx - 1];
 
 370     $::form->{"${_}_${idx}"} = $payment->{$_} for @fields;
 
 375   $main::lxdebug->enter_sub();
 
 377   my $form     = $main::form;
 
 378   my %myconfig = %main::myconfig;
 
 379   my $locale   = $main::locale;
 
 381   $main::auth->assert('vendor_invoice_edit');
 
 383   $form->{invtotal}    = $form->{invsubtotal};
 
 384   $form->{oldinvtotal} = $form->{invtotal};
 
 387   $form->{rows} = max 2,
 
 388     $form->numtextrows($form->{notes},    26, 8),
 
 389     $form->numtextrows($form->{intnotes}, 35, 8);
 
 392   # tax, total and subtotal calculations
 
 393   my ($tax, $subtotal);
 
 394   $form->{taxaccounts_array} = [ split / /, $form->{taxaccounts} ];
 
 396   foreach my $item (@{ $form->{taxaccounts_array} }) {
 
 397     if ($form->{"${item}_base"}) {
 
 398       if ($form->{taxincluded}) {
 
 399         $form->{"${item}_total"} = $form->round_amount( ($form->{"${item}_base"} * $form->{"${item}_rate"}
 
 400                                                                                  / (1 + $form->{"${item}_rate"})), 2);
 
 401         $form->{"${item}_netto"} = $form->round_amount( ($form->{"${item}_base"} - $form->{"${item}_total"}), 2);
 
 403         $form->{"${item}_total"} = $form->round_amount( $form->{"${item}_base"} * $form->{"${item}_rate"}, 2);
 
 404         $form->{invtotal} += $form->{"${item}_total"};
 
 411     $form->{follow_ups}            = FU->follow_ups('trans_id' => $form->{id}) || [];
 
 412     $form->{follow_ups_unfinished} = ( sum map { $_->{due} * 1 } @{ $form->{follow_ups} } ) || 0;
 
 419   $form->{paidaccounts}++ if ($form->{"paid_$form->{paidaccounts}"});
 
 420   $form->{paid_indices} = [ 1 .. $form->{paidaccounts} ];
 
 422   # Standard Konto für Umlaufvermögen
 
 423   my $accno_arap = IS->get_standard_accno_current_assets(\%myconfig, \%$form);
 
 425   for my $i (1 .. $form->{paidaccounts}) {
 
 426     $form->{"changeable_$i"} = 1;
 
 427     if (SL::DB::Default->get->payments_changeable == 0) {
 
 429       $form->{"changeable_$i"} = ($form->{"acc_trans_id_$i"})? 0 : 1;
 
 430     } elsif (SL::DB::Default->get->payments_changeable == 2) {
 
 432       $form->{"changeable_$i"} = (($form->{"gldate_$i"} eq '') ||
 
 433                                   ($form->current_date(\%myconfig) eq $form->{"gldate_$i"}));
 
 436     $form->{"selectAP_paid_$i"} = $form->{selectAP_paid};
 
 437     if (!$form->{"AP_paid_$i"}) {
 
 438       $form->{"selectAP_paid_$i"} =~ s/option>$accno_arap--(.*?)>/option selected>$accno_arap--$1>/;
 
 440       $form->{"selectAP_paid_$i"} =~ s/option>\Q$form->{"AP_paid_$i"}\E/option selected>$form->{"AP_paid_$i"}/;
 
 443     $totalpaid += $form->{"paid_$i"};
 
 446   $form->{ALL_DELIVERY_TERMS} = SL::DB::Manager::DeliveryTerm->get_all_sorted();
 
 448   print $form->parse_html_template('ir/form_footer', {
 
 449     is_type_credit_note => ($form->{type} eq "credit_note"),
 
 450     totalpaid           => $totalpaid,
 
 451     paid_missing        => $form->{invtotal} - $totalpaid,
 
 452     show_storno         => $form->{id} && !$form->{storno} && !IS->has_storno(\%myconfig, $form, "ap") && !$totalpaid,
 
 453     show_delete         => ($::instance_conf->get_ir_changeable == 2)
 
 454                              ? ($form->current_date(\%myconfig) eq $form->{gldate})
 
 455                              : ($::instance_conf->get_ir_changeable == 1),
 
 456     today               => DateTime->today,
 
 458 ##print $form->parse_html_template('ir/_payments'); # parser
 
 459 ##print $form->parse_html_template('webdav/_list'); # parser
 
 461   $main::lxdebug->leave_sub();
 
 465   $main::lxdebug->enter_sub();
 
 467   my $form     = $main::form;
 
 468   my %myconfig = %main::myconfig;
 
 470   $main::auth->assert('vendor_invoice_edit');
 
 472   &mark_as_paid_common(\%myconfig,"ap");
 
 474   $main::lxdebug->leave_sub();
 
 478   $main::lxdebug->enter_sub();
 
 480   my $form     = $main::form;
 
 481   my %myconfig = %main::myconfig;
 
 483   $main::auth->assert('vendor_invoice_edit');
 
 485   &check_name('vendor');
 
 487   if (!$form->{forex}) {        # read exchangerate from input field (not hidden)
 
 488     $form->{exchangerate} = $form->parse_amount(\%myconfig, $form->{exchangerate});
 
 490   $form->{forex}        = $form->check_exchangerate(\%myconfig, $form->{currency}, $form->{invdate}, 'sell');
 
 491   $form->{exchangerate} = $form->{forex} if $form->{forex};
 
 493   for my $i (1 .. $form->{paidaccounts}) {
 
 494     next unless $form->{"paid_$i"};
 
 495     map { $form->{"${_}_$i"} = $form->parse_amount(\%myconfig, $form->{"${_}_$i"}) } qw(paid exchangerate);
 
 496     $form->{"forex_$i"}        = $form->check_exchangerate(\%myconfig, $form->{currency}, $form->{"datepaid_$i"}, 'sell');
 
 497     $form->{"exchangerate_$i"} = $form->{"forex_$i"} if $form->{"forex_$i"};
 
 500   my $i            = $form->{rowcount};
 
 501   my $exchangerate = ($form->{exchangerate} * 1) || 1;
 
 503   if (   ($form->{"partnumber_$i"} eq "")
 
 504       && ($form->{"description_$i"} eq "")
 
 505       && ($form->{"partsgroup_$i"} eq "")) {
 
 506     $form->{creditremaining} += ($form->{oldinvtotal} - $form->{oldtotalpaid});
 
 511     IR->retrieve_item(\%myconfig, \%$form);
 
 513     my $rows = scalar @{ $form->{item_list} };
 
 515     $form->{"discount_$i"}   = $form->parse_amount(\%myconfig, $form->{"discount_$i"}) / 100.0;
 
 516     $form->{"discount_$i"} ||= $form->{vendor_discount};
 
 519       $form->{"qty_$i"} = $form->parse_amount(\%myconfig, $form->{"qty_$i"});
 
 520       if( !$form->{"qty_$i"} ) {
 
 521         $form->{"qty_$i"} = 1;
 
 526         select_item(mode => 'IR', pre_entered_qty => $form->{"qty_$i"});
 
 531         # override sellprice if there is one entered
 
 532         my $sellprice = $form->parse_amount(\%myconfig, $form->{"sellprice_$i"});
 
 534         map { $form->{item_list}[$i]{$_} =~ s/\"/"/g } qw(partnumber description unit);
 
 535         map { $form->{"${_}_$i"} = $form->{item_list}[0]{$_} } keys %{ $form->{item_list}[0] };
 
 537         $form->{"marge_price_factor_$i"} = $form->{item_list}->[0]->{price_factor};
 
 539         ($sellprice || $form->{"sellprice_$i"}) =~ /\.(\d+)/;
 
 540         my $dec_qty       = length $1;
 
 541         my $decimalplaces = max 2, $dec_qty;
 
 544           $form->{"sellprice_$i"} = $sellprice;
 
 546           my $record        = _make_record();
 
 547           my $price_source  = SL::PriceSource->new(record_item => $record->items->[$i-1], record => $record);
 
 548           my $best_price    = $price_source->best_price;
 
 549           my $best_discount = $price_source->best_discount;
 
 552             $::form->{"sellprice_$i"}           = $best_price->price;
 
 553             $::form->{"active_price_source_$i"} = $best_price->source;
 
 555           if ($best_discount) {
 
 556             $::form->{"discount_$i"}               = $best_discount->discount;
 
 557             $::form->{"active_discount_source_$i"} = $best_discount->source;
 
 560           # if there is an exchange rate adjust sellprice
 
 561           $form->{"sellprice_$i"} /= $exchangerate;
 
 564         my $amount                = $form->{"sellprice_$i"} * $form->{"qty_$i"} * (1 - $form->{"discount_$i"});
 
 565         $form->{creditremaining} -= $amount;
 
 566         $form->{"sellprice_$i"}   = $form->format_amount(\%myconfig, $form->{"sellprice_$i"}, $decimalplaces);
 
 567         $form->{"qty_$i"}         = $form->format_amount(\%myconfig, $form->{"qty_$i"},       $dec_qty);
 
 568         $form->{"discount_$i"}    = $form->format_amount(\%myconfig, $form->{"discount_$i"} * 100.0);
 
 575       # ok, so this is a new part
 
 576       # ask if it is a part or service item
 
 578       if (   $form->{"partsgroup_$i"}
 
 579           && ($form->{"partsnumber_$i"} eq "")
 
 580           && ($form->{"description_$i"} eq "")) {
 
 582         $form->{"discount_$i"} = "";
 
 586         $form->{"id_$i"}   = 0;
 
 591   $main::lxdebug->leave_sub();
 
 595   $main::lxdebug->enter_sub();
 
 597   my $form     = $main::form;
 
 598   my %myconfig = %main::myconfig;
 
 599   my $locale   = $main::locale;
 
 601   $main::auth->assert('vendor_invoice_edit');
 
 603   if ($form->{storno}) {
 
 604     $form->error($locale->text('Cannot storno storno invoice!'));
 
 607   if (IS->has_storno(\%myconfig, $form, "ap")) {
 
 608     $form->error($locale->text("Invoice has already been storno'd!"));
 
 611   $form->error($locale->text('Cannot post storno for a closed period!'))
 
 612     if ( $form->date_closed($form->{invdate}, \%myconfig));
 
 614   my $employee_id = $form->{employee_id};
 
 619   # Payments must not be recorded for the new storno invoice.
 
 620   $form->{paidaccounts} = 0;
 
 621   map { my $key = $_; delete $form->{$key} if grep { $key =~ /^$_/ } qw(datepaid_ gldate_ acc_trans_id_ source_ memo_ paid_ exchangerate_ AR_paid_) } keys %{ $form };
 
 622   # set new ids for storno invoice
 
 623   delete $form->{"invoice_id_$_"} for 1 .. $form->{"rowcount"};
 
 626   if(!exists $form->{addition} && $form->{id} ne "") {
 
 627     $form->{snumbers}  = qq|invnumber_| . $form->{invnumber};
 
 628     $form->{what_done} = "invoice";
 
 629     $form->{addition}  = "CANCELED";
 
 632   # /saving the history
 
 634   $form->{storno_id} = $form->{id};
 
 637   $form->{invnumber} = "Storno zu " . $form->{invnumber};
 
 639   $form->{employee_id} = $employee_id;
 
 641   $main::lxdebug->leave_sub();
 
 646   $main::lxdebug->enter_sub();
 
 648   my $form     = $main::form;
 
 649   my %myconfig = %main::myconfig;
 
 651   $main::auth->assert('vendor_invoice_edit');
 
 653   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);
 
 654   $form->{paidaccounts} = 1;
 
 656   $form->{invdate} = $form->current_date(\%myconfig);
 
 658   $form->{"converted_from_invoice_id_$_"} = delete $form->{"invoice_id_$_"} for 1 .. $form->{"rowcount"};
 
 660   $form->{useasnew} = 1;
 
 663   $main::lxdebug->leave_sub();
 
 667   $main::lxdebug->enter_sub();
 
 669   my $form     = $main::form;
 
 670   my %myconfig = %main::myconfig;
 
 671   my $locale   = $main::locale;
 
 673   $main::auth->assert('vendor_invoice_edit');
 
 675   $form->mtime_ischanged('ap') ;
 
 676   $form->{defaultcurrency} = $form->get_default_currency(\%myconfig);
 
 677   for my $i (1 .. $form->{paidaccounts}) {
 
 678     if ($form->{"paid_$i"}) {
 
 679       my $datepaid = $form->datetonum($form->{"datepaid_$i"}, \%myconfig);
 
 681       $form->isblank("datepaid_$i", $locale->text('Payment date missing!'));
 
 683       $form->error($locale->text('Cannot post payment for a closed period!'))
 
 684         if ($form->date_closed($form->{"datepaid_$i"}, \%myconfig));
 
 686       if ($form->{currency} ne $form->{defaultcurrency}) {
 
 687 #        $form->{"exchangerate_$i"} = $form->{exchangerate} if ($invdate == $datepaid); # invdate isn't set here
 
 688         $form->isblank("exchangerate_$i", $locale->text('Exchangerate for payment missing!'));
 
 693   ($form->{AP})      = split /--/, $form->{AP};
 
 694   ($form->{AP_paid}) = split /--/, $form->{AP_paid};
 
 695   if (IR->post_payment(\%myconfig, \%$form)){
 
 696     if (!exists $form->{addition} && $form->{id} ne "") {
 
 698       $form->{snumbers}  = qq|invnumber_| . $form->{invnumber};
 
 699       $form->{addition}  = "PAYMENT POSTED";
 
 700       $form->{what_done} = "invoice";
 
 702       # /saving the history
 
 705     $form->redirect($locale->text('Payment posted!'));
 
 708   $form->error($locale->text('Cannot post payment!'));
 
 710   $main::lxdebug->leave_sub();
 
 714   my $form  =  $main::form;
 
 716   my @dates = sort { $b->[1] cmp $a->[1] }
 
 717               map  { [ $_, $main::locale->reformat_date(\%main::myconfig, $_, 'yyyy-mm-dd') ] }
 
 719               map  { $form->{"datepaid_${_}"} }
 
 720               (1..$form->{rowcount});
 
 722   return @dates ? $dates[0]->[0] : undef;
 
 727   $main::lxdebug->enter_sub();
 
 729   my $form     = $main::form;
 
 730   my %myconfig = %main::myconfig;
 
 731   my $locale   = $main::locale;
 
 733   $main::auth->assert('vendor_invoice_edit');
 
 735   $form->mtime_ischanged('ap');
 
 736   $form->{defaultcurrency} = $form->get_default_currency(\%myconfig);
 
 738   $form->isblank("invdate",   $locale->text('Invoice Date missing!'));
 
 739   $form->isblank("vendor",    $locale->text('Vendor missing!'));
 
 740   $form->isblank("invnumber", $locale->text('Invnumber missing!'));
 
 742   $form->{invnumber} =~ s/^\s*//g;
 
 743   $form->{invnumber} =~ s/\s*$//g;
 
 745   # if the vendor changed get new values
 
 746   if (&check_name('vendor')) {
 
 751   if ($myconfig{mandatory_departments} && !$form->{department_id}) {
 
 752     $form->{saved_message} = $::locale->text('You have to specify a department.');
 
 757   remove_emptied_rows();
 
 760   my $closedto     = $form->datetonum($form->{closedto}, \%myconfig);
 
 761   my $invdate      = $form->datetonum($form->{invdate},  \%myconfig);
 
 762   my $max_datepaid = _max_datepaid();
 
 764   $form->error($locale->text('Cannot post transaction above the maximum future booking date!'))
 
 765     if ($form->date_max_future($invdate, \%myconfig));
 
 766   $form->error($locale->text('Cannot post invoice for a closed period!'))
 
 767     if ($invdate <= $closedto);
 
 769   $form->isblank("exchangerate", $locale->text('Exchangerate missing!'))
 
 770     if ($form->{currency} ne $form->{defaultcurrency});
 
 773   for $i (1 .. $form->{paidaccounts}) {
 
 774     if ($form->parse_amount(\%myconfig, $form->{"paid_$i"})) {
 
 775       my $datepaid = $form->datetonum($form->{"datepaid_$i"}, \%myconfig);
 
 777       $form->isblank("datepaid_$i", $locale->text('Payment date missing!'));
 
 779       $form->error($locale->text('Cannot post payment for a closed period!'))
 
 780         if ($form->date_closed($form->{"datepaid_$i"}, \%myconfig));
 
 782       if ($form->{currency} ne $form->{defaultcurrency}) {
 
 783         $form->{"exchangerate_$i"} = $form->{exchangerate}
 
 784           if ($invdate == $datepaid);
 
 785         $form->isblank("exchangerate_$i",
 
 786                        $locale->text('Exchangerate for payment missing!'));
 
 791   ($form->{AP})      = split /--/, $form->{AP};
 
 792   ($form->{AP_paid}) = split /--/, $form->{AP_paid};
 
 793   $form->{storno}  ||= 0;
 
 795   $form->{id} = 0 if $form->{postasnew};
 
 799   if (IR->post_invoice(\%myconfig, \%$form)){
 
 801     if(!exists $form->{addition} && $form->{id} ne "") {
 
 802       $form->{snumbers}  = qq|invnumber_| . $form->{invnumber};
 
 803       $form->{addition}  = "POSTED";
 
 804       $form->{what_done} = 'invoice';
 
 807     # /saving the history
 
 808     remove_draft() if $form->{remove_draft};
 
 809     $form->redirect(  $locale->text('Invoice')
 
 810                   . " $form->{invnumber} "
 
 811                   . $locale->text('posted!'));
 
 813   $form->error($locale->text('Cannot post invoice!'));
 
 815   $main::lxdebug->leave_sub();
 
 819   $main::lxdebug->enter_sub();
 
 821   my $form     = $main::form;
 
 822   my $locale   = $main::locale;
 
 824   $main::auth->assert('vendor_invoice_edit');
 
 828 <form method=post action=$form->{script}>
 
 831   # delete action variable
 
 832   map { delete $form->{$_} } qw(action header);
 
 834   foreach my $key (keys %$form) {
 
 835     next if (($key eq 'login') || ($key eq 'password') || ('' ne ref $form->{$key}));
 
 836     $form->{$key} =~ s/\"/"/g;
 
 837     print qq|<input type=hidden name=$key value="$form->{$key}">\n|;
 
 841 <h2 class=confirm>| . $locale->text('Confirm!') . qq|</h2>
 
 844     . $locale->text('Are you sure you want to delete Invoice Number')
 
 845     . qq| $form->{invnumber}</h4>
 
 847 <input name=action class=submit type=submit value="|
 
 848     . $locale->text('Yes') . qq|">
 
 852   $main::lxdebug->leave_sub();
 
 856   $main::lxdebug->enter_sub();
 
 858   my $form     = $main::form;
 
 859   my %myconfig = %main::myconfig;
 
 860   my $locale   = $main::locale;
 
 862   $main::auth->assert('vendor_invoice_edit');
 
 864   if (IR->delete_invoice(\%myconfig, \%$form)) {
 
 866     if(!exists $form->{addition}) {
 
 867       $form->{snumbers} = qq|invnumber_| . $form->{invnumber};
 
 868       $form->{addition} = "DELETED";
 
 871     # /saving the history
 
 872     $form->redirect($locale->text('Invoice deleted!'));
 
 874   $form->error($locale->text('Cannot delete invoice!'));
 
 876   $main::lxdebug->leave_sub();
 
 879 sub get_duedate_vendor {
 
 880   $::lxdebug->enter_sub;
 
 882   my $result = IR->get_duedate(
 
 883     vendor_id => $::form->{vendor_id},
 
 884     invdate   => $::form->{invdate},
 
 885     default   => $::form->{old_duedate},
 
 888   print $::form->ajax_response_header, $result;
 
 889   $::lxdebug->leave_sub;