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 = ?,
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}),
673 do_query($form, $dbh, $query, @values);
675 if ($form->{storno}) {
676 $query = qq|UPDATE ap SET paid = paid + amount WHERE id = ?|;
677 do_query($form, $dbh, $query, conv_i($form->{storno_id}));
679 $query = qq|UPDATE ap SET storno = 't' WHERE id = ?|;
680 do_query($form, $dbh, $query, conv_i($form->{storno_id}));
682 $query = qq!UPDATE ap SET intnotes = ? || intnotes WHERE id = ?!;
683 do_query($form, $dbh, $query, "Rechnung storniert am $form->{invdate} ", conv_i($form->{storno_id}));
685 $query = qq|UPDATE ap SET paid = amount WHERE id = ?|;
686 do_query($form, $dbh, $query, conv_i($form->{id}));
691 $form->{name} = $form->{vendor};
692 $form->{name} =~ s/--\Q$form->{vendor_id}\E//;
693 $form->add_shipto($dbh, $form->{id}, "AP");
695 # delete zero entries
696 do_query($form, $dbh, qq|DELETE FROM acc_trans WHERE amount = 0|);
698 Common::webdav_folder($form);
700 # Link this record to the records it was created from.
701 RecordLinks->create_links('dbh' => $dbh,
703 'from_table' => 'oe',
704 'from_ids' => $form->{convert_from_oe_ids},
706 'to_id' => $form->{id},
708 delete $form->{convert_from_oe_ids};
710 my @convert_from_do_ids = map { $_ * 1 } grep { $_ } split m/\s+/, $form->{convert_from_do_ids};
711 if (scalar @convert_from_do_ids) {
712 DO->close_orders('dbh' => $dbh,
713 'ids' => \@convert_from_do_ids);
715 RecordLinks->create_links('dbh' => $dbh,
717 'from_table' => 'delivery_orders',
718 'from_ids' => \@convert_from_do_ids,
720 'to_id' => $form->{id},
723 delete $form->{convert_from_do_ids};
725 ARAP->close_orders_if_billed('dbh' => $dbh,
726 'arap_id' => $form->{id},
729 # safety check datev export
730 if ($::instance_conf->get_datev_check_on_purchase_invoice) {
731 my $transdate = $::form->{invdate} ? DateTime->from_lxoffice($::form->{invdate}) : undef;
732 $transdate ||= DateTime->today;
734 my $datev = SL::DATEV->new(
735 exporttype => DATEV_ET_BUCHUNGEN,
736 format => DATEV_FORMAT_KNE,
744 if ($datev->errors) {
746 die join "\n", $::locale->text('DATEV check returned errors:'), $datev->errors;
751 if (!$provided_dbh) {
752 $rc = $dbh->commit();
756 $main::lxdebug->leave_sub();
761 sub reverse_invoice {
762 $main::lxdebug->enter_sub();
764 my ($dbh, $form) = @_;
766 # reverse inventory items
768 qq|SELECT i.parts_id, p.inventory_accno_id, p.expense_accno_id, i.qty, i.allocated, i.sellprice
769 FROM invoice i, parts p
770 WHERE (i.parts_id = p.id)
771 AND (i.trans_id = ?)|;
772 my $sth = prepare_execute_query($form, $dbh, $query, conv_i($form->{id}));
776 while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
777 $netamount += $form->round_amount($ref->{sellprice} * $ref->{qty} * -1, 2);
779 next unless $ref->{inventory_accno_id};
781 # if $ref->{allocated} > 0 than we sold that many items
782 next if ($ref->{allocated} <= 0);
784 # get references for sold items
786 qq|SELECT i.id, i.trans_id, i.allocated, a.transdate
788 WHERE (i.parts_id = ?)
789 AND (i.allocated < 0)
790 AND (i.trans_id = a.id)
791 ORDER BY transdate DESC|;
792 my $sth2 = prepare_execute_query($form, $dbh, $query, $ref->{parts_id});
794 while (my $pthref = $sth2->fetchrow_hashref("NAME_lc")) {
795 my $qty = $ref->{allocated};
796 if (($ref->{allocated} + $pthref->{allocated}) > 0) {
797 $qty = $pthref->{allocated} * -1;
800 my $amount = $form->round_amount($ref->{sellprice} * $qty, 2);
803 $form->update_balance($dbh, "invoice", "allocated", qq|id = $pthref->{id}|, $qty);
805 $form->update_balance($dbh, "acc_trans", "amount",
806 qq| (trans_id = $pthref->{trans_id})
807 AND (chart_id = $ref->{expense_accno_id})
808 AND (transdate = '$pthref->{transdate}')|,
811 $form->update_balance($dbh, "acc_trans", "amount",
812 qq| (trans_id = $pthref->{trans_id})
813 AND (chart_id = $ref->{inventory_accno_id})
814 AND (transdate = '$pthref->{transdate}')|,
817 last if (($ref->{allocated} -= $qty) <= 0);
823 my $id = conv_i($form->{id});
826 $query = qq|DELETE FROM acc_trans WHERE trans_id = ?|;
827 do_query($form, $dbh, $query, $id);
829 # delete invoice entries
830 $query = qq|DELETE FROM invoice WHERE trans_id = ?|;
831 do_query($form, $dbh, $query, $id);
833 $query = qq|DELETE FROM shipto WHERE (trans_id = ?) AND (module = 'AP')|;
834 do_query($form, $dbh, $query, $id);
836 $main::lxdebug->leave_sub();
840 $main::lxdebug->enter_sub();
842 my ($self, $myconfig, $form) = @_;
844 # connect to database
845 my $dbh = $form->dbconnect_noauto($myconfig);
847 &reverse_invoice($dbh, $form);
849 # delete zero entries
850 $query = qq|DELETE FROM acc_trans WHERE amount = 0|;
851 do_query($form, $dbh, $query);
854 $query = qq|DELETE FROM ap WHERE id = ?|;
855 do_query($form, $dbh, $query, conv_i($form->{id}));
857 my $rc = $dbh->commit;
860 $main::lxdebug->leave_sub();
865 sub retrieve_invoice {
866 $main::lxdebug->enter_sub();
868 my ($self, $myconfig, $form) = @_;
870 # connect to database
871 my $dbh = $form->dbconnect($myconfig);
873 my ($query, $sth, $ref, $q_invdate);
876 $q_invdate = qq|, COALESCE((SELECT transdate FROM ar WHERE id = (SELECT MAX(id) FROM ar)), current_date) AS invdate|;
877 if ($form->{vendor_id}) {
878 my $vendor_id = $dbh->quote($form->{vendor_id} * 1);
880 qq|, COALESCE((SELECT transdate FROM ar WHERE id = (SELECT MAX(id) FROM ar)), current_date) +
881 COALESCE((SELECT pt.terms_netto
883 LEFT JOIN payment_terms pt ON (v.payment_id = pt.id)
884 WHERE v.id = $vendor_id),
889 # get default accounts and last invoice number
892 (SELECT c.accno FROM chart c WHERE d.inventory_accno_id = c.id) AS inventory_accno,
893 (SELECT c.accno FROM chart c WHERE d.income_accno_id = c.id) AS income_accno,
894 (SELECT c.accno FROM chart c WHERE d.expense_accno_id = c.id) AS expense_accno,
895 (SELECT c.accno FROM chart c WHERE d.fxgain_accno_id = c.id) AS fxgain_accno,
896 (SELECT c.accno FROM chart c WHERE d.fxloss_accno_id = c.id) AS fxloss_accno,
900 $ref = selectfirst_hashref_query($form, $dbh, $query);
901 map { $form->{$_} = $ref->{$_} } keys %$ref;
905 $main::lxdebug->leave_sub();
911 $query = qq|SELECT cp_id, invnumber, transdate AS invdate, duedate,
912 orddate, quodate, globalproject_id,
913 ordnumber, quonumber, paid, taxincluded, notes, taxzone_id, storno, gldate,
914 intnotes, curr AS currency
917 $ref = selectfirst_hashref_query($form, $dbh, $query, conv_i($form->{id}));
918 map { $form->{$_} = $ref->{$_} } keys %$ref;
920 # remove any trailing whitespace
921 $form->{currency} =~ s/\s*$//;
923 $form->{exchangerate} = $form->get_exchangerate($dbh, $form->{currency}, $form->{invdate}, "sell");
926 $query = qq|SELECT * FROM shipto WHERE (trans_id = ?) AND (module = 'AP')|;
927 $ref = selectfirst_hashref_query($form, $dbh, $query, conv_i($form->{id}));
929 map { $form->{$_} = $ref->{$_} } keys %$ref;
931 my $transdate = $form->{invdate} ? $dbh->quote($form->{invdate}) : "current_date";
932 my $taxzone_id = $form->{taxzone_id} * 1;
934 $taxzone_id = 0 if ((3 < $taxzone_id) || (0 > $taxzone_id));
936 # retrieve individual items
939 c1.accno AS inventory_accno, c1.new_chart_id AS inventory_new_chart, date($transdate) - c1.valid_from AS inventory_valid,
940 c2.accno AS income_accno, c2.new_chart_id AS income_new_chart, date($transdate) - c2.valid_from AS income_valid,
941 c3.accno AS expense_accno, c3.new_chart_id AS expense_new_chart, date($transdate) - c3.valid_from AS expense_valid,
944 i.description, i.longdescription, i.qty, i.fxsellprice AS sellprice, i.parts_id AS id, i.unit, i.deliverydate, i.project_id, i.serialnumber,
945 i.price_factor_id, i.price_factor, i.marge_price_factor, i.discount,
946 p.partnumber, p.inventory_accno_id AS part_inventory_accno_id, p.bin, pr.projectnumber, pg.partsgroup
949 JOIN parts p ON (i.parts_id = p.id)
950 LEFT JOIN chart c1 ON ((SELECT inventory_accno_id FROM buchungsgruppen WHERE id = p.buchungsgruppen_id) = c1.id)
951 LEFT JOIN chart c2 ON ((SELECT income_accno_id_${taxzone_id} FROM buchungsgruppen WHERE id = p.buchungsgruppen_id) = c2.id)
952 LEFT JOIN chart c3 ON ((SELECT expense_accno_id_${taxzone_id} FROM buchungsgruppen WHERE id = p.buchungsgruppen_id) = c3.id)
953 LEFT JOIN project pr ON (i.project_id = pr.id)
954 LEFT JOIN partsgroup pg ON (pg.id = p.partsgroup_id)
959 $sth = prepare_execute_query($form, $dbh, $query, conv_i($form->{id}));
961 while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
962 # Retrieve custom variables.
963 my $cvars = CVar->get_custom_variables(dbh => $dbh,
965 sub_module => 'invoice',
966 trans_id => $ref->{invoice_id},
968 map { $ref->{"ic_cvar_$_->{name}"} = $_->{value} } @{ $cvars };
969 delete $ref->{invoice_id};
971 map({ delete($ref->{$_}); } qw(inventory_accno inventory_new_chart inventory_valid)) if !$ref->{"part_inventory_accno_id"};
972 delete($ref->{"part_inventory_accno_id"});
974 foreach my $type (qw(inventory income expense)) {
975 while ($ref->{"${type}_new_chart"} && ($ref->{"${type}_valid"} >=0)) {
976 my $query = qq|SELECT accno, new_chart_id, date($transdate) - valid_from FROM chart WHERE id = ?|;
977 @$ref{ map $type.$_, qw(_accno _new_chart _valid) } = selectrow_query($form, $dbh, $query, $ref->{"${type}_new_chart"});
981 # get tax rates and description
982 my $accno_id = ($form->{vc} eq "customer") ? $ref->{income_accno} : $ref->{expense_accno};
984 qq|SELECT c.accno, t.taxdescription, t.rate, t.taxnumber FROM tax t
985 LEFT JOIN chart c ON (c.id = t.chart_id)
987 (SELECT tk.tax_id FROM taxkeys tk
988 WHERE tk.chart_id = (SELECT id FROM chart WHERE accno = ?)
989 AND (startdate <= $transdate)
990 ORDER BY startdate DESC
993 my $stw = prepare_execute_query($form, $dbh, $query, $accno_id);
994 $ref->{taxaccounts} = "";
997 while (my $ptr = $stw->fetchrow_hashref("NAME_lc")) {
998 if (($ptr->{accno} eq "") && ($ptr->{rate} == 0)) {
1003 $ref->{taxaccounts} .= "$ptr->{accno} ";
1005 if (!($form->{taxaccounts} =~ /\Q$ptr->{accno}\E/)) {
1006 $form->{"$ptr->{accno}_rate"} = $ptr->{rate};
1007 $form->{"$ptr->{accno}_description"} = $ptr->{taxdescription};
1008 $form->{"$ptr->{accno}_taxnumber"} = $ptr->{taxnumber};
1009 $form->{taxaccounts} .= "$ptr->{accno} ";
1014 chop $ref->{taxaccounts};
1015 push @{ $form->{invoice_details} }, $ref;
1020 Common::webdav_folder($form);
1024 $main::lxdebug->leave_sub();
1028 $main::lxdebug->enter_sub();
1030 my ($self, $myconfig, $form, $params) = @_;
1032 $params = $form unless defined $params && ref $params eq "HASH";
1034 # connect to database
1035 my $dbh = $form->dbconnect($myconfig);
1037 my $dateformat = $myconfig->{dateformat};
1038 $dateformat .= "yy" if $myconfig->{dateformat} !~ /^y/;
1040 my $vid = conv_i($params->{vendor_id});
1041 my $vnr = conv_i($params->{vendornumber});
1044 ($params->{invdate})
1045 ? "to_date(" . $dbh->quote($params->{invdate}) . ", '$dateformat')"
1052 $where .= 'AND v.id = ?';
1056 $where .= 'AND v.vendornumber = ?';
1061 v.id AS vendor_id, v.name AS vendor, v.discount as vendor_discount,
1062 v.creditlimit, v.terms, v.notes AS intnotes,
1063 v.email, v.cc, v.bcc, v.language_id, v.payment_id,
1064 v.street, v.zipcode, v.city, v.country, v.taxzone_id, v.curr,
1065 $duedate + COALESCE(pt.terms_netto, 0) AS duedate,
1066 b.description AS business
1068 LEFT JOIN business b ON (b.id = v.business_id)
1069 LEFT JOIN payment_terms pt ON (v.payment_id = pt.id)
1071 my $ref = selectfirst_hashref_query($form, $dbh, $query, @values);
1072 map { $params->{$_} = $ref->{$_} } keys %$ref;
1074 # remove any trailing whitespace
1075 $form->{curr} =~ s/\s*$//;
1077 # use vendor currency if not empty
1078 $form->{currency} = $form->{curr} if $form->{curr};
1080 $params->{creditremaining} = $params->{creditlimit};
1082 $query = qq|SELECT SUM(amount - paid) FROM ap WHERE vendor_id = ?|;
1083 my ($unpaid_invoices) = selectfirst_array_query($form, $dbh, $query, $vid);
1084 $params->{creditremaining} -= $unpaid_invoices;
1086 $query = qq|SELECT o.amount,
1089 WHERE (e.curr = o.curr)
1090 AND (e.transdate = o.transdate)) AS exch
1092 WHERE (o.vendor_id = ?) AND (o.quotation = '0') AND (o.closed = '0')|;
1093 my $sth = prepare_execute_query($form, $dbh, $query, $vid);
1094 while (my ($amount, $exch) = $sth->fetchrow_array()) {
1095 $exch = 1 unless $exch;
1096 $params->{creditremaining} -= $amount * $exch;
1100 # get shipto if we do not convert an order or invoice
1101 if (!$params->{shipto}) {
1102 delete @{$params}{qw(shiptoname shiptostreet shiptozipcode shiptocity shiptocountry shiptocontact shiptophone shiptofax shiptoemail)};
1104 $query = qq|SELECT * FROM shipto WHERE (trans_id = ?) AND (module= 'CT')|;
1105 $ref = selectfirst_hashref_query($form, $dbh, $query, $vid);
1106 @{$params}{keys %$ref} = @{$ref}{keys %$ref};
1107 map { $params->{$_} = $ref->{$_} } keys %$ref;
1110 if (!$params->{id} && $params->{type} !~ /_(order|quotation)/) {
1111 # setup last accounts used
1113 qq|SELECT c.id, c.accno, c.description, c.link, c.category
1115 JOIN acc_trans ac ON (ac.chart_id = c.id)
1116 JOIN ap a ON (a.id = ac.trans_id)
1117 WHERE (a.vendor_id = ?)
1118 AND (NOT ((c.link LIKE '%_tax%') OR (c.link LIKE '%_paid%')))
1119 AND (a.id IN (SELECT max(a2.id) FROM ap a2 WHERE a2.vendor_id = ?))|;
1120 my $refs = selectall_hashref_query($form, $dbh, $query, $vid, $vid);
1124 if ($ref->{category} eq 'E') {
1126 my ($tax_id, $rate);
1127 if ($params->{initial_transdate}) {
1128 my $tax_query = qq|SELECT tk.tax_id, t.rate FROM taxkeys tk
1129 LEFT JOIN tax t ON (tk.tax_id = t.id)
1130 WHERE (tk.chart_id = ?) AND (startdate <= ?)
1131 ORDER BY tk.startdate DESC
1133 ($tax_id, $rate) = selectrow_query($form, $dbh, $tax_query, $ref->{id}, $params->{initial_transdate});
1134 $params->{"taxchart_$i"} = "${tax_id}--${rate}";
1137 $params->{"AP_amount_$i"} = "$ref->{accno}--$tax_id";
1140 if ($ref->{category} eq 'L') {
1141 $params->{APselected} = $params->{AP_1} = $ref->{accno};
1144 $params->{rowcount} = $i if ($i && !$params->{type});
1149 $main::lxdebug->leave_sub();
1153 $main::lxdebug->enter_sub();
1155 my ($self, $myconfig, $form) = @_;
1157 # connect to database
1158 my $dbh = $form->dbconnect($myconfig);
1160 my $i = $form->{rowcount};
1162 # don't include assemblies or obsolete parts
1163 my $where = "NOT p.assembly = '1' AND NOT p.obsolete = '1'";
1166 foreach my $table_column (qw(p.partnumber p.description pg.partsgroup)) {
1167 my $field = (split m{\.}, $table_column)[1];
1168 next unless $form->{"${field}_${i}"};
1169 $where .= " AND lower(${table_column}) LIKE lower(?)";
1170 push @values, '%' . $form->{"${field}_${i}"} . '%';
1172 #Es soll auch nach EAN gesucht werden, ohne Einschränkung durch Beschreibung
1173 if ($form->{"partnumber_$i"} && !$form->{"description_$i"}) {
1174 $where .= qq| OR (NOT p.obsolete = '1' AND p.ean = ? )|;
1175 push @values, $form->{"partnumber_$i"};
1178 # Search for part ID overrides all other criteria.
1179 if ($form->{"id_${i}"}) {
1180 $where = qq|p.id = ?|;
1181 @values = ($form->{"id_${i}"});
1184 if ($form->{"description_$i"}) {
1185 $where .= " ORDER BY p.description";
1187 $where .= " ORDER BY p.partnumber";
1191 if ($form->{type} eq "invoice") {
1192 $transdate = $form->{invdate} ? $dbh->quote($form->{invdate}) : "current_date";
1194 $transdate = $form->{transdate} ? $dbh->quote($form->{transdate}) : "current_date";
1197 my $taxzone_id = $form->{taxzone_id} * 1;
1198 $taxzone_id = 0 if ((3 < $taxzone_id) || (0 > $taxzone_id));
1202 p.id, p.partnumber, p.description, p.lastcost AS sellprice, p.listprice,
1203 p.unit, p.assembly, p.bin, p.onhand, p.formel,
1204 p.notes AS partnotes, p.notes AS longdescription, p.not_discountable,
1205 p.inventory_accno_id, p.price_factor_id,
1207 pfac.factor AS price_factor,
1209 c1.accno AS inventory_accno,
1210 c1.new_chart_id AS inventory_new_chart,
1211 date($transdate) - c1.valid_from AS inventory_valid,
1213 c2.accno AS income_accno,
1214 c2.new_chart_id AS income_new_chart,
1215 date($transdate) - c2.valid_from AS income_valid,
1217 c3.accno AS expense_accno,
1218 c3.new_chart_id AS expense_new_chart,
1219 date($transdate) - c3.valid_from AS expense_valid,
1224 LEFT JOIN chart c1 ON
1225 ((SELECT inventory_accno_id
1226 FROM buchungsgruppen
1227 WHERE id = p.buchungsgruppen_id) = c1.id)
1228 LEFT JOIN chart c2 ON
1229 ((SELECT income_accno_id_${taxzone_id}
1230 FROM buchungsgruppen
1231 WHERE id = p.buchungsgruppen_id) = c2.id)
1232 LEFT JOIN chart c3 ON
1233 ((SELECT expense_accno_id_${taxzone_id}
1234 FROM buchungsgruppen
1235 WHERE id = p.buchungsgruppen_id) = c3.id)
1236 LEFT JOIN partsgroup pg ON (pg.id = p.partsgroup_id)
1237 LEFT JOIN price_factors pfac ON (pfac.id = p.price_factor_id)
1239 my $sth = prepare_execute_query($form, $dbh, $query, @values);
1241 my @translation_queries = ( [ qq|SELECT tr.translation, tr.longdescription
1243 WHERE tr.language_id = ? AND tr.parts_id = ?| ],
1244 [ qq|SELECT tr.translation, tr.longdescription
1246 WHERE tr.language_id IN
1249 WHERE article_code = (SELECT article_code FROM language WHERE id = ?))
1252 map { push @{ $_ }, prepare_query($form, $dbh, $_->[0]) } @translation_queries;
1254 $form->{item_list} = [];
1255 while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
1257 # In der Buchungsgruppe ist immer ein Bestandskonto verknuepft, auch wenn
1258 # es sich um eine Dienstleistung handelt. Bei Dienstleistungen muss das
1259 # Buchungskonto also aus dem Ergebnis rausgenommen werden.
1260 if (!$ref->{inventory_accno_id}) {
1261 map({ delete($ref->{"inventory_${_}"}); } qw(accno new_chart valid));
1263 delete($ref->{inventory_accno_id});
1265 # get tax rates and description
1266 my $accno_id = ($form->{vc} eq "customer") ? $ref->{income_accno} : $ref->{expense_accno};
1268 qq|SELECT c.accno, t.taxdescription, t.rate, t.taxnumber
1270 LEFT JOIN chart c on (c.id = t.chart_id)
1278 AND (startdate <= $transdate)
1279 ORDER BY startdate DESC
1282 my $stw = prepare_execute_query($form, $dbh, $query, $accno_id);
1284 $ref->{taxaccounts} = "";
1286 while (my $ptr = $stw->fetchrow_hashref("NAME_lc")) {
1288 # if ($customertax{$ref->{accno}}) {
1289 if (($ptr->{accno} eq "") && ($ptr->{rate} == 0)) {
1294 $ref->{taxaccounts} .= "$ptr->{accno} ";
1296 if (!($form->{taxaccounts} =~ /\Q$ptr->{accno}\E/)) {
1297 $form->{"$ptr->{accno}_rate"} = $ptr->{rate};
1298 $form->{"$ptr->{accno}_description"} = $ptr->{taxdescription};
1299 $form->{"$ptr->{accno}_taxnumber"} = $ptr->{taxnumber};
1300 $form->{taxaccounts} .= "$ptr->{accno} ";
1303 if ($form->{language_id}) {
1304 for my $spec (@translation_queries) {
1305 do_statement($form, $spec->[1], $spec->[0], conv_i($form->{language_id}), conv_i($ref->{id}));
1306 my ($translation, $longdescription) = $spec->[1]->fetchrow_array;
1307 next unless $translation;
1308 $ref->{description} = $translation;
1309 $ref->{longdescription} = $longdescription;
1316 chop $ref->{taxaccounts};
1318 $ref->{onhand} *= 1;
1320 push @{ $form->{item_list} }, $ref;
1325 $_->[1]->finish for @translation_queries;
1327 foreach my $item (@{ $form->{item_list} }) {
1328 my $custom_variables = CVar->get_custom_variables(module => 'IC',
1329 trans_id => $item->{id},
1333 map { $item->{"ic_cvar_" . $_->{name} } = $_->{value} } @{ $custom_variables };
1338 $main::lxdebug->leave_sub();
1341 sub vendor_details {
1342 $main::lxdebug->enter_sub();
1344 my ($self, $myconfig, $form, @wanted_vars) = @_;
1346 # connect to database
1347 my $dbh = $form->dbconnect($myconfig);
1351 # get contact id, set it if nessessary
1352 $form->{cp_id} *= 1;
1354 if ($form->{cp_id}) {
1355 $contact = "AND cp.cp_id = ?";
1356 push @values, $form->{cp_id};
1359 # get rest for the vendor
1360 # fax and phone and email as vendor*
1362 qq|SELECT ct.*, cp.*, ct.notes as vendornotes, phone as vendorphone, fax as vendorfax, email as vendoremail,
1365 LEFT JOIN contacts cp ON (ct.id = cp.cp_cv_id)
1366 WHERE (ct.id = ?) $contact
1369 my $ref = selectfirst_hashref_query($form, $dbh, $query, $form->{vendor_id}, @values);
1371 # remove id and taxincluded before copy back
1372 delete @$ref{qw(id taxincluded)};
1374 @wanted_vars = grep({ $_ } @wanted_vars);
1375 if (scalar(@wanted_vars) > 0) {
1377 map({ $h_wanted_vars{$_} = 1; } @wanted_vars);
1378 map({ delete($ref->{$_}) unless ($h_wanted_vars{$_}); } keys(%{$ref}));
1381 map { $form->{$_} = $ref->{$_} } keys %$ref;
1382 # remove any trailing whitespace
1383 $form->{currency} =~ s/\s*$// if ($form->{currency});
1385 my $custom_variables = CVar->get_custom_variables('dbh' => $dbh,
1387 'trans_id' => $form->{vendor_id});
1388 map { $form->{"vc_cvar_$_->{name}"} = $_->{value} } @{ $custom_variables };
1390 $form->{cp_greeting} = GenericTranslations->get('dbh' => $dbh,
1391 'translation_type' => 'greetings::' . ($form->{cp_gender} eq 'f' ? 'female' : 'male'),
1392 'allow_fallback' => 1);
1396 $main::lxdebug->leave_sub();
1400 $main::lxdebug->enter_sub();
1402 my ($self, $myconfig, $form) = @_;
1404 # connect to database
1405 my $dbh = $form->dbconnect($myconfig);
1408 qq|SELECT accno, description, link
1410 WHERE link LIKE '%IC%'
1412 my $sth = prepare_execute_query($query, $dbh, $query);
1414 while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
1415 foreach my $key (split(/:/, $ref->{link})) {
1417 push @{ $form->{IC_links}{$key} },
1418 { accno => $ref->{accno},
1419 description => $ref->{description} };
1427 $main::lxdebug->leave_sub();
1430 sub _delete_payments {
1431 $main::lxdebug->enter_sub();
1433 my ($self, $form, $dbh) = @_;
1435 my @delete_acc_trans_ids;
1437 # Delete old payment entries from acc_trans.
1439 qq|SELECT acc_trans_id
1441 WHERE (trans_id = ?) AND fx_transaction
1445 SELECT at.acc_trans_id
1447 LEFT JOIN chart c ON (at.chart_id = c.id)
1448 WHERE (trans_id = ?) AND (c.link LIKE '%AP_paid%')|;
1449 push @delete_acc_trans_ids, selectall_array_query($form, $dbh, $query, conv_i($form->{id}), conv_i($form->{id}));
1452 qq|SELECT at.acc_trans_id
1454 LEFT JOIN chart c ON (at.chart_id = c.id)
1455 WHERE (trans_id = ?)
1456 AND ((c.link = 'AP') OR (c.link LIKE '%:AP') OR (c.link LIKE 'AP:%'))
1457 ORDER BY at.acc_trans_id
1459 push @delete_acc_trans_ids, selectall_array_query($form, $dbh, $query, conv_i($form->{id}));
1461 if (@delete_acc_trans_ids) {
1462 $query = qq|DELETE FROM acc_trans WHERE acc_trans_id IN (| . join(", ", @delete_acc_trans_ids) . qq|)|;
1463 do_query($form, $dbh, $query);
1466 $main::lxdebug->leave_sub();
1470 $main::lxdebug->enter_sub();
1472 my ($self, $myconfig, $form, $locale) = @_;
1474 # connect to database, turn off autocommit
1475 my $dbh = $form->dbconnect_noauto($myconfig);
1477 my (%payments, $old_form, $row, $item, $query, %keep_vars);
1479 $old_form = save_form();
1481 # Delete all entries in acc_trans from prior payments.
1482 if (SL::DB::Default->get->payments_changeable != 0) {
1483 $self->_delete_payments($form, $dbh);
1486 # Save the new payments the user made before cleaning up $form.
1487 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 };
1489 # Clean up $form so that old content won't tamper the results.
1490 %keep_vars = map { $_, 1 } qw(login password id);
1491 map { delete $form->{$_} unless $keep_vars{$_} } keys %{ $form };
1493 # Retrieve the invoice from the database.
1494 $self->retrieve_invoice($myconfig, $form);
1496 # Set up the content of $form in the way that IR::post_invoice() expects.
1497 $form->{exchangerate} = $form->format_amount($myconfig, $form->{exchangerate});
1499 for $row (1 .. scalar @{ $form->{invoice_details} }) {
1500 $item = $form->{invoice_details}->[$row - 1];
1502 map { $item->{$_} = $form->format_amount($myconfig, $item->{$_}) } qw(qty sellprice);
1504 map { $form->{"${_}_${row}"} = $item->{$_} } keys %{ $item };
1507 $form->{rowcount} = scalar @{ $form->{invoice_details} };
1509 delete @{$form}{qw(invoice_details paidaccounts storno paid)};
1511 # Restore the payment options from the user input.
1512 map { $form->{$_} = $payments{$_} } keys %payments;
1514 # Get the AP accno (which is normally done by Form::create_links()).
1518 LEFT JOIN chart c ON (at.chart_id = c.id)
1519 WHERE (trans_id = ?)
1520 AND ((c.link = 'AP') OR (c.link LIKE '%:AP') OR (c.link LIKE 'AP:%'))
1521 ORDER BY at.acc_trans_id
1524 ($form->{AP}) = selectfirst_array_query($form, $dbh, $query, conv_i($form->{id}));
1526 # Post the new payments.
1527 $self->post_invoice($myconfig, $form, $dbh, 1);
1529 restore_form($old_form);
1531 my $rc = $dbh->commit();
1534 $main::lxdebug->leave_sub();
1540 $::lxdebug->enter_sub;
1542 my ($self, %params) = @_;
1544 if (!$params{vendor_id} || !$params{invdate}) {
1545 $::lxdebug->leave_sub;
1546 return $params{default};
1549 my $dbh = $::form->get_standard_dbh;
1550 my $query = qq|SELECT ?::date + pt.terms_netto
1552 LEFT JOIN payment_terms pt ON (pt.id = v.payment_id)
1555 my ($duedate) = selectfirst_array_query($::form, $dbh, $query, $params{invdate}, $params{vendor_id});
1557 $duedate ||= $params{default};
1559 $::lxdebug->leave_sub;