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 if ( $::instance_conf->get_inventory_system eq 'periodic') {
107 # inventory account number is overwritten with expense account number, so
108 # never book incoming to inventory account but always to expense account
109 $form->{"inventory_accno_$i"} = $form->{"expense_accno_$i"}
113 if (!$item_units{$form->{"id_$i"}}) {
114 do_statement($form, $h_item_unit, $q_item_unit, $form->{"id_$i"});
115 ($item_units{$form->{"id_$i"}}) = $h_item_unit->fetchrow_array();
118 my $item_unit = $item_units{$form->{"id_$i"}};
120 if (defined($all_units->{$item_unit}->{factor})
121 && ($all_units->{$item_unit}->{factor} ne '')
122 && ($all_units->{$item_unit}->{factor} * 1 != 0)) {
123 $basefactor = $all_units->{$form->{"unit_$i"}}->{factor} / $all_units->{$item_unit}->{factor};
127 $baseqty = $form->{"qty_$i"} * $basefactor;
129 @taxaccounts = split / /, $form->{"taxaccounts_$i"};
134 $form->{"sellprice_$i"} = $form->parse_amount($myconfig, $form->{"sellprice_$i"});
135 (my $fxsellprice = $form->{"sellprice_$i"}) =~ /\.(\d+)/;
137 my $decimalplaces = ($dec > 2) ? $dec : 2;
139 map { $taxrate += $form->{"${_}_rate"} } @taxaccounts;
141 $price_factor = $price_factors{ $form->{"price_factor_id_$i"} } || 1;
142 #####################################################################
143 # das ist aus IS.pm kopiert. schlimm. jb 7.10.2009
144 # ich würde mir wünschen, dass diese vier stellen zusammengefasst werden
145 # ... vier stellen = (einkauf + verkauf) * (maske + backend)
146 # ansonsten stolpert man immer wieder viermal statt einmal heftig
147 # und auch das undo discount formatting ist nicht besonders wartungsfreundlich
149 # keine ahnung wofür das in IS.pm gemacht wird:
150 # my ($dec) = ($fxsellprice =~ /\.(\d+)/);
151 # $dec = length $dec;
152 # my $decimalplaces = ($dec > 2) ? $dec : 2;
154 # undo discount formatting
155 $form->{"discount_$i"} = $form->parse_amount($myconfig, $form->{"discount_$i"}) / 100;
157 $form->{"sellprice_$i"} = $fxsellprice * (1 - $form->{"discount_$i"});
159 ######################################################################
160 if ($form->{"inventory_accno_$i"}) {
162 $linetotal = $form->round_amount($form->{"sellprice_$i"} * $form->{"qty_$i"} / $price_factor, 2);
164 if ($form->{taxincluded}) {
166 $taxamount = $linetotal * ($taxrate / (1 + $taxrate));
167 $form->{"sellprice_$i"} = $form->{"sellprice_$i"} * (1 / (1 + $taxrate));
170 $taxamount = $linetotal * $taxrate;
173 $netamount += $linetotal;
175 if ($form->round_amount($taxrate, 7) == 0) {
176 if ($form->{taxincluded}) {
177 foreach $item (@taxaccounts) {
179 $form->round_amount($linetotal * $form->{"${item}_rate"} / (1 + abs($form->{"${item}_rate"})), 2);
180 $taxdiff += $taxamount;
181 $form->{amount}{ $form->{id} }{$item} -= $taxamount;
183 $form->{amount}{ $form->{id} }{ $taxaccounts[0] } += $taxdiff;
186 map { $form->{amount}{ $form->{id} }{$_} -= $linetotal * $form->{"${_}_rate"} } @taxaccounts;
190 map { $form->{amount}{ $form->{id} }{$_} -= $taxamount * $form->{"${_}_rate"} / $taxrate } @taxaccounts;
193 # add purchase to inventory, this one is without the tax!
194 $amount = $form->{"sellprice_$i"} * $form->{"qty_$i"} * $form->{exchangerate} / $price_factor;
195 $linetotal = $form->round_amount($form->{"sellprice_$i"} * $form->{"qty_$i"} / $price_factor, 2) * $form->{exchangerate};
196 $linetotal = $form->round_amount($linetotal, 2);
198 # this is the difference for the inventory
199 $invoicediff += ($amount - $linetotal);
201 $form->{amount}{ $form->{id} }{ $form->{"inventory_accno_$i"} } -= $linetotal;
203 # adjust and round sellprice
204 $form->{"sellprice_$i"} = $form->round_amount($form->{"sellprice_$i"} * $form->{exchangerate}, $decimalplaces);
206 $lastinventoryaccno = $form->{"inventory_accno_$i"};
208 next if $payments_only;
211 $query = qq|UPDATE parts SET lastcost = ? WHERE id = ?|;
212 @values = ($form->{"sellprice_$i"}, conv_i($form->{"id_$i"}));
213 do_query($form, $dbh, $query, @values);
215 # check if we sold the item already and
216 # make an entry for the expense and inventory
218 qq|SELECT i.id, i.qty, i.allocated, i.trans_id, i.base_qty,
219 p.inventory_accno_id, p.expense_accno_id, a.transdate
220 FROM invoice i, ar a, parts p
221 WHERE (i.parts_id = p.id)
223 AND ((i.base_qty + i.allocated) > 0)
224 AND (i.trans_id = a.id)
226 # ORDER BY transdate guarantees FIFO
228 # sold two items without having bought them yet, example result of query:
229 # id | qty | allocated | trans_id | inventory_accno_id | expense_accno_id | transdate
230 # ---+-----+-----------+----------+--------------------+------------------+------------
231 # 9 | 2 | 0 | 9 | 15 | 151 | 2011-01-05
233 # base_qty + allocated > 0 if article has already been sold but not bought yet
235 # select qty,allocated,base_qty,sellprice from invoice where trans_id = 9;
236 # qty | allocated | base_qty | sellprice
237 # -----+-----------+----------+------------
238 # 2 | 0 | 2 | 1000.00000
240 $sth = prepare_execute_query($form, $dbh, $query, conv_i($form->{"id_$i"}));
242 my $totalqty = $baseqty;
244 while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
245 my $qty = min $totalqty, ($ref->{base_qty} + $ref->{allocated});
246 $linetotal = $form->round_amount(($form->{"sellprice_$i"} * $qty) / $basefactor, 2);
248 if ( $::instance_conf->get_inventory_system eq 'perpetual' ) {
249 # Warenbestandsbuchungen nur bei Bestandsmethode
251 if ($ref->{allocated} < 0) {
253 # we have an entry for it already, adjust amount
254 $form->update_balance($dbh, "acc_trans", "amount",
255 qq| (trans_id = $ref->{trans_id})
256 AND (chart_id = $ref->{inventory_accno_id})
257 AND (transdate = '$ref->{transdate}')|,
260 $form->update_balance($dbh, "acc_trans", "amount",
261 qq| (trans_id = $ref->{trans_id})
262 AND (chart_id = $ref->{expense_accno_id})
263 AND (transdate = '$ref->{transdate}')|,
266 } elsif ($linetotal != 0) {
269 # add entry for inventory, this one is for the sold item
270 $query = qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate, taxkey) VALUES (?, ?, ?, ?, (SELECT taxkey_id FROM chart WHERE id = ?))|;
271 @values = ($ref->{trans_id}, $ref->{inventory_accno_id}, $linetotal, $ref->{transdate}, $ref->{inventory_accno_id});
272 do_query($form, $dbh, $query, @values);
275 $query = qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate, taxkey) VALUES (?, ?, ?, ?, (SELECT taxkey from tax WHERE chart_id = ?))|;
276 @values = ($ref->{trans_id}, $ref->{expense_accno_id}, ($linetotal * -1), $ref->{transdate}, $ref->{expense_accno_id});
277 do_query($form, $dbh, $query, @values);
281 # update allocated for sold item
282 $form->update_balance($dbh, "invoice", "allocated", qq|id = $ref->{id}|, $qty * -1);
286 last if ($totalqty -= $qty) <= 0;
291 } else { # if ($form->{"inventory_accno_id_$i"})
292 # part doesn't have an inventory_accno_id
293 # lastcost of the part is updated at the end
295 $linetotal = $form->round_amount($form->{"sellprice_$i"} * $form->{"qty_$i"} / $price_factor, 2);
297 if ($form->{taxincluded}) {
298 $taxamount = $linetotal * ($taxrate / (1 + $taxrate));
299 $form->{"sellprice_$i"} = $form->{"sellprice_$i"} * (1 / (1 + $taxrate));
302 $taxamount = $linetotal * $taxrate;
305 $netamount += $linetotal;
307 if ($form->round_amount($taxrate, 7) == 0) {
308 if ($form->{taxincluded}) {
309 foreach $item (@taxaccounts) {
310 $taxamount = $linetotal * $form->{"${item}_rate"} / (1 + abs($form->{"${item}_rate"}));
311 $totaltax += $taxamount;
312 $form->{amount}{ $form->{id} }{$item} -= $taxamount;
315 map { $form->{amount}{ $form->{id} }{$_} -= $linetotal * $form->{"${_}_rate"} } @taxaccounts;
318 map { $form->{amount}{ $form->{id} }{$_} -= $taxamount * $form->{"${_}_rate"} / $taxrate } @taxaccounts;
321 $amount = $form->{"sellprice_$i"} * $form->{"qty_$i"} * $form->{exchangerate} / $price_factor;
322 $linetotal = $form->round_amount($form->{"sellprice_$i"} * $form->{"qty_$i"} / $price_factor, 2) * $form->{exchangerate};
323 $linetotal = $form->round_amount($linetotal, 2);
325 # this is the difference for expense
326 $expensediff += ($amount - $linetotal);
328 # add amount to expense
329 $form->{amount}{ $form->{id} }{ $form->{"expense_accno_$i"} } -= $linetotal;
331 $lastexpenseaccno = $form->{"expense_accno_$i"};
333 # adjust and round sellprice
334 $form->{"sellprice_$i"} = $form->round_amount($form->{"sellprice_$i"} * $form->{exchangerate}, $decimalplaces);
336 next if $payments_only;
339 $query = qq|UPDATE parts SET lastcost = ? WHERE id = ?|;
340 do_query($form, $dbh, $query, $form->{"sellprice_$i"}, conv_i($form->{"id_$i"}));
343 next if $payments_only;
345 # save detail record in invoice table
346 my ($invoice_id) = selectfirst_array_query($form, $dbh, qq|SELECT nextval('invoiceid')|);
349 qq|INSERT INTO invoice (id, trans_id, parts_id, description, longdescription, qty, base_qty,
350 sellprice, fxsellprice, discount, allocated, unit, deliverydate,
351 project_id, serialnumber, price_factor_id, price_factor, marge_price_factor)
352 VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, (SELECT factor FROM price_factors WHERE id = ?), ?)|;
353 @values = ($invoice_id, conv_i($form->{id}), conv_i($form->{"id_$i"}),
354 $form->{"description_$i"}, $form->{"longdescription_$i"}, $form->{"qty_$i"} * -1,
355 $baseqty * -1, $form->{"sellprice_$i"}, $fxsellprice, $form->{"discount_$i"}, $allocated,
356 $form->{"unit_$i"}, conv_date($form->{deliverydate}),
357 conv_i($form->{"project_id_$i"}), $form->{"serialnumber_$i"},
358 conv_i($form->{"price_factor_id_$i"}), conv_i($form->{"price_factor_id_$i"}), conv_i($form->{"marge_price_factor_$i"}));
359 do_query($form, $dbh, $query, @values);
361 CVar->save_custom_variables(module => 'IC',
362 sub_module => 'invoice',
363 trans_id => $invoice_id,
364 configs => $ic_cvar_configs,
366 name_prefix => 'ic_',
367 name_postfix => "_$i",
371 $h_item_unit->finish();
373 $project_id = conv_i($form->{"globalproject_id"});
375 $form->{datepaid} = $form->{invdate};
377 # all amounts are in natural state, netamount includes the taxes
378 # if tax is included, netamount is rounded to 2 decimal places,
382 for my $i (1 .. $form->{paidaccounts}) {
383 $form->{"paid_$i"} = $form->parse_amount($myconfig, $form->{"paid_$i"});
384 $form->{paid} += $form->{"paid_$i"};
385 $form->{datepaid} = $form->{"datepaid_$i"} if $form->{"datepaid_$i"};
388 my ($tax, $paiddiff) = (0, 0);
390 $netamount = $form->round_amount($netamount, 2);
392 # figure out rounding errors for amount paid and total amount
393 if ($form->{taxincluded}) {
395 $amount = $form->round_amount($netamount * $form->{exchangerate}, 2);
396 $paiddiff = $amount - $netamount * $form->{exchangerate};
397 $netamount = $amount;
399 foreach $item (split / /, $form->{taxaccounts}) {
400 $amount = $form->{amount}{ $form->{id} }{$item} * $form->{exchangerate};
401 $form->{amount}{ $form->{id} }{$item} = $form->round_amount($amount, 2);
403 $amount = $form->{amount}{ $form->{id} }{$item} * -1;
405 $netamount -= $amount;
408 $invoicediff += $paiddiff;
409 $expensediff += $paiddiff;
411 ######## this only applies to tax included
413 # in the sales invoice case rounding errors only have to be corrected for
414 # income accounts, it is enough to add the total rounding error to one of
415 # the income accounts, with the one assigned to the last row being used
416 # (lastinventoryaccno)
418 # in the purchase invoice case rounding errors may be split between
419 # inventory accounts and expense accounts. After rounding, an error of 1
420 # cent is introduced if the total rounding error exceeds 0.005. The total
421 # error is made up of $invoicediff and $expensediff, however, so if both
422 # values are below 0.005, but add up to a total >= 0.005, correcting
423 # lastinventoryaccno and lastexpenseaccno separately has no effect after
424 # rounding. This caused bug 1579. Therefore when the combined total exceeds
425 # 0.005, but neither do individually, the account with the larger value
426 # shall receive the total rounding error, and the next time it is rounded
427 # the 1 cent correction will be introduced.
429 $form->{amount}{ $form->{id} }{$lastinventoryaccno} -= $invoicediff if $lastinventoryaccno;
430 $form->{amount}{ $form->{id} }{$lastexpenseaccno} -= $expensediff if $lastexpenseaccno;
432 if ( (abs($expensediff)+abs($invoicediff)) >= 0.005 and abs($expensediff) < 0.005 and abs($invoicediff) < 0.005 ) {
434 # in total the rounding error adds up to 1 cent effectively, correct the
435 # larger of the two numbers
437 if ( abs($form->{amount}{ $form->{id} }{$lastinventoryaccno}) > abs($form->{amount}{ $form->{id} }{$lastexpenseaccno}) ) {
438 # $invoicediff has already been deducted, now also deduct expensediff
439 $form->{amount}{ $form->{id} }{$lastinventoryaccno} -= $expensediff;
441 # expensediff has already been deducted, now also deduct invoicediff
442 $form->{amount}{ $form->{id} }{$lastexpenseaccno} -= $invoicediff;
447 $amount = $form->round_amount($netamount * $form->{exchangerate}, 2);
448 $paiddiff = $amount - $netamount * $form->{exchangerate};
449 $netamount = $amount;
451 foreach my $item (split / /, $form->{taxaccounts}) {
452 $form->{amount}{ $form->{id} }{$item} = $form->round_amount($form->{amount}{ $form->{id} }{$item}, 2);
453 $amount = $form->round_amount( $form->{amount}{ $form->{id} }{$item} * $form->{exchangerate} * -1, 2);
454 $paiddiff += $amount - $form->{amount}{ $form->{id} }{$item} * $form->{exchangerate} * -1;
455 $form->{amount}{ $form->{id} }{$item} = $form->round_amount($amount * -1, 2);
456 $amount = $form->{amount}{ $form->{id} }{$item} * -1;
461 $form->{amount}{ $form->{id} }{ $form->{AP} } = $netamount + $tax;
464 $form->{paid} = $form->round_amount($form->{paid} * $form->{exchangerate} + $paiddiff, 2) if $form->{paid} != 0;
466 # update exchangerate
468 $form->update_exchangerate($dbh, $form->{currency}, $form->{invdate}, 0, $form->{exchangerate})
469 if ($form->{currency} ne $defaultcurrency) && !$exchangerate;
471 # record acc_trans transactions
472 foreach my $trans_id (keys %{ $form->{amount} }) {
473 foreach my $accno (keys %{ $form->{amount}{$trans_id} }) {
474 $form->{amount}{$trans_id}{$accno} = $form->round_amount($form->{amount}{$trans_id}{$accno}, 2);
477 next if $payments_only || !$form->{amount}{$trans_id}{$accno};
479 $query = qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate, taxkey, project_id)
480 VALUES (?, (SELECT id FROM chart WHERE accno = ?), ?, ?,
481 (SELECT taxkey_id FROM chart WHERE accno = ?), ?)|;
482 @values = ($trans_id, $accno, $form->{amount}{$trans_id}{$accno},
483 conv_date($form->{invdate}), $accno, $project_id);
484 do_query($form, $dbh, $query, @values);
488 # deduct payment differences from paiddiff
489 for my $i (1 .. $form->{paidaccounts}) {
490 if ($form->{"paid_$i"} != 0) {
491 $amount = $form->round_amount($form->{"paid_$i"} * $form->{exchangerate}, 2);
492 $paiddiff -= $amount - $form->{"paid_$i"} * $form->{exchangerate};
496 # force AP entry if 0
498 $form->{amount}{ $form->{id} }{ $form->{AP} } = $form->{paid} if $form->{amount}{$form->{id}}{$form->{AP}} == 0;
500 # record payments and offsetting AP
501 for my $i (1 .. $form->{paidaccounts}) {
502 if ($form->{"acc_trans_id_$i"}
504 && ($::lx_office_conf{features}->{payments_changeable} == 0)) {
508 next if $form->{"paid_$i"} == 0;
510 my ($accno) = split /--/, $form->{"AP_paid_$i"};
511 $form->{"datepaid_$i"} = $form->{invdate} unless ($form->{"datepaid_$i"});
512 $form->{datepaid} = $form->{"datepaid_$i"};
514 $amount = $form->round_amount($form->{"paid_$i"} * $form->{exchangerate} + $paiddiff, 2) * -1;
517 if ($form->{amount}{ $form->{id} }{ $form->{AP} } != 0) {
518 $query = qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate, taxkey, project_id)
519 VALUES (?, (SELECT id FROM chart WHERE accno = ?), ?, ?,
520 (SELECT taxkey_id FROM chart WHERE accno = ?), ?)|;
521 @values = (conv_i($form->{id}), $form->{AP}, $amount,
522 $form->{"datepaid_$i"}, $form->{AP}, $project_id);
523 do_query($form, $dbh, $query, @values);
527 my $gldate = (conv_date($form->{"gldate_$i"}))? conv_date($form->{"gldate_$i"}) : conv_date($form->current_date($myconfig));
530 qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate, gldate, source, memo, taxkey, project_id)
531 VALUES (?, (SELECT id FROM chart WHERE accno = ?), ?, ?, ?, ?, ?,
532 (SELECT taxkey_id FROM chart WHERE accno = ?), ?)|;
533 @values = (conv_i($form->{id}), $accno, $form->{"paid_$i"}, $form->{"datepaid_$i"},
534 $gldate, $form->{"source_$i"}, $form->{"memo_$i"}, $accno, $project_id);
535 do_query($form, $dbh, $query, @values);
539 if ($form->{currency} eq $defaultcurrency) {
540 $form->{"exchangerate_$i"} = 1;
542 $exchangerate = $form->check_exchangerate($myconfig, $form->{currency}, $form->{"datepaid_$i"}, 'sell');
543 $form->{"exchangerate_$i"} = $exchangerate || $form->parse_amount($myconfig, $form->{"exchangerate_$i"});
546 # exchangerate difference
547 $form->{fx}{$accno}{ $form->{"datepaid_$i"} } += $form->{"paid_$i"} * ($form->{"exchangerate_$i"} - 1) + $paiddiff;
551 ($form->{"paid_$i"} * $form->{exchangerate}) -
552 ($form->{"paid_$i"} * $form->{"exchangerate_$i"});
554 $form->{fx}{ $form->{fxgain_accno} }{ $form->{"datepaid_$i"} } += $amount;
556 $form->{fx}{ $form->{fxloss_accno} }{ $form->{"datepaid_$i"} } += $amount;
561 # update exchange rate
562 $form->update_exchangerate($dbh, $form->{currency}, $form->{"datepaid_$i"}, 0, $form->{"exchangerate_$i"})
563 if ($form->{currency} ne $defaultcurrency) && !$exchangerate;
566 # record exchange rate differences and gains/losses
567 foreach my $accno (keys %{ $form->{fx} }) {
568 foreach my $transdate (keys %{ $form->{fx}{$accno} }) {
569 $form->{fx}{$accno}{$transdate} = $form->round_amount($form->{fx}{$accno}{$transdate}, 2);
570 next if ($form->{fx}{$accno}{$transdate} == 0);
572 $query = qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate, cleared, fx_transaction, taxkey, project_id)
573 VALUES (?, (SELECT id FROM chart WHERE accno = ?), ?, ?, '0', '1', 0, ?)|;
574 @values = (conv_i($form->{id}), $accno, $form->{fx}{$accno}{$transdate}, conv_date($transdate), $project_id);
575 do_query($form, $dbh, $query, @values);
579 IO->set_datepaid(table => 'ap', id => $form->{id}, dbh => $dbh);
581 if ($payments_only) {
582 $query = qq|UPDATE ap SET paid = ? WHERE id = ?|;
583 do_query($form, $dbh, $query, $form->{paid}, conv_i($form->{id}));
585 if (!$provided_dbh) {
590 $main::lxdebug->leave_sub();
594 $amount = $netamount + $tax;
596 # set values which could be empty
597 my $taxzone_id = $form->{taxzone_id} * 1;
599 # Seit neuestem wird die department_id schon übergeben UND $form->department nicht mehr
600 # korrekt zusammengebaut. Sehr wahrscheinlich beim Umstieg auf T8 kaputt gegangen
601 # Ich lass den Code von 2005 erstmal noch stehen ;-) jb 03-2011
602 # copy & paste von IS.pm
603 if (!$form->{department_id}){
604 $form->{department_id} = (split /--/, $form->{department})[1];
606 $form->{invnumber} = $form->{id} unless $form->{invnumber};
608 $taxzone_id = 0 if (3 < $taxzone_id) || (0 > $taxzone_id);
611 $query = qq|UPDATE ap SET
612 invnumber = ?, ordnumber = ?, quonumber = ?, transdate = ?,
613 orddate = ?, quodate = ?, vendor_id = ?, amount = ?,
614 netamount = ?, paid = ?, duedate = ?,
615 invoice = ?, taxzone_id = ?, notes = ?, taxincluded = ?,
616 intnotes = ?, curr = ?, storno_id = ?, storno = ?,
617 cp_id = ?, employee_id = ?, department_id = ?,
621 $form->{invnumber}, $form->{ordnumber}, $form->{quonumber}, conv_date($form->{invdate}),
622 conv_date($form->{orddate}), conv_date($form->{quodate}), conv_i($form->{vendor_id}), $amount,
623 $netamount, $form->{paid}, conv_date($form->{duedate}),
624 '1', $taxzone_id, $form->{notes}, $form->{taxincluded} ? 't' : 'f',
625 $form->{intnotes}, $form->{currency}, conv_i($form->{storno_id}), $form->{storno} ? 't' : 'f',
626 conv_i($form->{cp_id}), conv_i($form->{employee_id}), conv_i($form->{department_id}),
627 conv_i($form->{globalproject_id}),
630 do_query($form, $dbh, $query, @values);
632 if ($form->{storno}) {
633 $query = qq|UPDATE ap SET paid = paid + amount WHERE id = ?|;
634 do_query($form, $dbh, $query, conv_i($form->{storno_id}));
636 $query = qq|UPDATE ap SET storno = 't' WHERE id = ?|;
637 do_query($form, $dbh, $query, conv_i($form->{storno_id}));
639 $query = qq!UPDATE ap SET intnotes = ? || intnotes WHERE id = ?!;
640 do_query($form, $dbh, $query, "Rechnung storniert am $form->{invdate} ", conv_i($form->{storno_id}));
642 $query = qq|UPDATE ap SET paid = amount WHERE id = ?|;
643 do_query($form, $dbh, $query, conv_i($form->{id}));
648 $form->{name} = $form->{vendor};
649 $form->{name} =~ s/--\Q$form->{vendor_id}\E//;
650 $form->add_shipto($dbh, $form->{id}, "AP");
652 # delete zero entries
653 do_query($form, $dbh, qq|DELETE FROM acc_trans WHERE amount = 0|);
655 Common::webdav_folder($form);
657 # Link this record to the records it was created from.
658 RecordLinks->create_links('dbh' => $dbh,
660 'from_table' => 'oe',
661 'from_ids' => $form->{convert_from_oe_ids},
663 'to_id' => $form->{id},
665 delete $form->{convert_from_oe_ids};
667 my @convert_from_do_ids = map { $_ * 1 } grep { $_ } split m/\s+/, $form->{convert_from_do_ids};
668 if (scalar @convert_from_do_ids) {
669 DO->close_orders('dbh' => $dbh,
670 'ids' => \@convert_from_do_ids);
672 RecordLinks->create_links('dbh' => $dbh,
674 'from_table' => 'delivery_orders',
675 'from_ids' => \@convert_from_do_ids,
677 'to_id' => $form->{id},
680 delete $form->{convert_from_do_ids};
682 ARAP->close_orders_if_billed('dbh' => $dbh,
683 'arap_id' => $form->{id},
687 if (!$provided_dbh) {
688 $rc = $dbh->commit();
692 $main::lxdebug->leave_sub();
697 sub reverse_invoice {
698 $main::lxdebug->enter_sub();
700 my ($dbh, $form) = @_;
702 # reverse inventory items
704 qq|SELECT i.parts_id, p.inventory_accno_id, p.expense_accno_id, i.qty, i.allocated, i.sellprice
705 FROM invoice i, parts p
706 WHERE (i.parts_id = p.id)
707 AND (i.trans_id = ?)|;
708 my $sth = prepare_execute_query($form, $dbh, $query, conv_i($form->{id}));
712 while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
713 $netamount += $form->round_amount($ref->{sellprice} * $ref->{qty} * -1, 2);
715 next unless $ref->{inventory_accno_id};
717 # if $ref->{allocated} > 0 than we sold that many items
718 next if ($ref->{allocated} <= 0);
720 # get references for sold items
722 qq|SELECT i.id, i.trans_id, i.allocated, a.transdate
724 WHERE (i.parts_id = ?)
725 AND (i.allocated < 0)
726 AND (i.trans_id = a.id)
727 ORDER BY transdate DESC|;
728 my $sth2 = prepare_execute_query($form, $dbh, $query, $ref->{parts_id});
730 while (my $pthref = $sth2->fetchrow_hashref("NAME_lc")) {
731 my $qty = $ref->{allocated};
732 if (($ref->{allocated} + $pthref->{allocated}) > 0) {
733 $qty = $pthref->{allocated} * -1;
736 my $amount = $form->round_amount($ref->{sellprice} * $qty, 2);
739 $form->update_balance($dbh, "invoice", "allocated", qq|id = $pthref->{id}|, $qty);
741 $form->update_balance($dbh, "acc_trans", "amount",
742 qq| (trans_id = $pthref->{trans_id})
743 AND (chart_id = $ref->{expense_accno_id})
744 AND (transdate = '$pthref->{transdate}')|,
747 $form->update_balance($dbh, "acc_trans", "amount",
748 qq| (trans_id = $pthref->{trans_id})
749 AND (chart_id = $ref->{inventory_accno_id})
750 AND (transdate = '$pthref->{transdate}')|,
753 last if (($ref->{allocated} -= $qty) <= 0);
759 my $id = conv_i($form->{id});
762 $query = qq|DELETE FROM acc_trans WHERE trans_id = ?|;
763 do_query($form, $dbh, $query, $id);
765 # delete invoice entries
766 $query = qq|DELETE FROM invoice WHERE trans_id = ?|;
767 do_query($form, $dbh, $query, $id);
769 $query = qq|DELETE FROM shipto WHERE (trans_id = ?) AND (module = 'AP')|;
770 do_query($form, $dbh, $query, $id);
772 $main::lxdebug->leave_sub();
776 $main::lxdebug->enter_sub();
778 my ($self, $myconfig, $form) = @_;
780 # connect to database
781 my $dbh = $form->dbconnect_noauto($myconfig);
783 &reverse_invoice($dbh, $form);
785 # delete zero entries
786 $query = qq|DELETE FROM acc_trans WHERE amount = 0|;
787 do_query($form, $dbh, $query);
790 $query = qq|DELETE FROM ap WHERE id = ?|;
791 do_query($form, $dbh, $query, conv_i($form->{id}));
793 my $rc = $dbh->commit;
796 $main::lxdebug->leave_sub();
801 sub retrieve_invoice {
802 $main::lxdebug->enter_sub();
804 my ($self, $myconfig, $form) = @_;
806 # connect to database
807 my $dbh = $form->dbconnect($myconfig);
809 my ($query, $sth, $ref, $q_invdate);
812 $q_invdate = qq|, COALESCE((SELECT transdate FROM ar WHERE id = (SELECT MAX(id) FROM ar)), current_date) AS invdate|;
813 if ($form->{vendor_id}) {
814 my $vendor_id = $dbh->quote($form->{vendor_id} * 1);
816 qq|, COALESCE((SELECT transdate FROM ar WHERE id = (SELECT MAX(id) FROM ar)), current_date) +
817 COALESCE((SELECT pt.terms_netto
819 LEFT JOIN payment_terms pt ON (v.payment_id = pt.id)
820 WHERE v.id = $vendor_id),
825 # get default accounts and last invoice number
828 (SELECT c.accno FROM chart c WHERE d.inventory_accno_id = c.id) AS inventory_accno,
829 (SELECT c.accno FROM chart c WHERE d.income_accno_id = c.id) AS income_accno,
830 (SELECT c.accno FROM chart c WHERE d.expense_accno_id = c.id) AS expense_accno,
831 (SELECT c.accno FROM chart c WHERE d.fxgain_accno_id = c.id) AS fxgain_accno,
832 (SELECT c.accno FROM chart c WHERE d.fxloss_accno_id = c.id) AS fxloss_accno,
836 $ref = selectfirst_hashref_query($form, $dbh, $query);
837 map { $form->{$_} = $ref->{$_} } keys %$ref;
841 $main::lxdebug->leave_sub();
847 $query = qq|SELECT cp_id, invnumber, transdate AS invdate, duedate,
848 orddate, quodate, globalproject_id,
849 ordnumber, quonumber, paid, taxincluded, notes, taxzone_id, storno, gldate,
850 intnotes, curr AS currency
853 $ref = selectfirst_hashref_query($form, $dbh, $query, conv_i($form->{id}));
854 map { $form->{$_} = $ref->{$_} } keys %$ref;
856 $form->{exchangerate} = $form->get_exchangerate($dbh, $form->{currency}, $form->{invdate}, "sell");
859 $query = qq|SELECT * FROM shipto WHERE (trans_id = ?) AND (module = 'AP')|;
860 $ref = selectfirst_hashref_query($form, $dbh, $query, conv_i($form->{id}));
862 map { $form->{$_} = $ref->{$_} } keys %$ref;
864 my $transdate = $form->{invdate} ? $dbh->quote($form->{invdate}) : "current_date";
865 my $taxzone_id = $form->{taxzone_id} * 1;
867 $taxzone_id = 0 if ((3 < $taxzone_id) || (0 > $taxzone_id));
869 # retrieve individual items
872 c1.accno AS inventory_accno, c1.new_chart_id AS inventory_new_chart, date($transdate) - c1.valid_from AS inventory_valid,
873 c2.accno AS income_accno, c2.new_chart_id AS income_new_chart, date($transdate) - c2.valid_from AS income_valid,
874 c3.accno AS expense_accno, c3.new_chart_id AS expense_new_chart, date($transdate) - c3.valid_from AS expense_valid,
877 i.description, i.longdescription, i.qty, i.fxsellprice AS sellprice, i.parts_id AS id, i.unit, i.deliverydate, i.project_id, i.serialnumber,
878 i.price_factor_id, i.price_factor, i.marge_price_factor, i.discount,
879 p.partnumber, p.inventory_accno_id AS part_inventory_accno_id, p.bin, pr.projectnumber, pg.partsgroup
882 JOIN parts p ON (i.parts_id = p.id)
883 LEFT JOIN chart c1 ON ((SELECT inventory_accno_id FROM buchungsgruppen WHERE id = p.buchungsgruppen_id) = c1.id)
884 LEFT JOIN chart c2 ON ((SELECT income_accno_id_${taxzone_id} FROM buchungsgruppen WHERE id = p.buchungsgruppen_id) = c2.id)
885 LEFT JOIN chart c3 ON ((SELECT expense_accno_id_${taxzone_id} FROM buchungsgruppen WHERE id = p.buchungsgruppen_id) = c3.id)
886 LEFT JOIN project pr ON (i.project_id = pr.id)
887 LEFT JOIN partsgroup pg ON (pg.id = p.partsgroup_id)
892 $sth = prepare_execute_query($form, $dbh, $query, conv_i($form->{id}));
894 while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
895 # Retrieve custom variables.
896 my $cvars = CVar->get_custom_variables(dbh => $dbh,
898 sub_module => 'invoice',
899 trans_id => $ref->{invoice_id},
901 map { $ref->{"ic_cvar_$_->{name}"} = $_->{value} } @{ $cvars };
902 delete $ref->{invoice_id};
904 map({ delete($ref->{$_}); } qw(inventory_accno inventory_new_chart inventory_valid)) if !$ref->{"part_inventory_accno_id"};
905 delete($ref->{"part_inventory_accno_id"});
907 foreach my $type (qw(inventory income expense)) {
908 while ($ref->{"${type}_new_chart"} && ($ref->{"${type}_valid"} >=0)) {
909 my $query = qq|SELECT accno, new_chart_id, date($transdate) - valid_from FROM chart WHERE id = ?|;
910 @$ref{ map $type.$_, qw(_accno _new_chart _valid) } = selectrow_query($form, $dbh, $query, $ref->{"${type}_new_chart"});
914 # get tax rates and description
915 my $accno_id = ($form->{vc} eq "customer") ? $ref->{income_accno} : $ref->{expense_accno};
917 qq|SELECT c.accno, t.taxdescription, t.rate, t.taxnumber FROM tax t
918 LEFT JOIN chart c ON (c.id = t.chart_id)
920 (SELECT tk.tax_id FROM taxkeys tk
921 WHERE tk.chart_id = (SELECT id FROM chart WHERE accno = ?)
922 AND (startdate <= $transdate)
923 ORDER BY startdate DESC
926 my $stw = prepare_execute_query($form, $dbh, $query, $accno_id);
927 $ref->{taxaccounts} = "";
930 while (my $ptr = $stw->fetchrow_hashref("NAME_lc")) {
931 if (($ptr->{accno} eq "") && ($ptr->{rate} == 0)) {
936 $ref->{taxaccounts} .= "$ptr->{accno} ";
938 if (!($form->{taxaccounts} =~ /\Q$ptr->{accno}\E/)) {
939 $form->{"$ptr->{accno}_rate"} = $ptr->{rate};
940 $form->{"$ptr->{accno}_description"} = $ptr->{taxdescription};
941 $form->{"$ptr->{accno}_taxnumber"} = $ptr->{taxnumber};
942 $form->{taxaccounts} .= "$ptr->{accno} ";
947 chop $ref->{taxaccounts};
948 push @{ $form->{invoice_details} }, $ref;
953 Common::webdav_folder($form);
957 $main::lxdebug->leave_sub();
961 $main::lxdebug->enter_sub();
963 my ($self, $myconfig, $form, $params) = @_;
965 $params = $form unless defined $params && ref $params eq "HASH";
967 # connect to database
968 my $dbh = $form->dbconnect($myconfig);
970 my $dateformat = $myconfig->{dateformat};
971 $dateformat .= "yy" if $myconfig->{dateformat} !~ /^y/;
973 my $vid = conv_i($params->{vendor_id});
974 my $vnr = conv_i($params->{vendornumber});
978 ? "to_date(" . $dbh->quote($params->{invdate}) . ", '$dateformat')"
985 $where .= 'AND v.id = ?';
989 $where .= 'AND v.vendornumber = ?';
994 v.id AS vendor_id, v.name AS vendor, v.discount as vendor_discount,
995 v.creditlimit, v.terms, v.notes AS intnotes,
996 v.email, v.cc, v.bcc, v.language_id, v.payment_id,
997 v.street, v.zipcode, v.city, v.country, v.taxzone_id,
998 $duedate + COALESCE(pt.terms_netto, 0) AS duedate,
999 b.description AS business
1001 LEFT JOIN business b ON (b.id = v.business_id)
1002 LEFT JOIN payment_terms pt ON (v.payment_id = pt.id)
1004 my $ref = selectfirst_hashref_query($form, $dbh, $query, @values);
1005 map { $params->{$_} = $ref->{$_} } keys %$ref;
1007 $params->{creditremaining} = $params->{creditlimit};
1009 $query = qq|SELECT SUM(amount - paid) FROM ap WHERE vendor_id = ?|;
1010 my ($unpaid_invoices) = selectfirst_array_query($form, $dbh, $query, $vid);
1011 $params->{creditremaining} -= $unpaid_invoices;
1013 $query = qq|SELECT o.amount,
1016 WHERE (e.curr = o.curr)
1017 AND (e.transdate = o.transdate)) AS exch
1019 WHERE (o.vendor_id = ?) AND (o.quotation = '0') AND (o.closed = '0')|;
1020 my $sth = prepare_execute_query($form, $dbh, $query, $vid);
1021 while (my ($amount, $exch) = $sth->fetchrow_array()) {
1022 $exch = 1 unless $exch;
1023 $params->{creditremaining} -= $amount * $exch;
1027 # get shipto if we do not convert an order or invoice
1028 if (!$params->{shipto}) {
1029 delete @{$params}{qw(shiptoname shiptostreet shiptozipcode shiptocity shiptocountry shiptocontact shiptophone shiptofax shiptoemail)};
1031 $query = qq|SELECT * FROM shipto WHERE (trans_id = ?) AND (module= 'CT')|;
1032 $ref = selectfirst_hashref_query($form, $dbh, $query, $vid);
1033 @{$params}{keys %$ref} = @{$ref}{keys %$ref};
1034 map { $params->{$_} = $ref->{$_} } keys %$ref;
1037 if (!$params->{id} && $params->{type} !~ /_(order|quotation)/) {
1038 # setup last accounts used
1040 qq|SELECT c.id, c.accno, c.description, c.link, c.category
1042 JOIN acc_trans ac ON (ac.chart_id = c.id)
1043 JOIN ap a ON (a.id = ac.trans_id)
1044 WHERE (a.vendor_id = ?)
1045 AND (NOT ((c.link LIKE '%_tax%') OR (c.link LIKE '%_paid%')))
1046 AND (a.id IN (SELECT max(a2.id) FROM ap a2 WHERE a2.vendor_id = ?))|;
1047 my $refs = selectall_hashref_query($form, $dbh, $query, $vid, $vid);
1051 if ($ref->{category} eq 'E') {
1053 my ($tax_id, $rate);
1054 if ($params->{initial_transdate}) {
1055 my $tax_query = qq|SELECT tk.tax_id, t.rate FROM taxkeys tk
1056 LEFT JOIN tax t ON (tk.tax_id = t.id)
1057 WHERE (tk.chart_id = ?) AND (startdate <= ?)
1058 ORDER BY tk.startdate DESC
1060 ($tax_id, $rate) = selectrow_query($form, $dbh, $tax_query, $ref->{id}, $params->{initial_transdate});
1061 $params->{"taxchart_$i"} = "${tax_id}--${rate}";
1064 $params->{"AP_amount_$i"} = "$ref->{accno}--$tax_id";
1067 if ($ref->{category} eq 'L') {
1068 $params->{APselected} = $params->{AP_1} = $ref->{accno};
1071 $params->{rowcount} = $i if ($i && !$params->{type});
1076 $main::lxdebug->leave_sub();
1080 $main::lxdebug->enter_sub();
1082 my ($self, $myconfig, $form) = @_;
1084 # connect to database
1085 my $dbh = $form->dbconnect($myconfig);
1087 my $i = $form->{rowcount};
1089 # don't include assemblies or obsolete parts
1090 my $where = "NOT p.assembly = '1' AND NOT p.obsolete = '1'";
1093 foreach my $table_column (qw(p.partnumber p.description pg.partsgroup)) {
1094 my $field = (split m{\.}, $table_column)[1];
1095 next unless $form->{"${field}_${i}"};
1096 $where .= " AND lower(${table_column}) LIKE lower(?)";
1097 push @values, '%' . $form->{"${field}_${i}"} . '%';
1099 #Es soll auch nach EAN gesucht werden, ohne Einschränkung durch Beschreibung
1100 if ($form->{"partnumber_$i"} && !$form->{"description_$i"}) {
1101 $where .= qq| OR (NOT p.obsolete = '1' AND p.ean = ? )|;
1102 push @values, $form->{"partnumber_$i"};
1105 # Search for part ID overrides all other criteria.
1106 if ($form->{"id_${i}"}) {
1107 $where = qq|p.id = ?|;
1108 @values = ($form->{"id_${i}"});
1111 if ($form->{"description_$i"}) {
1112 $where .= " ORDER BY p.description";
1114 $where .= " ORDER BY p.partnumber";
1118 if ($form->{type} eq "invoice") {
1119 $transdate = $form->{invdate} ? $dbh->quote($form->{invdate}) : "current_date";
1121 $transdate = $form->{transdate} ? $dbh->quote($form->{transdate}) : "current_date";
1124 my $taxzone_id = $form->{taxzone_id} * 1;
1125 $taxzone_id = 0 if ((3 < $taxzone_id) || (0 > $taxzone_id));
1129 p.id, p.partnumber, p.description, p.lastcost AS sellprice, p.listprice,
1130 p.unit, p.assembly, p.bin, p.onhand, p.formel,
1131 p.notes AS partnotes, p.notes AS longdescription, p.not_discountable,
1132 p.inventory_accno_id, p.price_factor_id,
1134 pfac.factor AS price_factor,
1136 c1.accno AS inventory_accno,
1137 c1.new_chart_id AS inventory_new_chart,
1138 date($transdate) - c1.valid_from AS inventory_valid,
1140 c2.accno AS income_accno,
1141 c2.new_chart_id AS income_new_chart,
1142 date($transdate) - c2.valid_from AS income_valid,
1144 c3.accno AS expense_accno,
1145 c3.new_chart_id AS expense_new_chart,
1146 date($transdate) - c3.valid_from AS expense_valid,
1151 LEFT JOIN chart c1 ON
1152 ((SELECT inventory_accno_id
1153 FROM buchungsgruppen
1154 WHERE id = p.buchungsgruppen_id) = c1.id)
1155 LEFT JOIN chart c2 ON
1156 ((SELECT income_accno_id_${taxzone_id}
1157 FROM buchungsgruppen
1158 WHERE id = p.buchungsgruppen_id) = c2.id)
1159 LEFT JOIN chart c3 ON
1160 ((SELECT expense_accno_id_${taxzone_id}
1161 FROM buchungsgruppen
1162 WHERE id = p.buchungsgruppen_id) = c3.id)
1163 LEFT JOIN partsgroup pg ON (pg.id = p.partsgroup_id)
1164 LEFT JOIN price_factors pfac ON (pfac.id = p.price_factor_id)
1166 my $sth = prepare_execute_query($form, $dbh, $query, @values);
1168 my @translation_queries = ( [ qq|SELECT tr.translation, tr.longdescription
1170 WHERE tr.language_id = ? AND tr.parts_id = ?| ],
1171 [ qq|SELECT tr.translation, tr.longdescription
1173 WHERE tr.language_id IN
1176 WHERE article_code = (SELECT article_code FROM language WHERE id = ?))
1179 map { push @{ $_ }, prepare_query($form, $dbh, $_->[0]) } @translation_queries;
1181 $form->{item_list} = [];
1182 while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
1184 # In der Buchungsgruppe ist immer ein Bestandskonto verknuepft, auch wenn
1185 # es sich um eine Dienstleistung handelt. Bei Dienstleistungen muss das
1186 # Buchungskonto also aus dem Ergebnis rausgenommen werden.
1187 if (!$ref->{inventory_accno_id}) {
1188 map({ delete($ref->{"inventory_${_}"}); } qw(accno new_chart valid));
1190 delete($ref->{inventory_accno_id});
1192 # get tax rates and description
1193 my $accno_id = ($form->{vc} eq "customer") ? $ref->{income_accno} : $ref->{expense_accno};
1195 qq|SELECT c.accno, t.taxdescription, t.rate, t.taxnumber
1197 LEFT JOIN chart c on (c.id = t.chart_id)
1205 AND (startdate <= $transdate)
1206 ORDER BY startdate DESC
1209 my $stw = prepare_execute_query($form, $dbh, $query, $accno_id);
1211 $ref->{taxaccounts} = "";
1213 while (my $ptr = $stw->fetchrow_hashref("NAME_lc")) {
1215 # if ($customertax{$ref->{accno}}) {
1216 if (($ptr->{accno} eq "") && ($ptr->{rate} == 0)) {
1221 $ref->{taxaccounts} .= "$ptr->{accno} ";
1223 if (!($form->{taxaccounts} =~ /\Q$ptr->{accno}\E/)) {
1224 $form->{"$ptr->{accno}_rate"} = $ptr->{rate};
1225 $form->{"$ptr->{accno}_description"} = $ptr->{taxdescription};
1226 $form->{"$ptr->{accno}_taxnumber"} = $ptr->{taxnumber};
1227 $form->{taxaccounts} .= "$ptr->{accno} ";
1230 if ($form->{language_id}) {
1231 for my $spec (@translation_queries) {
1232 do_statement($form, $spec->[1], $spec->[0], conv_i($form->{language_id}), conv_i($ref->{id}));
1233 my ($translation, $longdescription) = $spec->[1]->fetchrow_array;
1234 next unless $translation;
1235 $ref->{description} = $translation;
1236 $ref->{longdescription} = $longdescription;
1243 chop $ref->{taxaccounts};
1245 $ref->{onhand} *= 1;
1247 push @{ $form->{item_list} }, $ref;
1252 $_->[1]->finish for @translation_queries;
1254 foreach my $item (@{ $form->{item_list} }) {
1255 my $custom_variables = CVar->get_custom_variables(module => 'IC',
1256 trans_id => $item->{id},
1260 map { $item->{"ic_cvar_" . $_->{name} } = $_->{value} } @{ $custom_variables };
1265 $main::lxdebug->leave_sub();
1268 sub vendor_details {
1269 $main::lxdebug->enter_sub();
1271 my ($self, $myconfig, $form, @wanted_vars) = @_;
1273 # connect to database
1274 my $dbh = $form->dbconnect($myconfig);
1278 # get contact id, set it if nessessary
1279 $form->{cp_id} *= 1;
1281 if ($form->{cp_id}) {
1282 $contact = "AND cp.cp_id = ?";
1283 push @values, $form->{cp_id};
1286 # get rest for the vendor
1287 # fax and phone and email as vendor*
1289 qq|SELECT ct.*, cp.*, ct.notes as vendornotes, phone as vendorphone, fax as vendorfax, email as vendoremail
1291 LEFT JOIN contacts cp ON (ct.id = cp.cp_cv_id)
1292 WHERE (ct.id = ?) $contact
1295 my $ref = selectfirst_hashref_query($form, $dbh, $query, $form->{vendor_id}, @values);
1297 # remove id and taxincluded before copy back
1298 delete @$ref{qw(id taxincluded)};
1300 @wanted_vars = grep({ $_ } @wanted_vars);
1301 if (scalar(@wanted_vars) > 0) {
1303 map({ $h_wanted_vars{$_} = 1; } @wanted_vars);
1304 map({ delete($ref->{$_}) unless ($h_wanted_vars{$_}); } keys(%{$ref}));
1307 map { $form->{$_} = $ref->{$_} } keys %$ref;
1309 my $custom_variables = CVar->get_custom_variables('dbh' => $dbh,
1311 'trans_id' => $form->{vendor_id});
1312 map { $form->{"vc_cvar_$_->{name}"} = $_->{value} } @{ $custom_variables };
1314 $form->{cp_greeting} = GenericTranslations->get('dbh' => $dbh,
1315 'translation_type' => 'greetings::' . ($form->{cp_gender} eq 'f' ? 'female' : 'male'),
1316 'allow_fallback' => 1);
1320 $main::lxdebug->leave_sub();
1324 $main::lxdebug->enter_sub();
1326 my ($self, $myconfig, $form) = @_;
1328 # connect to database
1329 my $dbh = $form->dbconnect($myconfig);
1332 qq|SELECT accno, description, link
1334 WHERE link LIKE '%IC%'
1336 my $sth = prepare_execute_query($query, $dbh, $query);
1338 while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
1339 foreach my $key (split(/:/, $ref->{link})) {
1341 push @{ $form->{IC_links}{$key} },
1342 { accno => $ref->{accno},
1343 description => $ref->{description} };
1351 $main::lxdebug->leave_sub();
1354 sub _delete_payments {
1355 $main::lxdebug->enter_sub();
1357 my ($self, $form, $dbh) = @_;
1359 my @delete_acc_trans_ids;
1361 # Delete old payment entries from acc_trans.
1363 qq|SELECT acc_trans_id
1365 WHERE (trans_id = ?) AND fx_transaction
1369 SELECT at.acc_trans_id
1371 LEFT JOIN chart c ON (at.chart_id = c.id)
1372 WHERE (trans_id = ?) AND (c.link LIKE '%AP_paid%')|;
1373 push @delete_acc_trans_ids, selectall_array_query($form, $dbh, $query, conv_i($form->{id}), conv_i($form->{id}));
1376 qq|SELECT at.acc_trans_id
1378 LEFT JOIN chart c ON (at.chart_id = c.id)
1379 WHERE (trans_id = ?)
1380 AND ((c.link = 'AP') OR (c.link LIKE '%:AP') OR (c.link LIKE 'AP:%'))
1381 ORDER BY at.acc_trans_id
1383 push @delete_acc_trans_ids, selectall_array_query($form, $dbh, $query, conv_i($form->{id}));
1385 if (@delete_acc_trans_ids) {
1386 $query = qq|DELETE FROM acc_trans WHERE acc_trans_id IN (| . join(", ", @delete_acc_trans_ids) . qq|)|;
1387 do_query($form, $dbh, $query);
1390 $main::lxdebug->leave_sub();
1394 $main::lxdebug->enter_sub();
1396 my ($self, $myconfig, $form, $locale) = @_;
1398 # connect to database, turn off autocommit
1399 my $dbh = $form->dbconnect_noauto($myconfig);
1401 my (%payments, $old_form, $row, $item, $query, %keep_vars);
1403 $old_form = save_form();
1405 # Delete all entries in acc_trans from prior payments.
1406 if ($::lx_office_conf{features}->{payments_changeable} != 0) {
1407 $self->_delete_payments($form, $dbh);
1410 # Save the new payments the user made before cleaning up $form.
1411 map { $payments{$_} = $form->{$_} } grep m/^datepaid_\d+$|^gldate_\d+$|^acc_trans_id_\d+$|^memo_\d+$|^source_\d+$|^exchangerate_\d+$|^paid_\d+$|^AP_paid_\d+$|^paidaccounts$/, keys %{ $form };
1413 # Clean up $form so that old content won't tamper the results.
1414 %keep_vars = map { $_, 1 } qw(login password id);
1415 map { delete $form->{$_} unless $keep_vars{$_} } keys %{ $form };
1417 # Retrieve the invoice from the database.
1418 $self->retrieve_invoice($myconfig, $form);
1420 # Set up the content of $form in the way that IR::post_invoice() expects.
1421 $form->{exchangerate} = $form->format_amount($myconfig, $form->{exchangerate});
1423 for $row (1 .. scalar @{ $form->{invoice_details} }) {
1424 $item = $form->{invoice_details}->[$row - 1];
1426 map { $item->{$_} = $form->format_amount($myconfig, $item->{$_}) } qw(qty sellprice);
1428 map { $form->{"${_}_${row}"} = $item->{$_} } keys %{ $item };
1431 $form->{rowcount} = scalar @{ $form->{invoice_details} };
1433 delete @{$form}{qw(invoice_details paidaccounts storno paid)};
1435 # Restore the payment options from the user input.
1436 map { $form->{$_} = $payments{$_} } keys %payments;
1438 # Get the AP accno (which is normally done by Form::create_links()).
1442 LEFT JOIN chart c ON (at.chart_id = c.id)
1443 WHERE (trans_id = ?)
1444 AND ((c.link = 'AP') OR (c.link LIKE '%:AP') OR (c.link LIKE 'AP:%'))
1445 ORDER BY at.acc_trans_id
1448 ($form->{AP}) = selectfirst_array_query($form, $dbh, $query, conv_i($form->{id}));
1450 # Post the new payments.
1451 $self->post_invoice($myconfig, $form, $dbh, 1);
1453 restore_form($old_form);
1455 my $rc = $dbh->commit();
1458 $main::lxdebug->leave_sub();
1464 $main::lxdebug->enter_sub();
1469 if (!$params{vendor_id} || !$params{invdate}) {
1470 $main::lxdebug->leave_sub();
1471 return $params{default};
1474 my $myconfig = \%main::myconfig;
1475 my $form = $main::form;
1477 my $dbh = $params{dbh} || $form->get_standard_dbh($myconfig);
1479 my $query = qq|SELECT ?::date + pt.terms_netto
1481 LEFT JOIN payment_terms pt ON (pt.id = v.payment_id)
1484 my ($sth, $duedate);
1486 if (($sth = $dbh->prepare($query)) && $sth->execute($params{invdate}, conv_i($params{vendor_id}))) {
1487 ($duedate) = $sth->fetchrow_array();
1493 $duedate ||= $params{default};
1495 $main::lxdebug->leave_sub();