1 #=====================================================================
 
   4 # Based on SQL-Ledger Version 2.1.9
 
   5 # Web http://www.lx-office.org
 
   7 #=====================================================================
 
   8 # SQL-Ledger Accounting
 
  11 #  Author: Dieter Simader
 
  12 #   Email: dsimader@sql-ledger.org
 
  13 #     Web: http://www.sql-ledger.org
 
  17 # This program is free software; you can redistribute it and/or modify
 
  18 # it under the terms of the GNU General Public License as published by
 
  19 # the Free Software Foundation; either version 2 of the License, or
 
  20 # (at your option) any later version.
 
  22 # This program is distributed in the hope that it will be useful,
 
  23 # but WITHOUT ANY WARRANTY; without even the implied warranty of
 
  24 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 
  25 # GNU General Public License for more details.
 
  26 # You should have received a copy of the GNU General Public License
 
  27 # along with this program; if not, write to the Free Software
 
  28 # Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
 
  29 #======================================================================
 
  31 # Inventory received module
 
  33 #======================================================================
 
  43 use SL::GenericTranslations;
 
  45 use List::Util qw(min);
 
  50   $main::lxdebug->enter_sub();
 
  52   my ($self, $myconfig, $form, $provided_dbh, $payments_only) = @_;
 
  54   # connect to database, turn off autocommit
 
  55   my $dbh = $provided_dbh ? $provided_dbh : $form->dbconnect_noauto($myconfig);
 
  56   $form->{defaultcurrency} = $form->get_default_currency($myconfig);
 
  58   my $ic_cvar_configs = CVar->get_configs(module => 'IC',
 
  61   my ($query, $sth, @values, $project_id);
 
  62   my ($allocated, $taxrate, $taxamount, $taxdiff, $item);
 
  63   my ($amount, $linetotal, $lastinventoryaccno, $lastexpenseaccno);
 
  64   my ($netamount, $invoicediff, $expensediff) = (0, 0, 0);
 
  66   my ($basefactor, $baseqty, @taxaccounts, $totaltax);
 
  68   my $all_units = AM->retrieve_units($myconfig, $form);
 
  70   if (!$payments_only) {
 
  72       &reverse_invoice($dbh, $form);
 
  74       ($form->{id}) = selectrow_query($form, $dbh, qq|SELECT nextval('glid')|);
 
  75       do_query($form, $dbh, qq|INSERT INTO ap (id, invnumber) VALUES (?, '')|, $form->{id});
 
  79   my ($currencies)    = selectfirst_array_query($form, $dbh, qq|SELECT curr FROM defaults|);
 
  80   my $defaultcurrency = (split m/:/, $currencies)[0];
 
  82   if ($form->{currency} eq $defaultcurrency) {
 
  83     $form->{exchangerate} = 1;
 
  85     $exchangerate = $form->check_exchangerate($myconfig, $form->{currency}, $form->{transdate}, 'sell');
 
  88   $form->{exchangerate} = $exchangerate || $form->parse_amount($myconfig, $form->{exchangerate});
 
  89   $form->{exchangerate} = 1 unless ($form->{exchangerate} * 1);
 
  92   my $q_item_unit = qq|SELECT unit FROM parts WHERE id = ?|;
 
  93   my $h_item_unit = prepare_query($form, $dbh, $q_item_unit);
 
  95   $form->get_lists('price_factors' => 'ALL_PRICE_FACTORS');
 
  96   my %price_factors = map { $_->{id} => $_->{factor} } @{ $form->{ALL_PRICE_FACTORS} };
 
  99   for my $i (1 .. $form->{rowcount}) {
 
 100     next unless $form->{"id_$i"};
 
 102     $form->{"qty_$i"}  = $form->parse_amount($myconfig, $form->{"qty_$i"});
 
 103     $form->{"qty_$i"} *= -1 if $form->{storno};
 
 105     $form->{"inventory_accno_$i"} = $form->{"expense_accno_$i"} if $main::eur;
 
 108     if (!$item_units{$form->{"id_$i"}}) {
 
 109       do_statement($form, $h_item_unit, $q_item_unit, $form->{"id_$i"});
 
 110       ($item_units{$form->{"id_$i"}}) = $h_item_unit->fetchrow_array();
 
 113     my $item_unit = $item_units{$form->{"id_$i"}};
 
 115     if (defined($all_units->{$item_unit}->{factor})
 
 116             && ($all_units->{$item_unit}->{factor} ne '')
 
 117             && ($all_units->{$item_unit}->{factor} * 1 != 0)) {
 
 118       $basefactor = $all_units->{$form->{"unit_$i"}}->{factor} / $all_units->{$item_unit}->{factor};
 
 122     $baseqty = $form->{"qty_$i"} * $basefactor;
 
 124     @taxaccounts = split / /, $form->{"taxaccounts_$i"};
 
 129     $form->{"sellprice_$i"} = $form->parse_amount($myconfig, $form->{"sellprice_$i"});
 
 130     (my $fxsellprice = $form->{"sellprice_$i"}) =~ /\.(\d+)/;
 
 132     my $decimalplaces = ($dec > 2) ? $dec : 2;
 
 134     map { $taxrate += $form->{"${_}_rate"} } @taxaccounts;
 
 136     $price_factor = $price_factors{ $form->{"price_factor_id_$i"} } || 1;
 
 137     #####################################################################
 
 138     # das ist aus IS.pm kopiert. schlimm. jb 7.10.2009
 
 139     # ich würde mir wünschen, dass diese vier stellen zusammengefasst werden
 
 140     # ... vier stellen = (einkauf + verkauf) * (maske + backend)
 
 141     # ansonsten stolpert man immer wieder viermal statt einmal heftig
 
 142     # und auch das undo discount formatting ist nicht besonders wartungsfreundlich
 
 144     # keep entered selling price
 
 145     $fxsellprice = $form->parse_amount($myconfig, $form->{"sellprice_$i"});
 
 147     # keine ahnung wofür das in IS.pm gemacht wird:
 
 148     #      my ($dec) = ($fxsellprice =~ /\.(\d+)/);
 
 149     #  $dec = length $dec;
 
 150     #  my $decimalplaces = ($dec > 2) ? $dec : 2;
 
 152     # undo discount formatting
 
 153     $form->{"discount_$i"} = $form->parse_amount($myconfig, $form->{"discount_$i"}) / 100;
 
 155     $form->{"sellprice_$i"} = $fxsellprice * (1 - $form->{"discount_$i"});
 
 157     ######################################################################
 
 158     if ($form->{"inventory_accno_$i"}) {
 
 160       $linetotal = $form->round_amount($form->{"sellprice_$i"} * $form->{"qty_$i"} / $price_factor, 2);
 
 162       if ($form->{taxincluded}) {
 
 163         $taxamount              = $linetotal * ($taxrate / (1 + $taxrate));
 
 164         $form->{"sellprice_$i"} = $form->{"sellprice_$i"} * (1 / (1 + $taxrate));
 
 166         $taxamount = $linetotal * $taxrate;
 
 169       $netamount += $linetotal;
 
 171       if ($form->round_amount($taxrate, 7) == 0) {
 
 172         if ($form->{taxincluded}) {
 
 173           foreach $item (@taxaccounts) {
 
 175               $form->round_amount($linetotal * $form->{"${item}_rate"} / (1 + abs($form->{"${item}_rate"})), 2);
 
 176             $taxdiff                              += $taxamount;
 
 177             $form->{amount}{ $form->{id} }{$item} -= $taxamount;
 
 179           $form->{amount}{ $form->{id} }{ $taxaccounts[0] } += $taxdiff;
 
 182           map { $form->{amount}{ $form->{id} }{$_} -= $linetotal * $form->{"${_}_rate"} } @taxaccounts;
 
 186         map { $form->{amount}{ $form->{id} }{$_} -= $taxamount * $form->{"${_}_rate"} / $taxrate } @taxaccounts;
 
 189       # add purchase to inventory, this one is without the tax!
 
 190       $amount    = $form->{"sellprice_$i"} * $form->{"qty_$i"} * $form->{exchangerate} / $price_factor;
 
 191       $linetotal = $form->round_amount($form->{"sellprice_$i"} * $form->{"qty_$i"} / $price_factor, 2) * $form->{exchangerate};
 
 192       $linetotal = $form->round_amount($linetotal, 2);
 
 194       # this is the difference for the inventory
 
 195       $invoicediff += ($amount - $linetotal);
 
 197       $form->{amount}{ $form->{id} }{ $form->{"inventory_accno_$i"} } -= $linetotal;
 
 199       # adjust and round sellprice
 
 200       $form->{"sellprice_$i"} = $form->round_amount($form->{"sellprice_$i"} * $form->{exchangerate}, $decimalplaces);
 
 202       $lastinventoryaccno = $form->{"inventory_accno_$i"};
 
 204       next if $payments_only;
 
 207       $query = qq|UPDATE parts SET lastcost = ? WHERE id = ?|;
 
 208       @values = ($form->{"sellprice_$i"}, conv_i($form->{"id_$i"}));
 
 209       do_query($form, $dbh, $query, @values);
 
 211       # check if we sold the item already and
 
 212       # make an entry for the expense and inventory
 
 214         qq|SELECT i.id, i.qty, i.allocated, i.trans_id,
 
 215              p.inventory_accno_id, p.expense_accno_id, a.transdate
 
 216            FROM invoice i, ar a, parts p
 
 217            WHERE (i.parts_id = p.id)
 
 219              AND ((i.base_qty + i.allocated) > 0)
 
 220              AND (i.trans_id = a.id)
 
 222       $sth = prepare_execute_query($form, $dbh, $query, conv_i($form->{"id_$i"}));
 
 224       my $totalqty = $baseqty;
 
 226       while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
 
 227         my $qty    = min $totalqty, ($ref->{base_qty} + $ref->{allocated});
 
 228         $linetotal = $form->round_amount(($form->{"sellprice_$i"} * $qty) / $basefactor, 2);
 
 230         if ($ref->{allocated} < 0) {
 
 232           # we have an entry for it already, adjust amount
 
 233           $form->update_balance($dbh, "acc_trans", "amount",
 
 234                                 qq|    (trans_id = $ref->{trans_id})
 
 235                                    AND (chart_id = $ref->{inventory_accno_id})
 
 236                                    AND (transdate = '$ref->{transdate}')|,
 
 239           $form->update_balance($dbh, "acc_trans", "amount",
 
 240                                 qq|    (trans_id = $ref->{trans_id})
 
 241                                    AND (chart_id = $ref->{expense_accno_id})
 
 242                                    AND (transdate = '$ref->{transdate}')|,
 
 245         } elsif ($linetotal != 0) {
 
 246           # add entry for inventory, this one is for the sold item
 
 247           $query = qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate, taxkey) VALUES (?, ?, ?, ?, (SELECT taxkey_id FROM chart WHERE id = ?))|;
 
 248           @values = ($ref->{trans_id},  $ref->{inventory_accno_id}, $linetotal, $ref->{transdate}, $ref->{inventory_accno_id});
 
 249           do_query($form, $dbh, $query, @values);
 
 252           $query = qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate, taxkey) VALUES (?, ?, ?, ?, (SELECT taxkey from tax WHERE chart_id = ?))|;
 
 253           @values = ($ref->{trans_id},  $ref->{expense_accno_id}, ($linetotal * -1), $ref->{transdate}, $ref->{expense_accno_id});
 
 254           do_query($form, $dbh, $query, @values);
 
 257         # update allocated for sold item
 
 258         $form->update_balance($dbh, "invoice", "allocated", qq|id = $ref->{id}|, $qty * -1);
 
 262         last if ($totalqty -= $qty) <= 0;
 
 267     } else {                    # if ($form->{"inventory_accno_id_$i"})
 
 269       $linetotal = $form->round_amount($form->{"sellprice_$i"} * $form->{"qty_$i"} / $price_factor, 2);
 
 271       if ($form->{taxincluded}) {
 
 272         $taxamount              = $linetotal * ($taxrate / (1 + $taxrate));
 
 273         $form->{"sellprice_$i"} = $form->{"sellprice_$i"} * (1 / (1 + $taxrate));
 
 276         $taxamount = $linetotal * $taxrate;
 
 279       $netamount += $linetotal;
 
 281       if ($form->round_amount($taxrate, 7) == 0) {
 
 282         if ($form->{taxincluded}) {
 
 283           foreach $item (@taxaccounts) {
 
 284             $taxamount = $linetotal * $form->{"${item}_rate"} / (1 + abs($form->{"${item}_rate"}));
 
 285             $totaltax += $taxamount;
 
 286             $form->{amount}{ $form->{id} }{$item} -= $taxamount;
 
 289           map { $form->{amount}{ $form->{id} }{$_} -= $linetotal * $form->{"${_}_rate"} } @taxaccounts;
 
 292         map { $form->{amount}{ $form->{id} }{$_} -= $taxamount * $form->{"${_}_rate"} / $taxrate } @taxaccounts;
 
 295       $amount    = $form->{"sellprice_$i"} * $form->{"qty_$i"} * $form->{exchangerate} / $price_factor;
 
 296       $linetotal = $form->round_amount($form->{"sellprice_$i"} * $form->{"qty_$i"} / $price_factor, 2) * $form->{exchangerate};
 
 297       $linetotal = $form->round_amount($linetotal, 2);
 
 299       # this is the difference for expense
 
 300       $expensediff += ($amount - $linetotal);
 
 302       # add amount to expense
 
 303       $form->{amount}{ $form->{id} }{ $form->{"expense_accno_$i"} } -= $linetotal;
 
 305       $lastexpenseaccno = $form->{"expense_accno_$i"};
 
 307       # adjust and round sellprice
 
 308       $form->{"sellprice_$i"} = $form->round_amount($form->{"sellprice_$i"} * $form->{exchangerate}, $decimalplaces);
 
 310       next if $payments_only;
 
 313       $query = qq|UPDATE parts SET lastcost = ? WHERE id = ?|;
 
 314       do_query($form, $dbh, $query, $form->{"sellprice_$i"}, conv_i($form->{"id_$i"}));
 
 317     next if $payments_only;
 
 319     # save detail record in invoice table
 
 320     my ($invoice_id) = selectfirst_array_query($form, $dbh, qq|SELECT nextval('invoiceid')|);
 
 323       qq|INSERT INTO invoice (id, trans_id, parts_id, description, qty, base_qty,
 
 324                               sellprice, fxsellprice, discount, allocated, unit, deliverydate,
 
 325                               project_id, serialnumber, price_factor_id, price_factor, marge_price_factor)
 
 326          VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, (SELECT factor FROM price_factors WHERE id = ?), ?)|;
 
 327     @values = ($invoice_id, conv_i($form->{id}), conv_i($form->{"id_$i"}),
 
 328                $form->{"description_$i"}, $form->{"qty_$i"} * -1,
 
 329                $baseqty * -1, $form->{"sellprice_$i"}, $fxsellprice, $form->{"discount_$i"}, $allocated,
 
 330                $form->{"unit_$i"}, conv_date($form->{deliverydate}),
 
 331                conv_i($form->{"project_id_$i"}), $form->{"serialnumber_$i"},
 
 332                conv_i($form->{"price_factor_id_$i"}), conv_i($form->{"price_factor_id_$i"}), conv_i($form->{"marge_price_factor_$i"}));
 
 333     do_query($form, $dbh, $query, @values);
 
 335     CVar->save_custom_variables(module       => 'IC',
 
 336                                 sub_module   => 'invoice',
 
 337                                 trans_id     => $invoice_id,
 
 338                                 configs      => $ic_cvar_configs,
 
 340                                 name_prefix  => 'ic_',
 
 341                                 name_postfix => "_$i",
 
 345   $h_item_unit->finish();
 
 347   $project_id = conv_i($form->{"globalproject_id"});
 
 349   $form->{datepaid} = $form->{invdate};
 
 351   # all amounts are in natural state, netamount includes the taxes
 
 352   # if tax is included, netamount is rounded to 2 decimal places,
 
 356   for my $i (1 .. $form->{paidaccounts}) {
 
 357     $form->{"paid_$i"}  = $form->parse_amount($myconfig, $form->{"paid_$i"});
 
 358     $form->{paid}      += $form->{"paid_$i"};
 
 359     $form->{datepaid}   = $form->{"datepaid_$i"} if $form->{"datepaid_$i"};
 
 362   my ($tax, $paiddiff) = (0, 0);
 
 364   $netamount = $form->round_amount($netamount, 2);
 
 366   # figure out rounding errors for amount paid and total amount
 
 367   if ($form->{taxincluded}) {
 
 369     $amount    = $form->round_amount($netamount * $form->{exchangerate}, 2);
 
 370     $paiddiff  = $amount - $netamount * $form->{exchangerate};
 
 371     $netamount = $amount;
 
 373     foreach $item (split / /, $form->{taxaccounts}) {
 
 374       $amount                               = $form->{amount}{ $form->{id} }{$item} * $form->{exchangerate};
 
 375       $form->{amount}{ $form->{id} }{$item} = $form->round_amount($amount, 2);
 
 377       $amount     = $form->{amount}{ $form->{id} }{$item} * -1;
 
 379       $netamount -= $amount;
 
 382     $invoicediff += $paiddiff;
 
 383     $expensediff += $paiddiff;
 
 385     ######## this only applies to tax included
 
 387     $form->{amount}{ $form->{id} }{$lastinventoryaccno} -= $invoicediff if $lastinventoryaccno;
 
 388     $form->{amount}{ $form->{id} }{$lastexpenseaccno}   -= $expensediff if $lastexpenseaccno;
 
 391     $amount    = $form->round_amount($netamount * $form->{exchangerate}, 2);
 
 392     $paiddiff  = $amount - $netamount * $form->{exchangerate};
 
 393     $netamount = $amount;
 
 395     foreach my $item (split / /, $form->{taxaccounts}) {
 
 396       $form->{amount}{ $form->{id} }{$item}  = $form->round_amount($form->{amount}{ $form->{id} }{$item}, 2);
 
 397       $amount                                = $form->round_amount( $form->{amount}{ $form->{id} }{$item} * $form->{exchangerate} * -1, 2);
 
 398       $paiddiff                             += $amount - $form->{amount}{ $form->{id} }{$item} * $form->{exchangerate} * -1;
 
 399       $form->{amount}{ $form->{id} }{$item}  = $form->round_amount($amount * -1, 2);
 
 400       $amount                                = $form->{amount}{ $form->{id} }{$item} * -1;
 
 405   $form->{amount}{ $form->{id} }{ $form->{AP} } = $netamount + $tax;
 
 408   $form->{paid} = $form->round_amount($form->{paid} * $form->{exchangerate} + $paiddiff, 2) if $form->{paid} != 0;
 
 410   # update exchangerate
 
 412   $form->update_exchangerate($dbh, $form->{currency}, $form->{invdate}, 0, $form->{exchangerate})
 
 413     if ($form->{currency} ne $defaultcurrency) && !$exchangerate;
 
 415   # record acc_trans transactions
 
 416   foreach my $trans_id (keys %{ $form->{amount} }) {
 
 417     foreach my $accno (keys %{ $form->{amount}{$trans_id} }) {
 
 418       $form->{amount}{$trans_id}{$accno} = $form->round_amount($form->{amount}{$trans_id}{$accno}, 2);
 
 420       next if $payments_only || !$form->{amount}{$trans_id}{$accno};
 
 422       $query = qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate, taxkey, project_id)
 
 423                   VALUES (?, (SELECT id FROM chart WHERE accno = ?), ?, ?,
 
 424                           (SELECT taxkey_id  FROM chart WHERE accno = ?), ?)|;
 
 425       @values = ($trans_id, $accno, $form->{amount}{$trans_id}{$accno},
 
 426                  conv_date($form->{invdate}), $accno, $project_id);
 
 427       do_query($form, $dbh, $query, @values);
 
 431   # deduct payment differences from paiddiff
 
 432   for my $i (1 .. $form->{paidaccounts}) {
 
 433     if ($form->{"paid_$i"} != 0) {
 
 434       $amount    = $form->round_amount($form->{"paid_$i"} * $form->{exchangerate}, 2);
 
 435       $paiddiff -= $amount - $form->{"paid_$i"} * $form->{exchangerate};
 
 439   # force AP entry if 0
 
 441   $form->{amount}{ $form->{id} }{ $form->{AP} } = $form->{paid} if $form->{amount}{$form->{id}}{$form->{AP}} == 0;
 
 443   # record payments and offsetting AP
 
 444   for my $i (1 .. $form->{paidaccounts}) {
 
 445     next if $form->{"paid_$i"} == 0;
 
 447     my ($accno)            = split /--/, $form->{"AP_paid_$i"};
 
 448     $form->{"datepaid_$i"} = $form->{invdate} unless ($form->{"datepaid_$i"});
 
 449     $form->{datepaid}      = $form->{"datepaid_$i"};
 
 451     $amount = $form->round_amount($form->{"paid_$i"} * $form->{exchangerate} + $paiddiff, 2) * -1;
 
 454     if ($form->{amount}{ $form->{id} }{ $form->{AP} } != 0) {
 
 455       $query = qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate, taxkey, project_id)
 
 456                   VALUES (?, (SELECT id FROM chart WHERE accno = ?), ?, ?,
 
 457                           (SELECT taxkey_id FROM chart WHERE accno = ?), ?)|;
 
 458       @values = (conv_i($form->{id}), $form->{AP}, $amount,
 
 459                  $form->{"datepaid_$i"}, $form->{AP}, $project_id);
 
 460       do_query($form, $dbh, $query, @values);
 
 464     $query = qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate, source, memo, taxkey, project_id)
 
 465                 VALUES (?, (SELECT id FROM chart WHERE accno = ?), ?, ?, ?, ?,
 
 466                 (SELECT taxkey_id FROM chart WHERE accno = ?), ?)|;
 
 467     @values = (conv_i($form->{id}), $accno, $form->{"paid_$i"}, $form->{"datepaid_$i"},
 
 468                $form->{"source_$i"}, $form->{"memo_$i"}, $accno, $project_id);
 
 469     do_query($form, $dbh, $query, @values);
 
 473     if ($form->{currency} eq $defaultcurrency) {
 
 474       $form->{"exchangerate_$i"} = 1;
 
 476       $exchangerate              = $form->check_exchangerate($myconfig, $form->{currency}, $form->{"datepaid_$i"}, 'sell');
 
 477       $form->{"exchangerate_$i"} = $exchangerate || $form->parse_amount($myconfig, $form->{"exchangerate_$i"});
 
 480     # exchangerate difference
 
 481     $form->{fx}{$accno}{ $form->{"datepaid_$i"} } += $form->{"paid_$i"} * ($form->{"exchangerate_$i"} - 1) + $paiddiff;
 
 485       ($form->{"paid_$i"} * $form->{exchangerate}) -
 
 486       ($form->{"paid_$i"} * $form->{"exchangerate_$i"});
 
 488       $form->{fx}{ $form->{fxgain_accno} }{ $form->{"datepaid_$i"} } += $amount;
 
 490       $form->{fx}{ $form->{fxloss_accno} }{ $form->{"datepaid_$i"} } += $amount;
 
 495     # update exchange rate
 
 496     $form->update_exchangerate($dbh, $form->{currency}, $form->{"datepaid_$i"}, 0, $form->{"exchangerate_$i"})
 
 497       if ($form->{currency} ne $defaultcurrency) && !$exchangerate;
 
 500   # record exchange rate differences and gains/losses
 
 501   foreach my $accno (keys %{ $form->{fx} }) {
 
 502     foreach my $transdate (keys %{ $form->{fx}{$accno} }) {
 
 503       $form->{fx}{$accno}{$transdate} = $form->round_amount($form->{fx}{$accno}{$transdate}, 2);
 
 504       next if ($form->{fx}{$accno}{$transdate} == 0);
 
 506       $query = qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate, cleared, fx_transaction, taxkey, project_id)
 
 507                   VALUES (?, (SELECT id FROM chart WHERE accno = ?), ?, ?, '0', '1', 0, ?)|;
 
 508       @values = (conv_i($form->{id}), $accno, $form->{fx}{$accno}{$transdate}, conv_date($transdate), $project_id);
 
 509       do_query($form, $dbh, $query, @values);
 
 513   if ($payments_only) {
 
 514     $query = qq|UPDATE ap SET paid = ?, datepaid = ? WHERE id = ?|;
 
 515     do_query($form, $dbh, $query,  $form->{paid}, $form->{paid} ? conv_date($form->{datepaid}) : undef, conv_i($form->{id}));
 
 517     if (!$provided_dbh) {
 
 522     $main::lxdebug->leave_sub();
 
 526   $amount = $netamount + $tax;
 
 528   # set values which could be empty
 
 529   my $taxzone_id         = $form->{taxzone_id} * 1;
 
 530   $form->{department_id} = (split /--/, $form->{department})[1];
 
 531   $form->{invnumber}     = $form->{id} unless $form->{invnumber};
 
 533   $taxzone_id = 0 if (3 < $taxzone_id) || (0 > $taxzone_id);
 
 536   $query = qq|UPDATE ap SET
 
 537                 invnumber    = ?, ordnumber   = ?, quonumber     = ?, transdate   = ?,
 
 538                 orddate      = ?, quodate     = ?, vendor_id     = ?, amount      = ?,
 
 539                 netamount    = ?, paid        = ?, duedate       = ?, datepaid    = ?,
 
 540                 invoice      = ?, taxzone_id  = ?, notes         = ?, taxincluded = ?,
 
 541                 intnotes     = ?, curr        = ?, storno_id     = ?, storno      = ?,
 
 542                 cp_id        = ?, employee_id = ?, department_id = ?,
 
 546                 $form->{invnumber},          $form->{ordnumber},           $form->{quonumber},      conv_date($form->{invdate}),
 
 547       conv_date($form->{orddate}), conv_date($form->{quodate}),     conv_i($form->{vendor_id}),               $amount,
 
 548                 $netamount,                  $form->{paid},      conv_date($form->{duedate}),       $form->{paid} ? conv_date($form->{datepaid}) : undef,
 
 549             '1',                             $taxzone_id,                  $form->{notes},          $form->{taxincluded} ? 't' : 'f',
 
 550                 $form->{intnotes},           $form->{currency},     conv_i($form->{storno_id}),     $form->{storno}      ? 't' : 'f',
 
 551          conv_i($form->{cp_id}),      conv_i($form->{employee_id}), conv_i($form->{department_id}),
 
 552          conv_i($form->{globalproject_id}),
 
 555   do_query($form, $dbh, $query, @values);
 
 557   if ($form->{storno}) {
 
 558     $query = qq|UPDATE ap SET paid = paid + amount WHERE id = ?|;
 
 559     do_query($form, $dbh, $query, conv_i($form->{storno_id}));
 
 561     $query = qq|UPDATE ap SET storno = 't' WHERE id = ?|;
 
 562     do_query($form, $dbh, $query, conv_i($form->{storno_id}));
 
 564     $query = qq!UPDATE ap SET intnotes = ? || intnotes WHERE id = ?!;
 
 565     do_query($form, $dbh, $query, "Rechnung storniert am $form->{invdate} ", conv_i($form->{storno_id}));
 
 567     $query = qq|UPDATE ap SET paid = amount WHERE id = ?|;
 
 568     do_query($form, $dbh, $query, conv_i($form->{id}));
 
 573   $form->{name} = $form->{vendor};
 
 574   $form->{name} =~ s/--\Q$form->{vendor_id}\E//;
 
 575   $form->add_shipto($dbh, $form->{id}, "AP");
 
 577   # delete zero entries
 
 578   do_query($form, $dbh, qq|DELETE FROM acc_trans WHERE amount = 0|);
 
 580   Common::webdav_folder($form) if ($main::webdav);
 
 582   # Link this record to the records it was created from.
 
 583   RecordLinks->create_links('dbh'        => $dbh,
 
 585                             'from_table' => 'oe',
 
 586                             'from_ids'   => $form->{convert_from_oe_ids},
 
 588                             'to_id'      => $form->{id},
 
 590   delete $form->{convert_from_oe_ids};
 
 592   my @convert_from_do_ids = map { $_ * 1 } grep { $_ } split m/\s+/, $form->{convert_from_do_ids};
 
 593   if (scalar @convert_from_do_ids) {
 
 594     DO->close_orders('dbh' => $dbh,
 
 595                      'ids' => \@convert_from_do_ids);
 
 597     RecordLinks->create_links('dbh'        => $dbh,
 
 599                               'from_table' => 'delivery_orders',
 
 600                               'from_ids'   => \@convert_from_do_ids,
 
 602                               'to_id'      => $form->{id},
 
 605   delete $form->{convert_from_do_ids};
 
 607   ARAP->close_orders_if_billed('dbh'     => $dbh,
 
 608                                'arap_id' => $form->{id},
 
 612   if (!$provided_dbh) {
 
 613     $rc = $dbh->commit();
 
 617   $main::lxdebug->leave_sub();
 
 622 sub reverse_invoice {
 
 623   $main::lxdebug->enter_sub();
 
 625   my ($dbh, $form) = @_;
 
 627   # reverse inventory items
 
 629     qq|SELECT i.parts_id, p.inventory_accno_id, p.expense_accno_id, i.qty, i.allocated, i.sellprice
 
 630        FROM invoice i, parts p
 
 631        WHERE (i.parts_id = p.id)
 
 632          AND (i.trans_id = ?)|;
 
 633   my $sth = prepare_execute_query($form, $dbh, $query, conv_i($form->{id}));
 
 637   while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
 
 638     $netamount += $form->round_amount($ref->{sellprice} * $ref->{qty} * -1, 2);
 
 640     next unless $ref->{inventory_accno_id};
 
 642     # if $ref->{allocated} > 0 than we sold that many items
 
 643     next if ($ref->{allocated} <= 0);
 
 645     # get references for sold items
 
 647       qq|SELECT i.id, i.trans_id, i.allocated, a.transdate
 
 649          WHERE (i.parts_id = ?)
 
 650            AND (i.allocated < 0)
 
 651            AND (i.trans_id = a.id)
 
 652          ORDER BY transdate DESC|;
 
 653       my $sth2 = prepare_execute_query($form, $dbh, $query, $ref->{parts_id});
 
 655       while (my $pthref = $sth2->fetchrow_hashref("NAME_lc")) {
 
 656         my $qty = $ref->{allocated};
 
 657         if (($ref->{allocated} + $pthref->{allocated}) > 0) {
 
 658           $qty = $pthref->{allocated} * -1;
 
 661         my $amount = $form->round_amount($ref->{sellprice} * $qty, 2);
 
 664         $form->update_balance($dbh, "invoice", "allocated", qq|id = $pthref->{id}|, $qty);
 
 666         $form->update_balance($dbh, "acc_trans", "amount",
 
 667                               qq|    (trans_id = $pthref->{trans_id})
 
 668                                  AND (chart_id = $ref->{expense_accno_id})
 
 669                                  AND (transdate = '$pthref->{transdate}')|,
 
 672         $form->update_balance($dbh, "acc_trans", "amount",
 
 673                               qq|    (trans_id = $pthref->{trans_id})
 
 674                                  AND (chart_id = $ref->{inventory_accno_id})
 
 675                                  AND (transdate = '$pthref->{transdate}')|,
 
 678         last if (($ref->{allocated} -= $qty) <= 0);
 
 684   my $id = conv_i($form->{id});
 
 687   $query = qq|DELETE FROM acc_trans WHERE trans_id = ?|;
 
 688   do_query($form, $dbh, $query, $id);
 
 690   # delete invoice entries
 
 691   $query = qq|DELETE FROM invoice WHERE trans_id = ?|;
 
 692   do_query($form, $dbh, $query, $id);
 
 694   $query = qq|DELETE FROM shipto WHERE (trans_id = ?) AND (module = 'AP')|;
 
 695   do_query($form, $dbh, $query, $id);
 
 697   $main::lxdebug->leave_sub();
 
 701   $main::lxdebug->enter_sub();
 
 703   my ($self, $myconfig, $form) = @_;
 
 705   # connect to database
 
 706   my $dbh = $form->dbconnect_noauto($myconfig);
 
 708   &reverse_invoice($dbh, $form);
 
 710   # delete zero entries
 
 711   $query = qq|DELETE FROM acc_trans WHERE amount = 0|;
 
 712   do_query($form, $dbh, $query);
 
 715   $query = qq|DELETE FROM ap WHERE id = ?|;
 
 716   do_query($form, $dbh, $query, conv_i($form->{id}));
 
 718   my $rc = $dbh->commit;
 
 721   $main::lxdebug->leave_sub();
 
 726 sub retrieve_invoice {
 
 727   $main::lxdebug->enter_sub();
 
 729   my ($self, $myconfig, $form) = @_;
 
 731   # connect to database
 
 732   my $dbh = $form->dbconnect($myconfig);
 
 734   my ($query, $sth, $ref, $q_invdate);
 
 737     $q_invdate = qq|, COALESCE((SELECT transdate FROM ar WHERE id = (SELECT MAX(id) FROM ar)), current_date) AS invdate|;
 
 738     if ($form->{vendor_id}) {
 
 739       my $vendor_id = $dbh->quote($form->{vendor_id} * 1);
 
 741         qq|, COALESCE((SELECT transdate FROM ar WHERE id = (SELECT MAX(id) FROM ar)), current_date) +
 
 742              COALESCE((SELECT pt.terms_netto
 
 744                        LEFT JOIN payment_terms pt ON (v.payment_id = pt.id)
 
 745                        WHERE v.id = $vendor_id),
 
 750   # get default accounts and last invoice number
 
 753                (SELECT c.accno FROM chart c WHERE d.inventory_accno_id = c.id) AS inventory_accno,
 
 754                (SELECT c.accno FROM chart c WHERE d.income_accno_id = c.id)    AS income_accno,
 
 755                (SELECT c.accno FROM chart c WHERE d.expense_accno_id = c.id)   AS expense_accno,
 
 756                (SELECT c.accno FROM chart c WHERE d.fxgain_accno_id = c.id)    AS fxgain_accno,
 
 757                (SELECT c.accno FROM chart c WHERE d.fxloss_accno_id = c.id)    AS fxloss_accno,
 
 761   $ref = selectfirst_hashref_query($form, $dbh, $query);
 
 762   map { $form->{$_} = $ref->{$_} } keys %$ref;
 
 766     $main::lxdebug->leave_sub();
 
 772   $query = qq|SELECT cp_id, invnumber, transdate AS invdate, duedate,
 
 773                 orddate, quodate, globalproject_id,
 
 774                 ordnumber, quonumber, paid, taxincluded, notes, taxzone_id, storno, gldate,
 
 775                 intnotes, curr AS currency
 
 778   $ref = selectfirst_hashref_query($form, $dbh, $query, conv_i($form->{id}));
 
 779   map { $form->{$_} = $ref->{$_} } keys %$ref;
 
 781   $form->{exchangerate}  = $form->get_exchangerate($dbh, $form->{currency}, $form->{invdate}, "sell");
 
 784   $query = qq|SELECT * FROM shipto WHERE (trans_id = ?) AND (module = 'AP')|;
 
 785   $ref = selectfirst_hashref_query($form, $dbh, $query, conv_i($form->{id}));
 
 787   map { $form->{$_} = $ref->{$_} } keys %$ref;
 
 789   my $transdate  = $form->{invdate} ? $dbh->quote($form->{invdate}) : "current_date";
 
 790   my $taxzone_id = $form->{taxzone_id} * 1;
 
 792   $taxzone_id = 0 if ((3 < $taxzone_id) || (0 > $taxzone_id));
 
 794   # retrieve individual items
 
 797         c1.accno AS inventory_accno, c1.new_chart_id AS inventory_new_chart, date($transdate) - c1.valid_from AS inventory_valid,
 
 798         c2.accno AS income_accno,    c2.new_chart_id AS income_new_chart,    date($transdate) - c2.valid_from AS income_valid,
 
 799         c3.accno AS expense_accno,   c3.new_chart_id AS expense_new_chart,   date($transdate) - c3.valid_from AS expense_valid,
 
 802         i.description, i.qty, i.fxsellprice AS sellprice, i.parts_id AS id, i.unit, i.deliverydate, i.project_id, i.serialnumber,
 
 803         i.price_factor_id, i.price_factor, i.marge_price_factor, i.discount,
 
 804         p.partnumber, p.inventory_accno_id AS part_inventory_accno_id, p.bin, pr.projectnumber, pg.partsgroup
 
 807         JOIN parts p ON (i.parts_id = p.id)
 
 808         LEFT JOIN chart c1 ON ((SELECT inventory_accno_id             FROM buchungsgruppen WHERE id = p.buchungsgruppen_id) = c1.id)
 
 809         LEFT JOIN chart c2 ON ((SELECT income_accno_id_${taxzone_id}  FROM buchungsgruppen WHERE id = p.buchungsgruppen_id) = c2.id)
 
 810         LEFT JOIN chart c3 ON ((SELECT expense_accno_id_${taxzone_id} FROM buchungsgruppen WHERE id = p.buchungsgruppen_id) = c3.id)
 
 811         LEFT JOIN project pr    ON (i.project_id = pr.id)
 
 812         LEFT JOIN partsgroup pg ON (pg.id = p.partsgroup_id)
 
 817   $sth = prepare_execute_query($form, $dbh, $query, conv_i($form->{id}));
 
 819   while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
 
 820     # Retrieve custom variables.
 
 821     my $cvars = CVar->get_custom_variables(dbh        => $dbh,
 
 823                                            sub_module => 'invoice',
 
 824                                            trans_id   => $ref->{invoice_id},
 
 826     map { $ref->{"ic_cvar_$_->{name}"} = $_->{value} } @{ $cvars };
 
 827     delete $ref->{invoice_id};
 
 829     map({ delete($ref->{$_}); } qw(inventory_accno inventory_new_chart inventory_valid)) if !$ref->{"part_inventory_accno_id"};
 
 830     delete($ref->{"part_inventory_accno_id"});
 
 832     foreach my $type (qw(inventory income expense)) {
 
 833       while ($ref->{"${type}_new_chart"} && ($ref->{"${type}_valid"} >=0)) {
 
 834         my $query = qq|SELECT accno, new_chart_id, date($transdate) - valid_from FROM chart WHERE id = ?|;
 
 835         @$ref{ map $type.$_, qw(_accno _new_chart _valid) } = selectrow_query($form, $dbh, $query, $ref->{"${type}_new_chart"});
 
 839     # get tax rates and description
 
 840     my $accno_id = ($form->{vc} eq "customer") ? $ref->{income_accno} : $ref->{expense_accno};
 
 842       qq|SELECT c.accno, t.taxdescription, t.rate, t.taxnumber FROM tax t
 
 843          LEFT JOIN chart c ON (c.id = t.chart_id)
 
 845            (SELECT tk.tax_id FROM taxkeys tk
 
 846             WHERE tk.chart_id = (SELECT id FROM chart WHERE accno = ?)
 
 847               AND (startdate <= $transdate)
 
 848             ORDER BY startdate DESC
 
 851     my $stw = prepare_execute_query($form, $dbh, $query, $accno_id);
 
 852     $ref->{taxaccounts} = "";
 
 855     while (my $ptr = $stw->fetchrow_hashref("NAME_lc")) {
 
 856       if (($ptr->{accno} eq "") && ($ptr->{rate} == 0)) {
 
 861       $ref->{taxaccounts} .= "$ptr->{accno} ";
 
 863       if (!($form->{taxaccounts} =~ /\Q$ptr->{accno}\E/)) {
 
 864         $form->{"$ptr->{accno}_rate"}         = $ptr->{rate};
 
 865         $form->{"$ptr->{accno}_description"}  = $ptr->{taxdescription};
 
 866         $form->{"$ptr->{accno}_taxnumber"}    = $ptr->{taxnumber};
 
 867         $form->{taxaccounts}                 .= "$ptr->{accno} ";
 
 872     chop $ref->{taxaccounts};
 
 873     push @{ $form->{invoice_details} }, $ref;
 
 878   Common::webdav_folder($form) if ($main::webdav);
 
 882   $main::lxdebug->leave_sub();
 
 886   $main::lxdebug->enter_sub();
 
 888   my ($self, $myconfig, $form, $params) = @_;
 
 890   $params = $form unless defined $params && ref $params eq "HASH";
 
 892   # connect to database
 
 893   my $dbh = $form->dbconnect($myconfig);
 
 895   my $dateformat = $myconfig->{dateformat};
 
 896   $dateformat .= "yy" if $myconfig->{dateformat} !~ /^y/;
 
 898   my $vid = conv_i($params->{vendor_id});
 
 899   my $vnr = conv_i($params->{vendornumber});
 
 903     ? "to_date(" . $dbh->quote($params->{invdate}) . ", '$dateformat')"
 
 910     $where .= 'AND v.id = ?';
 
 914     $where .= 'AND v.vendornumber = ?';
 
 919          v.id AS vendor_id, v.name AS vendor, v.discount as vendor_discount,
 
 920          v.creditlimit, v.terms, v.notes AS intnotes,
 
 921          v.email, v.cc, v.bcc, v.language_id, v.payment_id,
 
 922          v.street, v.zipcode, v.city, v.country, v.taxzone_id,
 
 923          $duedate + COALESCE(pt.terms_netto, 0) AS duedate,
 
 924          b.description AS business
 
 926        LEFT JOIN business b       ON (b.id = v.business_id)
 
 927        LEFT JOIN payment_terms pt ON (v.payment_id = pt.id)
 
 929   my $ref = selectfirst_hashref_query($form, $dbh, $query, @values);
 
 930   map { $params->{$_} = $ref->{$_} } keys %$ref;
 
 932   $params->{creditremaining} = $params->{creditlimit};
 
 934   $query = qq|SELECT SUM(amount - paid) FROM ap WHERE vendor_id = ?|;
 
 935   my ($unpaid_invoices) = selectfirst_array_query($form, $dbh, $query, $vid);
 
 936   $params->{creditremaining} -= $unpaid_invoices;
 
 938   $query = qq|SELECT o.amount,
 
 941                  WHERE (e.curr = o.curr)
 
 942                    AND (e.transdate = o.transdate)) AS exch
 
 944               WHERE (o.vendor_id = ?) AND (o.quotation = '0') AND (o.closed = '0')|;
 
 945   my $sth = prepare_execute_query($form, $dbh, $query, $vid);
 
 946   while (my ($amount, $exch) = $sth->fetchrow_array()) {
 
 947     $exch = 1 unless $exch;
 
 948     $params->{creditremaining} -= $amount * $exch;
 
 952   # get shipto if we do not convert an order or invoice
 
 953   if (!$params->{shipto}) {
 
 954     delete @{$params}{qw(shiptoname shiptostreet shiptozipcode shiptocity shiptocountry shiptocontact shiptophone shiptofax shiptoemail)};
 
 956     $query = qq|SELECT * FROM shipto WHERE (trans_id = ?) AND (module= 'CT')|;
 
 957     $ref = selectfirst_hashref_query($form, $dbh, $query, $vid);
 
 958     @{$params}{keys %$ref} = @{$ref}{keys %$ref};
 
 959     map { $params->{$_} = $ref->{$_} } keys %$ref;
 
 962   if (!$params->{id} && $params->{type} !~ /_(order|quotation)/) {
 
 963     # setup last accounts used
 
 965       qq|SELECT c.id, c.accno, c.description, c.link, c.category
 
 967          JOIN acc_trans ac ON (ac.chart_id = c.id)
 
 968          JOIN ap a         ON (a.id = ac.trans_id)
 
 969          WHERE (a.vendor_id = ?)
 
 970            AND (NOT ((c.link LIKE '%_tax%') OR (c.link LIKE '%_paid%')))
 
 971            AND (a.id IN (SELECT max(a2.id) FROM ap a2 WHERE a2.vendor_id = ?))|;
 
 972     my $refs = selectall_hashref_query($form, $dbh, $query, $vid, $vid);
 
 976       if ($ref->{category} eq 'E') {
 
 979         if ($params->{initial_transdate}) {
 
 980           my $tax_query = qq|SELECT tk.tax_id, t.rate FROM taxkeys tk
 
 981                              LEFT JOIN tax t ON (tk.tax_id = t.id)
 
 982                              WHERE (tk.chart_id = ?) AND (startdate <= ?)
 
 983                              ORDER BY tk.startdate DESC
 
 985           ($tax_id, $rate) = selectrow_query($form, $dbh, $tax_query, $ref->{id}, $params->{initial_transdate});
 
 986           $params->{"taxchart_$i"} = "${tax_id}--${rate}";
 
 989         $params->{"AP_amount_$i"} = "$ref->{accno}--$tax_id";
 
 992       if ($ref->{category} eq 'L') {
 
 993         $params->{APselected} = $params->{AP_1} = $ref->{accno};
 
 996     $params->{rowcount} = $i if ($i && !$params->{type});
 
1001   $main::lxdebug->leave_sub();
 
1005   $main::lxdebug->enter_sub();
 
1007   my ($self, $myconfig, $form) = @_;
 
1009   # connect to database
 
1010   my $dbh = $form->dbconnect($myconfig);
 
1012   my $i = $form->{rowcount};
 
1014   # don't include assemblies or obsolete parts
 
1015   my $where = "NOT p.assembly = '1' AND NOT p.obsolete = '1'";
 
1018   foreach my $table_column (qw(p.partnumber p.description pg.partsgroup)) {
 
1019     my $field = (split m{\.}, $table_column)[1];
 
1020     next unless $form->{"${field}_${i}"};
 
1021     $where .= " AND lower(${table_column}) LIKE lower(?)";
 
1022     push @values, '%' . $form->{"${field}_${i}"} . '%';
 
1024   #Es soll auch nach EAN gesucht werden, ohne Einschränkung durch Beschreibung
 
1025   if ($form->{"partnumber_$i"} && !$form->{"description_$i"}) {
 
1026       $where .= qq| OR (NOT p.obsolete = '1' AND p.ean = ? )|;
 
1027       push @values, $form->{"partnumber_$i"};
 
1030   if ($form->{"description_$i"}) {
 
1031     $where .= " ORDER BY p.description";
 
1033     $where .= " ORDER BY p.partnumber";
 
1037   if ($form->{type} eq "invoice") {
 
1038     $transdate = $form->{invdate} ? $dbh->quote($form->{invdate}) : "current_date";
 
1040     $transdate = $form->{transdate} ? $dbh->quote($form->{transdate}) : "current_date";
 
1043   my $taxzone_id = $form->{taxzone_id} * 1;
 
1044   $taxzone_id    = 0 if ((3 < $taxzone_id) || (0 > $taxzone_id));
 
1048          p.id, p.partnumber, p.description, p.lastcost AS sellprice, p.listprice,
 
1049          p.unit, p.assembly, p.bin, p.onhand, p.formel,
 
1050          p.notes AS partnotes, p.notes AS longdescription, p.not_discountable,
 
1051          p.inventory_accno_id, p.price_factor_id,
 
1053          pfac.factor AS price_factor,
 
1055          c1.accno                         AS inventory_accno,
 
1056          c1.new_chart_id                  AS inventory_new_chart,
 
1057          date($transdate) - c1.valid_from AS inventory_valid,
 
1059          c2.accno                         AS income_accno,
 
1060          c2.new_chart_id                  AS income_new_chart,
 
1061          date($transdate) - c2.valid_from AS income_valid,
 
1063          c3.accno                         AS expense_accno,
 
1064          c3.new_chart_id                  AS expense_new_chart,
 
1065          date($transdate) - c3.valid_from AS expense_valid,
 
1070        LEFT JOIN chart c1 ON
 
1071          ((SELECT inventory_accno_id
 
1072            FROM buchungsgruppen
 
1073            WHERE id = p.buchungsgruppen_id) = c1.id)
 
1074        LEFT JOIN chart c2 ON
 
1075          ((SELECT income_accno_id_${taxzone_id}
 
1076            FROM buchungsgruppen
 
1077            WHERE id = p.buchungsgruppen_id) = c2.id)
 
1078        LEFT JOIN chart c3 ON
 
1079          ((SELECT expense_accno_id_${taxzone_id}
 
1080            FROM buchungsgruppen
 
1081            WHERE id = p.buchungsgruppen_id) = c3.id)
 
1082        LEFT JOIN partsgroup pg ON (pg.id = p.partsgroup_id)
 
1083        LEFT JOIN price_factors pfac ON (pfac.id = p.price_factor_id)
 
1085   my $sth = prepare_execute_query($form, $dbh, $query, @values);
 
1087   $form->{item_list} = [];
 
1088   while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
 
1090     # In der Buchungsgruppe ist immer ein Bestandskonto verknuepft, auch wenn
 
1091     # es sich um eine Dienstleistung handelt. Bei Dienstleistungen muss das
 
1092     # Buchungskonto also aus dem Ergebnis rausgenommen werden.
 
1093     if (!$ref->{inventory_accno_id}) {
 
1094       map({ delete($ref->{"inventory_${_}"}); } qw(accno new_chart valid));
 
1096     delete($ref->{inventory_accno_id});
 
1098     # get tax rates and description
 
1099     my $accno_id = ($form->{vc} eq "customer") ? $ref->{income_accno} : $ref->{expense_accno};
 
1101       qq|SELECT c.accno, t.taxdescription, t.rate, t.taxnumber
 
1103          LEFT JOIN chart c on (c.id = t.chart_id)
 
1111               AND (startdate <= $transdate)
 
1112             ORDER BY startdate DESC
 
1115     my $stw = prepare_execute_query($form, $dbh, $query, $accno_id);
 
1117     $ref->{taxaccounts} = "";
 
1119     while (my $ptr = $stw->fetchrow_hashref("NAME_lc")) {
 
1121       #    if ($customertax{$ref->{accno}}) {
 
1122       if (($ptr->{accno} eq "") && ($ptr->{rate} == 0)) {
 
1127       $ref->{taxaccounts} .= "$ptr->{accno} ";
 
1129       if (!($form->{taxaccounts} =~ /\Q$ptr->{accno}\E/)) {
 
1130         $form->{"$ptr->{accno}_rate"}         = $ptr->{rate};
 
1131         $form->{"$ptr->{accno}_description"}  = $ptr->{taxdescription};
 
1132         $form->{"$ptr->{accno}_taxnumber"}    = $ptr->{taxnumber};
 
1133         $form->{taxaccounts}                 .= "$ptr->{accno} ";
 
1139     chop $ref->{taxaccounts};
 
1141     $ref->{onhand} *= 1;
 
1143     push @{ $form->{item_list} }, $ref;
 
1149   foreach my $item (@{ $form->{item_list} }) {
 
1150     my $custom_variables = CVar->get_custom_variables(module   => 'IC',
 
1151                                                       trans_id => $item->{id},
 
1155     map { $item->{"ic_cvar_" . $_->{name} } = $_->{value} } @{ $custom_variables };
 
1160   $main::lxdebug->leave_sub();
 
1163 sub vendor_details {
 
1164   $main::lxdebug->enter_sub();
 
1166   my ($self, $myconfig, $form, @wanted_vars) = @_;
 
1168   # connect to database
 
1169   my $dbh = $form->dbconnect($myconfig);
 
1173   # get contact id, set it if nessessary
 
1174   $form->{cp_id} *= 1;
 
1176   if ($form->{cp_id}) {
 
1177     $contact = "AND cp.cp_id = ?";
 
1178     push @values, $form->{cp_id};
 
1181   # get rest for the vendor
 
1182   # fax and phone and email as vendor*
 
1184     qq|SELECT ct.*, cp.*, ct.notes as vendornotes, phone as vendorphone, fax as vendorfax, email as vendoremail
 
1186        LEFT JOIN contacts cp ON (ct.id = cp.cp_cv_id)
 
1187        WHERE (ct.id = ?) $contact
 
1190   my $ref = selectfirst_hashref_query($form, $dbh, $query, $form->{vendor_id}, @values);
 
1192   # remove id and taxincluded before copy back
 
1193   delete @$ref{qw(id taxincluded)};
 
1195   @wanted_vars = grep({ $_ } @wanted_vars);
 
1196   if (scalar(@wanted_vars) > 0) {
 
1198     map({ $h_wanted_vars{$_} = 1; } @wanted_vars);
 
1199     map({ delete($ref->{$_}) unless ($h_wanted_vars{$_}); } keys(%{$ref}));
 
1202   map { $form->{$_} = $ref->{$_} } keys %$ref;
 
1204   my $custom_variables = CVar->get_custom_variables('dbh'      => $dbh,
 
1206                                                     'trans_id' => $form->{vendor_id});
 
1207   map { $form->{"vc_cvar_$_->{name}"} = $_->{value} } @{ $custom_variables };
 
1209   $form->{cp_greeting} = GenericTranslations->get('dbh'              => $dbh,
 
1210                                                   'translation_type' => 'greetings::' . ($form->{cp_gender} eq 'f' ? 'female' : 'male'),
 
1211                                                   'allow_fallback'   => 1);
 
1215   $main::lxdebug->leave_sub();
 
1219   $main::lxdebug->enter_sub();
 
1221   my ($self, $myconfig, $form) = @_;
 
1223   # connect to database
 
1224   my $dbh = $form->dbconnect($myconfig);
 
1227     qq|SELECT accno, description, link
 
1229        WHERE link LIKE '%IC%'
 
1231   my $sth = prepare_execute_query($query, $dbh, $query);
 
1233   while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
 
1234     foreach my $key (split(/:/, $ref->{link})) {
 
1236         push @{ $form->{IC_links}{$key} },
 
1237           { accno       => $ref->{accno},
 
1238             description => $ref->{description} };
 
1246   $main::lxdebug->leave_sub();
 
1249 sub _delete_payments {
 
1250   $main::lxdebug->enter_sub();
 
1252   my ($self, $form, $dbh) = @_;
 
1254   my @delete_acc_trans_ids;
 
1256   # Delete old payment entries from acc_trans.
 
1258     qq|SELECT acc_trans_id
 
1260        WHERE (trans_id = ?) AND fx_transaction
 
1264        SELECT at.acc_trans_id
 
1266        LEFT JOIN chart c ON (at.chart_id = c.id)
 
1267        WHERE (trans_id = ?) AND (c.link LIKE '%AP_paid%')|;
 
1268   push @delete_acc_trans_ids, selectall_array_query($form, $dbh, $query, conv_i($form->{id}), conv_i($form->{id}));
 
1271     qq|SELECT at.acc_trans_id
 
1273        LEFT JOIN chart c ON (at.chart_id = c.id)
 
1274        WHERE (trans_id = ?)
 
1275          AND ((c.link = 'AP') OR (c.link LIKE '%:AP') OR (c.link LIKE 'AP:%'))
 
1276        ORDER BY at.acc_trans_id
 
1278   push @delete_acc_trans_ids, selectall_array_query($form, $dbh, $query, conv_i($form->{id}));
 
1280   if (@delete_acc_trans_ids) {
 
1281     $query = qq|DELETE FROM acc_trans WHERE acc_trans_id IN (| . join(", ", @delete_acc_trans_ids) . qq|)|;
 
1282     do_query($form, $dbh, $query);
 
1285   $main::lxdebug->leave_sub();
 
1289   $main::lxdebug->enter_sub();
 
1291   my ($self, $myconfig, $form, $locale) = @_;
 
1293   # connect to database, turn off autocommit
 
1294   my $dbh = $form->dbconnect_noauto($myconfig);
 
1296   my (%payments, $old_form, $row, $item, $query, %keep_vars);
 
1298   $old_form = save_form();
 
1300   # Delete all entries in acc_trans from prior payments.
 
1301   $self->_delete_payments($form, $dbh);
 
1303   # Save the new payments the user made before cleaning up $form.
 
1304   map { $payments{$_} = $form->{$_} } grep m/^datepaid_\d+$|^memo_\d+$|^source_\d+$|^exchangerate_\d+$|^paid_\d+$|^AP_paid_\d+$|^paidaccounts$/, keys %{ $form };
 
1306   # Clean up $form so that old content won't tamper the results.
 
1307   %keep_vars = map { $_, 1 } qw(login password id);
 
1308   map { delete $form->{$_} unless $keep_vars{$_} } keys %{ $form };
 
1310   # Retrieve the invoice from the database.
 
1311   $self->retrieve_invoice($myconfig, $form);
 
1313   # Set up the content of $form in the way that IR::post_invoice() expects.
 
1314   $form->{exchangerate} = $form->format_amount($myconfig, $form->{exchangerate});
 
1316   for $row (1 .. scalar @{ $form->{invoice_details} }) {
 
1317     $item = $form->{invoice_details}->[$row - 1];
 
1319     map { $item->{$_} = $form->format_amount($myconfig, $item->{$_}) } qw(qty sellprice);
 
1321     map { $form->{"${_}_${row}"} = $item->{$_} } keys %{ $item };
 
1324   $form->{rowcount} = scalar @{ $form->{invoice_details} };
 
1326   delete @{$form}{qw(invoice_details paidaccounts storno paid)};
 
1328   # Restore the payment options from the user input.
 
1329   map { $form->{$_} = $payments{$_} } keys %payments;
 
1331   # Get the AP accno (which is normally done by Form::create_links()).
 
1335        LEFT JOIN chart c ON (at.chart_id = c.id)
 
1336        WHERE (trans_id = ?)
 
1337          AND ((c.link = 'AP') OR (c.link LIKE '%:AP') OR (c.link LIKE 'AP:%'))
 
1338        ORDER BY at.acc_trans_id
 
1341   ($form->{AP}) = selectfirst_array_query($form, $dbh, $query, conv_i($form->{id}));
 
1343   # Post the new payments.
 
1344   $self->post_invoice($myconfig, $form, $dbh, 1);
 
1346   restore_form($old_form);
 
1348   my $rc = $dbh->commit();
 
1351   $main::lxdebug->leave_sub();
 
1357   $main::lxdebug->enter_sub();
 
1362   if (!$params{vendor_id} || !$params{invdate}) {
 
1363     $main::lxdebug->leave_sub();
 
1364     return $params{default};
 
1367   my $myconfig = \%main::myconfig;
 
1368   my $form     = $main::form;
 
1370   my $dbh      = $params{dbh} || $form->get_standard_dbh($myconfig);
 
1372   my $query    = qq|SELECT ?::date + pt.terms_netto
 
1374                     LEFT JOIN payment_terms pt ON (pt.id = v.payment_id)
 
1377   my ($sth, $duedate);
 
1379   if (($sth = $dbh->prepare($query)) && $sth->execute($params{invdate}, conv_i($params{vendor_id}))) {
 
1380     ($duedate) = $sth->fetchrow_array();
 
1386   $duedate ||= $params{default};
 
1388   $main::lxdebug->leave_sub();