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 = ?),
273 (SELECT tax_id FROM taxkeys WHERE chart_id= (SELECT id FROM chart WHERE accno = ?) AND startdate <= ? ORDER BY startdate DESC LIMIT 1))|;
274 @values = ($ref->{trans_id}, $ref->{inventory_accno_id}, $linetotal, $ref->{transdate}, $ref->{inventory_accno_id}, $ref->{inventory_accno_id}, $ref->{transdate});
275 do_query($form, $dbh, $query, @values);
278 $query = qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate, taxkey, tax_id) VALUES (?, ?, ?, ?, (SELECT taxkey from tax WHERE chart_id = ?),
279 (SELECT tax_id FROM taxkeys WHERE chart_id= (SELECT id FROM chart WHERE accno = ?) AND startdate <= ? ORDER BY startdate DESC LIMIT 1))|;
280 @values = ($ref->{trans_id}, $ref->{expense_accno_id}, ($linetotal * -1), $ref->{transdate}, $ref->{expense_accno_id}, $ref->{expense_accno_id}, $ref->{transdate});
281 do_query($form, $dbh, $query, @values);
285 # update allocated for sold item
286 $form->update_balance($dbh, "invoice", "allocated", qq|id = $ref->{id}|, $qty * -1);
290 last if ($totalqty -= $qty) <= 0;
295 } else { # if ($form->{"inventory_accno_id_$i"})
296 # part doesn't have an inventory_accno_id
297 # lastcost of the part is updated at the end
299 $linetotal = $form->round_amount($form->{"sellprice_$i"} * $form->{"qty_$i"} / $price_factor, 2);
301 if ($form->{taxincluded}) {
302 $taxamount = $linetotal * ($taxrate / (1 + $taxrate));
303 $form->{"sellprice_$i"} = $form->{"sellprice_$i"} * (1 / (1 + $taxrate));
306 $taxamount = $linetotal * $taxrate;
309 $netamount += $linetotal;
311 if ($form->round_amount($taxrate, 7) == 0) {
312 if ($form->{taxincluded}) {
313 foreach $item (@taxaccounts) {
314 $taxamount = $linetotal * $form->{"${item}_rate"} / (1 + abs($form->{"${item}_rate"}));
315 $totaltax += $taxamount;
316 $form->{amount}{ $form->{id} }{$item} -= $taxamount;
319 map { $form->{amount}{ $form->{id} }{$_} -= $linetotal * $form->{"${_}_rate"} } @taxaccounts;
322 map { $form->{amount}{ $form->{id} }{$_} -= $taxamount * $form->{"${_}_rate"} / $taxrate } @taxaccounts;
325 $amount = $form->{"sellprice_$i"} * $form->{"qty_$i"} * $form->{exchangerate} / $price_factor;
326 $linetotal = $form->round_amount($form->{"sellprice_$i"} * $form->{"qty_$i"} / $price_factor, 2) * $form->{exchangerate};
327 $linetotal = $form->round_amount($linetotal, 2);
329 # this is the difference for expense
330 $expensediff += ($amount - $linetotal);
332 # add amount to expense
333 $form->{amount}{ $form->{id} }{ $form->{"expense_accno_$i"} } -= $linetotal;
335 $lastexpenseaccno = $form->{"expense_accno_$i"};
337 # adjust and round sellprice
338 $form->{"sellprice_$i"} = $form->round_amount($form->{"sellprice_$i"} * $form->{exchangerate}, $decimalplaces);
340 next if $payments_only;
343 $query = qq|UPDATE parts SET lastcost = ? WHERE id = ?|;
344 do_query($form, $dbh, $query, $form->{"sellprice_$i"} / $basefactor, conv_i($form->{"id_$i"}));
347 next if $payments_only;
349 # save detail record in invoice table
350 my ($invoice_id) = selectfirst_array_query($form, $dbh, qq|SELECT nextval('invoiceid')|);
353 qq|INSERT INTO invoice (id, trans_id, parts_id, description, longdescription, qty, base_qty,
354 sellprice, fxsellprice, discount, allocated, unit, deliverydate,
355 project_id, serialnumber, price_factor_id, price_factor, marge_price_factor)
356 VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, (SELECT factor FROM price_factors WHERE id = ?), ?)|;
357 @values = ($invoice_id, conv_i($form->{id}), conv_i($form->{"id_$i"}),
358 $form->{"description_$i"}, $form->{"longdescription_$i"}, $form->{"qty_$i"} * -1,
359 $baseqty * -1, $form->{"sellprice_$i"}, $fxsellprice, $form->{"discount_$i"}, $allocated,
360 $form->{"unit_$i"}, conv_date($form->{deliverydate}),
361 conv_i($form->{"project_id_$i"}), $form->{"serialnumber_$i"},
362 conv_i($form->{"price_factor_id_$i"}), conv_i($form->{"price_factor_id_$i"}), conv_i($form->{"marge_price_factor_$i"}));
363 do_query($form, $dbh, $query, @values);
365 CVar->save_custom_variables(module => 'IC',
366 sub_module => 'invoice',
367 trans_id => $invoice_id,
368 configs => $ic_cvar_configs,
370 name_prefix => 'ic_',
371 name_postfix => "_$i",
375 $h_item_unit->finish();
377 $project_id = conv_i($form->{"globalproject_id"});
379 $form->{datepaid} = $form->{invdate};
381 # all amounts are in natural state, netamount includes the taxes
382 # if tax is included, netamount is rounded to 2 decimal places,
386 for my $i (1 .. $form->{paidaccounts}) {
387 $form->{"paid_$i"} = $form->parse_amount($myconfig, $form->{"paid_$i"});
388 $form->{paid} += $form->{"paid_$i"};
389 $form->{datepaid} = $form->{"datepaid_$i"} if $form->{"datepaid_$i"};
392 my ($tax, $paiddiff) = (0, 0);
394 $netamount = $form->round_amount($netamount, 2);
396 # figure out rounding errors for amount paid and total amount
397 if ($form->{taxincluded}) {
399 $amount = $form->round_amount($netamount * $form->{exchangerate}, 2);
400 $paiddiff = $amount - $netamount * $form->{exchangerate};
401 $netamount = $amount;
403 foreach $item (split / /, $form->{taxaccounts}) {
404 $amount = $form->{amount}{ $form->{id} }{$item} * $form->{exchangerate};
405 $form->{amount}{ $form->{id} }{$item} = $form->round_amount($amount, 2);
407 $amount = $form->{amount}{ $form->{id} }{$item} * -1;
409 $netamount -= $amount;
412 $invoicediff += $paiddiff;
413 $expensediff += $paiddiff;
415 ######## this only applies to tax included
417 # in the sales invoice case rounding errors only have to be corrected for
418 # income accounts, it is enough to add the total rounding error to one of
419 # the income accounts, with the one assigned to the last row being used
420 # (lastinventoryaccno)
422 # in the purchase invoice case rounding errors may be split between
423 # inventory accounts and expense accounts. After rounding, an error of 1
424 # cent is introduced if the total rounding error exceeds 0.005. The total
425 # error is made up of $invoicediff and $expensediff, however, so if both
426 # values are below 0.005, but add up to a total >= 0.005, correcting
427 # lastinventoryaccno and lastexpenseaccno separately has no effect after
428 # rounding. This caused bug 1579. Therefore when the combined total exceeds
429 # 0.005, but neither do individually, the account with the larger value
430 # shall receive the total rounding error, and the next time it is rounded
431 # the 1 cent correction will be introduced.
433 $form->{amount}{ $form->{id} }{$lastinventoryaccno} -= $invoicediff if $lastinventoryaccno;
434 $form->{amount}{ $form->{id} }{$lastexpenseaccno} -= $expensediff if $lastexpenseaccno;
436 if ( (abs($expensediff)+abs($invoicediff)) >= 0.005 and abs($expensediff) < 0.005 and abs($invoicediff) < 0.005 ) {
438 # in total the rounding error adds up to 1 cent effectively, correct the
439 # larger of the two numbers
441 if ( abs($form->{amount}{ $form->{id} }{$lastinventoryaccno}) > abs($form->{amount}{ $form->{id} }{$lastexpenseaccno}) ) {
442 # $invoicediff has already been deducted, now also deduct expensediff
443 $form->{amount}{ $form->{id} }{$lastinventoryaccno} -= $expensediff;
445 # expensediff has already been deducted, now also deduct invoicediff
446 $form->{amount}{ $form->{id} }{$lastexpenseaccno} -= $invoicediff;
451 $amount = $form->round_amount($netamount * $form->{exchangerate}, 2);
452 $paiddiff = $amount - $netamount * $form->{exchangerate};
453 $netamount = $amount;
455 foreach my $item (split / /, $form->{taxaccounts}) {
456 $form->{amount}{ $form->{id} }{$item} = $form->round_amount($form->{amount}{ $form->{id} }{$item}, 2);
457 $amount = $form->round_amount( $form->{amount}{ $form->{id} }{$item} * $form->{exchangerate} * -1, 2);
458 $paiddiff += $amount - $form->{amount}{ $form->{id} }{$item} * $form->{exchangerate} * -1;
459 $form->{amount}{ $form->{id} }{$item} = $form->round_amount($amount * -1, 2);
460 $amount = $form->{amount}{ $form->{id} }{$item} * -1;
465 $form->{amount}{ $form->{id} }{ $form->{AP} } = $netamount + $tax;
468 $form->{paid} = $form->round_amount($form->{paid} * $form->{exchangerate} + $paiddiff, 2) if $form->{paid} != 0;
470 # update exchangerate
472 $form->update_exchangerate($dbh, $form->{currency}, $form->{invdate}, 0, $form->{exchangerate})
473 if ($form->{currency} ne $defaultcurrency) && !$exchangerate;
475 # record acc_trans transactions
476 foreach my $trans_id (keys %{ $form->{amount} }) {
477 foreach my $accno (keys %{ $form->{amount}{$trans_id} }) {
478 $form->{amount}{$trans_id}{$accno} = $form->round_amount($form->{amount}{$trans_id}{$accno}, 2);
481 next if $payments_only || !$form->{amount}{$trans_id}{$accno};
483 $query = qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate, taxkey, project_id, tax_id)
484 VALUES (?, (SELECT id FROM chart WHERE accno = ?), ?, ?,
485 (SELECT taxkey_id FROM chart WHERE accno = ?), ?,
486 (SELECT tax_id FROM taxkeys WHERE chart_id= (SELECT id FROM chart WHERE accno = ?) AND startdate <= ? ORDER BY startdate DESC LIMIT 1))|;
487 @values = ($trans_id, $accno, $form->{amount}{$trans_id}{$accno},
488 conv_date($form->{invdate}), $accno, $project_id, $accno, conv_date($form->{invdate}));
489 do_query($form, $dbh, $query, @values);
493 # deduct payment differences from paiddiff
494 for my $i (1 .. $form->{paidaccounts}) {
495 if ($form->{"paid_$i"} != 0) {
496 $amount = $form->round_amount($form->{"paid_$i"} * $form->{exchangerate}, 2);
497 $paiddiff -= $amount - $form->{"paid_$i"} * $form->{exchangerate};
501 # force AP entry if 0
503 $form->{amount}{ $form->{id} }{ $form->{AP} } = $form->{paid} if $form->{amount}{$form->{id}}{$form->{AP}} == 0;
505 # record payments and offsetting AP
506 for my $i (1 .. $form->{paidaccounts}) {
507 if ($form->{"acc_trans_id_$i"}
509 && (SL::DB::Default->get->payments_changeable == 0)) {
513 next if $form->{"paid_$i"} == 0;
515 my ($accno) = split /--/, $form->{"AP_paid_$i"};
516 $form->{"datepaid_$i"} = $form->{invdate} unless ($form->{"datepaid_$i"});
517 $form->{datepaid} = $form->{"datepaid_$i"};
519 $amount = $form->round_amount($form->{"paid_$i"} * $form->{exchangerate} + $paiddiff, 2) * -1;
522 if ($form->{amount}{ $form->{id} }{ $form->{AP} } != 0) {
523 $query = qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate, taxkey, project_id, tax_id)
524 VALUES (?, (SELECT id FROM chart WHERE accno = ?), ?, ?,
525 (SELECT taxkey_id FROM chart WHERE accno = ?), ?,
526 (SELECT tax_id FROM taxkeys WHERE chart_id= (SELECT id FROM chart WHERE accno = ?) AND startdate <= ? ORDER BY startdate DESC LIMIT 1))|;
527 @values = (conv_i($form->{id}), $form->{AP}, $amount,
528 $form->{"datepaid_$i"}, $form->{AP}, $project_id, $form->{AP}, conv_date($form->{"datepaid_$i"}));
529 do_query($form, $dbh, $query, @values);
533 my $gldate = (conv_date($form->{"gldate_$i"}))? conv_date($form->{"gldate_$i"}) : conv_date($form->current_date($myconfig));
536 qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate, gldate, source, memo, taxkey, project_id, tax_id)
537 VALUES (?, (SELECT id FROM chart WHERE accno = ?), ?, ?, ?, ?, ?,
538 (SELECT taxkey_id FROM chart WHERE accno = ?), ?,
539 (SELECT tax_id FROM taxkeys WHERE chart_id= (SELECT id FROM chart WHERE accno = ?) AND startdate <= ? ORDER BY startdate DESC LIMIT 1))|;
540 @values = (conv_i($form->{id}), $accno, $form->{"paid_$i"}, $form->{"datepaid_$i"},
541 $gldate, $form->{"source_$i"}, $form->{"memo_$i"}, $accno, $project_id, $accno, conv_date($form->{"datepaid_$i"}));
542 do_query($form, $dbh, $query, @values);
546 if ($form->{currency} eq $defaultcurrency) {
547 $form->{"exchangerate_$i"} = 1;
549 $exchangerate = $form->check_exchangerate($myconfig, $form->{currency}, $form->{"datepaid_$i"}, 'sell');
550 $form->{"exchangerate_$i"} = $exchangerate || $form->parse_amount($myconfig, $form->{"exchangerate_$i"});
553 # exchangerate difference
554 $form->{fx}{$accno}{ $form->{"datepaid_$i"} } += $form->{"paid_$i"} * ($form->{"exchangerate_$i"} - 1) + $paiddiff;
558 ($form->{"paid_$i"} * $form->{exchangerate}) -
559 ($form->{"paid_$i"} * $form->{"exchangerate_$i"});
561 $form->{fx}{ $form->{fxgain_accno} }{ $form->{"datepaid_$i"} } += $amount;
563 $form->{fx}{ $form->{fxloss_accno} }{ $form->{"datepaid_$i"} } += $amount;
568 # update exchange rate
569 $form->update_exchangerate($dbh, $form->{currency}, $form->{"datepaid_$i"}, 0, $form->{"exchangerate_$i"})
570 if ($form->{currency} ne $defaultcurrency) && !$exchangerate;
573 # record exchange rate differences and gains/losses
574 foreach my $accno (keys %{ $form->{fx} }) {
575 foreach my $transdate (keys %{ $form->{fx}{$accno} }) {
576 $form->{fx}{$accno}{$transdate} = $form->round_amount($form->{fx}{$accno}{$transdate}, 2);
577 next if ($form->{fx}{$accno}{$transdate} == 0);
579 $query = qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate, cleared, fx_transaction, taxkey, project_id, tax_id)
580 VALUES (?, (SELECT id FROM chart WHERE accno = ?), ?, ?, '0', '1', 0, ?,
581 (SELECT tax_id FROM taxkeys WHERE chart_id= (SELECT id FROM chart WHERE accno = ?) AND startdate <= ? ORDER BY startdate DESC LIMIT 1))|;
582 @values = (conv_i($form->{id}), $accno, $form->{fx}{$accno}{$transdate}, conv_date($transdate), $project_id, $accno, $form->{fx}{$accno}{$transdate});
583 do_query($form, $dbh, $query, @values);
587 IO->set_datepaid(table => 'ap', id => $form->{id}, dbh => $dbh);
589 if ($payments_only) {
590 $query = qq|UPDATE ap SET paid = ? WHERE id = ?|;
591 do_query($form, $dbh, $query, $form->{paid}, conv_i($form->{id}));
593 if (!$provided_dbh) {
598 $main::lxdebug->leave_sub();
602 $amount = $netamount + $tax;
604 # set values which could be empty
605 my $taxzone_id = $form->{taxzone_id} * 1;
607 # Seit neuestem wird die department_id schon übergeben UND $form->department nicht mehr
608 # korrekt zusammengebaut. Sehr wahrscheinlich beim Umstieg auf T8 kaputt gegangen
609 # Ich lass den Code von 2005 erstmal noch stehen ;-) jb 03-2011
610 # copy & paste von IS.pm
611 if (!$form->{department_id}){
612 $form->{department_id} = (split /--/, $form->{department})[1];
614 $form->{invnumber} = $form->{id} unless $form->{invnumber};
616 $taxzone_id = 0 if (3 < $taxzone_id) || (0 > $taxzone_id);
619 $query = qq|UPDATE ap SET
620 invnumber = ?, ordnumber = ?, quonumber = ?, transdate = ?,
621 orddate = ?, quodate = ?, vendor_id = ?, amount = ?,
622 netamount = ?, paid = ?, duedate = ?,
623 invoice = ?, taxzone_id = ?, notes = ?, taxincluded = ?,
624 intnotes = ?, curr = ?, storno_id = ?, storno = ?,
625 cp_id = ?, employee_id = ?, department_id = ?,
629 $form->{invnumber}, $form->{ordnumber}, $form->{quonumber}, conv_date($form->{invdate}),
630 conv_date($form->{orddate}), conv_date($form->{quodate}), conv_i($form->{vendor_id}), $amount,
631 $netamount, $form->{paid}, conv_date($form->{duedate}),
632 '1', $taxzone_id, $form->{notes}, $form->{taxincluded} ? 't' : 'f',
633 $form->{intnotes}, $form->{currency}, conv_i($form->{storno_id}), $form->{storno} ? 't' : 'f',
634 conv_i($form->{cp_id}), conv_i($form->{employee_id}), conv_i($form->{department_id}),
635 conv_i($form->{globalproject_id}),
638 do_query($form, $dbh, $query, @values);
640 if ($form->{storno}) {
641 $query = qq|UPDATE ap SET paid = paid + amount WHERE id = ?|;
642 do_query($form, $dbh, $query, conv_i($form->{storno_id}));
644 $query = qq|UPDATE ap SET storno = 't' WHERE id = ?|;
645 do_query($form, $dbh, $query, conv_i($form->{storno_id}));
647 $query = qq!UPDATE ap SET intnotes = ? || intnotes WHERE id = ?!;
648 do_query($form, $dbh, $query, "Rechnung storniert am $form->{invdate} ", conv_i($form->{storno_id}));
650 $query = qq|UPDATE ap SET paid = amount WHERE id = ?|;
651 do_query($form, $dbh, $query, conv_i($form->{id}));
656 $form->{name} = $form->{vendor};
657 $form->{name} =~ s/--\Q$form->{vendor_id}\E//;
658 $form->add_shipto($dbh, $form->{id}, "AP");
660 # delete zero entries
661 do_query($form, $dbh, qq|DELETE FROM acc_trans WHERE amount = 0|);
663 Common::webdav_folder($form);
665 # Link this record to the records it was created from.
666 RecordLinks->create_links('dbh' => $dbh,
668 'from_table' => 'oe',
669 'from_ids' => $form->{convert_from_oe_ids},
671 'to_id' => $form->{id},
673 delete $form->{convert_from_oe_ids};
675 my @convert_from_do_ids = map { $_ * 1 } grep { $_ } split m/\s+/, $form->{convert_from_do_ids};
676 if (scalar @convert_from_do_ids) {
677 DO->close_orders('dbh' => $dbh,
678 'ids' => \@convert_from_do_ids);
680 RecordLinks->create_links('dbh' => $dbh,
682 'from_table' => 'delivery_orders',
683 'from_ids' => \@convert_from_do_ids,
685 'to_id' => $form->{id},
688 delete $form->{convert_from_do_ids};
690 ARAP->close_orders_if_billed('dbh' => $dbh,
691 'arap_id' => $form->{id},
694 # safety check datev export
695 if ($::instance_conf->get_datev_check_on_purchase_invoice) {
696 my $transdate = $::form->{invdate} ? DateTime->from_lxoffice($::form->{invdate}) : undef;
697 $transdate ||= DateTime->today;
699 my $datev = SL::DATEV->new(
700 exporttype => DATEV_ET_BUCHUNGEN,
701 format => DATEV_FORMAT_KNE,
709 if ($datev->errors) {
711 die join "\n", $::locale->text('DATEV check returned errors:'), $datev->errors;
716 if (!$provided_dbh) {
717 $rc = $dbh->commit();
721 $main::lxdebug->leave_sub();
726 sub reverse_invoice {
727 $main::lxdebug->enter_sub();
729 my ($dbh, $form) = @_;
731 # reverse inventory items
733 qq|SELECT i.parts_id, p.inventory_accno_id, p.expense_accno_id, i.qty, i.allocated, i.sellprice
734 FROM invoice i, parts p
735 WHERE (i.parts_id = p.id)
736 AND (i.trans_id = ?)|;
737 my $sth = prepare_execute_query($form, $dbh, $query, conv_i($form->{id}));
741 while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
742 $netamount += $form->round_amount($ref->{sellprice} * $ref->{qty} * -1, 2);
744 next unless $ref->{inventory_accno_id};
746 # if $ref->{allocated} > 0 than we sold that many items
747 next if ($ref->{allocated} <= 0);
749 # get references for sold items
751 qq|SELECT i.id, i.trans_id, i.allocated, a.transdate
753 WHERE (i.parts_id = ?)
754 AND (i.allocated < 0)
755 AND (i.trans_id = a.id)
756 ORDER BY transdate DESC|;
757 my $sth2 = prepare_execute_query($form, $dbh, $query, $ref->{parts_id});
759 while (my $pthref = $sth2->fetchrow_hashref("NAME_lc")) {
760 my $qty = $ref->{allocated};
761 if (($ref->{allocated} + $pthref->{allocated}) > 0) {
762 $qty = $pthref->{allocated} * -1;
765 my $amount = $form->round_amount($ref->{sellprice} * $qty, 2);
768 $form->update_balance($dbh, "invoice", "allocated", qq|id = $pthref->{id}|, $qty);
770 $form->update_balance($dbh, "acc_trans", "amount",
771 qq| (trans_id = $pthref->{trans_id})
772 AND (chart_id = $ref->{expense_accno_id})
773 AND (transdate = '$pthref->{transdate}')|,
776 $form->update_balance($dbh, "acc_trans", "amount",
777 qq| (trans_id = $pthref->{trans_id})
778 AND (chart_id = $ref->{inventory_accno_id})
779 AND (transdate = '$pthref->{transdate}')|,
782 last if (($ref->{allocated} -= $qty) <= 0);
788 my $id = conv_i($form->{id});
791 $query = qq|DELETE FROM acc_trans WHERE trans_id = ?|;
792 do_query($form, $dbh, $query, $id);
794 # delete invoice entries
795 $query = qq|DELETE FROM invoice WHERE trans_id = ?|;
796 do_query($form, $dbh, $query, $id);
798 $query = qq|DELETE FROM shipto WHERE (trans_id = ?) AND (module = 'AP')|;
799 do_query($form, $dbh, $query, $id);
801 $main::lxdebug->leave_sub();
805 $main::lxdebug->enter_sub();
807 my ($self, $myconfig, $form) = @_;
809 # connect to database
810 my $dbh = $form->dbconnect_noauto($myconfig);
812 &reverse_invoice($dbh, $form);
814 # delete zero entries
815 $query = qq|DELETE FROM acc_trans WHERE amount = 0|;
816 do_query($form, $dbh, $query);
819 $query = qq|DELETE FROM ap WHERE id = ?|;
820 do_query($form, $dbh, $query, conv_i($form->{id}));
822 my $rc = $dbh->commit;
825 $main::lxdebug->leave_sub();
830 sub retrieve_invoice {
831 $main::lxdebug->enter_sub();
833 my ($self, $myconfig, $form) = @_;
835 # connect to database
836 my $dbh = $form->dbconnect($myconfig);
838 my ($query, $sth, $ref, $q_invdate);
841 $q_invdate = qq|, COALESCE((SELECT transdate FROM ar WHERE id = (SELECT MAX(id) FROM ar)), current_date) AS invdate|;
842 if ($form->{vendor_id}) {
843 my $vendor_id = $dbh->quote($form->{vendor_id} * 1);
845 qq|, COALESCE((SELECT transdate FROM ar WHERE id = (SELECT MAX(id) FROM ar)), current_date) +
846 COALESCE((SELECT pt.terms_netto
848 LEFT JOIN payment_terms pt ON (v.payment_id = pt.id)
849 WHERE v.id = $vendor_id),
854 # get default accounts and last invoice number
857 (SELECT c.accno FROM chart c WHERE d.inventory_accno_id = c.id) AS inventory_accno,
858 (SELECT c.accno FROM chart c WHERE d.income_accno_id = c.id) AS income_accno,
859 (SELECT c.accno FROM chart c WHERE d.expense_accno_id = c.id) AS expense_accno,
860 (SELECT c.accno FROM chart c WHERE d.fxgain_accno_id = c.id) AS fxgain_accno,
861 (SELECT c.accno FROM chart c WHERE d.fxloss_accno_id = c.id) AS fxloss_accno,
865 $ref = selectfirst_hashref_query($form, $dbh, $query);
866 map { $form->{$_} = $ref->{$_} } keys %$ref;
870 $main::lxdebug->leave_sub();
876 $query = qq|SELECT cp_id, invnumber, transdate AS invdate, duedate,
877 orddate, quodate, globalproject_id,
878 ordnumber, quonumber, paid, taxincluded, notes, taxzone_id, storno, gldate,
879 intnotes, curr AS currency
882 $ref = selectfirst_hashref_query($form, $dbh, $query, conv_i($form->{id}));
883 map { $form->{$_} = $ref->{$_} } keys %$ref;
885 # remove any trailing whitespace
886 $form->{currency} =~ s/\s*$//;
888 $form->{exchangerate} = $form->get_exchangerate($dbh, $form->{currency}, $form->{invdate}, "sell");
891 $query = qq|SELECT * FROM shipto WHERE (trans_id = ?) AND (module = 'AP')|;
892 $ref = selectfirst_hashref_query($form, $dbh, $query, conv_i($form->{id}));
894 map { $form->{$_} = $ref->{$_} } keys %$ref;
896 my $transdate = $form->{invdate} ? $dbh->quote($form->{invdate}) : "current_date";
897 my $taxzone_id = $form->{taxzone_id} * 1;
899 $taxzone_id = 0 if ((3 < $taxzone_id) || (0 > $taxzone_id));
901 # retrieve individual items
904 c1.accno AS inventory_accno, c1.new_chart_id AS inventory_new_chart, date($transdate) - c1.valid_from AS inventory_valid,
905 c2.accno AS income_accno, c2.new_chart_id AS income_new_chart, date($transdate) - c2.valid_from AS income_valid,
906 c3.accno AS expense_accno, c3.new_chart_id AS expense_new_chart, date($transdate) - c3.valid_from AS expense_valid,
909 i.description, i.longdescription, i.qty, i.fxsellprice AS sellprice, i.parts_id AS id, i.unit, i.deliverydate, i.project_id, i.serialnumber,
910 i.price_factor_id, i.price_factor, i.marge_price_factor, i.discount,
911 p.partnumber, p.inventory_accno_id AS part_inventory_accno_id, p.bin, pr.projectnumber, pg.partsgroup
914 JOIN parts p ON (i.parts_id = p.id)
915 LEFT JOIN chart c1 ON ((SELECT inventory_accno_id FROM buchungsgruppen WHERE id = p.buchungsgruppen_id) = c1.id)
916 LEFT JOIN chart c2 ON ((SELECT income_accno_id_${taxzone_id} FROM buchungsgruppen WHERE id = p.buchungsgruppen_id) = c2.id)
917 LEFT JOIN chart c3 ON ((SELECT expense_accno_id_${taxzone_id} FROM buchungsgruppen WHERE id = p.buchungsgruppen_id) = c3.id)
918 LEFT JOIN project pr ON (i.project_id = pr.id)
919 LEFT JOIN partsgroup pg ON (pg.id = p.partsgroup_id)
924 $sth = prepare_execute_query($form, $dbh, $query, conv_i($form->{id}));
926 while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
927 # Retrieve custom variables.
928 my $cvars = CVar->get_custom_variables(dbh => $dbh,
930 sub_module => 'invoice',
931 trans_id => $ref->{invoice_id},
933 map { $ref->{"ic_cvar_$_->{name}"} = $_->{value} } @{ $cvars };
934 delete $ref->{invoice_id};
936 map({ delete($ref->{$_}); } qw(inventory_accno inventory_new_chart inventory_valid)) if !$ref->{"part_inventory_accno_id"};
937 delete($ref->{"part_inventory_accno_id"});
939 foreach my $type (qw(inventory income expense)) {
940 while ($ref->{"${type}_new_chart"} && ($ref->{"${type}_valid"} >=0)) {
941 my $query = qq|SELECT accno, new_chart_id, date($transdate) - valid_from FROM chart WHERE id = ?|;
942 @$ref{ map $type.$_, qw(_accno _new_chart _valid) } = selectrow_query($form, $dbh, $query, $ref->{"${type}_new_chart"});
946 # get tax rates and description
947 my $accno_id = ($form->{vc} eq "customer") ? $ref->{income_accno} : $ref->{expense_accno};
949 qq|SELECT c.accno, t.taxdescription, t.rate, t.taxnumber FROM tax t
950 LEFT JOIN chart c ON (c.id = t.chart_id)
952 (SELECT tk.tax_id FROM taxkeys tk
953 WHERE tk.chart_id = (SELECT id FROM chart WHERE accno = ?)
954 AND (startdate <= $transdate)
955 ORDER BY startdate DESC
958 my $stw = prepare_execute_query($form, $dbh, $query, $accno_id);
959 $ref->{taxaccounts} = "";
962 while (my $ptr = $stw->fetchrow_hashref("NAME_lc")) {
963 if (($ptr->{accno} eq "") && ($ptr->{rate} == 0)) {
968 $ref->{taxaccounts} .= "$ptr->{accno} ";
970 if (!($form->{taxaccounts} =~ /\Q$ptr->{accno}\E/)) {
971 $form->{"$ptr->{accno}_rate"} = $ptr->{rate};
972 $form->{"$ptr->{accno}_description"} = $ptr->{taxdescription};
973 $form->{"$ptr->{accno}_taxnumber"} = $ptr->{taxnumber};
974 $form->{taxaccounts} .= "$ptr->{accno} ";
979 chop $ref->{taxaccounts};
980 push @{ $form->{invoice_details} }, $ref;
985 Common::webdav_folder($form);
989 $main::lxdebug->leave_sub();
993 $main::lxdebug->enter_sub();
995 my ($self, $myconfig, $form, $params) = @_;
997 $params = $form unless defined $params && ref $params eq "HASH";
999 # connect to database
1000 my $dbh = $form->dbconnect($myconfig);
1002 my $dateformat = $myconfig->{dateformat};
1003 $dateformat .= "yy" if $myconfig->{dateformat} !~ /^y/;
1005 my $vid = conv_i($params->{vendor_id});
1006 my $vnr = conv_i($params->{vendornumber});
1009 ($params->{invdate})
1010 ? "to_date(" . $dbh->quote($params->{invdate}) . ", '$dateformat')"
1017 $where .= 'AND v.id = ?';
1021 $where .= 'AND v.vendornumber = ?';
1026 v.id AS vendor_id, v.name AS vendor, v.discount as vendor_discount,
1027 v.creditlimit, v.terms, v.notes AS intnotes,
1028 v.email, v.cc, v.bcc, v.language_id, v.payment_id,
1029 v.street, v.zipcode, v.city, v.country, v.taxzone_id, v.curr,
1030 $duedate + COALESCE(pt.terms_netto, 0) AS duedate,
1031 b.description AS business
1033 LEFT JOIN business b ON (b.id = v.business_id)
1034 LEFT JOIN payment_terms pt ON (v.payment_id = pt.id)
1036 my $ref = selectfirst_hashref_query($form, $dbh, $query, @values);
1037 map { $params->{$_} = $ref->{$_} } keys %$ref;
1039 # remove any trailing whitespace
1040 $form->{curr} =~ s/\s*$//;
1042 # use vendor currency if not empty
1043 $form->{currency} = $form->{curr} if $form->{curr};
1045 $params->{creditremaining} = $params->{creditlimit};
1047 $query = qq|SELECT SUM(amount - paid) FROM ap WHERE vendor_id = ?|;
1048 my ($unpaid_invoices) = selectfirst_array_query($form, $dbh, $query, $vid);
1049 $params->{creditremaining} -= $unpaid_invoices;
1051 $query = qq|SELECT o.amount,
1054 WHERE (e.curr = o.curr)
1055 AND (e.transdate = o.transdate)) AS exch
1057 WHERE (o.vendor_id = ?) AND (o.quotation = '0') AND (o.closed = '0')|;
1058 my $sth = prepare_execute_query($form, $dbh, $query, $vid);
1059 while (my ($amount, $exch) = $sth->fetchrow_array()) {
1060 $exch = 1 unless $exch;
1061 $params->{creditremaining} -= $amount * $exch;
1065 # get shipto if we do not convert an order or invoice
1066 if (!$params->{shipto}) {
1067 delete @{$params}{qw(shiptoname shiptostreet shiptozipcode shiptocity shiptocountry shiptocontact shiptophone shiptofax shiptoemail)};
1069 $query = qq|SELECT * FROM shipto WHERE (trans_id = ?) AND (module= 'CT')|;
1070 $ref = selectfirst_hashref_query($form, $dbh, $query, $vid);
1071 @{$params}{keys %$ref} = @{$ref}{keys %$ref};
1072 map { $params->{$_} = $ref->{$_} } keys %$ref;
1075 if (!$params->{id} && $params->{type} !~ /_(order|quotation)/) {
1076 # setup last accounts used
1078 qq|SELECT c.id, c.accno, c.description, c.link, c.category
1080 JOIN acc_trans ac ON (ac.chart_id = c.id)
1081 JOIN ap a ON (a.id = ac.trans_id)
1082 WHERE (a.vendor_id = ?)
1083 AND (NOT ((c.link LIKE '%_tax%') OR (c.link LIKE '%_paid%')))
1084 AND (a.id IN (SELECT max(a2.id) FROM ap a2 WHERE a2.vendor_id = ?))|;
1085 my $refs = selectall_hashref_query($form, $dbh, $query, $vid, $vid);
1089 if ($ref->{category} eq 'E') {
1091 my ($tax_id, $rate);
1092 if ($params->{initial_transdate}) {
1093 my $tax_query = qq|SELECT tk.tax_id, t.rate FROM taxkeys tk
1094 LEFT JOIN tax t ON (tk.tax_id = t.id)
1095 WHERE (tk.chart_id = ?) AND (startdate <= ?)
1096 ORDER BY tk.startdate DESC
1098 ($tax_id, $rate) = selectrow_query($form, $dbh, $tax_query, $ref->{id}, $params->{initial_transdate});
1099 $params->{"taxchart_$i"} = "${tax_id}--${rate}";
1102 $params->{"AP_amount_$i"} = "$ref->{accno}--$tax_id";
1105 if ($ref->{category} eq 'L') {
1106 $params->{APselected} = $params->{AP_1} = $ref->{accno};
1109 $params->{rowcount} = $i if ($i && !$params->{type});
1114 $main::lxdebug->leave_sub();
1118 $main::lxdebug->enter_sub();
1120 my ($self, $myconfig, $form) = @_;
1122 # connect to database
1123 my $dbh = $form->dbconnect($myconfig);
1125 my $i = $form->{rowcount};
1127 # don't include assemblies or obsolete parts
1128 my $where = "NOT p.assembly = '1' AND NOT p.obsolete = '1'";
1131 foreach my $table_column (qw(p.partnumber p.description pg.partsgroup)) {
1132 my $field = (split m{\.}, $table_column)[1];
1133 next unless $form->{"${field}_${i}"};
1134 $where .= " AND lower(${table_column}) LIKE lower(?)";
1135 push @values, '%' . $form->{"${field}_${i}"} . '%';
1137 #Es soll auch nach EAN gesucht werden, ohne Einschränkung durch Beschreibung
1138 if ($form->{"partnumber_$i"} && !$form->{"description_$i"}) {
1139 $where .= qq| OR (NOT p.obsolete = '1' AND p.ean = ? )|;
1140 push @values, $form->{"partnumber_$i"};
1143 # Search for part ID overrides all other criteria.
1144 if ($form->{"id_${i}"}) {
1145 $where = qq|p.id = ?|;
1146 @values = ($form->{"id_${i}"});
1149 if ($form->{"description_$i"}) {
1150 $where .= " ORDER BY p.description";
1152 $where .= " ORDER BY p.partnumber";
1156 if ($form->{type} eq "invoice") {
1157 $transdate = $form->{invdate} ? $dbh->quote($form->{invdate}) : "current_date";
1159 $transdate = $form->{transdate} ? $dbh->quote($form->{transdate}) : "current_date";
1162 my $taxzone_id = $form->{taxzone_id} * 1;
1163 $taxzone_id = 0 if ((3 < $taxzone_id) || (0 > $taxzone_id));
1167 p.id, p.partnumber, p.description, p.lastcost AS sellprice, p.listprice,
1168 p.unit, p.assembly, p.bin, p.onhand, p.formel,
1169 p.notes AS partnotes, p.notes AS longdescription, p.not_discountable,
1170 p.inventory_accno_id, p.price_factor_id,
1172 pfac.factor AS price_factor,
1174 c1.accno AS inventory_accno,
1175 c1.new_chart_id AS inventory_new_chart,
1176 date($transdate) - c1.valid_from AS inventory_valid,
1178 c2.accno AS income_accno,
1179 c2.new_chart_id AS income_new_chart,
1180 date($transdate) - c2.valid_from AS income_valid,
1182 c3.accno AS expense_accno,
1183 c3.new_chart_id AS expense_new_chart,
1184 date($transdate) - c3.valid_from AS expense_valid,
1189 LEFT JOIN chart c1 ON
1190 ((SELECT inventory_accno_id
1191 FROM buchungsgruppen
1192 WHERE id = p.buchungsgruppen_id) = c1.id)
1193 LEFT JOIN chart c2 ON
1194 ((SELECT income_accno_id_${taxzone_id}
1195 FROM buchungsgruppen
1196 WHERE id = p.buchungsgruppen_id) = c2.id)
1197 LEFT JOIN chart c3 ON
1198 ((SELECT expense_accno_id_${taxzone_id}
1199 FROM buchungsgruppen
1200 WHERE id = p.buchungsgruppen_id) = c3.id)
1201 LEFT JOIN partsgroup pg ON (pg.id = p.partsgroup_id)
1202 LEFT JOIN price_factors pfac ON (pfac.id = p.price_factor_id)
1204 my $sth = prepare_execute_query($form, $dbh, $query, @values);
1206 my @translation_queries = ( [ qq|SELECT tr.translation, tr.longdescription
1208 WHERE tr.language_id = ? AND tr.parts_id = ?| ],
1209 [ qq|SELECT tr.translation, tr.longdescription
1211 WHERE tr.language_id IN
1214 WHERE article_code = (SELECT article_code FROM language WHERE id = ?))
1217 map { push @{ $_ }, prepare_query($form, $dbh, $_->[0]) } @translation_queries;
1219 $form->{item_list} = [];
1220 while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
1222 # In der Buchungsgruppe ist immer ein Bestandskonto verknuepft, auch wenn
1223 # es sich um eine Dienstleistung handelt. Bei Dienstleistungen muss das
1224 # Buchungskonto also aus dem Ergebnis rausgenommen werden.
1225 if (!$ref->{inventory_accno_id}) {
1226 map({ delete($ref->{"inventory_${_}"}); } qw(accno new_chart valid));
1228 delete($ref->{inventory_accno_id});
1230 # get tax rates and description
1231 my $accno_id = ($form->{vc} eq "customer") ? $ref->{income_accno} : $ref->{expense_accno};
1233 qq|SELECT c.accno, t.taxdescription, t.rate, t.taxnumber
1235 LEFT JOIN chart c on (c.id = t.chart_id)
1243 AND (startdate <= $transdate)
1244 ORDER BY startdate DESC
1247 my $stw = prepare_execute_query($form, $dbh, $query, $accno_id);
1249 $ref->{taxaccounts} = "";
1251 while (my $ptr = $stw->fetchrow_hashref("NAME_lc")) {
1253 # if ($customertax{$ref->{accno}}) {
1254 if (($ptr->{accno} eq "") && ($ptr->{rate} == 0)) {
1259 $ref->{taxaccounts} .= "$ptr->{accno} ";
1261 if (!($form->{taxaccounts} =~ /\Q$ptr->{accno}\E/)) {
1262 $form->{"$ptr->{accno}_rate"} = $ptr->{rate};
1263 $form->{"$ptr->{accno}_description"} = $ptr->{taxdescription};
1264 $form->{"$ptr->{accno}_taxnumber"} = $ptr->{taxnumber};
1265 $form->{taxaccounts} .= "$ptr->{accno} ";
1268 if ($form->{language_id}) {
1269 for my $spec (@translation_queries) {
1270 do_statement($form, $spec->[1], $spec->[0], conv_i($form->{language_id}), conv_i($ref->{id}));
1271 my ($translation, $longdescription) = $spec->[1]->fetchrow_array;
1272 next unless $translation;
1273 $ref->{description} = $translation;
1274 $ref->{longdescription} = $longdescription;
1281 chop $ref->{taxaccounts};
1283 $ref->{onhand} *= 1;
1285 push @{ $form->{item_list} }, $ref;
1290 $_->[1]->finish for @translation_queries;
1292 foreach my $item (@{ $form->{item_list} }) {
1293 my $custom_variables = CVar->get_custom_variables(module => 'IC',
1294 trans_id => $item->{id},
1298 map { $item->{"ic_cvar_" . $_->{name} } = $_->{value} } @{ $custom_variables };
1303 $main::lxdebug->leave_sub();
1306 sub vendor_details {
1307 $main::lxdebug->enter_sub();
1309 my ($self, $myconfig, $form, @wanted_vars) = @_;
1311 # connect to database
1312 my $dbh = $form->dbconnect($myconfig);
1316 # get contact id, set it if nessessary
1317 $form->{cp_id} *= 1;
1319 if ($form->{cp_id}) {
1320 $contact = "AND cp.cp_id = ?";
1321 push @values, $form->{cp_id};
1324 # get rest for the vendor
1325 # fax and phone and email as vendor*
1327 qq|SELECT ct.*, cp.*, ct.notes as vendornotes, phone as vendorphone, fax as vendorfax, email as vendoremail,
1330 LEFT JOIN contacts cp ON (ct.id = cp.cp_cv_id)
1331 WHERE (ct.id = ?) $contact
1334 my $ref = selectfirst_hashref_query($form, $dbh, $query, $form->{vendor_id}, @values);
1336 # remove id and taxincluded before copy back
1337 delete @$ref{qw(id taxincluded)};
1339 @wanted_vars = grep({ $_ } @wanted_vars);
1340 if (scalar(@wanted_vars) > 0) {
1342 map({ $h_wanted_vars{$_} = 1; } @wanted_vars);
1343 map({ delete($ref->{$_}) unless ($h_wanted_vars{$_}); } keys(%{$ref}));
1346 map { $form->{$_} = $ref->{$_} } keys %$ref;
1347 # remove any trailing whitespace
1348 $form->{currency} =~ s/\s*$// if ($form->{currency});
1350 my $custom_variables = CVar->get_custom_variables('dbh' => $dbh,
1352 'trans_id' => $form->{vendor_id});
1353 map { $form->{"vc_cvar_$_->{name}"} = $_->{value} } @{ $custom_variables };
1355 $form->{cp_greeting} = GenericTranslations->get('dbh' => $dbh,
1356 'translation_type' => 'greetings::' . ($form->{cp_gender} eq 'f' ? 'female' : 'male'),
1357 'allow_fallback' => 1);
1361 $main::lxdebug->leave_sub();
1365 $main::lxdebug->enter_sub();
1367 my ($self, $myconfig, $form) = @_;
1369 # connect to database
1370 my $dbh = $form->dbconnect($myconfig);
1373 qq|SELECT accno, description, link
1375 WHERE link LIKE '%IC%'
1377 my $sth = prepare_execute_query($query, $dbh, $query);
1379 while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
1380 foreach my $key (split(/:/, $ref->{link})) {
1382 push @{ $form->{IC_links}{$key} },
1383 { accno => $ref->{accno},
1384 description => $ref->{description} };
1392 $main::lxdebug->leave_sub();
1395 sub _delete_payments {
1396 $main::lxdebug->enter_sub();
1398 my ($self, $form, $dbh) = @_;
1400 my @delete_acc_trans_ids;
1402 # Delete old payment entries from acc_trans.
1404 qq|SELECT acc_trans_id
1406 WHERE (trans_id = ?) AND fx_transaction
1410 SELECT at.acc_trans_id
1412 LEFT JOIN chart c ON (at.chart_id = c.id)
1413 WHERE (trans_id = ?) AND (c.link LIKE '%AP_paid%')|;
1414 push @delete_acc_trans_ids, selectall_array_query($form, $dbh, $query, conv_i($form->{id}), conv_i($form->{id}));
1417 qq|SELECT at.acc_trans_id
1419 LEFT JOIN chart c ON (at.chart_id = c.id)
1420 WHERE (trans_id = ?)
1421 AND ((c.link = 'AP') OR (c.link LIKE '%:AP') OR (c.link LIKE 'AP:%'))
1422 ORDER BY at.acc_trans_id
1424 push @delete_acc_trans_ids, selectall_array_query($form, $dbh, $query, conv_i($form->{id}));
1426 if (@delete_acc_trans_ids) {
1427 $query = qq|DELETE FROM acc_trans WHERE acc_trans_id IN (| . join(", ", @delete_acc_trans_ids) . qq|)|;
1428 do_query($form, $dbh, $query);
1431 $main::lxdebug->leave_sub();
1435 $main::lxdebug->enter_sub();
1437 my ($self, $myconfig, $form, $locale) = @_;
1439 # connect to database, turn off autocommit
1440 my $dbh = $form->dbconnect_noauto($myconfig);
1442 my (%payments, $old_form, $row, $item, $query, %keep_vars);
1444 $old_form = save_form();
1446 # Delete all entries in acc_trans from prior payments.
1447 if (SL::DB::Default->get->payments_changeable != 0) {
1448 $self->_delete_payments($form, $dbh);
1451 # Save the new payments the user made before cleaning up $form.
1452 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 };
1454 # Clean up $form so that old content won't tamper the results.
1455 %keep_vars = map { $_, 1 } qw(login password id);
1456 map { delete $form->{$_} unless $keep_vars{$_} } keys %{ $form };
1458 # Retrieve the invoice from the database.
1459 $self->retrieve_invoice($myconfig, $form);
1461 # Set up the content of $form in the way that IR::post_invoice() expects.
1462 $form->{exchangerate} = $form->format_amount($myconfig, $form->{exchangerate});
1464 for $row (1 .. scalar @{ $form->{invoice_details} }) {
1465 $item = $form->{invoice_details}->[$row - 1];
1467 map { $item->{$_} = $form->format_amount($myconfig, $item->{$_}) } qw(qty sellprice);
1469 map { $form->{"${_}_${row}"} = $item->{$_} } keys %{ $item };
1472 $form->{rowcount} = scalar @{ $form->{invoice_details} };
1474 delete @{$form}{qw(invoice_details paidaccounts storno paid)};
1476 # Restore the payment options from the user input.
1477 map { $form->{$_} = $payments{$_} } keys %payments;
1479 # Get the AP accno (which is normally done by Form::create_links()).
1483 LEFT JOIN chart c ON (at.chart_id = c.id)
1484 WHERE (trans_id = ?)
1485 AND ((c.link = 'AP') OR (c.link LIKE '%:AP') OR (c.link LIKE 'AP:%'))
1486 ORDER BY at.acc_trans_id
1489 ($form->{AP}) = selectfirst_array_query($form, $dbh, $query, conv_i($form->{id}));
1491 # Post the new payments.
1492 $self->post_invoice($myconfig, $form, $dbh, 1);
1494 restore_form($old_form);
1496 my $rc = $dbh->commit();
1499 $main::lxdebug->leave_sub();
1505 $::lxdebug->enter_sub;
1507 my ($self, %params) = @_;
1509 if (!$params{vendor_id} || !$params{invdate}) {
1510 $::lxdebug->leave_sub;
1511 return $params{default};
1514 my $dbh = $::form->get_standard_dbh;
1515 my $query = qq|SELECT ?::date + pt.terms_netto
1517 LEFT JOIN payment_terms pt ON (pt.id = v.payment_id)
1520 my ($duedate) = selectfirst_array_query($::form, $dbh, $query, $params{invdate}, $params{vendor_id});
1522 $duedate ||= $params{default};
1524 $::lxdebug->leave_sub;