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;
 
  46 use List::Util qw(min);
 
  51   $main::lxdebug->enter_sub();
 
  53   my ($self, $myconfig, $form, $provided_dbh, $payments_only) = @_;
 
  55   # connect to database, turn off autocommit
 
  56   my $dbh = $provided_dbh ? $provided_dbh : $form->dbconnect_noauto($myconfig);
 
  57   $form->{defaultcurrency} = $form->get_default_currency($myconfig);
 
  59   my $ic_cvar_configs = CVar->get_configs(module => 'IC',
 
  62   my ($query, $sth, @values, $project_id);
 
  63   my ($allocated, $taxrate, $taxamount, $taxdiff, $item);
 
  64   my ($amount, $linetotal, $lastinventoryaccno, $lastexpenseaccno);
 
  65   my ($netamount, $invoicediff, $expensediff) = (0, 0, 0);
 
  67   my ($basefactor, $baseqty, @taxaccounts, $totaltax);
 
  69   my $all_units = AM->retrieve_units($myconfig, $form);
 
  71   if (!$payments_only) {
 
  73       &reverse_invoice($dbh, $form);
 
  75       ($form->{id}) = selectrow_query($form, $dbh, qq|SELECT nextval('glid')|);
 
  76       do_query($form, $dbh, qq|INSERT INTO ap (id, invnumber) VALUES (?, '')|, $form->{id});
 
  80   my ($currencies)    = selectfirst_array_query($form, $dbh, qq|SELECT curr FROM defaults|);
 
  81   my $defaultcurrency = (split m/:/, $currencies)[0];
 
  83   if ($form->{currency} eq $defaultcurrency) {
 
  84     $form->{exchangerate} = 1;
 
  86     $exchangerate = $form->check_exchangerate($myconfig, $form->{currency}, $form->{transdate}, 'sell');
 
  89   $form->{exchangerate} = $exchangerate || $form->parse_amount($myconfig, $form->{exchangerate});
 
  90   $form->{exchangerate} = 1 unless ($form->{exchangerate} * 1);
 
  93   my $q_item_unit = qq|SELECT unit FROM parts WHERE id = ?|;
 
  94   my $h_item_unit = prepare_query($form, $dbh, $q_item_unit);
 
  96   $form->get_lists('price_factors' => 'ALL_PRICE_FACTORS');
 
  97   my %price_factors = map { $_->{id} => $_->{factor} } @{ $form->{ALL_PRICE_FACTORS} };
 
 100   for my $i (1 .. $form->{rowcount}) {
 
 101     next unless $form->{"id_$i"};
 
 103     $form->{"qty_$i"}  = $form->parse_amount($myconfig, $form->{"qty_$i"});
 
 104     $form->{"qty_$i"} *= -1 if $form->{storno};
 
 106     $form->{"inventory_accno_$i"} = $form->{"expense_accno_$i"} if $::lx_office_conf{system}->{eur};
 
 109     if (!$item_units{$form->{"id_$i"}}) {
 
 110       do_statement($form, $h_item_unit, $q_item_unit, $form->{"id_$i"});
 
 111       ($item_units{$form->{"id_$i"}}) = $h_item_unit->fetchrow_array();
 
 114     my $item_unit = $item_units{$form->{"id_$i"}};
 
 116     if (defined($all_units->{$item_unit}->{factor})
 
 117             && ($all_units->{$item_unit}->{factor} ne '')
 
 118             && ($all_units->{$item_unit}->{factor} * 1 != 0)) {
 
 119       $basefactor = $all_units->{$form->{"unit_$i"}}->{factor} / $all_units->{$item_unit}->{factor};
 
 123     $baseqty = $form->{"qty_$i"} * $basefactor;
 
 125     @taxaccounts = split / /, $form->{"taxaccounts_$i"};
 
 130     $form->{"sellprice_$i"} = $form->parse_amount($myconfig, $form->{"sellprice_$i"});
 
 131     (my $fxsellprice = $form->{"sellprice_$i"}) =~ /\.(\d+)/;
 
 133     my $decimalplaces = ($dec > 2) ? $dec : 2;
 
 135     map { $taxrate += $form->{"${_}_rate"} } @taxaccounts;
 
 137     $price_factor = $price_factors{ $form->{"price_factor_id_$i"} } || 1;
 
 138     #####################################################################
 
 139     # das ist aus IS.pm kopiert. schlimm. jb 7.10.2009
 
 140     # ich würde mir wünschen, dass diese vier stellen zusammengefasst werden
 
 141     # ... vier stellen = (einkauf + verkauf) * (maske + backend)
 
 142     # ansonsten stolpert man immer wieder viermal statt einmal heftig
 
 143     # und auch das undo discount formatting ist nicht besonders wartungsfreundlich
 
 145     # keine ahnung wofür das in IS.pm gemacht wird:
 
 146     #      my ($dec) = ($fxsellprice =~ /\.(\d+)/);
 
 147     #  $dec = length $dec;
 
 148     #  my $decimalplaces = ($dec > 2) ? $dec : 2;
 
 150     # undo discount formatting
 
 151     $form->{"discount_$i"} = $form->parse_amount($myconfig, $form->{"discount_$i"}) / 100;
 
 153     $form->{"sellprice_$i"} = $fxsellprice * (1 - $form->{"discount_$i"});
 
 155     ######################################################################
 
 156     if ($form->{"inventory_accno_$i"}) {
 
 158       $linetotal = $form->round_amount($form->{"sellprice_$i"} * $form->{"qty_$i"} / $price_factor, 2);
 
 160       if ($form->{taxincluded}) {
 
 162         $taxamount              = $linetotal * ($taxrate / (1 + $taxrate));
 
 163         $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, longdescription, 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->{"longdescription_$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     # in the sales invoice case rounding errors only have to be corrected for
 
 388     # income accounts, it is enough to add the total rounding error to one of
 
 389     # the income accounts, with the one assigned to the last row being used
 
 390     # (lastinventoryaccno)
 
 392     # in the purchase invoice case rounding errors may be split between
 
 393     # inventory accounts and expense accounts. After rounding, an error of 1
 
 394     # cent is introduced if the total rounding error exceeds 0.005. The total
 
 395     # error is made up of $invoicediff and $expensediff, however, so if both
 
 396     # values are below 0.005, but add up to a total >= 0.005, correcting
 
 397     # lastinventoryaccno and lastexpenseaccno separately has no effect after
 
 398     # rounding. This caused bug 1579. Therefore when the combined total exceeds
 
 399     # 0.005, but neither do individually, the account with the larger value
 
 400     # shall receive the total rounding error, and the next time it is rounded
 
 401     # the 1 cent correction will be introduced.
 
 403     my $total_rounding_diff = $invoicediff+$expensediff;
 
 405     $form->{amount}{ $form->{id} }{$lastinventoryaccno} -= $invoicediff if $lastinventoryaccno;
 
 406     $form->{amount}{ $form->{id} }{$lastexpenseaccno}   -= $expensediff if $lastexpenseaccno;
 
 408     if ( ($expensediff+$invoicediff) >= 0.005 and $expensediff < 0.005 and $invoicediff < 0.005 ) {
 
 410       # in total the rounding error adds up to 1 cent effectively, correct the
 
 411       # larger of the two numbers
 
 413       if ( abs($form->{amount}{ $form->{id} }{$lastinventoryaccno}) > abs($form->{amount}{ $form->{id} }{$lastexpenseaccno}) ) {
 
 414         # $invoicediff has already been deducted, now also deduct expensediff
 
 415         $form->{amount}{ $form->{id} }{$lastinventoryaccno}   -= $expensediff;
 
 417         # expensediff has already been deducted, now also deduct invoicediff
 
 418         $form->{amount}{ $form->{id} }{$lastexpenseaccno}   -= $invoicediff;
 
 423     $amount    = $form->round_amount($netamount * $form->{exchangerate}, 2);
 
 424     $paiddiff  = $amount - $netamount * $form->{exchangerate};
 
 425     $netamount = $amount;
 
 427     foreach my $item (split / /, $form->{taxaccounts}) {
 
 428       $form->{amount}{ $form->{id} }{$item}  = $form->round_amount($form->{amount}{ $form->{id} }{$item}, 2);
 
 429       $amount                                = $form->round_amount( $form->{amount}{ $form->{id} }{$item} * $form->{exchangerate} * -1, 2);
 
 430       $paiddiff                             += $amount - $form->{amount}{ $form->{id} }{$item} * $form->{exchangerate} * -1;
 
 431       $form->{amount}{ $form->{id} }{$item}  = $form->round_amount($amount * -1, 2);
 
 432       $amount                                = $form->{amount}{ $form->{id} }{$item} * -1;
 
 437   $form->{amount}{ $form->{id} }{ $form->{AP} } = $netamount + $tax;
 
 440   $form->{paid} = $form->round_amount($form->{paid} * $form->{exchangerate} + $paiddiff, 2) if $form->{paid} != 0;
 
 442 # update exchangerate
 
 444   $form->update_exchangerate($dbh, $form->{currency}, $form->{invdate}, 0, $form->{exchangerate})
 
 445     if ($form->{currency} ne $defaultcurrency) && !$exchangerate;
 
 447 # record acc_trans transactions
 
 448   foreach my $trans_id (keys %{ $form->{amount} }) {
 
 449     foreach my $accno (keys %{ $form->{amount}{$trans_id} }) {
 
 450       $form->{amount}{$trans_id}{$accno} = $form->round_amount($form->{amount}{$trans_id}{$accno}, 2);
 
 453       next if $payments_only || !$form->{amount}{$trans_id}{$accno};
 
 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 = ($trans_id, $accno, $form->{amount}{$trans_id}{$accno},
 
 459                  conv_date($form->{invdate}), $accno, $project_id);
 
 460       do_query($form, $dbh, $query, @values);
 
 464   # deduct payment differences from paiddiff
 
 465   for my $i (1 .. $form->{paidaccounts}) {
 
 466     if ($form->{"paid_$i"} != 0) {
 
 467       $amount    = $form->round_amount($form->{"paid_$i"} * $form->{exchangerate}, 2);
 
 468       $paiddiff -= $amount - $form->{"paid_$i"} * $form->{exchangerate};
 
 472   # force AP entry if 0
 
 474   $form->{amount}{ $form->{id} }{ $form->{AP} } = $form->{paid} if $form->{amount}{$form->{id}}{$form->{AP}} == 0;
 
 476   # record payments and offsetting AP
 
 477   for my $i (1 .. $form->{paidaccounts}) {
 
 478     next if $form->{"paid_$i"} == 0;
 
 480     my ($accno)            = split /--/, $form->{"AP_paid_$i"};
 
 481     $form->{"datepaid_$i"} = $form->{invdate} unless ($form->{"datepaid_$i"});
 
 482     $form->{datepaid}      = $form->{"datepaid_$i"};
 
 484     $amount = $form->round_amount($form->{"paid_$i"} * $form->{exchangerate} + $paiddiff, 2) * -1;
 
 487     if ($form->{amount}{ $form->{id} }{ $form->{AP} } != 0) {
 
 488       $query = qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate, taxkey, project_id)
 
 489                   VALUES (?, (SELECT id FROM chart WHERE accno = ?), ?, ?,
 
 490                           (SELECT taxkey_id FROM chart WHERE accno = ?), ?)|;
 
 491       @values = (conv_i($form->{id}), $form->{AP}, $amount,
 
 492                  $form->{"datepaid_$i"}, $form->{AP}, $project_id);
 
 493       do_query($form, $dbh, $query, @values);
 
 497     $query = qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate, source, memo, taxkey, project_id)
 
 498                 VALUES (?, (SELECT id FROM chart WHERE accno = ?), ?, ?, ?, ?,
 
 499                 (SELECT taxkey_id FROM chart WHERE accno = ?), ?)|;
 
 500     @values = (conv_i($form->{id}), $accno, $form->{"paid_$i"}, $form->{"datepaid_$i"},
 
 501                $form->{"source_$i"}, $form->{"memo_$i"}, $accno, $project_id);
 
 502     do_query($form, $dbh, $query, @values);
 
 506     if ($form->{currency} eq $defaultcurrency) {
 
 507       $form->{"exchangerate_$i"} = 1;
 
 509       $exchangerate              = $form->check_exchangerate($myconfig, $form->{currency}, $form->{"datepaid_$i"}, 'sell');
 
 510       $form->{"exchangerate_$i"} = $exchangerate || $form->parse_amount($myconfig, $form->{"exchangerate_$i"});
 
 513     # exchangerate difference
 
 514     $form->{fx}{$accno}{ $form->{"datepaid_$i"} } += $form->{"paid_$i"} * ($form->{"exchangerate_$i"} - 1) + $paiddiff;
 
 518       ($form->{"paid_$i"} * $form->{exchangerate}) -
 
 519       ($form->{"paid_$i"} * $form->{"exchangerate_$i"});
 
 521       $form->{fx}{ $form->{fxgain_accno} }{ $form->{"datepaid_$i"} } += $amount;
 
 523       $form->{fx}{ $form->{fxloss_accno} }{ $form->{"datepaid_$i"} } += $amount;
 
 528     # update exchange rate
 
 529     $form->update_exchangerate($dbh, $form->{currency}, $form->{"datepaid_$i"}, 0, $form->{"exchangerate_$i"})
 
 530       if ($form->{currency} ne $defaultcurrency) && !$exchangerate;
 
 533   # record exchange rate differences and gains/losses
 
 534   foreach my $accno (keys %{ $form->{fx} }) {
 
 535     foreach my $transdate (keys %{ $form->{fx}{$accno} }) {
 
 536       $form->{fx}{$accno}{$transdate} = $form->round_amount($form->{fx}{$accno}{$transdate}, 2);
 
 537       next if ($form->{fx}{$accno}{$transdate} == 0);
 
 539       $query = qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate, cleared, fx_transaction, taxkey, project_id)
 
 540                   VALUES (?, (SELECT id FROM chart WHERE accno = ?), ?, ?, '0', '1', 0, ?)|;
 
 541       @values = (conv_i($form->{id}), $accno, $form->{fx}{$accno}{$transdate}, conv_date($transdate), $project_id);
 
 542       do_query($form, $dbh, $query, @values);
 
 546   IO->set_datepaid(table => 'ap', id => $form->{id}, dbh => $dbh);
 
 548   if ($payments_only) {
 
 549     $query = qq|UPDATE ap SET paid = ? WHERE id = ?|;
 
 550     do_query($form, $dbh, $query, $form->{paid}, conv_i($form->{id}));
 
 552     if (!$provided_dbh) {
 
 557     $main::lxdebug->leave_sub();
 
 561   $amount = $netamount + $tax;
 
 563   # set values which could be empty
 
 564   my $taxzone_id         = $form->{taxzone_id} * 1;
 
 566   # Seit neuestem wird die department_id schon übergeben UND $form->department nicht mehr
 
 567   # korrekt zusammengebaut. Sehr wahrscheinlich beim Umstieg auf T8 kaputt gegangen
 
 568   # Ich lass den Code von 2005 erstmal noch stehen ;-) jb 03-2011
 
 569   # copy & paste von IS.pm
 
 570   if (!$form->{department_id}){
 
 571     $form->{department_id} = (split /--/, $form->{department})[1];
 
 573   $form->{invnumber}     = $form->{id} unless $form->{invnumber};
 
 575   $taxzone_id = 0 if (3 < $taxzone_id) || (0 > $taxzone_id);
 
 578   $query = qq|UPDATE ap SET
 
 579                 invnumber    = ?, ordnumber   = ?, quonumber     = ?, transdate   = ?,
 
 580                 orddate      = ?, quodate     = ?, vendor_id     = ?, amount      = ?,
 
 581                 netamount    = ?, paid        = ?, duedate       = ?,
 
 582                 invoice      = ?, taxzone_id  = ?, notes         = ?, taxincluded = ?,
 
 583                 intnotes     = ?, curr        = ?, storno_id     = ?, storno      = ?,
 
 584                 cp_id        = ?, employee_id = ?, department_id = ?,
 
 588                 $form->{invnumber},          $form->{ordnumber},           $form->{quonumber},      conv_date($form->{invdate}),
 
 589       conv_date($form->{orddate}), conv_date($form->{quodate}),     conv_i($form->{vendor_id}),               $amount,
 
 590                 $netamount,                  $form->{paid},      conv_date($form->{duedate}),
 
 591             '1',                             $taxzone_id,                  $form->{notes},          $form->{taxincluded} ? 't' : 'f',
 
 592                 $form->{intnotes},           $form->{currency},     conv_i($form->{storno_id}),     $form->{storno}      ? 't' : 'f',
 
 593          conv_i($form->{cp_id}),      conv_i($form->{employee_id}), conv_i($form->{department_id}),
 
 594          conv_i($form->{globalproject_id}),
 
 597   do_query($form, $dbh, $query, @values);
 
 599   if ($form->{storno}) {
 
 600     $query = qq|UPDATE ap SET paid = paid + amount WHERE id = ?|;
 
 601     do_query($form, $dbh, $query, conv_i($form->{storno_id}));
 
 603     $query = qq|UPDATE ap SET storno = 't' WHERE id = ?|;
 
 604     do_query($form, $dbh, $query, conv_i($form->{storno_id}));
 
 606     $query = qq!UPDATE ap SET intnotes = ? || intnotes WHERE id = ?!;
 
 607     do_query($form, $dbh, $query, "Rechnung storniert am $form->{invdate} ", conv_i($form->{storno_id}));
 
 609     $query = qq|UPDATE ap SET paid = amount WHERE id = ?|;
 
 610     do_query($form, $dbh, $query, conv_i($form->{id}));
 
 615   $form->{name} = $form->{vendor};
 
 616   $form->{name} =~ s/--\Q$form->{vendor_id}\E//;
 
 617   $form->add_shipto($dbh, $form->{id}, "AP");
 
 619   # delete zero entries
 
 620   do_query($form, $dbh, qq|DELETE FROM acc_trans WHERE amount = 0|);
 
 622   Common::webdav_folder($form);
 
 624   # Link this record to the records it was created from.
 
 625   RecordLinks->create_links('dbh'        => $dbh,
 
 627                             'from_table' => 'oe',
 
 628                             'from_ids'   => $form->{convert_from_oe_ids},
 
 630                             'to_id'      => $form->{id},
 
 632   delete $form->{convert_from_oe_ids};
 
 634   my @convert_from_do_ids = map { $_ * 1 } grep { $_ } split m/\s+/, $form->{convert_from_do_ids};
 
 635   if (scalar @convert_from_do_ids) {
 
 636     DO->close_orders('dbh' => $dbh,
 
 637                      'ids' => \@convert_from_do_ids);
 
 639     RecordLinks->create_links('dbh'        => $dbh,
 
 641                               'from_table' => 'delivery_orders',
 
 642                               'from_ids'   => \@convert_from_do_ids,
 
 644                               'to_id'      => $form->{id},
 
 647   delete $form->{convert_from_do_ids};
 
 649   ARAP->close_orders_if_billed('dbh'     => $dbh,
 
 650                                'arap_id' => $form->{id},
 
 654   if (!$provided_dbh) {
 
 655     $rc = $dbh->commit();
 
 659   $main::lxdebug->leave_sub();
 
 664 sub reverse_invoice {
 
 665   $main::lxdebug->enter_sub();
 
 667   my ($dbh, $form) = @_;
 
 669   # reverse inventory items
 
 671     qq|SELECT i.parts_id, p.inventory_accno_id, p.expense_accno_id, i.qty, i.allocated, i.sellprice
 
 672        FROM invoice i, parts p
 
 673        WHERE (i.parts_id = p.id)
 
 674          AND (i.trans_id = ?)|;
 
 675   my $sth = prepare_execute_query($form, $dbh, $query, conv_i($form->{id}));
 
 679   while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
 
 680     $netamount += $form->round_amount($ref->{sellprice} * $ref->{qty} * -1, 2);
 
 682     next unless $ref->{inventory_accno_id};
 
 684     # if $ref->{allocated} > 0 than we sold that many items
 
 685     next if ($ref->{allocated} <= 0);
 
 687     # get references for sold items
 
 689       qq|SELECT i.id, i.trans_id, i.allocated, a.transdate
 
 691          WHERE (i.parts_id = ?)
 
 692            AND (i.allocated < 0)
 
 693            AND (i.trans_id = a.id)
 
 694          ORDER BY transdate DESC|;
 
 695       my $sth2 = prepare_execute_query($form, $dbh, $query, $ref->{parts_id});
 
 697       while (my $pthref = $sth2->fetchrow_hashref("NAME_lc")) {
 
 698         my $qty = $ref->{allocated};
 
 699         if (($ref->{allocated} + $pthref->{allocated}) > 0) {
 
 700           $qty = $pthref->{allocated} * -1;
 
 703         my $amount = $form->round_amount($ref->{sellprice} * $qty, 2);
 
 706         $form->update_balance($dbh, "invoice", "allocated", qq|id = $pthref->{id}|, $qty);
 
 708         $form->update_balance($dbh, "acc_trans", "amount",
 
 709                               qq|    (trans_id = $pthref->{trans_id})
 
 710                                  AND (chart_id = $ref->{expense_accno_id})
 
 711                                  AND (transdate = '$pthref->{transdate}')|,
 
 714         $form->update_balance($dbh, "acc_trans", "amount",
 
 715                               qq|    (trans_id = $pthref->{trans_id})
 
 716                                  AND (chart_id = $ref->{inventory_accno_id})
 
 717                                  AND (transdate = '$pthref->{transdate}')|,
 
 720         last if (($ref->{allocated} -= $qty) <= 0);
 
 726   my $id = conv_i($form->{id});
 
 729   $query = qq|DELETE FROM acc_trans WHERE trans_id = ?|;
 
 730   do_query($form, $dbh, $query, $id);
 
 732   # delete invoice entries
 
 733   $query = qq|DELETE FROM invoice WHERE trans_id = ?|;
 
 734   do_query($form, $dbh, $query, $id);
 
 736   $query = qq|DELETE FROM shipto WHERE (trans_id = ?) AND (module = 'AP')|;
 
 737   do_query($form, $dbh, $query, $id);
 
 739   $main::lxdebug->leave_sub();
 
 743   $main::lxdebug->enter_sub();
 
 745   my ($self, $myconfig, $form) = @_;
 
 747   # connect to database
 
 748   my $dbh = $form->dbconnect_noauto($myconfig);
 
 750   &reverse_invoice($dbh, $form);
 
 752   # delete zero entries
 
 753   $query = qq|DELETE FROM acc_trans WHERE amount = 0|;
 
 754   do_query($form, $dbh, $query);
 
 757   $query = qq|DELETE FROM ap WHERE id = ?|;
 
 758   do_query($form, $dbh, $query, conv_i($form->{id}));
 
 760   my $rc = $dbh->commit;
 
 763   $main::lxdebug->leave_sub();
 
 768 sub retrieve_invoice {
 
 769   $main::lxdebug->enter_sub();
 
 771   my ($self, $myconfig, $form) = @_;
 
 773   # connect to database
 
 774   my $dbh = $form->dbconnect($myconfig);
 
 776   my ($query, $sth, $ref, $q_invdate);
 
 779     $q_invdate = qq|, COALESCE((SELECT transdate FROM ar WHERE id = (SELECT MAX(id) FROM ar)), current_date) AS invdate|;
 
 780     if ($form->{vendor_id}) {
 
 781       my $vendor_id = $dbh->quote($form->{vendor_id} * 1);
 
 783         qq|, COALESCE((SELECT transdate FROM ar WHERE id = (SELECT MAX(id) FROM ar)), current_date) +
 
 784              COALESCE((SELECT pt.terms_netto
 
 786                        LEFT JOIN payment_terms pt ON (v.payment_id = pt.id)
 
 787                        WHERE v.id = $vendor_id),
 
 792   # get default accounts and last invoice number
 
 795                (SELECT c.accno FROM chart c WHERE d.inventory_accno_id = c.id) AS inventory_accno,
 
 796                (SELECT c.accno FROM chart c WHERE d.income_accno_id = c.id)    AS income_accno,
 
 797                (SELECT c.accno FROM chart c WHERE d.expense_accno_id = c.id)   AS expense_accno,
 
 798                (SELECT c.accno FROM chart c WHERE d.fxgain_accno_id = c.id)    AS fxgain_accno,
 
 799                (SELECT c.accno FROM chart c WHERE d.fxloss_accno_id = c.id)    AS fxloss_accno,
 
 803   $ref = selectfirst_hashref_query($form, $dbh, $query);
 
 804   map { $form->{$_} = $ref->{$_} } keys %$ref;
 
 808     $main::lxdebug->leave_sub();
 
 814   $query = qq|SELECT cp_id, invnumber, transdate AS invdate, duedate,
 
 815                 orddate, quodate, globalproject_id,
 
 816                 ordnumber, quonumber, paid, taxincluded, notes, taxzone_id, storno, gldate,
 
 817                 intnotes, curr AS currency
 
 820   $ref = selectfirst_hashref_query($form, $dbh, $query, conv_i($form->{id}));
 
 821   map { $form->{$_} = $ref->{$_} } keys %$ref;
 
 823   $form->{exchangerate}  = $form->get_exchangerate($dbh, $form->{currency}, $form->{invdate}, "sell");
 
 826   $query = qq|SELECT * FROM shipto WHERE (trans_id = ?) AND (module = 'AP')|;
 
 827   $ref = selectfirst_hashref_query($form, $dbh, $query, conv_i($form->{id}));
 
 829   map { $form->{$_} = $ref->{$_} } keys %$ref;
 
 831   my $transdate  = $form->{invdate} ? $dbh->quote($form->{invdate}) : "current_date";
 
 832   my $taxzone_id = $form->{taxzone_id} * 1;
 
 834   $taxzone_id = 0 if ((3 < $taxzone_id) || (0 > $taxzone_id));
 
 836   # retrieve individual items
 
 839         c1.accno AS inventory_accno, c1.new_chart_id AS inventory_new_chart, date($transdate) - c1.valid_from AS inventory_valid,
 
 840         c2.accno AS income_accno,    c2.new_chart_id AS income_new_chart,    date($transdate) - c2.valid_from AS income_valid,
 
 841         c3.accno AS expense_accno,   c3.new_chart_id AS expense_new_chart,   date($transdate) - c3.valid_from AS expense_valid,
 
 844         i.description, i.longdescription, i.qty, i.fxsellprice AS sellprice, i.parts_id AS id, i.unit, i.deliverydate, i.project_id, i.serialnumber,
 
 845         i.price_factor_id, i.price_factor, i.marge_price_factor, i.discount,
 
 846         p.partnumber, p.inventory_accno_id AS part_inventory_accno_id, p.bin, pr.projectnumber, pg.partsgroup
 
 849         JOIN parts p ON (i.parts_id = p.id)
 
 850         LEFT JOIN chart c1 ON ((SELECT inventory_accno_id             FROM buchungsgruppen WHERE id = p.buchungsgruppen_id) = c1.id)
 
 851         LEFT JOIN chart c2 ON ((SELECT income_accno_id_${taxzone_id}  FROM buchungsgruppen WHERE id = p.buchungsgruppen_id) = c2.id)
 
 852         LEFT JOIN chart c3 ON ((SELECT expense_accno_id_${taxzone_id} FROM buchungsgruppen WHERE id = p.buchungsgruppen_id) = c3.id)
 
 853         LEFT JOIN project pr    ON (i.project_id = pr.id)
 
 854         LEFT JOIN partsgroup pg ON (pg.id = p.partsgroup_id)
 
 859   $sth = prepare_execute_query($form, $dbh, $query, conv_i($form->{id}));
 
 861   while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
 
 862     # Retrieve custom variables.
 
 863     my $cvars = CVar->get_custom_variables(dbh        => $dbh,
 
 865                                            sub_module => 'invoice',
 
 866                                            trans_id   => $ref->{invoice_id},
 
 868     map { $ref->{"ic_cvar_$_->{name}"} = $_->{value} } @{ $cvars };
 
 869     delete $ref->{invoice_id};
 
 871     map({ delete($ref->{$_}); } qw(inventory_accno inventory_new_chart inventory_valid)) if !$ref->{"part_inventory_accno_id"};
 
 872     delete($ref->{"part_inventory_accno_id"});
 
 874     foreach my $type (qw(inventory income expense)) {
 
 875       while ($ref->{"${type}_new_chart"} && ($ref->{"${type}_valid"} >=0)) {
 
 876         my $query = qq|SELECT accno, new_chart_id, date($transdate) - valid_from FROM chart WHERE id = ?|;
 
 877         @$ref{ map $type.$_, qw(_accno _new_chart _valid) } = selectrow_query($form, $dbh, $query, $ref->{"${type}_new_chart"});
 
 881     # get tax rates and description
 
 882     my $accno_id = ($form->{vc} eq "customer") ? $ref->{income_accno} : $ref->{expense_accno};
 
 884       qq|SELECT c.accno, t.taxdescription, t.rate, t.taxnumber FROM tax t
 
 885          LEFT JOIN chart c ON (c.id = t.chart_id)
 
 887            (SELECT tk.tax_id FROM taxkeys tk
 
 888             WHERE tk.chart_id = (SELECT id FROM chart WHERE accno = ?)
 
 889               AND (startdate <= $transdate)
 
 890             ORDER BY startdate DESC
 
 893     my $stw = prepare_execute_query($form, $dbh, $query, $accno_id);
 
 894     $ref->{taxaccounts} = "";
 
 897     while (my $ptr = $stw->fetchrow_hashref("NAME_lc")) {
 
 898       if (($ptr->{accno} eq "") && ($ptr->{rate} == 0)) {
 
 903       $ref->{taxaccounts} .= "$ptr->{accno} ";
 
 905       if (!($form->{taxaccounts} =~ /\Q$ptr->{accno}\E/)) {
 
 906         $form->{"$ptr->{accno}_rate"}         = $ptr->{rate};
 
 907         $form->{"$ptr->{accno}_description"}  = $ptr->{taxdescription};
 
 908         $form->{"$ptr->{accno}_taxnumber"}    = $ptr->{taxnumber};
 
 909         $form->{taxaccounts}                 .= "$ptr->{accno} ";
 
 914     chop $ref->{taxaccounts};
 
 915     push @{ $form->{invoice_details} }, $ref;
 
 920   Common::webdav_folder($form);
 
 924   $main::lxdebug->leave_sub();
 
 928   $main::lxdebug->enter_sub();
 
 930   my ($self, $myconfig, $form, $params) = @_;
 
 932   $params = $form unless defined $params && ref $params eq "HASH";
 
 934   # connect to database
 
 935   my $dbh = $form->dbconnect($myconfig);
 
 937   my $dateformat = $myconfig->{dateformat};
 
 938   $dateformat .= "yy" if $myconfig->{dateformat} !~ /^y/;
 
 940   my $vid = conv_i($params->{vendor_id});
 
 941   my $vnr = conv_i($params->{vendornumber});
 
 945     ? "to_date(" . $dbh->quote($params->{invdate}) . ", '$dateformat')"
 
 952     $where .= 'AND v.id = ?';
 
 956     $where .= 'AND v.vendornumber = ?';
 
 961          v.id AS vendor_id, v.name AS vendor, v.discount as vendor_discount,
 
 962          v.creditlimit, v.terms, v.notes AS intnotes,
 
 963          v.email, v.cc, v.bcc, v.language_id, v.payment_id,
 
 964          v.street, v.zipcode, v.city, v.country, v.taxzone_id,
 
 965          $duedate + COALESCE(pt.terms_netto, 0) AS duedate,
 
 966          b.description AS business
 
 968        LEFT JOIN business b       ON (b.id = v.business_id)
 
 969        LEFT JOIN payment_terms pt ON (v.payment_id = pt.id)
 
 971   my $ref = selectfirst_hashref_query($form, $dbh, $query, @values);
 
 972   map { $params->{$_} = $ref->{$_} } keys %$ref;
 
 974   $params->{creditremaining} = $params->{creditlimit};
 
 976   $query = qq|SELECT SUM(amount - paid) FROM ap WHERE vendor_id = ?|;
 
 977   my ($unpaid_invoices) = selectfirst_array_query($form, $dbh, $query, $vid);
 
 978   $params->{creditremaining} -= $unpaid_invoices;
 
 980   $query = qq|SELECT o.amount,
 
 983                  WHERE (e.curr = o.curr)
 
 984                    AND (e.transdate = o.transdate)) AS exch
 
 986               WHERE (o.vendor_id = ?) AND (o.quotation = '0') AND (o.closed = '0')|;
 
 987   my $sth = prepare_execute_query($form, $dbh, $query, $vid);
 
 988   while (my ($amount, $exch) = $sth->fetchrow_array()) {
 
 989     $exch = 1 unless $exch;
 
 990     $params->{creditremaining} -= $amount * $exch;
 
 994   # get shipto if we do not convert an order or invoice
 
 995   if (!$params->{shipto}) {
 
 996     delete @{$params}{qw(shiptoname shiptostreet shiptozipcode shiptocity shiptocountry shiptocontact shiptophone shiptofax shiptoemail)};
 
 998     $query = qq|SELECT * FROM shipto WHERE (trans_id = ?) AND (module= 'CT')|;
 
 999     $ref = selectfirst_hashref_query($form, $dbh, $query, $vid);
 
1000     @{$params}{keys %$ref} = @{$ref}{keys %$ref};
 
1001     map { $params->{$_} = $ref->{$_} } keys %$ref;
 
1004   if (!$params->{id} && $params->{type} !~ /_(order|quotation)/) {
 
1005     # setup last accounts used
 
1007       qq|SELECT c.id, c.accno, c.description, c.link, c.category
 
1009          JOIN acc_trans ac ON (ac.chart_id = c.id)
 
1010          JOIN ap a         ON (a.id = ac.trans_id)
 
1011          WHERE (a.vendor_id = ?)
 
1012            AND (NOT ((c.link LIKE '%_tax%') OR (c.link LIKE '%_paid%')))
 
1013            AND (a.id IN (SELECT max(a2.id) FROM ap a2 WHERE a2.vendor_id = ?))|;
 
1014     my $refs = selectall_hashref_query($form, $dbh, $query, $vid, $vid);
 
1018       if ($ref->{category} eq 'E') {
 
1020         my ($tax_id, $rate);
 
1021         if ($params->{initial_transdate}) {
 
1022           my $tax_query = qq|SELECT tk.tax_id, t.rate FROM taxkeys tk
 
1023                              LEFT JOIN tax t ON (tk.tax_id = t.id)
 
1024                              WHERE (tk.chart_id = ?) AND (startdate <= ?)
 
1025                              ORDER BY tk.startdate DESC
 
1027           ($tax_id, $rate) = selectrow_query($form, $dbh, $tax_query, $ref->{id}, $params->{initial_transdate});
 
1028           $params->{"taxchart_$i"} = "${tax_id}--${rate}";
 
1031         $params->{"AP_amount_$i"} = "$ref->{accno}--$tax_id";
 
1034       if ($ref->{category} eq 'L') {
 
1035         $params->{APselected} = $params->{AP_1} = $ref->{accno};
 
1038     $params->{rowcount} = $i if ($i && !$params->{type});
 
1043   $main::lxdebug->leave_sub();
 
1047   $main::lxdebug->enter_sub();
 
1049   my ($self, $myconfig, $form) = @_;
 
1051   # connect to database
 
1052   my $dbh = $form->dbconnect($myconfig);
 
1054   my $i = $form->{rowcount};
 
1056   # don't include assemblies or obsolete parts
 
1057   my $where = "NOT p.assembly = '1' AND NOT p.obsolete = '1'";
 
1060   foreach my $table_column (qw(p.partnumber p.description pg.partsgroup)) {
 
1061     my $field = (split m{\.}, $table_column)[1];
 
1062     next unless $form->{"${field}_${i}"};
 
1063     $where .= " AND lower(${table_column}) LIKE lower(?)";
 
1064     push @values, '%' . $form->{"${field}_${i}"} . '%';
 
1066   #Es soll auch nach EAN gesucht werden, ohne Einschränkung durch Beschreibung
 
1067   if ($form->{"partnumber_$i"} && !$form->{"description_$i"}) {
 
1068       $where .= qq| OR (NOT p.obsolete = '1' AND p.ean = ? )|;
 
1069       push @values, $form->{"partnumber_$i"};
 
1072   if ($form->{"description_$i"}) {
 
1073     $where .= " ORDER BY p.description";
 
1075     $where .= " ORDER BY p.partnumber";
 
1079   if ($form->{type} eq "invoice") {
 
1080     $transdate = $form->{invdate} ? $dbh->quote($form->{invdate}) : "current_date";
 
1082     $transdate = $form->{transdate} ? $dbh->quote($form->{transdate}) : "current_date";
 
1085   my $taxzone_id = $form->{taxzone_id} * 1;
 
1086   $taxzone_id    = 0 if ((3 < $taxzone_id) || (0 > $taxzone_id));
 
1090          p.id, p.partnumber, p.description, p.lastcost AS sellprice, p.listprice,
 
1091          p.unit, p.assembly, p.bin, p.onhand, p.formel,
 
1092          p.notes AS partnotes, p.notes AS longdescription, p.not_discountable,
 
1093          p.inventory_accno_id, p.price_factor_id,
 
1095          pfac.factor AS price_factor,
 
1097          c1.accno                         AS inventory_accno,
 
1098          c1.new_chart_id                  AS inventory_new_chart,
 
1099          date($transdate) - c1.valid_from AS inventory_valid,
 
1101          c2.accno                         AS income_accno,
 
1102          c2.new_chart_id                  AS income_new_chart,
 
1103          date($transdate) - c2.valid_from AS income_valid,
 
1105          c3.accno                         AS expense_accno,
 
1106          c3.new_chart_id                  AS expense_new_chart,
 
1107          date($transdate) - c3.valid_from AS expense_valid,
 
1112        LEFT JOIN chart c1 ON
 
1113          ((SELECT inventory_accno_id
 
1114            FROM buchungsgruppen
 
1115            WHERE id = p.buchungsgruppen_id) = c1.id)
 
1116        LEFT JOIN chart c2 ON
 
1117          ((SELECT income_accno_id_${taxzone_id}
 
1118            FROM buchungsgruppen
 
1119            WHERE id = p.buchungsgruppen_id) = c2.id)
 
1120        LEFT JOIN chart c3 ON
 
1121          ((SELECT expense_accno_id_${taxzone_id}
 
1122            FROM buchungsgruppen
 
1123            WHERE id = p.buchungsgruppen_id) = c3.id)
 
1124        LEFT JOIN partsgroup pg ON (pg.id = p.partsgroup_id)
 
1125        LEFT JOIN price_factors pfac ON (pfac.id = p.price_factor_id)
 
1127   my $sth = prepare_execute_query($form, $dbh, $query, @values);
 
1129   $form->{item_list} = [];
 
1130   while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
 
1132     # In der Buchungsgruppe ist immer ein Bestandskonto verknuepft, auch wenn
 
1133     # es sich um eine Dienstleistung handelt. Bei Dienstleistungen muss das
 
1134     # Buchungskonto also aus dem Ergebnis rausgenommen werden.
 
1135     if (!$ref->{inventory_accno_id}) {
 
1136       map({ delete($ref->{"inventory_${_}"}); } qw(accno new_chart valid));
 
1138     delete($ref->{inventory_accno_id});
 
1140     # get tax rates and description
 
1141     my $accno_id = ($form->{vc} eq "customer") ? $ref->{income_accno} : $ref->{expense_accno};
 
1143       qq|SELECT c.accno, t.taxdescription, t.rate, t.taxnumber
 
1145          LEFT JOIN chart c on (c.id = t.chart_id)
 
1153               AND (startdate <= $transdate)
 
1154             ORDER BY startdate DESC
 
1157     my $stw = prepare_execute_query($form, $dbh, $query, $accno_id);
 
1159     $ref->{taxaccounts} = "";
 
1161     while (my $ptr = $stw->fetchrow_hashref("NAME_lc")) {
 
1163       #    if ($customertax{$ref->{accno}}) {
 
1164       if (($ptr->{accno} eq "") && ($ptr->{rate} == 0)) {
 
1169       $ref->{taxaccounts} .= "$ptr->{accno} ";
 
1171       if (!($form->{taxaccounts} =~ /\Q$ptr->{accno}\E/)) {
 
1172         $form->{"$ptr->{accno}_rate"}         = $ptr->{rate};
 
1173         $form->{"$ptr->{accno}_description"}  = $ptr->{taxdescription};
 
1174         $form->{"$ptr->{accno}_taxnumber"}    = $ptr->{taxnumber};
 
1175         $form->{taxaccounts}                 .= "$ptr->{accno} ";
 
1181     chop $ref->{taxaccounts};
 
1183     $ref->{onhand} *= 1;
 
1185     push @{ $form->{item_list} }, $ref;
 
1191   foreach my $item (@{ $form->{item_list} }) {
 
1192     my $custom_variables = CVar->get_custom_variables(module   => 'IC',
 
1193                                                       trans_id => $item->{id},
 
1197     map { $item->{"ic_cvar_" . $_->{name} } = $_->{value} } @{ $custom_variables };
 
1202   $main::lxdebug->leave_sub();
 
1205 sub vendor_details {
 
1206   $main::lxdebug->enter_sub();
 
1208   my ($self, $myconfig, $form, @wanted_vars) = @_;
 
1210   # connect to database
 
1211   my $dbh = $form->dbconnect($myconfig);
 
1215   # get contact id, set it if nessessary
 
1216   $form->{cp_id} *= 1;
 
1218   if ($form->{cp_id}) {
 
1219     $contact = "AND cp.cp_id = ?";
 
1220     push @values, $form->{cp_id};
 
1223   # get rest for the vendor
 
1224   # fax and phone and email as vendor*
 
1226     qq|SELECT ct.*, cp.*, ct.notes as vendornotes, phone as vendorphone, fax as vendorfax, email as vendoremail
 
1228        LEFT JOIN contacts cp ON (ct.id = cp.cp_cv_id)
 
1229        WHERE (ct.id = ?) $contact
 
1232   my $ref = selectfirst_hashref_query($form, $dbh, $query, $form->{vendor_id}, @values);
 
1234   # remove id and taxincluded before copy back
 
1235   delete @$ref{qw(id taxincluded)};
 
1237   @wanted_vars = grep({ $_ } @wanted_vars);
 
1238   if (scalar(@wanted_vars) > 0) {
 
1240     map({ $h_wanted_vars{$_} = 1; } @wanted_vars);
 
1241     map({ delete($ref->{$_}) unless ($h_wanted_vars{$_}); } keys(%{$ref}));
 
1244   map { $form->{$_} = $ref->{$_} } keys %$ref;
 
1246   my $custom_variables = CVar->get_custom_variables('dbh'      => $dbh,
 
1248                                                     'trans_id' => $form->{vendor_id});
 
1249   map { $form->{"vc_cvar_$_->{name}"} = $_->{value} } @{ $custom_variables };
 
1251   $form->{cp_greeting} = GenericTranslations->get('dbh'              => $dbh,
 
1252                                                   'translation_type' => 'greetings::' . ($form->{cp_gender} eq 'f' ? 'female' : 'male'),
 
1253                                                   'allow_fallback'   => 1);
 
1257   $main::lxdebug->leave_sub();
 
1261   $main::lxdebug->enter_sub();
 
1263   my ($self, $myconfig, $form) = @_;
 
1265   # connect to database
 
1266   my $dbh = $form->dbconnect($myconfig);
 
1269     qq|SELECT accno, description, link
 
1271        WHERE link LIKE '%IC%'
 
1273   my $sth = prepare_execute_query($query, $dbh, $query);
 
1275   while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
 
1276     foreach my $key (split(/:/, $ref->{link})) {
 
1278         push @{ $form->{IC_links}{$key} },
 
1279           { accno       => $ref->{accno},
 
1280             description => $ref->{description} };
 
1288   $main::lxdebug->leave_sub();
 
1291 sub _delete_payments {
 
1292   $main::lxdebug->enter_sub();
 
1294   my ($self, $form, $dbh) = @_;
 
1296   my @delete_acc_trans_ids;
 
1298   # Delete old payment entries from acc_trans.
 
1300     qq|SELECT acc_trans_id
 
1302        WHERE (trans_id = ?) AND fx_transaction
 
1306        SELECT at.acc_trans_id
 
1308        LEFT JOIN chart c ON (at.chart_id = c.id)
 
1309        WHERE (trans_id = ?) AND (c.link LIKE '%AP_paid%')|;
 
1310   push @delete_acc_trans_ids, selectall_array_query($form, $dbh, $query, conv_i($form->{id}), conv_i($form->{id}));
 
1313     qq|SELECT at.acc_trans_id
 
1315        LEFT JOIN chart c ON (at.chart_id = c.id)
 
1316        WHERE (trans_id = ?)
 
1317          AND ((c.link = 'AP') OR (c.link LIKE '%:AP') OR (c.link LIKE 'AP:%'))
 
1318        ORDER BY at.acc_trans_id
 
1320   push @delete_acc_trans_ids, selectall_array_query($form, $dbh, $query, conv_i($form->{id}));
 
1322   if (@delete_acc_trans_ids) {
 
1323     $query = qq|DELETE FROM acc_trans WHERE acc_trans_id IN (| . join(", ", @delete_acc_trans_ids) . qq|)|;
 
1324     do_query($form, $dbh, $query);
 
1327   $main::lxdebug->leave_sub();
 
1331   $main::lxdebug->enter_sub();
 
1333   my ($self, $myconfig, $form, $locale) = @_;
 
1335   # connect to database, turn off autocommit
 
1336   my $dbh = $form->dbconnect_noauto($myconfig);
 
1338   my (%payments, $old_form, $row, $item, $query, %keep_vars);
 
1340   $old_form = save_form();
 
1342   # Delete all entries in acc_trans from prior payments.
 
1343   $self->_delete_payments($form, $dbh);
 
1345   # Save the new payments the user made before cleaning up $form.
 
1346   map { $payments{$_} = $form->{$_} } grep m/^datepaid_\d+$|^memo_\d+$|^source_\d+$|^exchangerate_\d+$|^paid_\d+$|^AP_paid_\d+$|^paidaccounts$/, keys %{ $form };
 
1348   # Clean up $form so that old content won't tamper the results.
 
1349   %keep_vars = map { $_, 1 } qw(login password id);
 
1350   map { delete $form->{$_} unless $keep_vars{$_} } keys %{ $form };
 
1352   # Retrieve the invoice from the database.
 
1353   $self->retrieve_invoice($myconfig, $form);
 
1355   # Set up the content of $form in the way that IR::post_invoice() expects.
 
1356   $form->{exchangerate} = $form->format_amount($myconfig, $form->{exchangerate});
 
1358   for $row (1 .. scalar @{ $form->{invoice_details} }) {
 
1359     $item = $form->{invoice_details}->[$row - 1];
 
1361     map { $item->{$_} = $form->format_amount($myconfig, $item->{$_}) } qw(qty sellprice);
 
1363     map { $form->{"${_}_${row}"} = $item->{$_} } keys %{ $item };
 
1366   $form->{rowcount} = scalar @{ $form->{invoice_details} };
 
1368   delete @{$form}{qw(invoice_details paidaccounts storno paid)};
 
1370   # Restore the payment options from the user input.
 
1371   map { $form->{$_} = $payments{$_} } keys %payments;
 
1373   # Get the AP accno (which is normally done by Form::create_links()).
 
1377        LEFT JOIN chart c ON (at.chart_id = c.id)
 
1378        WHERE (trans_id = ?)
 
1379          AND ((c.link = 'AP') OR (c.link LIKE '%:AP') OR (c.link LIKE 'AP:%'))
 
1380        ORDER BY at.acc_trans_id
 
1383   ($form->{AP}) = selectfirst_array_query($form, $dbh, $query, conv_i($form->{id}));
 
1385   # Post the new payments.
 
1386   $self->post_invoice($myconfig, $form, $dbh, 1);
 
1388   restore_form($old_form);
 
1390   my $rc = $dbh->commit();
 
1393   $main::lxdebug->leave_sub();
 
1399   $main::lxdebug->enter_sub();
 
1404   if (!$params{vendor_id} || !$params{invdate}) {
 
1405     $main::lxdebug->leave_sub();
 
1406     return $params{default};
 
1409   my $myconfig = \%main::myconfig;
 
1410   my $form     = $main::form;
 
1412   my $dbh      = $params{dbh} || $form->get_standard_dbh($myconfig);
 
1414   my $query    = qq|SELECT ?::date + pt.terms_netto
 
1416                     LEFT JOIN payment_terms pt ON (pt.id = v.payment_id)
 
1419   my ($sth, $duedate);
 
1421   if (($sth = $dbh->prepare($query)) && $sth->execute($params{invdate}, conv_i($params{vendor_id}))) {
 
1422     ($duedate) = $sth->fetchrow_array();
 
1428   $duedate ||= $params{default};
 
1430   $main::lxdebug->leave_sub();