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;
45 use SL::HTML::Restrict;
49 use List::Util qw(min);
54 $main::lxdebug->enter_sub();
56 my ($self, $myconfig, $form, $provided_dbh, $payments_only) = @_;
58 # connect to database, turn off autocommit
59 my $dbh = $provided_dbh ? $provided_dbh : $form->dbconnect_noauto($myconfig);
60 my $restricter = SL::HTML::Restrict->create;
62 $form->{defaultcurrency} = $form->get_default_currency($myconfig);
63 my $defaultcurrency = $form->{defaultcurrency};
65 my $ic_cvar_configs = CVar->get_configs(module => 'IC',
68 my ($query, $sth, @values, $project_id);
69 my ($allocated, $taxrate, $taxamount, $taxdiff, $item);
70 my ($amount, $linetotal, $lastinventoryaccno, $lastexpenseaccno);
71 my ($netamount, $invoicediff, $expensediff) = (0, 0, 0);
73 my ($basefactor, $baseqty, @taxaccounts, $totaltax);
75 my $all_units = AM->retrieve_units($myconfig, $form);
78 if (!$payments_only) {
80 &reverse_invoice($dbh, $form);
82 ($form->{id}) = selectrow_query($form, $dbh, qq|SELECT nextval('glid')|);
83 do_query($form, $dbh, qq|INSERT INTO ap (id, invnumber, currency_id) VALUES (?, '', (SELECT id FROM currencies WHERE name=?))|, $form->{id}, $form->{currency});
87 if ($form->{currency} eq $defaultcurrency) {
88 $form->{exchangerate} = 1;
90 $exchangerate = $form->check_exchangerate($myconfig, $form->{currency}, $form->{invdate}, 'sell');
93 $form->{exchangerate} = $exchangerate || $form->parse_amount($myconfig, $form->{exchangerate});
94 $form->{exchangerate} = 1 unless ($form->{exchangerate} * 1);
97 my $q_item_unit = qq|SELECT unit FROM parts WHERE id = ?|;
98 my $h_item_unit = prepare_query($form, $dbh, $q_item_unit);
100 $form->get_lists('price_factors' => 'ALL_PRICE_FACTORS');
101 my %price_factors = map { $_->{id} => $_->{factor} } @{ $form->{ALL_PRICE_FACTORS} };
104 for my $i (1 .. $form->{rowcount}) {
105 next unless $form->{"id_$i"};
107 $form->{"qty_$i"} = $form->parse_amount($myconfig, $form->{"qty_$i"});
108 $form->{"qty_$i"} *= -1 if $form->{storno};
110 if ( $::instance_conf->get_inventory_system eq 'periodic') {
111 # inventory account number is overwritten with expense account number, so
112 # never book incoming to inventory account but always to expense account
113 $form->{"inventory_accno_$i"} = $form->{"expense_accno_$i"}
117 if (!$item_units{$form->{"id_$i"}}) {
118 do_statement($form, $h_item_unit, $q_item_unit, $form->{"id_$i"});
119 ($item_units{$form->{"id_$i"}}) = $h_item_unit->fetchrow_array();
122 my $item_unit = $item_units{$form->{"id_$i"}};
124 if (defined($all_units->{$item_unit}->{factor})
125 && ($all_units->{$item_unit}->{factor} ne '')
126 && ($all_units->{$item_unit}->{factor} * 1 != 0)) {
127 $basefactor = $all_units->{$form->{"unit_$i"}}->{factor} / $all_units->{$item_unit}->{factor};
131 $baseqty = $form->{"qty_$i"} * $basefactor;
133 @taxaccounts = split / /, $form->{"taxaccounts_$i"};
138 $form->{"sellprice_$i"} = $form->parse_amount($myconfig, $form->{"sellprice_$i"});
139 (my $fxsellprice = $form->{"sellprice_$i"}) =~ /\.(\d+)/;
141 my $decimalplaces = ($dec > 2) ? $dec : 2;
143 map { $taxrate += $form->{"${_}_rate"} } @taxaccounts;
145 $price_factor = $price_factors{ $form->{"price_factor_id_$i"} } || 1;
146 #####################################################################
147 # das ist aus IS.pm kopiert. schlimm. jb 7.10.2009
148 # ich würde mir wünschen, dass diese vier stellen zusammengefasst werden
149 # ... vier stellen = (einkauf + verkauf) * (maske + backend)
150 # ansonsten stolpert man immer wieder viermal statt einmal heftig
151 # und auch das undo discount formatting ist nicht besonders wartungsfreundlich
153 # keine ahnung wofür das in IS.pm gemacht wird:
154 # my ($dec) = ($fxsellprice =~ /\.(\d+)/);
155 # $dec = length $dec;
156 # my $decimalplaces = ($dec > 2) ? $dec : 2;
158 # undo discount formatting
159 $form->{"discount_$i"} = $form->parse_amount($myconfig, $form->{"discount_$i"}) / 100;
161 $form->{"sellprice_$i"} = $fxsellprice * (1 - $form->{"discount_$i"});
163 ######################################################################
164 if ($form->{"inventory_accno_$i"}) {
166 $linetotal = $form->round_amount($form->{"sellprice_$i"} * $form->{"qty_$i"} / $price_factor, 2);
168 if ($form->{taxincluded}) {
170 $taxamount = $linetotal * ($taxrate / (1 + $taxrate));
171 $form->{"sellprice_$i"} = $form->{"sellprice_$i"} * (1 / (1 + $taxrate));
174 $taxamount = $linetotal * $taxrate;
177 $netamount += $linetotal;
179 if ($form->round_amount($taxrate, 7) == 0) {
180 if ($form->{taxincluded}) {
181 foreach $item (@taxaccounts) {
183 $form->round_amount($linetotal * $form->{"${item}_rate"} / (1 + abs($form->{"${item}_rate"})), 2);
184 $taxdiff += $taxamount;
185 $form->{amount}{ $form->{id} }{$item} -= $taxamount;
187 $form->{amount}{ $form->{id} }{ $taxaccounts[0] } += $taxdiff;
190 map { $form->{amount}{ $form->{id} }{$_} -= $linetotal * $form->{"${_}_rate"} } @taxaccounts;
194 map { $form->{amount}{ $form->{id} }{$_} -= $taxamount * $form->{"${_}_rate"} / $taxrate } @taxaccounts;
197 # add purchase to inventory, this one is without the tax!
198 $amount = $form->{"sellprice_$i"} * $form->{"qty_$i"} * $form->{exchangerate} / $price_factor;
199 $linetotal = $form->round_amount($form->{"sellprice_$i"} * $form->{"qty_$i"} / $price_factor, 2) * $form->{exchangerate};
200 $linetotal = $form->round_amount($linetotal, 2);
202 # this is the difference for the inventory
203 $invoicediff += ($amount - $linetotal);
205 $form->{amount}{ $form->{id} }{ $form->{"inventory_accno_$i"} } -= $linetotal;
207 # adjust and round sellprice
208 $form->{"sellprice_$i"} = $form->round_amount($form->{"sellprice_$i"} * $form->{exchangerate}, $decimalplaces);
210 $lastinventoryaccno = $form->{"inventory_accno_$i"};
212 next if $payments_only;
214 # update parts table by setting lastcost to current price, don't allow negative values by using abs
215 $query = qq|UPDATE parts SET lastcost = ? WHERE id = ?|;
216 @values = (abs($fxsellprice * $form->{exchangerate} / $basefactor), conv_i($form->{"id_$i"}));
217 do_query($form, $dbh, $query, @values);
219 # check if we sold the item already and
220 # make an entry for the expense and inventory
221 my $taxzone = $form->{taxzone_id} * 1;
223 qq|SELECT i.id, i.qty, i.allocated, i.trans_id, i.base_qty,
224 bg.inventory_accno_id, tc.expense_accno_id AS expense_accno_id, a.transdate
225 FROM invoice i, ar a, parts p, buchungsgruppen bg, taxzone_charts tc
226 WHERE (i.parts_id = p.id)
228 AND ((i.base_qty + i.allocated) > 0)
229 AND (i.trans_id = a.id)
230 AND (p.buchungsgruppen_id = bg.id)
231 AND (tc.buchungsgruppen_id = p.buchungsgruppen_id)
232 AND (tc.taxzone_id = ${taxzone})
234 # ORDER BY transdate guarantees FIFO
236 # sold two items without having bought them yet, example result of query:
237 # id | qty | allocated | trans_id | inventory_accno_id | expense_accno_id | transdate
238 # ---+-----+-----------+----------+--------------------+------------------+------------
239 # 9 | 2 | 0 | 9 | 15 | 151 | 2011-01-05
241 # base_qty + allocated > 0 if article has already been sold but not bought yet
243 # select qty,allocated,base_qty,sellprice from invoice where trans_id = 9;
244 # qty | allocated | base_qty | sellprice
245 # -----+-----------+----------+------------
246 # 2 | 0 | 2 | 1000.00000
248 $sth = prepare_execute_query($form, $dbh, $query, conv_i($form->{"id_$i"}));
250 my $totalqty = $baseqty;
252 while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
253 my $qty = min $totalqty, ($ref->{base_qty} + $ref->{allocated});
254 $linetotal = $form->round_amount(($form->{"sellprice_$i"} * $qty) / $basefactor, 2);
256 if ( $::instance_conf->get_inventory_system eq 'perpetual' ) {
257 # Warenbestandsbuchungen nur bei Bestandsmethode
259 if ($ref->{allocated} < 0) {
261 # we have an entry for it already, adjust amount
262 $form->update_balance($dbh, "acc_trans", "amount",
263 qq| (trans_id = $ref->{trans_id})
264 AND (chart_id = $ref->{inventory_accno_id})
265 AND (transdate = '$ref->{transdate}')|,
268 $form->update_balance($dbh, "acc_trans", "amount",
269 qq| (trans_id = $ref->{trans_id})
270 AND (chart_id = $ref->{expense_accno_id})
271 AND (transdate = '$ref->{transdate}')|,
274 } elsif ($linetotal != 0) {
277 # add entry for inventory, this one is for the sold item
278 $query = qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate, taxkey, tax_id, chart_link) VALUES (?, ?, ?, ?,
283 ORDER BY startdate DESC LIMIT 1),
288 ORDER BY startdate DESC LIMIT 1),
289 (SELECT link FROM chart WHERE id = ?))|;
290 @values = ($ref->{trans_id}, $ref->{inventory_accno_id}, $linetotal, $ref->{transdate}, $ref->{inventory_accno_id}, $ref->{transdate}, $ref->{inventory_accno_id}, $ref->{transdate},
291 $ref->{inventory_accno_id});
292 do_query($form, $dbh, $query, @values);
295 $query = qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate, taxkey, tax_id, chart_link) VALUES (?, ?, ?, ?,
300 ORDER BY startdate DESC LIMIT 1),
305 ORDER BY startdate DESC LIMIT 1),
306 (SELECT link FROM chart WHERE id = ?))|;
307 @values = ($ref->{trans_id}, $ref->{expense_accno_id}, ($linetotal * -1), $ref->{transdate}, $ref->{expense_accno_id}, $ref->{transdate}, $ref->{expense_accno_id}, $ref->{transdate},
308 $ref->{expense_accno_id});
309 do_query($form, $dbh, $query, @values);
313 # update allocated for sold item
314 $form->update_balance($dbh, "invoice", "allocated", qq|id = $ref->{id}|, $qty * -1);
318 last if ($totalqty -= $qty) <= 0;
323 } else { # if ($form->{"inventory_accno_id_$i"})
324 # part doesn't have an inventory_accno_id
325 # lastcost of the part is updated at the end
327 $linetotal = $form->round_amount($form->{"sellprice_$i"} * $form->{"qty_$i"} / $price_factor, 2);
329 if ($form->{taxincluded}) {
330 $taxamount = $linetotal * ($taxrate / (1 + $taxrate));
331 $form->{"sellprice_$i"} = $form->{"sellprice_$i"} * (1 / (1 + $taxrate));
334 $taxamount = $linetotal * $taxrate;
337 $netamount += $linetotal;
339 if ($form->round_amount($taxrate, 7) == 0) {
340 if ($form->{taxincluded}) {
341 foreach $item (@taxaccounts) {
342 $taxamount = $linetotal * $form->{"${item}_rate"} / (1 + abs($form->{"${item}_rate"}));
343 $totaltax += $taxamount;
344 $form->{amount}{ $form->{id} }{$item} -= $taxamount;
347 map { $form->{amount}{ $form->{id} }{$_} -= $linetotal * $form->{"${_}_rate"} } @taxaccounts;
350 map { $form->{amount}{ $form->{id} }{$_} -= $taxamount * $form->{"${_}_rate"} / $taxrate } @taxaccounts;
353 $amount = $form->{"sellprice_$i"} * $form->{"qty_$i"} * $form->{exchangerate} / $price_factor;
354 $linetotal = $form->round_amount($form->{"sellprice_$i"} * $form->{"qty_$i"} / $price_factor, 2) * $form->{exchangerate};
355 $linetotal = $form->round_amount($linetotal, 2);
357 # this is the difference for expense
358 $expensediff += ($amount - $linetotal);
360 # add amount to expense
361 $form->{amount}{ $form->{id} }{ $form->{"expense_accno_$i"} } -= $linetotal;
363 $lastexpenseaccno = $form->{"expense_accno_$i"};
365 # adjust and round sellprice
366 $form->{"sellprice_$i"} = $form->round_amount($form->{"sellprice_$i"} * $form->{exchangerate}, $decimalplaces);
368 next if $payments_only;
371 $query = qq|UPDATE parts SET lastcost = ? WHERE id = ?|;
372 do_query($form, $dbh, $query, $form->{"sellprice_$i"} / $basefactor, conv_i($form->{"id_$i"}));
375 next if $payments_only;
377 # save detail record in invoice table
378 my ($invoice_id) = selectfirst_array_query($form, $dbh, qq|SELECT nextval('invoiceid')|);
381 qq|INSERT INTO invoice (id, trans_id, parts_id, description, longdescription, qty, base_qty,
382 sellprice, fxsellprice, discount, allocated, unit, deliverydate,
383 project_id, serialnumber, price_factor_id, price_factor, marge_price_factor)
384 VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, (SELECT factor FROM price_factors WHERE id = ?), ?)|;
385 @values = ($invoice_id, conv_i($form->{id}), conv_i($form->{"id_$i"}),
386 $form->{"description_$i"}, $restricter->process($form->{"longdescription_$i"}), $form->{"qty_$i"} * -1,
387 $baseqty * -1, $form->{"sellprice_$i"}, $fxsellprice, $form->{"discount_$i"}, $allocated,
388 $form->{"unit_$i"}, conv_date($form->{deliverydate}),
389 conv_i($form->{"project_id_$i"}), $form->{"serialnumber_$i"},
390 conv_i($form->{"price_factor_id_$i"}), conv_i($form->{"price_factor_id_$i"}), conv_i($form->{"marge_price_factor_$i"}));
391 do_query($form, $dbh, $query, @values);
393 CVar->save_custom_variables(module => 'IC',
394 sub_module => 'invoice',
395 trans_id => $invoice_id,
396 configs => $ic_cvar_configs,
398 name_prefix => 'ic_',
399 name_postfix => "_$i",
403 $h_item_unit->finish();
405 $project_id = conv_i($form->{"globalproject_id"});
407 $form->{datepaid} = $form->{invdate};
409 # all amounts are in natural state, netamount includes the taxes
410 # if tax is included, netamount is rounded to 2 decimal places,
414 for my $i (1 .. $form->{paidaccounts}) {
415 $form->{"paid_$i"} = $form->parse_amount($myconfig, $form->{"paid_$i"});
416 $form->{paid} += $form->{"paid_$i"};
417 $form->{datepaid} = $form->{"datepaid_$i"} if $form->{"datepaid_$i"};
420 my ($tax, $paiddiff) = (0, 0);
422 $netamount = $form->round_amount($netamount, 2);
424 # figure out rounding errors for amount paid and total amount
425 if ($form->{taxincluded}) {
427 $amount = $form->round_amount($netamount * $form->{exchangerate}, 2);
428 $paiddiff = $amount - $netamount * $form->{exchangerate};
429 $netamount = $amount;
431 foreach $item (split / /, $form->{taxaccounts}) {
432 $amount = $form->{amount}{ $form->{id} }{$item} * $form->{exchangerate};
433 $form->{amount}{ $form->{id} }{$item} = $form->round_amount($amount, 2);
435 $amount = $form->{amount}{ $form->{id} }{$item} * -1;
437 $netamount -= $amount;
440 $invoicediff += $paiddiff;
441 $expensediff += $paiddiff;
443 ######## this only applies to tax included
445 # in the sales invoice case rounding errors only have to be corrected for
446 # income accounts, it is enough to add the total rounding error to one of
447 # the income accounts, with the one assigned to the last row being used
448 # (lastinventoryaccno)
450 # in the purchase invoice case rounding errors may be split between
451 # inventory accounts and expense accounts. After rounding, an error of 1
452 # cent is introduced if the total rounding error exceeds 0.005. The total
453 # error is made up of $invoicediff and $expensediff, however, so if both
454 # values are below 0.005, but add up to a total >= 0.005, correcting
455 # lastinventoryaccno and lastexpenseaccno separately has no effect after
456 # rounding. This caused bug 1579. Therefore when the combined total exceeds
457 # 0.005, but neither do individually, the account with the larger value
458 # shall receive the total rounding error, and the next time it is rounded
459 # the 1 cent correction will be introduced.
461 $form->{amount}{ $form->{id} }{$lastinventoryaccno} -= $invoicediff if $lastinventoryaccno;
462 $form->{amount}{ $form->{id} }{$lastexpenseaccno} -= $expensediff if $lastexpenseaccno;
464 if ( (abs($expensediff)+abs($invoicediff)) >= 0.005 and abs($expensediff) < 0.005 and abs($invoicediff) < 0.005 ) {
466 # in total the rounding error adds up to 1 cent effectively, correct the
467 # larger of the two numbers
469 if ( abs($form->{amount}{ $form->{id} }{$lastinventoryaccno}) > abs($form->{amount}{ $form->{id} }{$lastexpenseaccno}) ) {
470 # $invoicediff has already been deducted, now also deduct expensediff
471 $form->{amount}{ $form->{id} }{$lastinventoryaccno} -= $expensediff;
473 # expensediff has already been deducted, now also deduct invoicediff
474 $form->{amount}{ $form->{id} }{$lastexpenseaccno} -= $invoicediff;
479 $amount = $form->round_amount($netamount * $form->{exchangerate}, 2);
480 $paiddiff = $amount - $netamount * $form->{exchangerate};
481 $netamount = $amount;
483 foreach my $item (split / /, $form->{taxaccounts}) {
484 $form->{amount}{ $form->{id} }{$item} = $form->round_amount($form->{amount}{ $form->{id} }{$item}, 2);
485 $amount = $form->round_amount( $form->{amount}{ $form->{id} }{$item} * $form->{exchangerate} * -1, 2);
486 $paiddiff += $amount - $form->{amount}{ $form->{id} }{$item} * $form->{exchangerate} * -1;
487 $form->{amount}{ $form->{id} }{$item} = $form->round_amount($amount * -1, 2);
488 $amount = $form->{amount}{ $form->{id} }{$item} * -1;
493 $form->{amount}{ $form->{id} }{ $form->{AP} } = $netamount + $tax;
496 $form->{paid} = $form->round_amount($form->{paid} * $form->{exchangerate} + $paiddiff, 2) if $form->{paid} != 0;
498 # update exchangerate
500 $form->update_exchangerate($dbh, $form->{currency}, $form->{invdate}, 0, $form->{exchangerate})
501 if ($form->{currency} ne $defaultcurrency) && !$exchangerate;
503 # record acc_trans transactions
504 foreach my $trans_id (keys %{ $form->{amount} }) {
505 foreach my $accno (keys %{ $form->{amount}{$trans_id} }) {
506 $form->{amount}{$trans_id}{$accno} = $form->round_amount($form->{amount}{$trans_id}{$accno}, 2);
509 next if $payments_only || !$form->{amount}{$trans_id}{$accno};
511 $query = qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate, taxkey, project_id, tax_id, chart_link)
512 VALUES (?, (SELECT id FROM chart WHERE accno = ?), ?, ?,
515 WHERE chart_id= (SELECT id
519 ORDER BY startdate DESC LIMIT 1),
523 WHERE chart_id= (SELECT id
527 ORDER BY startdate DESC LIMIT 1),
528 (SELECT link FROM chart WHERE accno = ?))|;
529 @values = ($trans_id, $accno, $form->{amount}{$trans_id}{$accno},
530 conv_date($form->{invdate}), $accno, conv_date($form->{invdate}), $project_id, $accno, conv_date($form->{invdate}), $accno);
531 do_query($form, $dbh, $query, @values);
535 # deduct payment differences from paiddiff
536 for my $i (1 .. $form->{paidaccounts}) {
537 if ($form->{"paid_$i"} != 0) {
538 $amount = $form->round_amount($form->{"paid_$i"} * $form->{exchangerate}, 2);
539 $paiddiff -= $amount - $form->{"paid_$i"} * $form->{exchangerate};
543 # force AP entry if 0
545 $form->{amount}{ $form->{id} }{ $form->{AP} } = $form->{paid} if $form->{amount}{$form->{id}}{$form->{AP}} == 0;
547 # record payments and offsetting AP
548 for my $i (1 .. $form->{paidaccounts}) {
549 if ($form->{"acc_trans_id_$i"}
551 && (SL::DB::Default->get->payments_changeable == 0)) {
555 next if $form->{"paid_$i"} == 0;
557 my ($accno) = split /--/, $form->{"AP_paid_$i"};
558 $form->{"datepaid_$i"} = $form->{invdate} unless ($form->{"datepaid_$i"});
559 $form->{datepaid} = $form->{"datepaid_$i"};
561 $amount = $form->round_amount($form->{"paid_$i"} * $form->{exchangerate} + $paiddiff, 2) * -1;
564 if ($form->{amount}{ $form->{id} }{ $form->{AP} } != 0) {
565 $query = qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate, taxkey, project_id, tax_id, chart_link)
566 VALUES (?, (SELECT id FROM chart WHERE accno = ?), ?, ?,
569 WHERE chart_id= (SELECT id
573 ORDER BY startdate DESC LIMIT 1),
577 WHERE chart_id= (SELECT id
581 ORDER BY startdate DESC LIMIT 1),
582 (SELECT link FROM chart WHERE accno = ?))|;
583 @values = (conv_i($form->{id}), $form->{AP}, $amount,
584 $form->{"datepaid_$i"}, $form->{AP}, conv_date($form->{"datepaid_$i"}), $project_id, $form->{AP}, conv_date($form->{"datepaid_$i"}), $form->{AP});
585 do_query($form, $dbh, $query, @values);
589 my $gldate = (conv_date($form->{"gldate_$i"}))? conv_date($form->{"gldate_$i"}) : conv_date($form->current_date($myconfig));
592 qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate, gldate, source, memo, taxkey, project_id, tax_id, chart_link)
593 VALUES (?, (SELECT id FROM chart WHERE accno = ?), ?, ?, ?, ?, ?,
596 WHERE chart_id= (SELECT id
597 FROM chart WHERE accno = ?)
599 ORDER BY startdate DESC LIMIT 1),
603 WHERE chart_id= (SELECT id
604 FROM chart WHERE accno = ?)
606 ORDER BY startdate DESC LIMIT 1),
607 (SELECT link FROM chart WHERE accno = ?))|;
608 @values = (conv_i($form->{id}), $accno, $form->{"paid_$i"}, $form->{"datepaid_$i"},
609 $gldate, $form->{"source_$i"}, $form->{"memo_$i"}, $accno, conv_date($form->{"datepaid_$i"}), $project_id, $accno, conv_date($form->{"datepaid_$i"}), $accno);
610 do_query($form, $dbh, $query, @values);
614 if ($form->{currency} eq $defaultcurrency) {
615 $form->{"exchangerate_$i"} = 1;
617 $exchangerate = $form->check_exchangerate($myconfig, $form->{currency}, $form->{"datepaid_$i"}, 'sell');
618 $form->{"exchangerate_$i"} = $exchangerate || $form->parse_amount($myconfig, $form->{"exchangerate_$i"});
621 # exchangerate difference
622 $form->{fx}{$accno}{ $form->{"datepaid_$i"} } += $form->{"paid_$i"} * ($form->{"exchangerate_$i"} - 1) + $paiddiff;
626 ($form->{"paid_$i"} * $form->{exchangerate}) -
627 ($form->{"paid_$i"} * $form->{"exchangerate_$i"});
629 $form->{fx}{ $form->{fxgain_accno} }{ $form->{"datepaid_$i"} } += $amount;
631 $form->{fx}{ $form->{fxloss_accno} }{ $form->{"datepaid_$i"} } += $amount;
636 # update exchange rate
637 $form->update_exchangerate($dbh, $form->{currency}, $form->{"datepaid_$i"}, 0, $form->{"exchangerate_$i"})
638 if ($form->{currency} ne $defaultcurrency) && !$exchangerate;
641 # record exchange rate differences and gains/losses
642 foreach my $accno (keys %{ $form->{fx} }) {
643 foreach my $transdate (keys %{ $form->{fx}{$accno} }) {
644 $form->{fx}{$accno}{$transdate} = $form->round_amount($form->{fx}{$accno}{$transdate}, 2);
645 next if ($form->{fx}{$accno}{$transdate} == 0);
647 $query = qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate, cleared, fx_transaction, taxkey, project_id, tax_id, chart_link)
648 VALUES (?, (SELECT id FROM chart WHERE accno = ?), ?, ?, '0', '1', 0, ?,
649 (SELECT id FROM tax WHERE taxkey=0 LIMIT 1),
650 (SELECT link FROM chart WHERE accno = ?))|;
651 @values = (conv_i($form->{id}), $accno, $form->{fx}{$accno}{$transdate}, conv_date($transdate), $project_id, $accno);
652 do_query($form, $dbh, $query, @values);
656 IO->set_datepaid(table => 'ap', id => $form->{id}, dbh => $dbh);
658 if ($payments_only) {
659 $query = qq|UPDATE ap SET paid = ? WHERE id = ?|;
660 do_query($form, $dbh, $query, $form->{paid}, conv_i($form->{id}));
662 if (!$provided_dbh) {
667 $main::lxdebug->leave_sub();
671 $amount = $netamount + $tax;
673 # set values which could be empty
674 my $taxzone_id = $form->{taxzone_id} * 1;
676 # Seit neuestem wird die department_id schon übergeben UND $form->department nicht mehr
677 # korrekt zusammengebaut. Sehr wahrscheinlich beim Umstieg auf T8 kaputt gegangen
678 # Ich lass den Code von 2005 erstmal noch stehen ;-) jb 03-2011
679 # copy & paste von IS.pm
680 if (!$form->{department_id}){
681 $form->{department_id} = (split /--/, $form->{department})[1];
683 $form->{invnumber} = $form->{id} unless $form->{invnumber};
685 $taxzone_id = 0 if (3 < $taxzone_id) || (0 > $taxzone_id);
688 $query = qq|UPDATE ap SET
689 invnumber = ?, ordnumber = ?, quonumber = ?, transdate = ?,
690 orddate = ?, quodate = ?, vendor_id = ?, amount = ?,
691 netamount = ?, paid = ?, duedate = ?,
692 invoice = ?, taxzone_id = ?, notes = ?, taxincluded = ?,
693 intnotes = ?, storno_id = ?, storno = ?,
694 cp_id = ?, employee_id = ?, department_id = ?, delivery_term_id = ?,
695 globalproject_id = ?, direct_debit = ?
698 $form->{invnumber}, $form->{ordnumber}, $form->{quonumber}, conv_date($form->{invdate}),
699 conv_date($form->{orddate}), conv_date($form->{quodate}), conv_i($form->{vendor_id}), $amount,
700 $netamount, $form->{paid}, conv_date($form->{duedate}),
701 '1', $taxzone_id, $form->{notes}, $form->{taxincluded} ? 't' : 'f',
702 $form->{intnotes}, conv_i($form->{storno_id}), $form->{storno} ? 't' : 'f',
703 conv_i($form->{cp_id}), conv_i($form->{employee_id}), conv_i($form->{department_id}), conv_i($form->{delivery_term_id}),
704 conv_i($form->{globalproject_id}),
705 $form->{direct_debit} ? 't' : 'f',
708 do_query($form, $dbh, $query, @values);
710 if ($form->{storno}) {
711 $query = qq|UPDATE ap SET paid = paid + amount WHERE id = ?|;
712 do_query($form, $dbh, $query, conv_i($form->{storno_id}));
714 $query = qq|UPDATE ap SET storno = 't' WHERE id = ?|;
715 do_query($form, $dbh, $query, conv_i($form->{storno_id}));
717 $query = qq!UPDATE ap SET intnotes = ? || intnotes WHERE id = ?!;
718 do_query($form, $dbh, $query, "Rechnung storniert am $form->{invdate} ", conv_i($form->{storno_id}));
720 $query = qq|UPDATE ap SET paid = amount WHERE id = ?|;
721 do_query($form, $dbh, $query, conv_i($form->{id}));
725 $form->{name} = $form->{vendor};
726 $form->{name} =~ s/--\Q$form->{vendor_id}\E//;
729 $form->add_shipto($dbh, $form->{id}, "AP");
731 # delete zero entries
732 do_query($form, $dbh, qq|DELETE FROM acc_trans WHERE amount = 0|);
734 Common::webdav_folder($form);
736 # Link this record to the records it was created from.
737 RecordLinks->create_links('dbh' => $dbh,
739 'from_table' => 'oe',
740 'from_ids' => $form->{convert_from_oe_ids},
742 'to_id' => $form->{id},
744 delete $form->{convert_from_oe_ids};
746 my @convert_from_do_ids = map { $_ * 1 } grep { $_ } split m/\s+/, $form->{convert_from_do_ids};
747 if (scalar @convert_from_do_ids) {
748 DO->close_orders('dbh' => $dbh,
749 'ids' => \@convert_from_do_ids);
751 RecordLinks->create_links('dbh' => $dbh,
753 'from_table' => 'delivery_orders',
754 'from_ids' => \@convert_from_do_ids,
756 'to_id' => $form->{id},
759 delete $form->{convert_from_do_ids};
761 ARAP->close_orders_if_billed('dbh' => $dbh,
762 'arap_id' => $form->{id},
765 # safety check datev export
766 if ($::instance_conf->get_datev_check_on_purchase_invoice) {
767 my $transdate = $::form->{invdate} ? DateTime->from_lxoffice($::form->{invdate}) : undef;
768 $transdate ||= DateTime->today;
770 my $datev = SL::DATEV->new(
771 exporttype => DATEV_ET_BUCHUNGEN,
772 format => DATEV_FORMAT_KNE,
776 trans_id => $form->{id},
781 if ($datev->errors) {
783 die join "\n", $::locale->text('DATEV check returned errors:'), $datev->errors;
788 if (!$provided_dbh) {
789 $rc = $dbh->commit();
793 $main::lxdebug->leave_sub();
798 sub reverse_invoice {
799 $main::lxdebug->enter_sub();
801 my ($dbh, $form) = @_;
803 # reverse inventory items
805 qq|SELECT i.parts_id, p.inventory_accno_id, p.expense_accno_id, i.qty, i.allocated, i.sellprice
806 FROM invoice i, parts p
807 WHERE (i.parts_id = p.id)
808 AND (i.trans_id = ?)|;
809 my $sth = prepare_execute_query($form, $dbh, $query, conv_i($form->{id}));
813 while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
814 $netamount += $form->round_amount($ref->{sellprice} * $ref->{qty} * -1, 2);
816 next unless $ref->{inventory_accno_id};
818 # if $ref->{allocated} > 0 than we sold that many items
819 next if ($ref->{allocated} <= 0);
821 # get references for sold items
823 qq|SELECT i.id, i.trans_id, i.allocated, a.transdate
825 WHERE (i.parts_id = ?)
826 AND (i.allocated < 0)
827 AND (i.trans_id = a.id)
828 ORDER BY transdate DESC|;
829 my $sth2 = prepare_execute_query($form, $dbh, $query, $ref->{parts_id});
831 while (my $pthref = $sth2->fetchrow_hashref("NAME_lc")) {
832 my $qty = $ref->{allocated};
833 if (($ref->{allocated} + $pthref->{allocated}) > 0) {
834 $qty = $pthref->{allocated} * -1;
837 my $amount = $form->round_amount($ref->{sellprice} * $qty, 2);
840 $form->update_balance($dbh, "invoice", "allocated", qq|id = $pthref->{id}|, $qty);
842 $form->update_balance($dbh, "acc_trans", "amount",
843 qq| (trans_id = $pthref->{trans_id})
844 AND (chart_id = $ref->{expense_accno_id})
845 AND (transdate = '$pthref->{transdate}')|,
848 $form->update_balance($dbh, "acc_trans", "amount",
849 qq| (trans_id = $pthref->{trans_id})
850 AND (chart_id = $ref->{inventory_accno_id})
851 AND (transdate = '$pthref->{transdate}')|,
854 last if (($ref->{allocated} -= $qty) <= 0);
860 my $id = conv_i($form->{id});
863 $query = qq|DELETE FROM acc_trans WHERE trans_id = ?|;
864 do_query($form, $dbh, $query, $id);
866 # delete invoice entries
867 $query = qq|DELETE FROM invoice WHERE trans_id = ?|;
868 do_query($form, $dbh, $query, $id);
870 $query = qq|DELETE FROM shipto WHERE (trans_id = ?) AND (module = 'AP')|;
871 do_query($form, $dbh, $query, $id);
873 $main::lxdebug->leave_sub();
877 $main::lxdebug->enter_sub();
879 my ($self, $myconfig, $form) = @_;
881 # connect to database
882 my $dbh = $form->dbconnect_noauto($myconfig);
884 &reverse_invoice($dbh, $form);
886 # delete zero entries
887 $query = qq|DELETE FROM acc_trans WHERE amount = 0|;
888 do_query($form, $dbh, $query);
891 $query = qq|DELETE FROM ap WHERE id = ?|;
892 do_query($form, $dbh, $query, conv_i($form->{id}));
894 my $rc = $dbh->commit;
897 $main::lxdebug->leave_sub();
902 sub retrieve_invoice {
903 $main::lxdebug->enter_sub();
905 my ($self, $myconfig, $form) = @_;
907 # connect to database
908 my $dbh = $form->dbconnect($myconfig);
910 my ($query, $sth, $ref, $q_invdate);
913 $q_invdate = qq|, COALESCE((SELECT transdate FROM ar WHERE id = (SELECT MAX(id) FROM ar)), current_date) AS invdate|;
914 if ($form->{vendor_id}) {
915 my $vendor_id = $dbh->quote($form->{vendor_id} * 1);
917 qq|, COALESCE((SELECT transdate FROM ar WHERE id = (SELECT MAX(id) FROM ar)), current_date) +
918 COALESCE((SELECT pt.terms_netto
920 LEFT JOIN payment_terms pt ON (v.payment_id = pt.id)
921 WHERE v.id = $vendor_id),
926 # get default accounts and last invoice number
929 (SELECT c.accno FROM chart c WHERE d.inventory_accno_id = c.id) AS inventory_accno,
930 (SELECT c.accno FROM chart c WHERE d.income_accno_id = c.id) AS income_accno,
931 (SELECT c.accno FROM chart c WHERE d.expense_accno_id = c.id) AS expense_accno,
932 (SELECT c.accno FROM chart c WHERE d.fxgain_accno_id = c.id) AS fxgain_accno,
933 (SELECT c.accno FROM chart c WHERE d.fxloss_accno_id = c.id) AS fxloss_accno
936 $ref = selectfirst_hashref_query($form, $dbh, $query);
937 map { $form->{$_} = $ref->{$_} } keys %$ref;
941 $main::lxdebug->leave_sub();
947 $query = qq|SELECT cp_id, invnumber, transdate AS invdate, duedate,
948 orddate, quodate, globalproject_id,
949 ordnumber, quonumber, paid, taxincluded, notes, taxzone_id, storno, gldate,
950 intnotes, (SELECT cu.name FROM currencies cu WHERE cu.id=ap.currency_id) AS currency, direct_debit,
954 $ref = selectfirst_hashref_query($form, $dbh, $query, conv_i($form->{id}));
955 map { $form->{$_} = $ref->{$_} } keys %$ref;
957 $form->{exchangerate} = $form->get_exchangerate($dbh, $form->{currency}, $form->{invdate}, "sell");
960 $query = qq|SELECT * FROM shipto WHERE (trans_id = ?) AND (module = 'AP')|;
961 $ref = selectfirst_hashref_query($form, $dbh, $query, conv_i($form->{id}));
963 map { $form->{$_} = $ref->{$_} } keys %$ref;
965 my $transdate = $form->{invdate} ? $dbh->quote($form->{invdate}) : "current_date";
966 my $taxzone_id = $form->{taxzone_id} * 1;
968 $taxzone_id = 0 if ((3 < $taxzone_id) || (0 > $taxzone_id));
970 # retrieve individual items
973 c1.accno AS inventory_accno, c1.new_chart_id AS inventory_new_chart, date($transdate) - c1.valid_from AS inventory_valid,
974 c2.accno AS income_accno, c2.new_chart_id AS income_new_chart, date($transdate) - c2.valid_from AS income_valid,
975 c3.accno AS expense_accno, c3.new_chart_id AS expense_new_chart, date($transdate) - c3.valid_from AS expense_valid,
978 i.description, i.longdescription, i.qty, i.fxsellprice AS sellprice, i.parts_id AS id, i.unit, i.deliverydate, i.project_id, i.serialnumber,
979 i.price_factor_id, i.price_factor, i.marge_price_factor, i.discount,
980 p.partnumber, p.inventory_accno_id AS part_inventory_accno_id, pr.projectnumber, pg.partsgroup
983 JOIN parts p ON (i.parts_id = p.id)
984 LEFT JOIN chart c1 ON ((SELECT inventory_accno_id FROM buchungsgruppen WHERE id = p.buchungsgruppen_id) = c1.id)
985 LEFT JOIN chart c2 ON ((SELECT tc.income_accno_id FROM taxzone_charts tc where tc.taxzone_id = '$taxzone_id' and tc.buchungsgruppen_id = p.buchungsgruppen_id) = c2.id)
986 LEFT JOIN chart c3 ON ((SELECT tc.expense_accno_id FROM taxzone_charts tc where tc.taxzone_id = '$taxzone_id' and tc.buchungsgruppen_id = p.buchungsgruppen_id) = c3.id)
987 LEFT JOIN project pr ON (i.project_id = pr.id)
988 LEFT JOIN partsgroup pg ON (pg.id = p.partsgroup_id)
993 $sth = prepare_execute_query($form, $dbh, $query, conv_i($form->{id}));
995 while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
996 # Retrieve custom variables.
997 my $cvars = CVar->get_custom_variables(dbh => $dbh,
999 sub_module => 'invoice',
1000 trans_id => $ref->{invoice_id},
1002 map { $ref->{"ic_cvar_$_->{name}"} = $_->{value} } @{ $cvars };
1003 delete $ref->{invoice_id};
1005 map({ delete($ref->{$_}); } qw(inventory_accno inventory_new_chart inventory_valid)) if !$ref->{"part_inventory_accno_id"};
1006 delete($ref->{"part_inventory_accno_id"});
1008 foreach my $type (qw(inventory income expense)) {
1009 while ($ref->{"${type}_new_chart"} && ($ref->{"${type}_valid"} >=0)) {
1010 my $query = qq|SELECT accno, new_chart_id, date($transdate) - valid_from FROM chart WHERE id = ?|;
1011 @$ref{ map $type.$_, qw(_accno _new_chart _valid) } = selectrow_query($form, $dbh, $query, $ref->{"${type}_new_chart"});
1015 # get tax rates and description
1016 my $accno_id = ($form->{vc} eq "customer") ? $ref->{income_accno} : $ref->{expense_accno};
1018 qq|SELECT c.accno, t.taxdescription, t.rate, t.taxnumber FROM tax t
1019 LEFT JOIN chart c ON (c.id = t.chart_id)
1021 (SELECT tk.tax_id FROM taxkeys tk
1022 WHERE tk.chart_id = (SELECT id FROM chart WHERE accno = ?)
1023 AND (startdate <= $transdate)
1024 ORDER BY startdate DESC
1027 my $stw = prepare_execute_query($form, $dbh, $query, $accno_id);
1028 $ref->{taxaccounts} = "";
1031 while (my $ptr = $stw->fetchrow_hashref("NAME_lc")) {
1032 if (($ptr->{accno} eq "") && ($ptr->{rate} == 0)) {
1037 $ref->{taxaccounts} .= "$ptr->{accno} ";
1039 if (!($form->{taxaccounts} =~ /\Q$ptr->{accno}\E/)) {
1040 $form->{"$ptr->{accno}_rate"} = $ptr->{rate};
1041 $form->{"$ptr->{accno}_description"} = $ptr->{taxdescription};
1042 $form->{"$ptr->{accno}_taxnumber"} = $ptr->{taxnumber};
1043 $form->{taxaccounts} .= "$ptr->{accno} ";
1048 chop $ref->{taxaccounts};
1049 push @{ $form->{invoice_details} }, $ref;
1054 Common::webdav_folder($form);
1058 $main::lxdebug->leave_sub();
1062 $main::lxdebug->enter_sub();
1064 my ($self, $myconfig, $form, $params) = @_;
1066 $params = $form unless defined $params && ref $params eq "HASH";
1068 # connect to database
1069 my $dbh = $form->dbconnect($myconfig);
1071 my $dateformat = $myconfig->{dateformat};
1072 $dateformat .= "yy" if $myconfig->{dateformat} !~ /^y/;
1074 my $vid = conv_i($params->{vendor_id});
1075 my $vnr = conv_i($params->{vendornumber});
1078 ($params->{invdate})
1079 ? "to_date(" . $dbh->quote($params->{invdate}) . ", '$dateformat')"
1086 $where .= 'AND v.id = ?';
1090 $where .= 'AND v.vendornumber = ?';
1095 v.id AS vendor_id, v.name AS vendor, v.discount as vendor_discount,
1096 v.creditlimit, v.terms, v.notes AS intnotes,
1097 v.email, v.cc, v.bcc, v.language_id, v.payment_id, v.delivery_term_id,
1098 v.street, v.zipcode, v.city, v.country, v.taxzone_id, cu.name AS curr, v.direct_debit,
1099 $duedate + COALESCE(pt.terms_netto, 0) AS duedate,
1100 b.description AS business
1102 LEFT JOIN business b ON (b.id = v.business_id)
1103 LEFT JOIN payment_terms pt ON (v.payment_id = pt.id)
1104 LEFT JOIN currencies cu ON (v.currency_id = cu.id)
1106 my $ref = selectfirst_hashref_query($form, $dbh, $query, @values);
1107 map { $params->{$_} = $ref->{$_} } keys %$ref;
1109 # use vendor currency
1110 $form->{currency} = $form->{curr};
1112 $params->{creditremaining} = $params->{creditlimit};
1114 $query = qq|SELECT SUM(amount - paid) FROM ap WHERE vendor_id = ?|;
1115 my ($unpaid_invoices) = selectfirst_array_query($form, $dbh, $query, $vid);
1116 $params->{creditremaining} -= $unpaid_invoices;
1118 $query = qq|SELECT o.amount,
1121 WHERE (e.currency_id = o.currency_id)
1122 AND (e.transdate = o.transdate)) AS exch
1124 WHERE (o.vendor_id = ?) AND (o.quotation = '0') AND (o.closed = '0')|;
1125 my $sth = prepare_execute_query($form, $dbh, $query, $vid);
1126 while (my ($amount, $exch) = $sth->fetchrow_array()) {
1127 $exch = 1 unless $exch;
1128 $params->{creditremaining} -= $amount * $exch;
1132 if (!$params->{id} && $params->{type} !~ /_(order|quotation)/) {
1133 # setup last accounts used
1135 qq|SELECT c.id, c.accno, c.description, c.link, c.category
1137 JOIN acc_trans ac ON (ac.chart_id = c.id)
1138 JOIN ap a ON (a.id = ac.trans_id)
1139 WHERE (a.vendor_id = ?)
1140 AND (NOT ((c.link LIKE '%_tax%') OR (c.link LIKE '%_paid%')))
1141 AND (a.id IN (SELECT max(a2.id) FROM ap a2 WHERE a2.vendor_id = ?))|;
1142 my $refs = selectall_hashref_query($form, $dbh, $query, $vid, $vid);
1146 if ($ref->{category} eq 'E') {
1148 my ($tax_id, $rate);
1149 if ($params->{initial_transdate}) {
1150 my $tax_query = qq|SELECT tk.tax_id, t.rate FROM taxkeys tk
1151 LEFT JOIN tax t ON (tk.tax_id = t.id)
1152 WHERE (tk.chart_id = ?) AND (startdate <= ?)
1153 ORDER BY tk.startdate DESC
1155 ($tax_id, $rate) = selectrow_query($form, $dbh, $tax_query, $ref->{id}, $params->{initial_transdate});
1156 $params->{"taxchart_$i"} = "${tax_id}--${rate}";
1159 $params->{"AP_amount_$i"} = "$ref->{accno}--$tax_id";
1162 if ($ref->{category} eq 'L') {
1163 $params->{APselected} = $params->{AP_1} = $ref->{accno};
1166 $params->{rowcount} = $i if ($i && !$params->{type});
1171 $main::lxdebug->leave_sub();
1175 $main::lxdebug->enter_sub();
1177 my ($self, $myconfig, $form) = @_;
1179 # connect to database
1180 my $dbh = $form->dbconnect($myconfig);
1182 my $i = $form->{rowcount};
1184 # don't include assemblies or obsolete parts
1185 my $where = "NOT p.assembly = '1' AND NOT p.obsolete = '1'";
1188 foreach my $table_column (qw(p.partnumber p.description pg.partsgroup)) {
1189 my $field = (split m{\.}, $table_column)[1];
1190 next unless $form->{"${field}_${i}"};
1191 $where .= " AND lower(${table_column}) LIKE lower(?)";
1192 push @values, '%' . $form->{"${field}_${i}"} . '%';
1194 #Es soll auch nach EAN gesucht werden, ohne Einschränkung durch Beschreibung
1195 if ($form->{"partnumber_$i"} && !$form->{"description_$i"}) {
1196 $where .= qq| OR (NOT p.obsolete = '1' AND p.ean = ? )|;
1197 push @values, $form->{"partnumber_$i"};
1200 # Search for part ID overrides all other criteria.
1201 if ($form->{"id_${i}"}) {
1202 $where = qq|p.id = ?|;
1203 @values = ($form->{"id_${i}"});
1206 if ($form->{"description_$i"}) {
1207 $where .= " ORDER BY p.description";
1209 $where .= " ORDER BY p.partnumber";
1213 if ($form->{type} eq "invoice") {
1214 $transdate = $form->{deliverydate} ? $dbh->quote($form->{deliverydate})
1215 : $form->{invdate} ? $dbh->quote($form->{invdate})
1218 $transdate = $form->{transdate} ? $dbh->quote($form->{transdate}) : "current_date";
1221 my $taxzone_id = $form->{taxzone_id} * 1;
1222 $taxzone_id = 0 if ((3 < $taxzone_id) || (0 > $taxzone_id));
1226 p.id, p.partnumber, p.description, p.lastcost AS sellprice, p.listprice,
1227 p.unit, p.assembly, p.onhand, p.formel,
1228 p.notes AS partnotes, p.notes AS longdescription, p.not_discountable,
1229 p.inventory_accno_id, p.price_factor_id,
1231 pfac.factor AS price_factor,
1233 c1.accno AS inventory_accno,
1234 c1.new_chart_id AS inventory_new_chart,
1235 date($transdate) - c1.valid_from AS inventory_valid,
1237 c2.accno AS income_accno,
1238 c2.new_chart_id AS income_new_chart,
1239 date($transdate) - c2.valid_from AS income_valid,
1241 c3.accno AS expense_accno,
1242 c3.new_chart_id AS expense_new_chart,
1243 date($transdate) - c3.valid_from AS expense_valid,
1248 LEFT JOIN chart c1 ON
1249 ((SELECT inventory_accno_id
1250 FROM buchungsgruppen
1251 WHERE id = p.buchungsgruppen_id) = c1.id)
1252 LEFT JOIN chart c2 ON
1253 ((SELECT tc.income_accno_id
1254 FROM taxzone_charts tc
1255 WHERE tc.taxzone_id = '$taxzone_id' and tc.buchungsgruppen_id = p.buchungsgruppen_id) = c2.id)
1256 LEFT JOIN chart c3 ON
1257 ((SELECT tc.expense_accno_id
1258 FROM taxzone_charts tc
1259 WHERE tc.taxzone_id = '$taxzone_id' and tc.buchungsgruppen_id = p.buchungsgruppen_id) = c3.id)
1260 LEFT JOIN partsgroup pg ON (pg.id = p.partsgroup_id)
1261 LEFT JOIN price_factors pfac ON (pfac.id = p.price_factor_id)
1263 my $sth = prepare_execute_query($form, $dbh, $query, @values);
1265 my @translation_queries = ( [ qq|SELECT tr.translation, tr.longdescription
1267 WHERE tr.language_id = ? AND tr.parts_id = ?| ],
1268 [ qq|SELECT tr.translation, tr.longdescription
1270 WHERE tr.language_id IN
1273 WHERE article_code = (SELECT article_code FROM language WHERE id = ?))
1276 map { push @{ $_ }, prepare_query($form, $dbh, $_->[0]) } @translation_queries;
1278 $form->{item_list} = [];
1279 while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
1281 # In der Buchungsgruppe ist immer ein Bestandskonto verknuepft, auch wenn
1282 # es sich um eine Dienstleistung handelt. Bei Dienstleistungen muss das
1283 # Buchungskonto also aus dem Ergebnis rausgenommen werden.
1284 if (!$ref->{inventory_accno_id}) {
1285 map({ delete($ref->{"inventory_${_}"}); } qw(accno new_chart valid));
1287 delete($ref->{inventory_accno_id});
1289 # get tax rates and description
1290 my $accno_id = ($form->{vc} eq "customer") ? $ref->{income_accno} : $ref->{expense_accno};
1292 qq|SELECT c.accno, t.taxdescription, t.rate, t.taxnumber
1294 LEFT JOIN chart c on (c.id = t.chart_id)
1302 AND (startdate <= $transdate)
1303 ORDER BY startdate DESC
1306 my $stw = prepare_execute_query($form, $dbh, $query, $accno_id);
1308 $ref->{taxaccounts} = "";
1310 while (my $ptr = $stw->fetchrow_hashref("NAME_lc")) {
1312 if (($ptr->{accno} eq "") && ($ptr->{rate} == 0)) {
1317 $ref->{taxaccounts} .= "$ptr->{accno} ";
1319 if (!($form->{taxaccounts} =~ /\Q$ptr->{accno}\E/)) {
1320 $form->{"$ptr->{accno}_rate"} = $ptr->{rate};
1321 $form->{"$ptr->{accno}_description"} = $ptr->{taxdescription};
1322 $form->{"$ptr->{accno}_taxnumber"} = $ptr->{taxnumber};
1323 $form->{taxaccounts} .= "$ptr->{accno} ";
1326 if ($form->{language_id}) {
1327 for my $spec (@translation_queries) {
1328 do_statement($form, $spec->[1], $spec->[0], conv_i($form->{language_id}), conv_i($ref->{id}));
1329 my ($translation, $longdescription) = $spec->[1]->fetchrow_array;
1330 next unless $translation;
1331 $ref->{description} = $translation;
1332 $ref->{longdescription} = $longdescription;
1339 chop $ref->{taxaccounts};
1341 $ref->{onhand} *= 1;
1343 push @{ $form->{item_list} }, $ref;
1348 $_->[1]->finish for @translation_queries;
1350 foreach my $item (@{ $form->{item_list} }) {
1351 my $custom_variables = CVar->get_custom_variables(module => 'IC',
1352 trans_id => $item->{id},
1356 map { $item->{"ic_cvar_" . $_->{name} } = $_->{value} } @{ $custom_variables };
1361 $main::lxdebug->leave_sub();
1364 sub vendor_details {
1365 $main::lxdebug->enter_sub();
1367 my ($self, $myconfig, $form, @wanted_vars) = @_;
1369 # connect to database
1370 my $dbh = $form->dbconnect($myconfig);
1374 # get contact id, set it if nessessary
1375 $form->{cp_id} *= 1;
1377 if ($form->{cp_id}) {
1378 $contact = "AND cp.cp_id = ?";
1379 push @values, $form->{cp_id};
1382 # get rest for the vendor
1383 # fax and phone and email as vendor*
1385 qq|SELECT ct.*, cp.*, ct.notes as vendornotes, phone as vendorphone, fax as vendorfax, email as vendoremail,
1388 LEFT JOIN contacts cp ON (ct.id = cp.cp_cv_id)
1389 LEFT JOIN currencies cu ON (ct.currency_id = cu.id)
1390 WHERE (ct.id = ?) $contact
1393 my $ref = selectfirst_hashref_query($form, $dbh, $query, $form->{vendor_id}, @values);
1395 # remove id and taxincluded before copy back
1396 delete @$ref{qw(id taxincluded)};
1398 @wanted_vars = grep({ $_ } @wanted_vars);
1399 if (scalar(@wanted_vars) > 0) {
1401 map({ $h_wanted_vars{$_} = 1; } @wanted_vars);
1402 map({ delete($ref->{$_}) unless ($h_wanted_vars{$_}); } keys(%{$ref}));
1405 map { $form->{$_} = $ref->{$_} } keys %$ref;
1407 my $custom_variables = CVar->get_custom_variables('dbh' => $dbh,
1409 'trans_id' => $form->{vendor_id});
1410 map { $form->{"vc_cvar_$_->{name}"} = $_->{value} } @{ $custom_variables };
1412 $form->{cp_greeting} = GenericTranslations->get('dbh' => $dbh,
1413 'translation_type' => 'greetings::' . ($form->{cp_gender} eq 'f' ? 'female' : 'male'),
1414 'allow_fallback' => 1);
1418 $main::lxdebug->leave_sub();
1422 $main::lxdebug->enter_sub();
1424 my ($self, $myconfig, $form) = @_;
1426 # connect to database
1427 my $dbh = $form->dbconnect($myconfig);
1430 qq|SELECT accno, description, link
1432 WHERE link LIKE '%IC%'
1434 my $sth = prepare_execute_query($query, $dbh, $query);
1436 while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
1437 foreach my $key (split(/:/, $ref->{link})) {
1439 push @{ $form->{IC_links}{$key} },
1440 { accno => $ref->{accno},
1441 description => $ref->{description} };
1449 $main::lxdebug->leave_sub();
1452 sub _delete_payments {
1453 $main::lxdebug->enter_sub();
1455 my ($self, $form, $dbh) = @_;
1457 my @delete_acc_trans_ids;
1459 # Delete old payment entries from acc_trans.
1461 qq|SELECT acc_trans_id
1463 WHERE (trans_id = ?) AND fx_transaction
1467 SELECT at.acc_trans_id
1469 LEFT JOIN chart c ON (at.chart_id = c.id)
1470 WHERE (trans_id = ?) AND (c.link LIKE '%AP_paid%')|;
1471 push @delete_acc_trans_ids, selectall_array_query($form, $dbh, $query, conv_i($form->{id}), conv_i($form->{id}));
1474 qq|SELECT at.acc_trans_id
1476 LEFT JOIN chart c ON (at.chart_id = c.id)
1477 WHERE (trans_id = ?)
1478 AND ((c.link = 'AP') OR (c.link LIKE '%:AP') OR (c.link LIKE 'AP:%'))
1479 ORDER BY at.acc_trans_id
1481 push @delete_acc_trans_ids, selectall_array_query($form, $dbh, $query, conv_i($form->{id}));
1483 if (@delete_acc_trans_ids) {
1484 $query = qq|DELETE FROM acc_trans WHERE acc_trans_id IN (| . join(", ", @delete_acc_trans_ids) . qq|)|;
1485 do_query($form, $dbh, $query);
1488 $main::lxdebug->leave_sub();
1492 $main::lxdebug->enter_sub();
1494 my ($self, $myconfig, $form, $locale) = @_;
1496 # connect to database, turn off autocommit
1497 my $dbh = $form->dbconnect_noauto($myconfig);
1499 my (%payments, $old_form, $row, $item, $query, %keep_vars);
1501 $old_form = save_form();
1503 # Delete all entries in acc_trans from prior payments.
1504 if (SL::DB::Default->get->payments_changeable != 0) {
1505 $self->_delete_payments($form, $dbh);
1508 # Save the new payments the user made before cleaning up $form.
1509 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 };
1511 # Clean up $form so that old content won't tamper the results.
1512 %keep_vars = map { $_, 1 } qw(login password id);
1513 map { delete $form->{$_} unless $keep_vars{$_} } keys %{ $form };
1515 # Retrieve the invoice from the database.
1516 $self->retrieve_invoice($myconfig, $form);
1518 # Set up the content of $form in the way that IR::post_invoice() expects.
1519 $form->{exchangerate} = $form->format_amount($myconfig, $form->{exchangerate});
1521 for $row (1 .. scalar @{ $form->{invoice_details} }) {
1522 $item = $form->{invoice_details}->[$row - 1];
1524 map { $item->{$_} = $form->format_amount($myconfig, $item->{$_}) } qw(qty sellprice);
1526 map { $form->{"${_}_${row}"} = $item->{$_} } keys %{ $item };
1529 $form->{rowcount} = scalar @{ $form->{invoice_details} };
1531 delete @{$form}{qw(invoice_details paidaccounts storno paid)};
1533 # Restore the payment options from the user input.
1534 map { $form->{$_} = $payments{$_} } keys %payments;
1536 # Get the AP accno (which is normally done by Form::create_links()).
1540 LEFT JOIN chart c ON (at.chart_id = c.id)
1541 WHERE (trans_id = ?)
1542 AND ((c.link = 'AP') OR (c.link LIKE '%:AP') OR (c.link LIKE 'AP:%'))
1543 ORDER BY at.acc_trans_id
1546 ($form->{AP}) = selectfirst_array_query($form, $dbh, $query, conv_i($form->{id}));
1548 # Post the new payments.
1549 $self->post_invoice($myconfig, $form, $dbh, 1);
1551 restore_form($old_form);
1553 my $rc = $dbh->commit();
1556 $main::lxdebug->leave_sub();
1562 $::lxdebug->enter_sub;
1564 my ($self, %params) = @_;
1566 if (!$params{vendor_id} || !$params{invdate}) {
1567 $::lxdebug->leave_sub;
1568 return $params{default};
1571 my $dbh = $::form->get_standard_dbh;
1572 my $query = qq|SELECT ?::date + pt.terms_netto
1574 LEFT JOIN payment_terms pt ON (pt.id = v.payment_id)
1577 my ($duedate) = selectfirst_array_query($::form, $dbh, $query, $params{invdate}, $params{vendor_id});
1579 $duedate ||= $params{default};
1581 $::lxdebug->leave_sub;