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 #======================================================================
41 use SL::DATEV qw(:CONSTANTS);
44 use SL::GenericTranslations;
48 use List::Util qw(min);
53 $main::lxdebug->enter_sub();
55 my ($self, $myconfig, $form, $provided_dbh, $payments_only) = @_;
57 # connect to database, turn off autocommit
58 my $dbh = $provided_dbh ? $provided_dbh : $form->dbconnect_noauto($myconfig);
59 $form->{defaultcurrency} = $form->get_default_currency($myconfig);
61 my $ic_cvar_configs = CVar->get_configs(module => 'IC',
64 my ($query, $sth, @values, $project_id);
65 my ($allocated, $taxrate, $taxamount, $taxdiff, $item);
66 my ($amount, $linetotal, $lastinventoryaccno, $lastexpenseaccno);
67 my ($netamount, $invoicediff, $expensediff) = (0, 0, 0);
69 my ($basefactor, $baseqty, @taxaccounts, $totaltax);
71 my $all_units = AM->retrieve_units($myconfig, $form);
73 if (!$payments_only) {
75 &reverse_invoice($dbh, $form);
77 ($form->{id}) = selectrow_query($form, $dbh, qq|SELECT nextval('glid')|);
78 do_query($form, $dbh, qq|INSERT INTO ap (id, invnumber) VALUES (?, '')|, $form->{id});
82 my ($currencies) = selectfirst_array_query($form, $dbh, qq|SELECT curr FROM defaults|);
83 my $defaultcurrency = (split m/:/, $currencies)[0];
85 if ($form->{currency} eq $defaultcurrency) {
86 $form->{exchangerate} = 1;
88 $exchangerate = $form->check_exchangerate($myconfig, $form->{currency}, $form->{invdate}, 'sell');
91 $form->{exchangerate} = $exchangerate || $form->parse_amount($myconfig, $form->{exchangerate});
92 $form->{exchangerate} = 1 unless ($form->{exchangerate} * 1);
95 my $q_item_unit = qq|SELECT unit FROM parts WHERE id = ?|;
96 my $h_item_unit = prepare_query($form, $dbh, $q_item_unit);
98 $form->get_lists('price_factors' => 'ALL_PRICE_FACTORS');
99 my %price_factors = map { $_->{id} => $_->{factor} } @{ $form->{ALL_PRICE_FACTORS} };
102 for my $i (1 .. $form->{rowcount}) {
103 next unless $form->{"id_$i"};
105 $form->{"qty_$i"} = $form->parse_amount($myconfig, $form->{"qty_$i"});
106 $form->{"qty_$i"} *= -1 if $form->{storno};
108 if ( $::instance_conf->get_inventory_system eq 'periodic') {
109 # inventory account number is overwritten with expense account number, so
110 # never book incoming to inventory account but always to expense account
111 $form->{"inventory_accno_$i"} = $form->{"expense_accno_$i"}
115 if (!$item_units{$form->{"id_$i"}}) {
116 do_statement($form, $h_item_unit, $q_item_unit, $form->{"id_$i"});
117 ($item_units{$form->{"id_$i"}}) = $h_item_unit->fetchrow_array();
120 my $item_unit = $item_units{$form->{"id_$i"}};
122 if (defined($all_units->{$item_unit}->{factor})
123 && ($all_units->{$item_unit}->{factor} ne '')
124 && ($all_units->{$item_unit}->{factor} * 1 != 0)) {
125 $basefactor = $all_units->{$form->{"unit_$i"}}->{factor} / $all_units->{$item_unit}->{factor};
129 $baseqty = $form->{"qty_$i"} * $basefactor;
131 @taxaccounts = split / /, $form->{"taxaccounts_$i"};
136 $form->{"sellprice_$i"} = $form->parse_amount($myconfig, $form->{"sellprice_$i"});
137 (my $fxsellprice = $form->{"sellprice_$i"}) =~ /\.(\d+)/;
139 my $decimalplaces = ($dec > 2) ? $dec : 2;
141 map { $taxrate += $form->{"${_}_rate"} } @taxaccounts;
143 $price_factor = $price_factors{ $form->{"price_factor_id_$i"} } || 1;
144 #####################################################################
145 # das ist aus IS.pm kopiert. schlimm. jb 7.10.2009
146 # ich würde mir wünschen, dass diese vier stellen zusammengefasst werden
147 # ... vier stellen = (einkauf + verkauf) * (maske + backend)
148 # ansonsten stolpert man immer wieder viermal statt einmal heftig
149 # und auch das undo discount formatting ist nicht besonders wartungsfreundlich
151 # keine ahnung wofür das in IS.pm gemacht wird:
152 # my ($dec) = ($fxsellprice =~ /\.(\d+)/);
153 # $dec = length $dec;
154 # my $decimalplaces = ($dec > 2) ? $dec : 2;
156 # undo discount formatting
157 $form->{"discount_$i"} = $form->parse_amount($myconfig, $form->{"discount_$i"}) / 100;
159 $form->{"sellprice_$i"} = $fxsellprice * (1 - $form->{"discount_$i"});
161 ######################################################################
162 if ($form->{"inventory_accno_$i"}) {
164 $linetotal = $form->round_amount($form->{"sellprice_$i"} * $form->{"qty_$i"} / $price_factor, 2);
166 if ($form->{taxincluded}) {
168 $taxamount = $linetotal * ($taxrate / (1 + $taxrate));
169 $form->{"sellprice_$i"} = $form->{"sellprice_$i"} * (1 / (1 + $taxrate));
172 $taxamount = $linetotal * $taxrate;
175 $netamount += $linetotal;
177 if ($form->round_amount($taxrate, 7) == 0) {
178 if ($form->{taxincluded}) {
179 foreach $item (@taxaccounts) {
181 $form->round_amount($linetotal * $form->{"${item}_rate"} / (1 + abs($form->{"${item}_rate"})), 2);
182 $taxdiff += $taxamount;
183 $form->{amount}{ $form->{id} }{$item} -= $taxamount;
185 $form->{amount}{ $form->{id} }{ $taxaccounts[0] } += $taxdiff;
188 map { $form->{amount}{ $form->{id} }{$_} -= $linetotal * $form->{"${_}_rate"} } @taxaccounts;
192 map { $form->{amount}{ $form->{id} }{$_} -= $taxamount * $form->{"${_}_rate"} / $taxrate } @taxaccounts;
195 # add purchase to inventory, this one is without the tax!
196 $amount = $form->{"sellprice_$i"} * $form->{"qty_$i"} * $form->{exchangerate} / $price_factor;
197 $linetotal = $form->round_amount($form->{"sellprice_$i"} * $form->{"qty_$i"} / $price_factor, 2) * $form->{exchangerate};
198 $linetotal = $form->round_amount($linetotal, 2);
200 # this is the difference for the inventory
201 $invoicediff += ($amount - $linetotal);
203 $form->{amount}{ $form->{id} }{ $form->{"inventory_accno_$i"} } -= $linetotal;
205 # adjust and round sellprice
206 $form->{"sellprice_$i"} = $form->round_amount($form->{"sellprice_$i"} * $form->{exchangerate}, $decimalplaces);
208 $lastinventoryaccno = $form->{"inventory_accno_$i"};
210 next if $payments_only;
212 # update parts table by setting lastcost to current price, don't allow negative values by using abs
213 $query = qq|UPDATE parts SET lastcost = ? WHERE id = ?|;
214 @values = (abs($form->{"sellprice_$i"} / $basefactor), conv_i($form->{"id_$i"}));
215 do_query($form, $dbh, $query, @values);
217 # check if we sold the item already and
218 # make an entry for the expense and inventory
220 qq|SELECT i.id, i.qty, i.allocated, i.trans_id, i.base_qty,
221 p.inventory_accno_id, p.expense_accno_id, a.transdate
222 FROM invoice i, ar a, parts p
223 WHERE (i.parts_id = p.id)
225 AND ((i.base_qty + i.allocated) > 0)
226 AND (i.trans_id = a.id)
228 # ORDER BY transdate guarantees FIFO
230 # sold two items without having bought them yet, example result of query:
231 # id | qty | allocated | trans_id | inventory_accno_id | expense_accno_id | transdate
232 # ---+-----+-----------+----------+--------------------+------------------+------------
233 # 9 | 2 | 0 | 9 | 15 | 151 | 2011-01-05
235 # base_qty + allocated > 0 if article has already been sold but not bought yet
237 # select qty,allocated,base_qty,sellprice from invoice where trans_id = 9;
238 # qty | allocated | base_qty | sellprice
239 # -----+-----------+----------+------------
240 # 2 | 0 | 2 | 1000.00000
242 $sth = prepare_execute_query($form, $dbh, $query, conv_i($form->{"id_$i"}));
244 my $totalqty = $baseqty;
246 while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
247 my $qty = min $totalqty, ($ref->{base_qty} + $ref->{allocated});
248 $linetotal = $form->round_amount(($form->{"sellprice_$i"} * $qty) / $basefactor, 2);
250 if ( $::instance_conf->get_inventory_system eq 'perpetual' ) {
251 # Warenbestandsbuchungen nur bei Bestandsmethode
253 if ($ref->{allocated} < 0) {
255 # we have an entry for it already, adjust amount
256 $form->update_balance($dbh, "acc_trans", "amount",
257 qq| (trans_id = $ref->{trans_id})
258 AND (chart_id = $ref->{inventory_accno_id})
259 AND (transdate = '$ref->{transdate}')|,
262 $form->update_balance($dbh, "acc_trans", "amount",
263 qq| (trans_id = $ref->{trans_id})
264 AND (chart_id = $ref->{expense_accno_id})
265 AND (transdate = '$ref->{transdate}')|,
268 } elsif ($linetotal != 0) {
271 # add entry for inventory, this one is for the sold item
272 $query = qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate, taxkey, tax_id) VALUES (?, ?, ?, ?, (SELECT taxkey_id FROM chart WHERE id = ?),
275 WHERE chart_id= (SELECT id
279 ORDER BY startdate DESC LIMIT 1))|;
280 @values = ($ref->{trans_id}, $ref->{inventory_accno_id}, $linetotal, $ref->{transdate}, $ref->{inventory_accno_id}, $ref->{inventory_accno_id}, $ref->{transdate});
281 do_query($form, $dbh, $query, @values);
284 $query = qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate, taxkey, tax_id) VALUES (?, ?, ?, ?, (SELECT taxkey from tax WHERE chart_id = ?),
287 WHERE chart_id= (SELECT id
291 ORDER BY startdate DESC LIMIT 1))|;
292 @values = ($ref->{trans_id}, $ref->{expense_accno_id}, ($linetotal * -1), $ref->{transdate}, $ref->{expense_accno_id}, $ref->{expense_accno_id}, $ref->{transdate});
293 do_query($form, $dbh, $query, @values);
297 # update allocated for sold item
298 $form->update_balance($dbh, "invoice", "allocated", qq|id = $ref->{id}|, $qty * -1);
302 last if ($totalqty -= $qty) <= 0;
307 } else { # if ($form->{"inventory_accno_id_$i"})
308 # part doesn't have an inventory_accno_id
309 # lastcost of the part is updated at the end
311 $linetotal = $form->round_amount($form->{"sellprice_$i"} * $form->{"qty_$i"} / $price_factor, 2);
313 if ($form->{taxincluded}) {
314 $taxamount = $linetotal * ($taxrate / (1 + $taxrate));
315 $form->{"sellprice_$i"} = $form->{"sellprice_$i"} * (1 / (1 + $taxrate));
318 $taxamount = $linetotal * $taxrate;
321 $netamount += $linetotal;
323 if ($form->round_amount($taxrate, 7) == 0) {
324 if ($form->{taxincluded}) {
325 foreach $item (@taxaccounts) {
326 $taxamount = $linetotal * $form->{"${item}_rate"} / (1 + abs($form->{"${item}_rate"}));
327 $totaltax += $taxamount;
328 $form->{amount}{ $form->{id} }{$item} -= $taxamount;
331 map { $form->{amount}{ $form->{id} }{$_} -= $linetotal * $form->{"${_}_rate"} } @taxaccounts;
334 map { $form->{amount}{ $form->{id} }{$_} -= $taxamount * $form->{"${_}_rate"} / $taxrate } @taxaccounts;
337 $amount = $form->{"sellprice_$i"} * $form->{"qty_$i"} * $form->{exchangerate} / $price_factor;
338 $linetotal = $form->round_amount($form->{"sellprice_$i"} * $form->{"qty_$i"} / $price_factor, 2) * $form->{exchangerate};
339 $linetotal = $form->round_amount($linetotal, 2);
341 # this is the difference for expense
342 $expensediff += ($amount - $linetotal);
344 # add amount to expense
345 $form->{amount}{ $form->{id} }{ $form->{"expense_accno_$i"} } -= $linetotal;
347 $lastexpenseaccno = $form->{"expense_accno_$i"};
349 # adjust and round sellprice
350 $form->{"sellprice_$i"} = $form->round_amount($form->{"sellprice_$i"} * $form->{exchangerate}, $decimalplaces);
352 next if $payments_only;
355 $query = qq|UPDATE parts SET lastcost = ? WHERE id = ?|;
356 do_query($form, $dbh, $query, $form->{"sellprice_$i"} / $basefactor, conv_i($form->{"id_$i"}));
359 next if $payments_only;
361 # save detail record in invoice table
362 my ($invoice_id) = selectfirst_array_query($form, $dbh, qq|SELECT nextval('invoiceid')|);
365 qq|INSERT INTO invoice (id, trans_id, parts_id, description, longdescription, qty, base_qty,
366 sellprice, fxsellprice, discount, allocated, unit, deliverydate,
367 project_id, serialnumber, price_factor_id, price_factor, marge_price_factor)
368 VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, (SELECT factor FROM price_factors WHERE id = ?), ?)|;
369 @values = ($invoice_id, conv_i($form->{id}), conv_i($form->{"id_$i"}),
370 $form->{"description_$i"}, $form->{"longdescription_$i"}, $form->{"qty_$i"} * -1,
371 $baseqty * -1, $form->{"sellprice_$i"}, $fxsellprice, $form->{"discount_$i"}, $allocated,
372 $form->{"unit_$i"}, conv_date($form->{deliverydate}),
373 conv_i($form->{"project_id_$i"}), $form->{"serialnumber_$i"},
374 conv_i($form->{"price_factor_id_$i"}), conv_i($form->{"price_factor_id_$i"}), conv_i($form->{"marge_price_factor_$i"}));
375 do_query($form, $dbh, $query, @values);
377 CVar->save_custom_variables(module => 'IC',
378 sub_module => 'invoice',
379 trans_id => $invoice_id,
380 configs => $ic_cvar_configs,
382 name_prefix => 'ic_',
383 name_postfix => "_$i",
387 $h_item_unit->finish();
389 $project_id = conv_i($form->{"globalproject_id"});
391 $form->{datepaid} = $form->{invdate};
393 # all amounts are in natural state, netamount includes the taxes
394 # if tax is included, netamount is rounded to 2 decimal places,
398 for my $i (1 .. $form->{paidaccounts}) {
399 $form->{"paid_$i"} = $form->parse_amount($myconfig, $form->{"paid_$i"});
400 $form->{paid} += $form->{"paid_$i"};
401 $form->{datepaid} = $form->{"datepaid_$i"} if $form->{"datepaid_$i"};
404 my ($tax, $paiddiff) = (0, 0);
406 $netamount = $form->round_amount($netamount, 2);
408 # figure out rounding errors for amount paid and total amount
409 if ($form->{taxincluded}) {
411 $amount = $form->round_amount($netamount * $form->{exchangerate}, 2);
412 $paiddiff = $amount - $netamount * $form->{exchangerate};
413 $netamount = $amount;
415 foreach $item (split / /, $form->{taxaccounts}) {
416 $amount = $form->{amount}{ $form->{id} }{$item} * $form->{exchangerate};
417 $form->{amount}{ $form->{id} }{$item} = $form->round_amount($amount, 2);
419 $amount = $form->{amount}{ $form->{id} }{$item} * -1;
421 $netamount -= $amount;
424 $invoicediff += $paiddiff;
425 $expensediff += $paiddiff;
427 ######## this only applies to tax included
429 # in the sales invoice case rounding errors only have to be corrected for
430 # income accounts, it is enough to add the total rounding error to one of
431 # the income accounts, with the one assigned to the last row being used
432 # (lastinventoryaccno)
434 # in the purchase invoice case rounding errors may be split between
435 # inventory accounts and expense accounts. After rounding, an error of 1
436 # cent is introduced if the total rounding error exceeds 0.005. The total
437 # error is made up of $invoicediff and $expensediff, however, so if both
438 # values are below 0.005, but add up to a total >= 0.005, correcting
439 # lastinventoryaccno and lastexpenseaccno separately has no effect after
440 # rounding. This caused bug 1579. Therefore when the combined total exceeds
441 # 0.005, but neither do individually, the account with the larger value
442 # shall receive the total rounding error, and the next time it is rounded
443 # the 1 cent correction will be introduced.
445 $form->{amount}{ $form->{id} }{$lastinventoryaccno} -= $invoicediff if $lastinventoryaccno;
446 $form->{amount}{ $form->{id} }{$lastexpenseaccno} -= $expensediff if $lastexpenseaccno;
448 if ( (abs($expensediff)+abs($invoicediff)) >= 0.005 and abs($expensediff) < 0.005 and abs($invoicediff) < 0.005 ) {
450 # in total the rounding error adds up to 1 cent effectively, correct the
451 # larger of the two numbers
453 if ( abs($form->{amount}{ $form->{id} }{$lastinventoryaccno}) > abs($form->{amount}{ $form->{id} }{$lastexpenseaccno}) ) {
454 # $invoicediff has already been deducted, now also deduct expensediff
455 $form->{amount}{ $form->{id} }{$lastinventoryaccno} -= $expensediff;
457 # expensediff has already been deducted, now also deduct invoicediff
458 $form->{amount}{ $form->{id} }{$lastexpenseaccno} -= $invoicediff;
463 $amount = $form->round_amount($netamount * $form->{exchangerate}, 2);
464 $paiddiff = $amount - $netamount * $form->{exchangerate};
465 $netamount = $amount;
467 foreach my $item (split / /, $form->{taxaccounts}) {
468 $form->{amount}{ $form->{id} }{$item} = $form->round_amount($form->{amount}{ $form->{id} }{$item}, 2);
469 $amount = $form->round_amount( $form->{amount}{ $form->{id} }{$item} * $form->{exchangerate} * -1, 2);
470 $paiddiff += $amount - $form->{amount}{ $form->{id} }{$item} * $form->{exchangerate} * -1;
471 $form->{amount}{ $form->{id} }{$item} = $form->round_amount($amount * -1, 2);
472 $amount = $form->{amount}{ $form->{id} }{$item} * -1;
477 $form->{amount}{ $form->{id} }{ $form->{AP} } = $netamount + $tax;
480 $form->{paid} = $form->round_amount($form->{paid} * $form->{exchangerate} + $paiddiff, 2) if $form->{paid} != 0;
482 # update exchangerate
484 $form->update_exchangerate($dbh, $form->{currency}, $form->{invdate}, 0, $form->{exchangerate})
485 if ($form->{currency} ne $defaultcurrency) && !$exchangerate;
487 # record acc_trans transactions
488 foreach my $trans_id (keys %{ $form->{amount} }) {
489 foreach my $accno (keys %{ $form->{amount}{$trans_id} }) {
490 $form->{amount}{$trans_id}{$accno} = $form->round_amount($form->{amount}{$trans_id}{$accno}, 2);
493 next if $payments_only || !$form->{amount}{$trans_id}{$accno};
495 $query = qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate, taxkey, project_id, tax_id)
496 VALUES (?, (SELECT id FROM chart WHERE accno = ?), ?, ?,
497 (SELECT taxkey_id FROM chart WHERE accno = ?), ?,
500 WHERE chart_id= (SELECT id
504 ORDER BY startdate DESC LIMIT 1))|;
505 @values = ($trans_id, $accno, $form->{amount}{$trans_id}{$accno},
506 conv_date($form->{invdate}), $accno, $project_id, $accno, conv_date($form->{invdate}));
507 do_query($form, $dbh, $query, @values);
511 # deduct payment differences from paiddiff
512 for my $i (1 .. $form->{paidaccounts}) {
513 if ($form->{"paid_$i"} != 0) {
514 $amount = $form->round_amount($form->{"paid_$i"} * $form->{exchangerate}, 2);
515 $paiddiff -= $amount - $form->{"paid_$i"} * $form->{exchangerate};
519 # force AP entry if 0
521 $form->{amount}{ $form->{id} }{ $form->{AP} } = $form->{paid} if $form->{amount}{$form->{id}}{$form->{AP}} == 0;
523 # record payments and offsetting AP
524 for my $i (1 .. $form->{paidaccounts}) {
525 if ($form->{"acc_trans_id_$i"}
527 && (SL::DB::Default->get->payments_changeable == 0)) {
531 next if $form->{"paid_$i"} == 0;
533 my ($accno) = split /--/, $form->{"AP_paid_$i"};
534 $form->{"datepaid_$i"} = $form->{invdate} unless ($form->{"datepaid_$i"});
535 $form->{datepaid} = $form->{"datepaid_$i"};
537 $amount = $form->round_amount($form->{"paid_$i"} * $form->{exchangerate} + $paiddiff, 2) * -1;
540 if ($form->{amount}{ $form->{id} }{ $form->{AP} } != 0) {
541 $query = qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate, taxkey, project_id, tax_id)
542 VALUES (?, (SELECT id FROM chart WHERE accno = ?), ?, ?,
543 (SELECT taxkey_id FROM chart WHERE accno = ?), ?,
546 WHERE chart_id= (SELECT id
550 ORDER BY startdate DESC LIMIT 1))|;
551 @values = (conv_i($form->{id}), $form->{AP}, $amount,
552 $form->{"datepaid_$i"}, $form->{AP}, $project_id, $form->{AP}, conv_date($form->{"datepaid_$i"}));
553 do_query($form, $dbh, $query, @values);
557 my $gldate = (conv_date($form->{"gldate_$i"}))? conv_date($form->{"gldate_$i"}) : conv_date($form->current_date($myconfig));
560 qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate, gldate, source, memo, taxkey, project_id, tax_id)
561 VALUES (?, (SELECT id FROM chart WHERE accno = ?), ?, ?, ?, ?, ?,
562 (SELECT taxkey_id FROM chart WHERE accno = ?), ?,
565 WHERE chart_id= (SELECT id
566 FROM chart WHERE accno = ?)
568 ORDER BY startdate DESC LIMIT 1))|;
569 @values = (conv_i($form->{id}), $accno, $form->{"paid_$i"}, $form->{"datepaid_$i"},
570 $gldate, $form->{"source_$i"}, $form->{"memo_$i"}, $accno, $project_id, $accno, conv_date($form->{"datepaid_$i"}));
571 do_query($form, $dbh, $query, @values);
575 if ($form->{currency} eq $defaultcurrency) {
576 $form->{"exchangerate_$i"} = 1;
578 $exchangerate = $form->check_exchangerate($myconfig, $form->{currency}, $form->{"datepaid_$i"}, 'sell');
579 $form->{"exchangerate_$i"} = $exchangerate || $form->parse_amount($myconfig, $form->{"exchangerate_$i"});
582 # exchangerate difference
583 $form->{fx}{$accno}{ $form->{"datepaid_$i"} } += $form->{"paid_$i"} * ($form->{"exchangerate_$i"} - 1) + $paiddiff;
587 ($form->{"paid_$i"} * $form->{exchangerate}) -
588 ($form->{"paid_$i"} * $form->{"exchangerate_$i"});
590 $form->{fx}{ $form->{fxgain_accno} }{ $form->{"datepaid_$i"} } += $amount;
592 $form->{fx}{ $form->{fxloss_accno} }{ $form->{"datepaid_$i"} } += $amount;
597 # update exchange rate
598 $form->update_exchangerate($dbh, $form->{currency}, $form->{"datepaid_$i"}, 0, $form->{"exchangerate_$i"})
599 if ($form->{currency} ne $defaultcurrency) && !$exchangerate;
602 # record exchange rate differences and gains/losses
603 foreach my $accno (keys %{ $form->{fx} }) {
604 foreach my $transdate (keys %{ $form->{fx}{$accno} }) {
605 $form->{fx}{$accno}{$transdate} = $form->round_amount($form->{fx}{$accno}{$transdate}, 2);
606 next if ($form->{fx}{$accno}{$transdate} == 0);
608 $query = qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate, cleared, fx_transaction, taxkey, project_id, tax_id)
609 VALUES (?, (SELECT id FROM chart WHERE accno = ?), ?, ?, '0', '1', 0, ?,
612 WHERE chart_id= (SELECT id
616 ORDER BY startdate DESC LIMIT 1))|;
617 @values = (conv_i($form->{id}), $accno, $form->{fx}{$accno}{$transdate}, conv_date($transdate), $project_id, $accno, $form->{fx}{$accno}{$transdate});
618 do_query($form, $dbh, $query, @values);
622 IO->set_datepaid(table => 'ap', id => $form->{id}, dbh => $dbh);
624 if ($payments_only) {
625 $query = qq|UPDATE ap SET paid = ? WHERE id = ?|;
626 do_query($form, $dbh, $query, $form->{paid}, conv_i($form->{id}));
628 if (!$provided_dbh) {
633 $main::lxdebug->leave_sub();
637 $amount = $netamount + $tax;
639 # set values which could be empty
640 my $taxzone_id = $form->{taxzone_id} * 1;
642 # Seit neuestem wird die department_id schon übergeben UND $form->department nicht mehr
643 # korrekt zusammengebaut. Sehr wahrscheinlich beim Umstieg auf T8 kaputt gegangen
644 # Ich lass den Code von 2005 erstmal noch stehen ;-) jb 03-2011
645 # copy & paste von IS.pm
646 if (!$form->{department_id}){
647 $form->{department_id} = (split /--/, $form->{department})[1];
649 $form->{invnumber} = $form->{id} unless $form->{invnumber};
651 $taxzone_id = 0 if (3 < $taxzone_id) || (0 > $taxzone_id);
654 $query = qq|UPDATE ap SET
655 invnumber = ?, ordnumber = ?, quonumber = ?, transdate = ?,
656 orddate = ?, quodate = ?, vendor_id = ?, amount = ?,
657 netamount = ?, paid = ?, duedate = ?,
658 invoice = ?, taxzone_id = ?, notes = ?, taxincluded = ?,
659 intnotes = ?, curr = ?, storno_id = ?, storno = ?,
660 cp_id = ?, employee_id = ?, department_id = ?,
661 globalproject_id = ?, direct_debit = ?
664 $form->{invnumber}, $form->{ordnumber}, $form->{quonumber}, conv_date($form->{invdate}),
665 conv_date($form->{orddate}), conv_date($form->{quodate}), conv_i($form->{vendor_id}), $amount,
666 $netamount, $form->{paid}, conv_date($form->{duedate}),
667 '1', $taxzone_id, $form->{notes}, $form->{taxincluded} ? 't' : 'f',
668 $form->{intnotes}, $form->{currency}, conv_i($form->{storno_id}), $form->{storno} ? 't' : 'f',
669 conv_i($form->{cp_id}), conv_i($form->{employee_id}), conv_i($form->{department_id}),
670 conv_i($form->{globalproject_id}),
671 $form->{direct_debit} ? 't' : 'f',
674 do_query($form, $dbh, $query, @values);
676 if ($form->{storno}) {
677 $query = qq|UPDATE ap SET paid = paid + amount WHERE id = ?|;
678 do_query($form, $dbh, $query, conv_i($form->{storno_id}));
680 $query = qq|UPDATE ap SET storno = 't' WHERE id = ?|;
681 do_query($form, $dbh, $query, conv_i($form->{storno_id}));
683 $query = qq!UPDATE ap SET intnotes = ? || intnotes WHERE id = ?!;
684 do_query($form, $dbh, $query, "Rechnung storniert am $form->{invdate} ", conv_i($form->{storno_id}));
686 $query = qq|UPDATE ap SET paid = amount WHERE id = ?|;
687 do_query($form, $dbh, $query, conv_i($form->{id}));
692 $form->{name} = $form->{vendor};
693 $form->{name} =~ s/--\Q$form->{vendor_id}\E//;
694 $form->add_shipto($dbh, $form->{id}, "AP");
696 # delete zero entries
697 do_query($form, $dbh, qq|DELETE FROM acc_trans WHERE amount = 0|);
699 Common::webdav_folder($form);
701 # Link this record to the records it was created from.
702 RecordLinks->create_links('dbh' => $dbh,
704 'from_table' => 'oe',
705 'from_ids' => $form->{convert_from_oe_ids},
707 'to_id' => $form->{id},
709 delete $form->{convert_from_oe_ids};
711 my @convert_from_do_ids = map { $_ * 1 } grep { $_ } split m/\s+/, $form->{convert_from_do_ids};
712 if (scalar @convert_from_do_ids) {
713 DO->close_orders('dbh' => $dbh,
714 'ids' => \@convert_from_do_ids);
716 RecordLinks->create_links('dbh' => $dbh,
718 'from_table' => 'delivery_orders',
719 'from_ids' => \@convert_from_do_ids,
721 'to_id' => $form->{id},
724 delete $form->{convert_from_do_ids};
726 ARAP->close_orders_if_billed('dbh' => $dbh,
727 'arap_id' => $form->{id},
730 # safety check datev export
731 if ($::instance_conf->get_datev_check_on_purchase_invoice) {
732 my $transdate = $::form->{invdate} ? DateTime->from_lxoffice($::form->{invdate}) : undef;
733 $transdate ||= DateTime->today;
735 my $datev = SL::DATEV->new(
736 exporttype => DATEV_ET_BUCHUNGEN,
737 format => DATEV_FORMAT_KNE,
745 if ($datev->errors) {
747 die join "\n", $::locale->text('DATEV check returned errors:'), $datev->errors;
752 if (!$provided_dbh) {
753 $rc = $dbh->commit();
757 $main::lxdebug->leave_sub();
762 sub reverse_invoice {
763 $main::lxdebug->enter_sub();
765 my ($dbh, $form) = @_;
767 # reverse inventory items
769 qq|SELECT i.parts_id, p.inventory_accno_id, p.expense_accno_id, i.qty, i.allocated, i.sellprice
770 FROM invoice i, parts p
771 WHERE (i.parts_id = p.id)
772 AND (i.trans_id = ?)|;
773 my $sth = prepare_execute_query($form, $dbh, $query, conv_i($form->{id}));
777 while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
778 $netamount += $form->round_amount($ref->{sellprice} * $ref->{qty} * -1, 2);
780 next unless $ref->{inventory_accno_id};
782 # if $ref->{allocated} > 0 than we sold that many items
783 next if ($ref->{allocated} <= 0);
785 # get references for sold items
787 qq|SELECT i.id, i.trans_id, i.allocated, a.transdate
789 WHERE (i.parts_id = ?)
790 AND (i.allocated < 0)
791 AND (i.trans_id = a.id)
792 ORDER BY transdate DESC|;
793 my $sth2 = prepare_execute_query($form, $dbh, $query, $ref->{parts_id});
795 while (my $pthref = $sth2->fetchrow_hashref("NAME_lc")) {
796 my $qty = $ref->{allocated};
797 if (($ref->{allocated} + $pthref->{allocated}) > 0) {
798 $qty = $pthref->{allocated} * -1;
801 my $amount = $form->round_amount($ref->{sellprice} * $qty, 2);
804 $form->update_balance($dbh, "invoice", "allocated", qq|id = $pthref->{id}|, $qty);
806 $form->update_balance($dbh, "acc_trans", "amount",
807 qq| (trans_id = $pthref->{trans_id})
808 AND (chart_id = $ref->{expense_accno_id})
809 AND (transdate = '$pthref->{transdate}')|,
812 $form->update_balance($dbh, "acc_trans", "amount",
813 qq| (trans_id = $pthref->{trans_id})
814 AND (chart_id = $ref->{inventory_accno_id})
815 AND (transdate = '$pthref->{transdate}')|,
818 last if (($ref->{allocated} -= $qty) <= 0);
824 my $id = conv_i($form->{id});
827 $query = qq|DELETE FROM acc_trans WHERE trans_id = ?|;
828 do_query($form, $dbh, $query, $id);
830 # delete invoice entries
831 $query = qq|DELETE FROM invoice WHERE trans_id = ?|;
832 do_query($form, $dbh, $query, $id);
834 $query = qq|DELETE FROM shipto WHERE (trans_id = ?) AND (module = 'AP')|;
835 do_query($form, $dbh, $query, $id);
837 $main::lxdebug->leave_sub();
841 $main::lxdebug->enter_sub();
843 my ($self, $myconfig, $form) = @_;
845 # connect to database
846 my $dbh = $form->dbconnect_noauto($myconfig);
848 &reverse_invoice($dbh, $form);
850 # delete zero entries
851 $query = qq|DELETE FROM acc_trans WHERE amount = 0|;
852 do_query($form, $dbh, $query);
855 $query = qq|DELETE FROM ap WHERE id = ?|;
856 do_query($form, $dbh, $query, conv_i($form->{id}));
858 my $rc = $dbh->commit;
861 $main::lxdebug->leave_sub();
866 sub retrieve_invoice {
867 $main::lxdebug->enter_sub();
869 my ($self, $myconfig, $form) = @_;
871 # connect to database
872 my $dbh = $form->dbconnect($myconfig);
874 my ($query, $sth, $ref, $q_invdate);
877 $q_invdate = qq|, COALESCE((SELECT transdate FROM ar WHERE id = (SELECT MAX(id) FROM ar)), current_date) AS invdate|;
878 if ($form->{vendor_id}) {
879 my $vendor_id = $dbh->quote($form->{vendor_id} * 1);
881 qq|, COALESCE((SELECT transdate FROM ar WHERE id = (SELECT MAX(id) FROM ar)), current_date) +
882 COALESCE((SELECT pt.terms_netto
884 LEFT JOIN payment_terms pt ON (v.payment_id = pt.id)
885 WHERE v.id = $vendor_id),
890 # get default accounts and last invoice number
893 (SELECT c.accno FROM chart c WHERE d.inventory_accno_id = c.id) AS inventory_accno,
894 (SELECT c.accno FROM chart c WHERE d.income_accno_id = c.id) AS income_accno,
895 (SELECT c.accno FROM chart c WHERE d.expense_accno_id = c.id) AS expense_accno,
896 (SELECT c.accno FROM chart c WHERE d.fxgain_accno_id = c.id) AS fxgain_accno,
897 (SELECT c.accno FROM chart c WHERE d.fxloss_accno_id = c.id) AS fxloss_accno,
901 $ref = selectfirst_hashref_query($form, $dbh, $query);
902 map { $form->{$_} = $ref->{$_} } keys %$ref;
906 $main::lxdebug->leave_sub();
912 $query = qq|SELECT cp_id, invnumber, transdate AS invdate, duedate,
913 orddate, quodate, globalproject_id,
914 ordnumber, quonumber, paid, taxincluded, notes, taxzone_id, storno, gldate,
915 intnotes, curr AS currency, direct_debit
918 $ref = selectfirst_hashref_query($form, $dbh, $query, conv_i($form->{id}));
919 map { $form->{$_} = $ref->{$_} } keys %$ref;
921 # remove any trailing whitespace
922 $form->{currency} =~ s/\s*$//;
924 $form->{exchangerate} = $form->get_exchangerate($dbh, $form->{currency}, $form->{invdate}, "sell");
927 $query = qq|SELECT * FROM shipto WHERE (trans_id = ?) AND (module = 'AP')|;
928 $ref = selectfirst_hashref_query($form, $dbh, $query, conv_i($form->{id}));
930 map { $form->{$_} = $ref->{$_} } keys %$ref;
932 my $transdate = $form->{invdate} ? $dbh->quote($form->{invdate}) : "current_date";
933 my $taxzone_id = $form->{taxzone_id} * 1;
935 $taxzone_id = 0 if ((3 < $taxzone_id) || (0 > $taxzone_id));
937 # retrieve individual items
940 c1.accno AS inventory_accno, c1.new_chart_id AS inventory_new_chart, date($transdate) - c1.valid_from AS inventory_valid,
941 c2.accno AS income_accno, c2.new_chart_id AS income_new_chart, date($transdate) - c2.valid_from AS income_valid,
942 c3.accno AS expense_accno, c3.new_chart_id AS expense_new_chart, date($transdate) - c3.valid_from AS expense_valid,
945 i.description, i.longdescription, i.qty, i.fxsellprice AS sellprice, i.parts_id AS id, i.unit, i.deliverydate, i.project_id, i.serialnumber,
946 i.price_factor_id, i.price_factor, i.marge_price_factor, i.discount,
947 p.partnumber, p.inventory_accno_id AS part_inventory_accno_id, p.bin, pr.projectnumber, pg.partsgroup
950 JOIN parts p ON (i.parts_id = p.id)
951 LEFT JOIN chart c1 ON ((SELECT inventory_accno_id FROM buchungsgruppen WHERE id = p.buchungsgruppen_id) = c1.id)
952 LEFT JOIN chart c2 ON ((SELECT income_accno_id_${taxzone_id} FROM buchungsgruppen WHERE id = p.buchungsgruppen_id) = c2.id)
953 LEFT JOIN chart c3 ON ((SELECT expense_accno_id_${taxzone_id} FROM buchungsgruppen WHERE id = p.buchungsgruppen_id) = c3.id)
954 LEFT JOIN project pr ON (i.project_id = pr.id)
955 LEFT JOIN partsgroup pg ON (pg.id = p.partsgroup_id)
960 $sth = prepare_execute_query($form, $dbh, $query, conv_i($form->{id}));
962 while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
963 # Retrieve custom variables.
964 my $cvars = CVar->get_custom_variables(dbh => $dbh,
966 sub_module => 'invoice',
967 trans_id => $ref->{invoice_id},
969 map { $ref->{"ic_cvar_$_->{name}"} = $_->{value} } @{ $cvars };
970 delete $ref->{invoice_id};
972 map({ delete($ref->{$_}); } qw(inventory_accno inventory_new_chart inventory_valid)) if !$ref->{"part_inventory_accno_id"};
973 delete($ref->{"part_inventory_accno_id"});
975 foreach my $type (qw(inventory income expense)) {
976 while ($ref->{"${type}_new_chart"} && ($ref->{"${type}_valid"} >=0)) {
977 my $query = qq|SELECT accno, new_chart_id, date($transdate) - valid_from FROM chart WHERE id = ?|;
978 @$ref{ map $type.$_, qw(_accno _new_chart _valid) } = selectrow_query($form, $dbh, $query, $ref->{"${type}_new_chart"});
982 # get tax rates and description
983 my $accno_id = ($form->{vc} eq "customer") ? $ref->{income_accno} : $ref->{expense_accno};
985 qq|SELECT c.accno, t.taxdescription, t.rate, t.taxnumber FROM tax t
986 LEFT JOIN chart c ON (c.id = t.chart_id)
988 (SELECT tk.tax_id FROM taxkeys tk
989 WHERE tk.chart_id = (SELECT id FROM chart WHERE accno = ?)
990 AND (startdate <= $transdate)
991 ORDER BY startdate DESC
994 my $stw = prepare_execute_query($form, $dbh, $query, $accno_id);
995 $ref->{taxaccounts} = "";
998 while (my $ptr = $stw->fetchrow_hashref("NAME_lc")) {
999 if (($ptr->{accno} eq "") && ($ptr->{rate} == 0)) {
1004 $ref->{taxaccounts} .= "$ptr->{accno} ";
1006 if (!($form->{taxaccounts} =~ /\Q$ptr->{accno}\E/)) {
1007 $form->{"$ptr->{accno}_rate"} = $ptr->{rate};
1008 $form->{"$ptr->{accno}_description"} = $ptr->{taxdescription};
1009 $form->{"$ptr->{accno}_taxnumber"} = $ptr->{taxnumber};
1010 $form->{taxaccounts} .= "$ptr->{accno} ";
1015 chop $ref->{taxaccounts};
1016 push @{ $form->{invoice_details} }, $ref;
1021 Common::webdav_folder($form);
1025 $main::lxdebug->leave_sub();
1029 $main::lxdebug->enter_sub();
1031 my ($self, $myconfig, $form, $params) = @_;
1033 $params = $form unless defined $params && ref $params eq "HASH";
1035 # connect to database
1036 my $dbh = $form->dbconnect($myconfig);
1038 my $dateformat = $myconfig->{dateformat};
1039 $dateformat .= "yy" if $myconfig->{dateformat} !~ /^y/;
1041 my $vid = conv_i($params->{vendor_id});
1042 my $vnr = conv_i($params->{vendornumber});
1045 ($params->{invdate})
1046 ? "to_date(" . $dbh->quote($params->{invdate}) . ", '$dateformat')"
1053 $where .= 'AND v.id = ?';
1057 $where .= 'AND v.vendornumber = ?';
1062 v.id AS vendor_id, v.name AS vendor, v.discount as vendor_discount,
1063 v.creditlimit, v.terms, v.notes AS intnotes,
1064 v.email, v.cc, v.bcc, v.language_id, v.payment_id,
1065 v.street, v.zipcode, v.city, v.country, v.taxzone_id, v.curr, v.direct_debit,
1066 $duedate + COALESCE(pt.terms_netto, 0) AS duedate,
1067 b.description AS business
1069 LEFT JOIN business b ON (b.id = v.business_id)
1070 LEFT JOIN payment_terms pt ON (v.payment_id = pt.id)
1072 my $ref = selectfirst_hashref_query($form, $dbh, $query, @values);
1073 map { $params->{$_} = $ref->{$_} } keys %$ref;
1075 # remove any trailing whitespace
1076 $form->{curr} =~ s/\s*$//;
1078 # use vendor currency if not empty
1079 $form->{currency} = $form->{curr} if $form->{curr};
1081 $params->{creditremaining} = $params->{creditlimit};
1083 $query = qq|SELECT SUM(amount - paid) FROM ap WHERE vendor_id = ?|;
1084 my ($unpaid_invoices) = selectfirst_array_query($form, $dbh, $query, $vid);
1085 $params->{creditremaining} -= $unpaid_invoices;
1087 $query = qq|SELECT o.amount,
1090 WHERE (e.curr = o.curr)
1091 AND (e.transdate = o.transdate)) AS exch
1093 WHERE (o.vendor_id = ?) AND (o.quotation = '0') AND (o.closed = '0')|;
1094 my $sth = prepare_execute_query($form, $dbh, $query, $vid);
1095 while (my ($amount, $exch) = $sth->fetchrow_array()) {
1096 $exch = 1 unless $exch;
1097 $params->{creditremaining} -= $amount * $exch;
1101 # get shipto if we do not convert an order or invoice
1102 if (!$params->{shipto}) {
1103 delete @{$params}{qw(shiptoname shiptostreet shiptozipcode shiptocity shiptocountry shiptocontact shiptophone shiptofax shiptoemail)};
1105 $query = qq|SELECT * FROM shipto WHERE (trans_id = ?) AND (module= 'CT')|;
1106 $ref = selectfirst_hashref_query($form, $dbh, $query, $vid);
1107 @{$params}{keys %$ref} = @{$ref}{keys %$ref};
1108 map { $params->{$_} = $ref->{$_} } keys %$ref;
1111 if (!$params->{id} && $params->{type} !~ /_(order|quotation)/) {
1112 # setup last accounts used
1114 qq|SELECT c.id, c.accno, c.description, c.link, c.category
1116 JOIN acc_trans ac ON (ac.chart_id = c.id)
1117 JOIN ap a ON (a.id = ac.trans_id)
1118 WHERE (a.vendor_id = ?)
1119 AND (NOT ((c.link LIKE '%_tax%') OR (c.link LIKE '%_paid%')))
1120 AND (a.id IN (SELECT max(a2.id) FROM ap a2 WHERE a2.vendor_id = ?))|;
1121 my $refs = selectall_hashref_query($form, $dbh, $query, $vid, $vid);
1125 if ($ref->{category} eq 'E') {
1127 my ($tax_id, $rate);
1128 if ($params->{initial_transdate}) {
1129 my $tax_query = qq|SELECT tk.tax_id, t.rate FROM taxkeys tk
1130 LEFT JOIN tax t ON (tk.tax_id = t.id)
1131 WHERE (tk.chart_id = ?) AND (startdate <= ?)
1132 ORDER BY tk.startdate DESC
1134 ($tax_id, $rate) = selectrow_query($form, $dbh, $tax_query, $ref->{id}, $params->{initial_transdate});
1135 $params->{"taxchart_$i"} = "${tax_id}--${rate}";
1138 $params->{"AP_amount_$i"} = "$ref->{accno}--$tax_id";
1141 if ($ref->{category} eq 'L') {
1142 $params->{APselected} = $params->{AP_1} = $ref->{accno};
1145 $params->{rowcount} = $i if ($i && !$params->{type});
1150 $main::lxdebug->leave_sub();
1154 $main::lxdebug->enter_sub();
1156 my ($self, $myconfig, $form) = @_;
1158 # connect to database
1159 my $dbh = $form->dbconnect($myconfig);
1161 my $i = $form->{rowcount};
1163 # don't include assemblies or obsolete parts
1164 my $where = "NOT p.assembly = '1' AND NOT p.obsolete = '1'";
1167 foreach my $table_column (qw(p.partnumber p.description pg.partsgroup)) {
1168 my $field = (split m{\.}, $table_column)[1];
1169 next unless $form->{"${field}_${i}"};
1170 $where .= " AND lower(${table_column}) LIKE lower(?)";
1171 push @values, '%' . $form->{"${field}_${i}"} . '%';
1173 #Es soll auch nach EAN gesucht werden, ohne Einschränkung durch Beschreibung
1174 if ($form->{"partnumber_$i"} && !$form->{"description_$i"}) {
1175 $where .= qq| OR (NOT p.obsolete = '1' AND p.ean = ? )|;
1176 push @values, $form->{"partnumber_$i"};
1179 # Search for part ID overrides all other criteria.
1180 if ($form->{"id_${i}"}) {
1181 $where = qq|p.id = ?|;
1182 @values = ($form->{"id_${i}"});
1185 if ($form->{"description_$i"}) {
1186 $where .= " ORDER BY p.description";
1188 $where .= " ORDER BY p.partnumber";
1192 if ($form->{type} eq "invoice") {
1193 $transdate = $form->{invdate} ? $dbh->quote($form->{invdate}) : "current_date";
1195 $transdate = $form->{transdate} ? $dbh->quote($form->{transdate}) : "current_date";
1198 my $taxzone_id = $form->{taxzone_id} * 1;
1199 $taxzone_id = 0 if ((3 < $taxzone_id) || (0 > $taxzone_id));
1203 p.id, p.partnumber, p.description, p.lastcost AS sellprice, p.listprice,
1204 p.unit, p.assembly, p.bin, p.onhand, p.formel,
1205 p.notes AS partnotes, p.notes AS longdescription, p.not_discountable,
1206 p.inventory_accno_id, p.price_factor_id,
1208 pfac.factor AS price_factor,
1210 c1.accno AS inventory_accno,
1211 c1.new_chart_id AS inventory_new_chart,
1212 date($transdate) - c1.valid_from AS inventory_valid,
1214 c2.accno AS income_accno,
1215 c2.new_chart_id AS income_new_chart,
1216 date($transdate) - c2.valid_from AS income_valid,
1218 c3.accno AS expense_accno,
1219 c3.new_chart_id AS expense_new_chart,
1220 date($transdate) - c3.valid_from AS expense_valid,
1225 LEFT JOIN chart c1 ON
1226 ((SELECT inventory_accno_id
1227 FROM buchungsgruppen
1228 WHERE id = p.buchungsgruppen_id) = c1.id)
1229 LEFT JOIN chart c2 ON
1230 ((SELECT income_accno_id_${taxzone_id}
1231 FROM buchungsgruppen
1232 WHERE id = p.buchungsgruppen_id) = c2.id)
1233 LEFT JOIN chart c3 ON
1234 ((SELECT expense_accno_id_${taxzone_id}
1235 FROM buchungsgruppen
1236 WHERE id = p.buchungsgruppen_id) = c3.id)
1237 LEFT JOIN partsgroup pg ON (pg.id = p.partsgroup_id)
1238 LEFT JOIN price_factors pfac ON (pfac.id = p.price_factor_id)
1240 my $sth = prepare_execute_query($form, $dbh, $query, @values);
1242 my @translation_queries = ( [ qq|SELECT tr.translation, tr.longdescription
1244 WHERE tr.language_id = ? AND tr.parts_id = ?| ],
1245 [ qq|SELECT tr.translation, tr.longdescription
1247 WHERE tr.language_id IN
1250 WHERE article_code = (SELECT article_code FROM language WHERE id = ?))
1253 map { push @{ $_ }, prepare_query($form, $dbh, $_->[0]) } @translation_queries;
1255 $form->{item_list} = [];
1256 while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
1258 # In der Buchungsgruppe ist immer ein Bestandskonto verknuepft, auch wenn
1259 # es sich um eine Dienstleistung handelt. Bei Dienstleistungen muss das
1260 # Buchungskonto also aus dem Ergebnis rausgenommen werden.
1261 if (!$ref->{inventory_accno_id}) {
1262 map({ delete($ref->{"inventory_${_}"}); } qw(accno new_chart valid));
1264 delete($ref->{inventory_accno_id});
1266 # get tax rates and description
1267 my $accno_id = ($form->{vc} eq "customer") ? $ref->{income_accno} : $ref->{expense_accno};
1269 qq|SELECT c.accno, t.taxdescription, t.rate, t.taxnumber
1271 LEFT JOIN chart c on (c.id = t.chart_id)
1279 AND (startdate <= $transdate)
1280 ORDER BY startdate DESC
1283 my $stw = prepare_execute_query($form, $dbh, $query, $accno_id);
1285 $ref->{taxaccounts} = "";
1287 while (my $ptr = $stw->fetchrow_hashref("NAME_lc")) {
1289 # if ($customertax{$ref->{accno}}) {
1290 if (($ptr->{accno} eq "") && ($ptr->{rate} == 0)) {
1295 $ref->{taxaccounts} .= "$ptr->{accno} ";
1297 if (!($form->{taxaccounts} =~ /\Q$ptr->{accno}\E/)) {
1298 $form->{"$ptr->{accno}_rate"} = $ptr->{rate};
1299 $form->{"$ptr->{accno}_description"} = $ptr->{taxdescription};
1300 $form->{"$ptr->{accno}_taxnumber"} = $ptr->{taxnumber};
1301 $form->{taxaccounts} .= "$ptr->{accno} ";
1304 if ($form->{language_id}) {
1305 for my $spec (@translation_queries) {
1306 do_statement($form, $spec->[1], $spec->[0], conv_i($form->{language_id}), conv_i($ref->{id}));
1307 my ($translation, $longdescription) = $spec->[1]->fetchrow_array;
1308 next unless $translation;
1309 $ref->{description} = $translation;
1310 $ref->{longdescription} = $longdescription;
1317 chop $ref->{taxaccounts};
1319 $ref->{onhand} *= 1;
1321 push @{ $form->{item_list} }, $ref;
1326 $_->[1]->finish for @translation_queries;
1328 foreach my $item (@{ $form->{item_list} }) {
1329 my $custom_variables = CVar->get_custom_variables(module => 'IC',
1330 trans_id => $item->{id},
1334 map { $item->{"ic_cvar_" . $_->{name} } = $_->{value} } @{ $custom_variables };
1339 $main::lxdebug->leave_sub();
1342 sub vendor_details {
1343 $main::lxdebug->enter_sub();
1345 my ($self, $myconfig, $form, @wanted_vars) = @_;
1347 # connect to database
1348 my $dbh = $form->dbconnect($myconfig);
1352 # get contact id, set it if nessessary
1353 $form->{cp_id} *= 1;
1355 if ($form->{cp_id}) {
1356 $contact = "AND cp.cp_id = ?";
1357 push @values, $form->{cp_id};
1360 # get rest for the vendor
1361 # fax and phone and email as vendor*
1363 qq|SELECT ct.*, cp.*, ct.notes as vendornotes, phone as vendorphone, fax as vendorfax, email as vendoremail,
1366 LEFT JOIN contacts cp ON (ct.id = cp.cp_cv_id)
1367 WHERE (ct.id = ?) $contact
1370 my $ref = selectfirst_hashref_query($form, $dbh, $query, $form->{vendor_id}, @values);
1372 # remove id and taxincluded before copy back
1373 delete @$ref{qw(id taxincluded)};
1375 @wanted_vars = grep({ $_ } @wanted_vars);
1376 if (scalar(@wanted_vars) > 0) {
1378 map({ $h_wanted_vars{$_} = 1; } @wanted_vars);
1379 map({ delete($ref->{$_}) unless ($h_wanted_vars{$_}); } keys(%{$ref}));
1382 map { $form->{$_} = $ref->{$_} } keys %$ref;
1383 # remove any trailing whitespace
1384 $form->{currency} =~ s/\s*$// if ($form->{currency});
1386 my $custom_variables = CVar->get_custom_variables('dbh' => $dbh,
1388 'trans_id' => $form->{vendor_id});
1389 map { $form->{"vc_cvar_$_->{name}"} = $_->{value} } @{ $custom_variables };
1391 $form->{cp_greeting} = GenericTranslations->get('dbh' => $dbh,
1392 'translation_type' => 'greetings::' . ($form->{cp_gender} eq 'f' ? 'female' : 'male'),
1393 'allow_fallback' => 1);
1397 $main::lxdebug->leave_sub();
1401 $main::lxdebug->enter_sub();
1403 my ($self, $myconfig, $form) = @_;
1405 # connect to database
1406 my $dbh = $form->dbconnect($myconfig);
1409 qq|SELECT accno, description, link
1411 WHERE link LIKE '%IC%'
1413 my $sth = prepare_execute_query($query, $dbh, $query);
1415 while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
1416 foreach my $key (split(/:/, $ref->{link})) {
1418 push @{ $form->{IC_links}{$key} },
1419 { accno => $ref->{accno},
1420 description => $ref->{description} };
1428 $main::lxdebug->leave_sub();
1431 sub _delete_payments {
1432 $main::lxdebug->enter_sub();
1434 my ($self, $form, $dbh) = @_;
1436 my @delete_acc_trans_ids;
1438 # Delete old payment entries from acc_trans.
1440 qq|SELECT acc_trans_id
1442 WHERE (trans_id = ?) AND fx_transaction
1446 SELECT at.acc_trans_id
1448 LEFT JOIN chart c ON (at.chart_id = c.id)
1449 WHERE (trans_id = ?) AND (c.link LIKE '%AP_paid%')|;
1450 push @delete_acc_trans_ids, selectall_array_query($form, $dbh, $query, conv_i($form->{id}), conv_i($form->{id}));
1453 qq|SELECT at.acc_trans_id
1455 LEFT JOIN chart c ON (at.chart_id = c.id)
1456 WHERE (trans_id = ?)
1457 AND ((c.link = 'AP') OR (c.link LIKE '%:AP') OR (c.link LIKE 'AP:%'))
1458 ORDER BY at.acc_trans_id
1460 push @delete_acc_trans_ids, selectall_array_query($form, $dbh, $query, conv_i($form->{id}));
1462 if (@delete_acc_trans_ids) {
1463 $query = qq|DELETE FROM acc_trans WHERE acc_trans_id IN (| . join(", ", @delete_acc_trans_ids) . qq|)|;
1464 do_query($form, $dbh, $query);
1467 $main::lxdebug->leave_sub();
1471 $main::lxdebug->enter_sub();
1473 my ($self, $myconfig, $form, $locale) = @_;
1475 # connect to database, turn off autocommit
1476 my $dbh = $form->dbconnect_noauto($myconfig);
1478 my (%payments, $old_form, $row, $item, $query, %keep_vars);
1480 $old_form = save_form();
1482 # Delete all entries in acc_trans from prior payments.
1483 if (SL::DB::Default->get->payments_changeable != 0) {
1484 $self->_delete_payments($form, $dbh);
1487 # Save the new payments the user made before cleaning up $form.
1488 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 };
1490 # Clean up $form so that old content won't tamper the results.
1491 %keep_vars = map { $_, 1 } qw(login password id);
1492 map { delete $form->{$_} unless $keep_vars{$_} } keys %{ $form };
1494 # Retrieve the invoice from the database.
1495 $self->retrieve_invoice($myconfig, $form);
1497 # Set up the content of $form in the way that IR::post_invoice() expects.
1498 $form->{exchangerate} = $form->format_amount($myconfig, $form->{exchangerate});
1500 for $row (1 .. scalar @{ $form->{invoice_details} }) {
1501 $item = $form->{invoice_details}->[$row - 1];
1503 map { $item->{$_} = $form->format_amount($myconfig, $item->{$_}) } qw(qty sellprice);
1505 map { $form->{"${_}_${row}"} = $item->{$_} } keys %{ $item };
1508 $form->{rowcount} = scalar @{ $form->{invoice_details} };
1510 delete @{$form}{qw(invoice_details paidaccounts storno paid)};
1512 # Restore the payment options from the user input.
1513 map { $form->{$_} = $payments{$_} } keys %payments;
1515 # Get the AP accno (which is normally done by Form::create_links()).
1519 LEFT JOIN chart c ON (at.chart_id = c.id)
1520 WHERE (trans_id = ?)
1521 AND ((c.link = 'AP') OR (c.link LIKE '%:AP') OR (c.link LIKE 'AP:%'))
1522 ORDER BY at.acc_trans_id
1525 ($form->{AP}) = selectfirst_array_query($form, $dbh, $query, conv_i($form->{id}));
1527 # Post the new payments.
1528 $self->post_invoice($myconfig, $form, $dbh, 1);
1530 restore_form($old_form);
1532 my $rc = $dbh->commit();
1535 $main::lxdebug->leave_sub();
1541 $::lxdebug->enter_sub;
1543 my ($self, %params) = @_;
1545 if (!$params{vendor_id} || !$params{invdate}) {
1546 $::lxdebug->leave_sub;
1547 return $params{default};
1550 my $dbh = $::form->get_standard_dbh;
1551 my $query = qq|SELECT ?::date + pt.terms_netto
1553 LEFT JOIN payment_terms pt ON (pt.id = v.payment_id)
1556 my ($duedate) = selectfirst_array_query($::form, $dbh, $query, $params{invdate}, $params{vendor_id});
1558 $duedate ||= $params{default};
1560 $::lxdebug->leave_sub;