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, bg.expense_accno_id_${taxzone} AS expense_accno_id, a.transdate
225 FROM invoice i, ar a, parts p, buchungsgruppen bg
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)
232 # ORDER BY transdate guarantees FIFO
234 # sold two items without having bought them yet, example result of query:
235 # id | qty | allocated | trans_id | inventory_accno_id | expense_accno_id | transdate
236 # ---+-----+-----------+----------+--------------------+------------------+------------
237 # 9 | 2 | 0 | 9 | 15 | 151 | 2011-01-05
239 # base_qty + allocated > 0 if article has already been sold but not bought yet
241 # select qty,allocated,base_qty,sellprice from invoice where trans_id = 9;
242 # qty | allocated | base_qty | sellprice
243 # -----+-----------+----------+------------
244 # 2 | 0 | 2 | 1000.00000
246 $sth = prepare_execute_query($form, $dbh, $query, conv_i($form->{"id_$i"}));
248 my $totalqty = $baseqty;
250 while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
251 my $qty = min $totalqty, ($ref->{base_qty} + $ref->{allocated});
252 $linetotal = $form->round_amount(($form->{"sellprice_$i"} * $qty) / $basefactor, 2);
254 if ( $::instance_conf->get_inventory_system eq 'perpetual' ) {
255 # Warenbestandsbuchungen nur bei Bestandsmethode
257 if ($ref->{allocated} < 0) {
259 # we have an entry for it already, adjust amount
260 $form->update_balance($dbh, "acc_trans", "amount",
261 qq| (trans_id = $ref->{trans_id})
262 AND (chart_id = $ref->{inventory_accno_id})
263 AND (transdate = '$ref->{transdate}')|,
266 $form->update_balance($dbh, "acc_trans", "amount",
267 qq| (trans_id = $ref->{trans_id})
268 AND (chart_id = $ref->{expense_accno_id})
269 AND (transdate = '$ref->{transdate}')|,
272 } elsif ($linetotal != 0) {
275 # add entry for inventory, this one is for the sold item
276 $query = qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate, taxkey, tax_id, chart_link) VALUES (?, ?, ?, ?,
281 ORDER BY startdate DESC LIMIT 1),
286 ORDER BY startdate DESC LIMIT 1),
287 (SELECT link FROM chart WHERE id = ?))|;
288 @values = ($ref->{trans_id}, $ref->{inventory_accno_id}, $linetotal, $ref->{transdate}, $ref->{inventory_accno_id}, $ref->{transdate}, $ref->{inventory_accno_id}, $ref->{transdate},
289 $ref->{inventory_accno_id});
290 do_query($form, $dbh, $query, @values);
293 $query = qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate, taxkey, tax_id, chart_link) VALUES (?, ?, ?, ?,
298 ORDER BY startdate DESC LIMIT 1),
303 ORDER BY startdate DESC LIMIT 1),
304 (SELECT link FROM chart WHERE id = ?))|;
305 @values = ($ref->{trans_id}, $ref->{expense_accno_id}, ($linetotal * -1), $ref->{transdate}, $ref->{expense_accno_id}, $ref->{transdate}, $ref->{expense_accno_id}, $ref->{transdate},
306 $ref->{expense_accno_id});
307 do_query($form, $dbh, $query, @values);
311 # update allocated for sold item
312 $form->update_balance($dbh, "invoice", "allocated", qq|id = $ref->{id}|, $qty * -1);
316 last if ($totalqty -= $qty) <= 0;
321 } else { # if ($form->{"inventory_accno_id_$i"})
322 # part doesn't have an inventory_accno_id
323 # lastcost of the part is updated at the end
325 $linetotal = $form->round_amount($form->{"sellprice_$i"} * $form->{"qty_$i"} / $price_factor, 2);
327 if ($form->{taxincluded}) {
328 $taxamount = $linetotal * ($taxrate / (1 + $taxrate));
329 $form->{"sellprice_$i"} = $form->{"sellprice_$i"} * (1 / (1 + $taxrate));
332 $taxamount = $linetotal * $taxrate;
335 $netamount += $linetotal;
337 if ($form->round_amount($taxrate, 7) == 0) {
338 if ($form->{taxincluded}) {
339 foreach $item (@taxaccounts) {
340 $taxamount = $linetotal * $form->{"${item}_rate"} / (1 + abs($form->{"${item}_rate"}));
341 $totaltax += $taxamount;
342 $form->{amount}{ $form->{id} }{$item} -= $taxamount;
345 map { $form->{amount}{ $form->{id} }{$_} -= $linetotal * $form->{"${_}_rate"} } @taxaccounts;
348 map { $form->{amount}{ $form->{id} }{$_} -= $taxamount * $form->{"${_}_rate"} / $taxrate } @taxaccounts;
351 $amount = $form->{"sellprice_$i"} * $form->{"qty_$i"} * $form->{exchangerate} / $price_factor;
352 $linetotal = $form->round_amount($form->{"sellprice_$i"} * $form->{"qty_$i"} / $price_factor, 2) * $form->{exchangerate};
353 $linetotal = $form->round_amount($linetotal, 2);
355 # this is the difference for expense
356 $expensediff += ($amount - $linetotal);
358 # add amount to expense
359 $form->{amount}{ $form->{id} }{ $form->{"expense_accno_$i"} } -= $linetotal;
361 $lastexpenseaccno = $form->{"expense_accno_$i"};
363 # adjust and round sellprice
364 $form->{"sellprice_$i"} = $form->round_amount($form->{"sellprice_$i"} * $form->{exchangerate}, $decimalplaces);
366 next if $payments_only;
369 $query = qq|UPDATE parts SET lastcost = ? WHERE id = ?|;
370 do_query($form, $dbh, $query, $form->{"sellprice_$i"} / $basefactor, conv_i($form->{"id_$i"}));
373 next if $payments_only;
375 # save detail record in invoice table
376 my ($invoice_id) = selectfirst_array_query($form, $dbh, qq|SELECT nextval('invoiceid')|);
379 qq|INSERT INTO invoice (id, trans_id, parts_id, description, longdescription, qty, base_qty,
380 sellprice, fxsellprice, discount, allocated, unit, deliverydate,
381 project_id, serialnumber, price_factor_id, price_factor, marge_price_factor)
382 VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, (SELECT factor FROM price_factors WHERE id = ?), ?)|;
383 @values = ($invoice_id, conv_i($form->{id}), conv_i($form->{"id_$i"}),
384 $form->{"description_$i"}, $restricter->process($form->{"longdescription_$i"}), $form->{"qty_$i"} * -1,
385 $baseqty * -1, $form->{"sellprice_$i"}, $fxsellprice, $form->{"discount_$i"}, $allocated,
386 $form->{"unit_$i"}, conv_date($form->{deliverydate}),
387 conv_i($form->{"project_id_$i"}), $form->{"serialnumber_$i"},
388 conv_i($form->{"price_factor_id_$i"}), conv_i($form->{"price_factor_id_$i"}), conv_i($form->{"marge_price_factor_$i"}));
389 do_query($form, $dbh, $query, @values);
391 CVar->save_custom_variables(module => 'IC',
392 sub_module => 'invoice',
393 trans_id => $invoice_id,
394 configs => $ic_cvar_configs,
396 name_prefix => 'ic_',
397 name_postfix => "_$i",
401 $h_item_unit->finish();
403 $project_id = conv_i($form->{"globalproject_id"});
405 $form->{datepaid} = $form->{invdate};
407 # all amounts are in natural state, netamount includes the taxes
408 # if tax is included, netamount is rounded to 2 decimal places,
412 for my $i (1 .. $form->{paidaccounts}) {
413 $form->{"paid_$i"} = $form->parse_amount($myconfig, $form->{"paid_$i"});
414 $form->{paid} += $form->{"paid_$i"};
415 $form->{datepaid} = $form->{"datepaid_$i"} if $form->{"datepaid_$i"};
418 my ($tax, $paiddiff) = (0, 0);
420 $netamount = $form->round_amount($netamount, 2);
422 # figure out rounding errors for amount paid and total amount
423 if ($form->{taxincluded}) {
425 $amount = $form->round_amount($netamount * $form->{exchangerate}, 2);
426 $paiddiff = $amount - $netamount * $form->{exchangerate};
427 $netamount = $amount;
429 foreach $item (split / /, $form->{taxaccounts}) {
430 $amount = $form->{amount}{ $form->{id} }{$item} * $form->{exchangerate};
431 $form->{amount}{ $form->{id} }{$item} = $form->round_amount($amount, 2);
433 $amount = $form->{amount}{ $form->{id} }{$item} * -1;
435 $netamount -= $amount;
438 $invoicediff += $paiddiff;
439 $expensediff += $paiddiff;
441 ######## this only applies to tax included
443 # in the sales invoice case rounding errors only have to be corrected for
444 # income accounts, it is enough to add the total rounding error to one of
445 # the income accounts, with the one assigned to the last row being used
446 # (lastinventoryaccno)
448 # in the purchase invoice case rounding errors may be split between
449 # inventory accounts and expense accounts. After rounding, an error of 1
450 # cent is introduced if the total rounding error exceeds 0.005. The total
451 # error is made up of $invoicediff and $expensediff, however, so if both
452 # values are below 0.005, but add up to a total >= 0.005, correcting
453 # lastinventoryaccno and lastexpenseaccno separately has no effect after
454 # rounding. This caused bug 1579. Therefore when the combined total exceeds
455 # 0.005, but neither do individually, the account with the larger value
456 # shall receive the total rounding error, and the next time it is rounded
457 # the 1 cent correction will be introduced.
459 $form->{amount}{ $form->{id} }{$lastinventoryaccno} -= $invoicediff if $lastinventoryaccno;
460 $form->{amount}{ $form->{id} }{$lastexpenseaccno} -= $expensediff if $lastexpenseaccno;
462 if ( (abs($expensediff)+abs($invoicediff)) >= 0.005 and abs($expensediff) < 0.005 and abs($invoicediff) < 0.005 ) {
464 # in total the rounding error adds up to 1 cent effectively, correct the
465 # larger of the two numbers
467 if ( abs($form->{amount}{ $form->{id} }{$lastinventoryaccno}) > abs($form->{amount}{ $form->{id} }{$lastexpenseaccno}) ) {
468 # $invoicediff has already been deducted, now also deduct expensediff
469 $form->{amount}{ $form->{id} }{$lastinventoryaccno} -= $expensediff;
471 # expensediff has already been deducted, now also deduct invoicediff
472 $form->{amount}{ $form->{id} }{$lastexpenseaccno} -= $invoicediff;
477 $amount = $form->round_amount($netamount * $form->{exchangerate}, 2);
478 $paiddiff = $amount - $netamount * $form->{exchangerate};
479 $netamount = $amount;
481 foreach my $item (split / /, $form->{taxaccounts}) {
482 $form->{amount}{ $form->{id} }{$item} = $form->round_amount($form->{amount}{ $form->{id} }{$item}, 2);
483 $amount = $form->round_amount( $form->{amount}{ $form->{id} }{$item} * $form->{exchangerate} * -1, 2);
484 $paiddiff += $amount - $form->{amount}{ $form->{id} }{$item} * $form->{exchangerate} * -1;
485 $form->{amount}{ $form->{id} }{$item} = $form->round_amount($amount * -1, 2);
486 $amount = $form->{amount}{ $form->{id} }{$item} * -1;
491 $form->{amount}{ $form->{id} }{ $form->{AP} } = $netamount + $tax;
494 $form->{paid} = $form->round_amount($form->{paid} * $form->{exchangerate} + $paiddiff, 2) if $form->{paid} != 0;
496 # update exchangerate
498 $form->update_exchangerate($dbh, $form->{currency}, $form->{invdate}, 0, $form->{exchangerate})
499 if ($form->{currency} ne $defaultcurrency) && !$exchangerate;
501 # record acc_trans transactions
502 foreach my $trans_id (keys %{ $form->{amount} }) {
503 foreach my $accno (keys %{ $form->{amount}{$trans_id} }) {
504 $form->{amount}{$trans_id}{$accno} = $form->round_amount($form->{amount}{$trans_id}{$accno}, 2);
507 next if $payments_only || !$form->{amount}{$trans_id}{$accno};
509 $query = qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate, taxkey, project_id, tax_id, chart_link)
510 VALUES (?, (SELECT id FROM chart WHERE accno = ?), ?, ?,
513 WHERE chart_id= (SELECT id
517 ORDER BY startdate DESC LIMIT 1),
521 WHERE chart_id= (SELECT id
525 ORDER BY startdate DESC LIMIT 1),
526 (SELECT link FROM chart WHERE accno = ?))|;
527 @values = ($trans_id, $accno, $form->{amount}{$trans_id}{$accno},
528 conv_date($form->{invdate}), $accno, conv_date($form->{invdate}), $project_id, $accno, conv_date($form->{invdate}), $accno);
529 do_query($form, $dbh, $query, @values);
533 # deduct payment differences from paiddiff
534 for my $i (1 .. $form->{paidaccounts}) {
535 if ($form->{"paid_$i"} != 0) {
536 $amount = $form->round_amount($form->{"paid_$i"} * $form->{exchangerate}, 2);
537 $paiddiff -= $amount - $form->{"paid_$i"} * $form->{exchangerate};
541 # force AP entry if 0
543 $form->{amount}{ $form->{id} }{ $form->{AP} } = $form->{paid} if $form->{amount}{$form->{id}}{$form->{AP}} == 0;
545 # record payments and offsetting AP
546 for my $i (1 .. $form->{paidaccounts}) {
547 if ($form->{"acc_trans_id_$i"}
549 && (SL::DB::Default->get->payments_changeable == 0)) {
553 next if $form->{"paid_$i"} == 0;
555 my ($accno) = split /--/, $form->{"AP_paid_$i"};
556 $form->{"datepaid_$i"} = $form->{invdate} unless ($form->{"datepaid_$i"});
557 $form->{datepaid} = $form->{"datepaid_$i"};
559 $amount = $form->round_amount($form->{"paid_$i"} * $form->{exchangerate} + $paiddiff, 2) * -1;
562 if ($form->{amount}{ $form->{id} }{ $form->{AP} } != 0) {
563 $query = qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate, taxkey, project_id, tax_id, chart_link)
564 VALUES (?, (SELECT id FROM chart WHERE accno = ?), ?, ?,
567 WHERE chart_id= (SELECT id
571 ORDER BY startdate DESC LIMIT 1),
575 WHERE chart_id= (SELECT id
579 ORDER BY startdate DESC LIMIT 1),
580 (SELECT link FROM chart WHERE accno = ?))|;
581 @values = (conv_i($form->{id}), $form->{AP}, $amount,
582 $form->{"datepaid_$i"}, $form->{AP}, conv_date($form->{"datepaid_$i"}), $project_id, $form->{AP}, conv_date($form->{"datepaid_$i"}), $form->{AP});
583 do_query($form, $dbh, $query, @values);
587 my $gldate = (conv_date($form->{"gldate_$i"}))? conv_date($form->{"gldate_$i"}) : conv_date($form->current_date($myconfig));
590 qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate, gldate, source, memo, taxkey, project_id, tax_id, chart_link)
591 VALUES (?, (SELECT id FROM chart WHERE accno = ?), ?, ?, ?, ?, ?,
594 WHERE chart_id= (SELECT id
595 FROM chart WHERE accno = ?)
597 ORDER BY startdate DESC LIMIT 1),
601 WHERE chart_id= (SELECT id
602 FROM chart WHERE accno = ?)
604 ORDER BY startdate DESC LIMIT 1),
605 (SELECT link FROM chart WHERE accno = ?))|;
606 @values = (conv_i($form->{id}), $accno, $form->{"paid_$i"}, $form->{"datepaid_$i"},
607 $gldate, $form->{"source_$i"}, $form->{"memo_$i"}, $accno, conv_date($form->{"datepaid_$i"}), $project_id, $accno, conv_date($form->{"datepaid_$i"}), $accno);
608 do_query($form, $dbh, $query, @values);
612 if ($form->{currency} eq $defaultcurrency) {
613 $form->{"exchangerate_$i"} = 1;
615 $exchangerate = $form->check_exchangerate($myconfig, $form->{currency}, $form->{"datepaid_$i"}, 'sell');
616 $form->{"exchangerate_$i"} = $exchangerate || $form->parse_amount($myconfig, $form->{"exchangerate_$i"});
619 # exchangerate difference
620 $form->{fx}{$accno}{ $form->{"datepaid_$i"} } += $form->{"paid_$i"} * ($form->{"exchangerate_$i"} - 1) + $paiddiff;
624 ($form->{"paid_$i"} * $form->{exchangerate}) -
625 ($form->{"paid_$i"} * $form->{"exchangerate_$i"});
627 $form->{fx}{ $form->{fxgain_accno} }{ $form->{"datepaid_$i"} } += $amount;
629 $form->{fx}{ $form->{fxloss_accno} }{ $form->{"datepaid_$i"} } += $amount;
634 # update exchange rate
635 $form->update_exchangerate($dbh, $form->{currency}, $form->{"datepaid_$i"}, 0, $form->{"exchangerate_$i"})
636 if ($form->{currency} ne $defaultcurrency) && !$exchangerate;
639 # record exchange rate differences and gains/losses
640 foreach my $accno (keys %{ $form->{fx} }) {
641 foreach my $transdate (keys %{ $form->{fx}{$accno} }) {
642 $form->{fx}{$accno}{$transdate} = $form->round_amount($form->{fx}{$accno}{$transdate}, 2);
643 next if ($form->{fx}{$accno}{$transdate} == 0);
645 $query = qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate, cleared, fx_transaction, taxkey, project_id, tax_id, chart_link)
646 VALUES (?, (SELECT id FROM chart WHERE accno = ?), ?, ?, '0', '1', 0, ?,
647 (SELECT id FROM tax WHERE taxkey=0 LIMIT 1),
648 (SELECT link FROM chart WHERE accno = ?))|;
649 @values = (conv_i($form->{id}), $accno, $form->{fx}{$accno}{$transdate}, conv_date($transdate), $project_id, $accno);
650 do_query($form, $dbh, $query, @values);
654 IO->set_datepaid(table => 'ap', id => $form->{id}, dbh => $dbh);
656 if ($payments_only) {
657 $query = qq|UPDATE ap SET paid = ? WHERE id = ?|;
658 do_query($form, $dbh, $query, $form->{paid}, conv_i($form->{id}));
660 if (!$provided_dbh) {
665 $main::lxdebug->leave_sub();
669 $amount = $netamount + $tax;
671 # set values which could be empty
672 my $taxzone_id = $form->{taxzone_id} * 1;
674 # Seit neuestem wird die department_id schon übergeben UND $form->department nicht mehr
675 # korrekt zusammengebaut. Sehr wahrscheinlich beim Umstieg auf T8 kaputt gegangen
676 # Ich lass den Code von 2005 erstmal noch stehen ;-) jb 03-2011
677 # copy & paste von IS.pm
678 if (!$form->{department_id}){
679 $form->{department_id} = (split /--/, $form->{department})[1];
681 $form->{invnumber} = $form->{id} unless $form->{invnumber};
683 $taxzone_id = 0 if (3 < $taxzone_id) || (0 > $taxzone_id);
686 $query = qq|UPDATE ap SET
687 invnumber = ?, ordnumber = ?, quonumber = ?, transdate = ?,
688 orddate = ?, quodate = ?, vendor_id = ?, amount = ?,
689 netamount = ?, paid = ?, duedate = ?,
690 invoice = ?, taxzone_id = ?, notes = ?, taxincluded = ?,
691 intnotes = ?, storno_id = ?, storno = ?,
692 cp_id = ?, employee_id = ?, department_id = ?, delivery_term_id = ?,
693 globalproject_id = ?, direct_debit = ?
696 $form->{invnumber}, $form->{ordnumber}, $form->{quonumber}, conv_date($form->{invdate}),
697 conv_date($form->{orddate}), conv_date($form->{quodate}), conv_i($form->{vendor_id}), $amount,
698 $netamount, $form->{paid}, conv_date($form->{duedate}),
699 '1', $taxzone_id, $form->{notes}, $form->{taxincluded} ? 't' : 'f',
700 $form->{intnotes}, conv_i($form->{storno_id}), $form->{storno} ? 't' : 'f',
701 conv_i($form->{cp_id}), conv_i($form->{employee_id}), conv_i($form->{department_id}), conv_i($form->{delivery_term_id}),
702 conv_i($form->{globalproject_id}),
703 $form->{direct_debit} ? 't' : 'f',
706 do_query($form, $dbh, $query, @values);
708 if ($form->{storno}) {
709 $query = qq|UPDATE ap SET paid = paid + amount WHERE id = ?|;
710 do_query($form, $dbh, $query, conv_i($form->{storno_id}));
712 $query = qq|UPDATE ap SET storno = 't' WHERE id = ?|;
713 do_query($form, $dbh, $query, conv_i($form->{storno_id}));
715 $query = qq!UPDATE ap SET intnotes = ? || intnotes WHERE id = ?!;
716 do_query($form, $dbh, $query, "Rechnung storniert am $form->{invdate} ", conv_i($form->{storno_id}));
718 $query = qq|UPDATE ap SET paid = amount WHERE id = ?|;
719 do_query($form, $dbh, $query, conv_i($form->{id}));
724 $form->{name} = $form->{vendor};
725 $form->{name} =~ s/--\Q$form->{vendor_id}\E//;
726 $form->add_shipto($dbh, $form->{id}, "AP");
728 # delete zero entries
729 do_query($form, $dbh, qq|DELETE FROM acc_trans WHERE amount = 0|);
731 Common::webdav_folder($form);
733 # Link this record to the records it was created from.
734 RecordLinks->create_links('dbh' => $dbh,
736 'from_table' => 'oe',
737 'from_ids' => $form->{convert_from_oe_ids},
739 'to_id' => $form->{id},
741 delete $form->{convert_from_oe_ids};
743 my @convert_from_do_ids = map { $_ * 1 } grep { $_ } split m/\s+/, $form->{convert_from_do_ids};
744 if (scalar @convert_from_do_ids) {
745 DO->close_orders('dbh' => $dbh,
746 'ids' => \@convert_from_do_ids);
748 RecordLinks->create_links('dbh' => $dbh,
750 'from_table' => 'delivery_orders',
751 'from_ids' => \@convert_from_do_ids,
753 'to_id' => $form->{id},
756 delete $form->{convert_from_do_ids};
758 ARAP->close_orders_if_billed('dbh' => $dbh,
759 'arap_id' => $form->{id},
762 # safety check datev export
763 if ($::instance_conf->get_datev_check_on_purchase_invoice) {
764 my $transdate = $::form->{invdate} ? DateTime->from_lxoffice($::form->{invdate}) : undef;
765 $transdate ||= DateTime->today;
767 my $datev = SL::DATEV->new(
768 exporttype => DATEV_ET_BUCHUNGEN,
769 format => DATEV_FORMAT_KNE,
773 trans_id => $form->{id},
778 if ($datev->errors) {
780 die join "\n", $::locale->text('DATEV check returned errors:'), $datev->errors;
785 if (!$provided_dbh) {
786 $rc = $dbh->commit();
790 $main::lxdebug->leave_sub();
795 sub reverse_invoice {
796 $main::lxdebug->enter_sub();
798 my ($dbh, $form) = @_;
800 # reverse inventory items
802 qq|SELECT i.parts_id, p.inventory_accno_id, p.expense_accno_id, i.qty, i.allocated, i.sellprice
803 FROM invoice i, parts p
804 WHERE (i.parts_id = p.id)
805 AND (i.trans_id = ?)|;
806 my $sth = prepare_execute_query($form, $dbh, $query, conv_i($form->{id}));
810 while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
811 $netamount += $form->round_amount($ref->{sellprice} * $ref->{qty} * -1, 2);
813 next unless $ref->{inventory_accno_id};
815 # if $ref->{allocated} > 0 than we sold that many items
816 next if ($ref->{allocated} <= 0);
818 # get references for sold items
820 qq|SELECT i.id, i.trans_id, i.allocated, a.transdate
822 WHERE (i.parts_id = ?)
823 AND (i.allocated < 0)
824 AND (i.trans_id = a.id)
825 ORDER BY transdate DESC|;
826 my $sth2 = prepare_execute_query($form, $dbh, $query, $ref->{parts_id});
828 while (my $pthref = $sth2->fetchrow_hashref("NAME_lc")) {
829 my $qty = $ref->{allocated};
830 if (($ref->{allocated} + $pthref->{allocated}) > 0) {
831 $qty = $pthref->{allocated} * -1;
834 my $amount = $form->round_amount($ref->{sellprice} * $qty, 2);
837 $form->update_balance($dbh, "invoice", "allocated", qq|id = $pthref->{id}|, $qty);
839 $form->update_balance($dbh, "acc_trans", "amount",
840 qq| (trans_id = $pthref->{trans_id})
841 AND (chart_id = $ref->{expense_accno_id})
842 AND (transdate = '$pthref->{transdate}')|,
845 $form->update_balance($dbh, "acc_trans", "amount",
846 qq| (trans_id = $pthref->{trans_id})
847 AND (chart_id = $ref->{inventory_accno_id})
848 AND (transdate = '$pthref->{transdate}')|,
851 last if (($ref->{allocated} -= $qty) <= 0);
857 my $id = conv_i($form->{id});
860 $query = qq|DELETE FROM acc_trans WHERE trans_id = ?|;
861 do_query($form, $dbh, $query, $id);
863 # delete invoice entries
864 $query = qq|DELETE FROM invoice WHERE trans_id = ?|;
865 do_query($form, $dbh, $query, $id);
867 $query = qq|DELETE FROM shipto WHERE (trans_id = ?) AND (module = 'AP')|;
868 do_query($form, $dbh, $query, $id);
870 $main::lxdebug->leave_sub();
874 $main::lxdebug->enter_sub();
876 my ($self, $myconfig, $form) = @_;
878 # connect to database
879 my $dbh = $form->dbconnect_noauto($myconfig);
881 &reverse_invoice($dbh, $form);
883 # delete zero entries
884 $query = qq|DELETE FROM acc_trans WHERE amount = 0|;
885 do_query($form, $dbh, $query);
888 $query = qq|DELETE FROM ap WHERE id = ?|;
889 do_query($form, $dbh, $query, conv_i($form->{id}));
891 my $rc = $dbh->commit;
894 $main::lxdebug->leave_sub();
899 sub retrieve_invoice {
900 $main::lxdebug->enter_sub();
902 my ($self, $myconfig, $form) = @_;
904 # connect to database
905 my $dbh = $form->dbconnect($myconfig);
907 my ($query, $sth, $ref, $q_invdate);
910 $q_invdate = qq|, COALESCE((SELECT transdate FROM ar WHERE id = (SELECT MAX(id) FROM ar)), current_date) AS invdate|;
911 if ($form->{vendor_id}) {
912 my $vendor_id = $dbh->quote($form->{vendor_id} * 1);
914 qq|, COALESCE((SELECT transdate FROM ar WHERE id = (SELECT MAX(id) FROM ar)), current_date) +
915 COALESCE((SELECT pt.terms_netto
917 LEFT JOIN payment_terms pt ON (v.payment_id = pt.id)
918 WHERE v.id = $vendor_id),
923 # get default accounts and last invoice number
926 (SELECT c.accno FROM chart c WHERE d.inventory_accno_id = c.id) AS inventory_accno,
927 (SELECT c.accno FROM chart c WHERE d.income_accno_id = c.id) AS income_accno,
928 (SELECT c.accno FROM chart c WHERE d.expense_accno_id = c.id) AS expense_accno,
929 (SELECT c.accno FROM chart c WHERE d.fxgain_accno_id = c.id) AS fxgain_accno,
930 (SELECT c.accno FROM chart c WHERE d.fxloss_accno_id = c.id) AS fxloss_accno
933 $ref = selectfirst_hashref_query($form, $dbh, $query);
934 map { $form->{$_} = $ref->{$_} } keys %$ref;
938 $main::lxdebug->leave_sub();
944 $query = qq|SELECT cp_id, invnumber, transdate AS invdate, duedate,
945 orddate, quodate, globalproject_id,
946 ordnumber, quonumber, paid, taxincluded, notes, taxzone_id, storno, gldate,
947 intnotes, (SELECT cu.name FROM currencies cu WHERE cu.id=ap.currency_id) AS currency, direct_debit,
951 $ref = selectfirst_hashref_query($form, $dbh, $query, conv_i($form->{id}));
952 map { $form->{$_} = $ref->{$_} } keys %$ref;
954 $form->{exchangerate} = $form->get_exchangerate($dbh, $form->{currency}, $form->{invdate}, "sell");
957 $query = qq|SELECT * FROM shipto WHERE (trans_id = ?) AND (module = 'AP')|;
958 $ref = selectfirst_hashref_query($form, $dbh, $query, conv_i($form->{id}));
960 map { $form->{$_} = $ref->{$_} } keys %$ref;
962 my $transdate = $form->{invdate} ? $dbh->quote($form->{invdate}) : "current_date";
963 my $taxzone_id = $form->{taxzone_id} * 1;
965 $taxzone_id = 0 if ((3 < $taxzone_id) || (0 > $taxzone_id));
967 # retrieve individual items
970 c1.accno AS inventory_accno, c1.new_chart_id AS inventory_new_chart, date($transdate) - c1.valid_from AS inventory_valid,
971 c2.accno AS income_accno, c2.new_chart_id AS income_new_chart, date($transdate) - c2.valid_from AS income_valid,
972 c3.accno AS expense_accno, c3.new_chart_id AS expense_new_chart, date($transdate) - c3.valid_from AS expense_valid,
975 i.description, i.longdescription, i.qty, i.fxsellprice AS sellprice, i.parts_id AS id, i.unit, i.deliverydate, i.project_id, i.serialnumber,
976 i.price_factor_id, i.price_factor, i.marge_price_factor, i.discount,
977 p.partnumber, p.inventory_accno_id AS part_inventory_accno_id, pr.projectnumber, pg.partsgroup
980 JOIN parts p ON (i.parts_id = p.id)
981 LEFT JOIN chart c1 ON ((SELECT inventory_accno_id FROM buchungsgruppen WHERE id = p.buchungsgruppen_id) = c1.id)
982 LEFT JOIN chart c2 ON ((SELECT income_accno_id_${taxzone_id} FROM buchungsgruppen WHERE id = p.buchungsgruppen_id) = c2.id)
983 LEFT JOIN chart c3 ON ((SELECT expense_accno_id_${taxzone_id} FROM buchungsgruppen WHERE id = p.buchungsgruppen_id) = c3.id)
984 LEFT JOIN project pr ON (i.project_id = pr.id)
985 LEFT JOIN partsgroup pg ON (pg.id = p.partsgroup_id)
990 $sth = prepare_execute_query($form, $dbh, $query, conv_i($form->{id}));
992 while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
993 # Retrieve custom variables.
994 my $cvars = CVar->get_custom_variables(dbh => $dbh,
996 sub_module => 'invoice',
997 trans_id => $ref->{invoice_id},
999 map { $ref->{"ic_cvar_$_->{name}"} = $_->{value} } @{ $cvars };
1000 delete $ref->{invoice_id};
1002 map({ delete($ref->{$_}); } qw(inventory_accno inventory_new_chart inventory_valid)) if !$ref->{"part_inventory_accno_id"};
1003 delete($ref->{"part_inventory_accno_id"});
1005 foreach my $type (qw(inventory income expense)) {
1006 while ($ref->{"${type}_new_chart"} && ($ref->{"${type}_valid"} >=0)) {
1007 my $query = qq|SELECT accno, new_chart_id, date($transdate) - valid_from FROM chart WHERE id = ?|;
1008 @$ref{ map $type.$_, qw(_accno _new_chart _valid) } = selectrow_query($form, $dbh, $query, $ref->{"${type}_new_chart"});
1012 # get tax rates and description
1013 my $accno_id = ($form->{vc} eq "customer") ? $ref->{income_accno} : $ref->{expense_accno};
1015 qq|SELECT c.accno, t.taxdescription, t.rate, t.taxnumber FROM tax t
1016 LEFT JOIN chart c ON (c.id = t.chart_id)
1018 (SELECT tk.tax_id FROM taxkeys tk
1019 WHERE tk.chart_id = (SELECT id FROM chart WHERE accno = ?)
1020 AND (startdate <= $transdate)
1021 ORDER BY startdate DESC
1024 my $stw = prepare_execute_query($form, $dbh, $query, $accno_id);
1025 $ref->{taxaccounts} = "";
1028 while (my $ptr = $stw->fetchrow_hashref("NAME_lc")) {
1029 if (($ptr->{accno} eq "") && ($ptr->{rate} == 0)) {
1034 $ref->{taxaccounts} .= "$ptr->{accno} ";
1036 if (!($form->{taxaccounts} =~ /\Q$ptr->{accno}\E/)) {
1037 $form->{"$ptr->{accno}_rate"} = $ptr->{rate};
1038 $form->{"$ptr->{accno}_description"} = $ptr->{taxdescription};
1039 $form->{"$ptr->{accno}_taxnumber"} = $ptr->{taxnumber};
1040 $form->{taxaccounts} .= "$ptr->{accno} ";
1045 chop $ref->{taxaccounts};
1046 push @{ $form->{invoice_details} }, $ref;
1051 Common::webdav_folder($form);
1055 $main::lxdebug->leave_sub();
1059 $main::lxdebug->enter_sub();
1061 my ($self, $myconfig, $form, $params) = @_;
1063 $params = $form unless defined $params && ref $params eq "HASH";
1065 # connect to database
1066 my $dbh = $form->dbconnect($myconfig);
1068 my $dateformat = $myconfig->{dateformat};
1069 $dateformat .= "yy" if $myconfig->{dateformat} !~ /^y/;
1071 my $vid = conv_i($params->{vendor_id});
1072 my $vnr = conv_i($params->{vendornumber});
1075 ($params->{invdate})
1076 ? "to_date(" . $dbh->quote($params->{invdate}) . ", '$dateformat')"
1083 $where .= 'AND v.id = ?';
1087 $where .= 'AND v.vendornumber = ?';
1092 v.id AS vendor_id, v.name AS vendor, v.discount as vendor_discount,
1093 v.creditlimit, v.terms, v.notes AS intnotes,
1094 v.email, v.cc, v.bcc, v.language_id, v.payment_id, v.delivery_term_id,
1095 v.street, v.zipcode, v.city, v.country, v.taxzone_id, cu.name AS curr, v.direct_debit,
1096 $duedate + COALESCE(pt.terms_netto, 0) AS duedate,
1097 b.description AS business
1099 LEFT JOIN business b ON (b.id = v.business_id)
1100 LEFT JOIN payment_terms pt ON (v.payment_id = pt.id)
1101 LEFT JOIN currencies cu ON (v.currency_id = cu.id)
1103 my $ref = selectfirst_hashref_query($form, $dbh, $query, @values);
1104 map { $params->{$_} = $ref->{$_} } keys %$ref;
1106 # use vendor currency
1107 $form->{currency} = $form->{curr};
1109 $params->{creditremaining} = $params->{creditlimit};
1111 $query = qq|SELECT SUM(amount - paid) FROM ap WHERE vendor_id = ?|;
1112 my ($unpaid_invoices) = selectfirst_array_query($form, $dbh, $query, $vid);
1113 $params->{creditremaining} -= $unpaid_invoices;
1115 $query = qq|SELECT o.amount,
1118 WHERE (e.currency_id = o.currency_id)
1119 AND (e.transdate = o.transdate)) AS exch
1121 WHERE (o.vendor_id = ?) AND (o.quotation = '0') AND (o.closed = '0')|;
1122 my $sth = prepare_execute_query($form, $dbh, $query, $vid);
1123 while (my ($amount, $exch) = $sth->fetchrow_array()) {
1124 $exch = 1 unless $exch;
1125 $params->{creditremaining} -= $amount * $exch;
1129 # get shipto if we do not convert an order or invoice
1130 if (!$params->{shipto}) {
1131 delete @{$params}{qw(shiptoname shiptostreet shiptozipcode shiptocity shiptocountry shiptocontact shiptophone shiptofax shiptoemail)};
1133 $query = qq|SELECT * FROM shipto WHERE (trans_id = ?) AND (module= 'CT')|;
1134 $ref = selectfirst_hashref_query($form, $dbh, $query, $vid);
1135 @{$params}{keys %$ref} = @{$ref}{keys %$ref};
1136 map { $params->{$_} = $ref->{$_} } keys %$ref;
1139 if (!$params->{id} && $params->{type} !~ /_(order|quotation)/) {
1140 # setup last accounts used
1142 qq|SELECT c.id, c.accno, c.description, c.link, c.category
1144 JOIN acc_trans ac ON (ac.chart_id = c.id)
1145 JOIN ap a ON (a.id = ac.trans_id)
1146 WHERE (a.vendor_id = ?)
1147 AND (NOT ((c.link LIKE '%_tax%') OR (c.link LIKE '%_paid%')))
1148 AND (a.id IN (SELECT max(a2.id) FROM ap a2 WHERE a2.vendor_id = ?))|;
1149 my $refs = selectall_hashref_query($form, $dbh, $query, $vid, $vid);
1153 if ($ref->{category} eq 'E') {
1155 my ($tax_id, $rate);
1156 if ($params->{initial_transdate}) {
1157 my $tax_query = qq|SELECT tk.tax_id, t.rate FROM taxkeys tk
1158 LEFT JOIN tax t ON (tk.tax_id = t.id)
1159 WHERE (tk.chart_id = ?) AND (startdate <= ?)
1160 ORDER BY tk.startdate DESC
1162 ($tax_id, $rate) = selectrow_query($form, $dbh, $tax_query, $ref->{id}, $params->{initial_transdate});
1163 $params->{"taxchart_$i"} = "${tax_id}--${rate}";
1166 $params->{"AP_amount_$i"} = "$ref->{accno}--$tax_id";
1169 if ($ref->{category} eq 'L') {
1170 $params->{APselected} = $params->{AP_1} = $ref->{accno};
1173 $params->{rowcount} = $i if ($i && !$params->{type});
1178 $main::lxdebug->leave_sub();
1182 $main::lxdebug->enter_sub();
1184 my ($self, $myconfig, $form) = @_;
1186 # connect to database
1187 my $dbh = $form->dbconnect($myconfig);
1189 my $i = $form->{rowcount};
1191 # don't include assemblies or obsolete parts
1192 my $where = "NOT p.assembly = '1' AND NOT p.obsolete = '1'";
1195 foreach my $table_column (qw(p.partnumber p.description pg.partsgroup)) {
1196 my $field = (split m{\.}, $table_column)[1];
1197 next unless $form->{"${field}_${i}"};
1198 $where .= " AND lower(${table_column}) LIKE lower(?)";
1199 push @values, '%' . $form->{"${field}_${i}"} . '%';
1201 #Es soll auch nach EAN gesucht werden, ohne Einschränkung durch Beschreibung
1202 if ($form->{"partnumber_$i"} && !$form->{"description_$i"}) {
1203 $where .= qq| OR (NOT p.obsolete = '1' AND p.ean = ? )|;
1204 push @values, $form->{"partnumber_$i"};
1207 # Search for part ID overrides all other criteria.
1208 if ($form->{"id_${i}"}) {
1209 $where = qq|p.id = ?|;
1210 @values = ($form->{"id_${i}"});
1213 if ($form->{"description_$i"}) {
1214 $where .= " ORDER BY p.description";
1216 $where .= " ORDER BY p.partnumber";
1220 if ($form->{type} eq "invoice") {
1221 $transdate = $form->{deliverydate} ? $dbh->quote($form->{deliverydate})
1222 : $form->{invdate} ? $dbh->quote($form->{invdate})
1225 $transdate = $form->{transdate} ? $dbh->quote($form->{transdate}) : "current_date";
1228 my $taxzone_id = $form->{taxzone_id} * 1;
1229 $taxzone_id = 0 if ((3 < $taxzone_id) || (0 > $taxzone_id));
1233 p.id, p.partnumber, p.description, p.lastcost AS sellprice, p.listprice,
1234 p.unit, p.assembly, p.onhand, p.formel,
1235 p.notes AS partnotes, p.notes AS longdescription, p.not_discountable,
1236 p.inventory_accno_id, p.price_factor_id,
1238 pfac.factor AS price_factor,
1240 c1.accno AS inventory_accno,
1241 c1.new_chart_id AS inventory_new_chart,
1242 date($transdate) - c1.valid_from AS inventory_valid,
1244 c2.accno AS income_accno,
1245 c2.new_chart_id AS income_new_chart,
1246 date($transdate) - c2.valid_from AS income_valid,
1248 c3.accno AS expense_accno,
1249 c3.new_chart_id AS expense_new_chart,
1250 date($transdate) - c3.valid_from AS expense_valid,
1255 LEFT JOIN chart c1 ON
1256 ((SELECT inventory_accno_id
1257 FROM buchungsgruppen
1258 WHERE id = p.buchungsgruppen_id) = c1.id)
1259 LEFT JOIN chart c2 ON
1260 ((SELECT income_accno_id_${taxzone_id}
1261 FROM buchungsgruppen
1262 WHERE id = p.buchungsgruppen_id) = c2.id)
1263 LEFT JOIN chart c3 ON
1264 ((SELECT expense_accno_id_${taxzone_id}
1265 FROM buchungsgruppen
1266 WHERE id = p.buchungsgruppen_id) = c3.id)
1267 LEFT JOIN partsgroup pg ON (pg.id = p.partsgroup_id)
1268 LEFT JOIN price_factors pfac ON (pfac.id = p.price_factor_id)
1270 my $sth = prepare_execute_query($form, $dbh, $query, @values);
1272 my @translation_queries = ( [ qq|SELECT tr.translation, tr.longdescription
1274 WHERE tr.language_id = ? AND tr.parts_id = ?| ],
1275 [ qq|SELECT tr.translation, tr.longdescription
1277 WHERE tr.language_id IN
1280 WHERE article_code = (SELECT article_code FROM language WHERE id = ?))
1283 map { push @{ $_ }, prepare_query($form, $dbh, $_->[0]) } @translation_queries;
1285 $form->{item_list} = [];
1286 while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
1288 # In der Buchungsgruppe ist immer ein Bestandskonto verknuepft, auch wenn
1289 # es sich um eine Dienstleistung handelt. Bei Dienstleistungen muss das
1290 # Buchungskonto also aus dem Ergebnis rausgenommen werden.
1291 if (!$ref->{inventory_accno_id}) {
1292 map({ delete($ref->{"inventory_${_}"}); } qw(accno new_chart valid));
1294 delete($ref->{inventory_accno_id});
1296 # get tax rates and description
1297 my $accno_id = ($form->{vc} eq "customer") ? $ref->{income_accno} : $ref->{expense_accno};
1299 qq|SELECT c.accno, t.taxdescription, t.rate, t.taxnumber
1301 LEFT JOIN chart c on (c.id = t.chart_id)
1309 AND (startdate <= $transdate)
1310 ORDER BY startdate DESC
1313 my $stw = prepare_execute_query($form, $dbh, $query, $accno_id);
1315 $ref->{taxaccounts} = "";
1317 while (my $ptr = $stw->fetchrow_hashref("NAME_lc")) {
1319 if (($ptr->{accno} eq "") && ($ptr->{rate} == 0)) {
1324 $ref->{taxaccounts} .= "$ptr->{accno} ";
1326 if (!($form->{taxaccounts} =~ /\Q$ptr->{accno}\E/)) {
1327 $form->{"$ptr->{accno}_rate"} = $ptr->{rate};
1328 $form->{"$ptr->{accno}_description"} = $ptr->{taxdescription};
1329 $form->{"$ptr->{accno}_taxnumber"} = $ptr->{taxnumber};
1330 $form->{taxaccounts} .= "$ptr->{accno} ";
1333 if ($form->{language_id}) {
1334 for my $spec (@translation_queries) {
1335 do_statement($form, $spec->[1], $spec->[0], conv_i($form->{language_id}), conv_i($ref->{id}));
1336 my ($translation, $longdescription) = $spec->[1]->fetchrow_array;
1337 next unless $translation;
1338 $ref->{description} = $translation;
1339 $ref->{longdescription} = $longdescription;
1346 chop $ref->{taxaccounts};
1348 $ref->{onhand} *= 1;
1350 push @{ $form->{item_list} }, $ref;
1355 $_->[1]->finish for @translation_queries;
1357 foreach my $item (@{ $form->{item_list} }) {
1358 my $custom_variables = CVar->get_custom_variables(module => 'IC',
1359 trans_id => $item->{id},
1363 map { $item->{"ic_cvar_" . $_->{name} } = $_->{value} } @{ $custom_variables };
1368 $main::lxdebug->leave_sub();
1371 sub vendor_details {
1372 $main::lxdebug->enter_sub();
1374 my ($self, $myconfig, $form, @wanted_vars) = @_;
1376 # connect to database
1377 my $dbh = $form->dbconnect($myconfig);
1381 # get contact id, set it if nessessary
1382 $form->{cp_id} *= 1;
1384 if ($form->{cp_id}) {
1385 $contact = "AND cp.cp_id = ?";
1386 push @values, $form->{cp_id};
1389 # get rest for the vendor
1390 # fax and phone and email as vendor*
1392 qq|SELECT ct.*, cp.*, ct.notes as vendornotes, phone as vendorphone, fax as vendorfax, email as vendoremail,
1395 LEFT JOIN contacts cp ON (ct.id = cp.cp_cv_id)
1396 LEFT JOIN currencies cu ON (ct.currency_id = cu.id)
1397 WHERE (ct.id = ?) $contact
1400 my $ref = selectfirst_hashref_query($form, $dbh, $query, $form->{vendor_id}, @values);
1402 # remove id and taxincluded before copy back
1403 delete @$ref{qw(id taxincluded)};
1405 @wanted_vars = grep({ $_ } @wanted_vars);
1406 if (scalar(@wanted_vars) > 0) {
1408 map({ $h_wanted_vars{$_} = 1; } @wanted_vars);
1409 map({ delete($ref->{$_}) unless ($h_wanted_vars{$_}); } keys(%{$ref}));
1412 map { $form->{$_} = $ref->{$_} } keys %$ref;
1414 my $custom_variables = CVar->get_custom_variables('dbh' => $dbh,
1416 'trans_id' => $form->{vendor_id});
1417 map { $form->{"vc_cvar_$_->{name}"} = $_->{value} } @{ $custom_variables };
1419 $form->{cp_greeting} = GenericTranslations->get('dbh' => $dbh,
1420 'translation_type' => 'greetings::' . ($form->{cp_gender} eq 'f' ? 'female' : 'male'),
1421 'allow_fallback' => 1);
1425 $main::lxdebug->leave_sub();
1429 $main::lxdebug->enter_sub();
1431 my ($self, $myconfig, $form) = @_;
1433 # connect to database
1434 my $dbh = $form->dbconnect($myconfig);
1437 qq|SELECT accno, description, link
1439 WHERE link LIKE '%IC%'
1441 my $sth = prepare_execute_query($query, $dbh, $query);
1443 while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
1444 foreach my $key (split(/:/, $ref->{link})) {
1446 push @{ $form->{IC_links}{$key} },
1447 { accno => $ref->{accno},
1448 description => $ref->{description} };
1456 $main::lxdebug->leave_sub();
1459 sub _delete_payments {
1460 $main::lxdebug->enter_sub();
1462 my ($self, $form, $dbh) = @_;
1464 my @delete_acc_trans_ids;
1466 # Delete old payment entries from acc_trans.
1468 qq|SELECT acc_trans_id
1470 WHERE (trans_id = ?) AND fx_transaction
1474 SELECT at.acc_trans_id
1476 LEFT JOIN chart c ON (at.chart_id = c.id)
1477 WHERE (trans_id = ?) AND (c.link LIKE '%AP_paid%')|;
1478 push @delete_acc_trans_ids, selectall_array_query($form, $dbh, $query, conv_i($form->{id}), conv_i($form->{id}));
1481 qq|SELECT at.acc_trans_id
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
1488 push @delete_acc_trans_ids, selectall_array_query($form, $dbh, $query, conv_i($form->{id}));
1490 if (@delete_acc_trans_ids) {
1491 $query = qq|DELETE FROM acc_trans WHERE acc_trans_id IN (| . join(", ", @delete_acc_trans_ids) . qq|)|;
1492 do_query($form, $dbh, $query);
1495 $main::lxdebug->leave_sub();
1499 $main::lxdebug->enter_sub();
1501 my ($self, $myconfig, $form, $locale) = @_;
1503 # connect to database, turn off autocommit
1504 my $dbh = $form->dbconnect_noauto($myconfig);
1506 my (%payments, $old_form, $row, $item, $query, %keep_vars);
1508 $old_form = save_form();
1510 # Delete all entries in acc_trans from prior payments.
1511 if (SL::DB::Default->get->payments_changeable != 0) {
1512 $self->_delete_payments($form, $dbh);
1515 # Save the new payments the user made before cleaning up $form.
1516 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 };
1518 # Clean up $form so that old content won't tamper the results.
1519 %keep_vars = map { $_, 1 } qw(login password id);
1520 map { delete $form->{$_} unless $keep_vars{$_} } keys %{ $form };
1522 # Retrieve the invoice from the database.
1523 $self->retrieve_invoice($myconfig, $form);
1525 # Set up the content of $form in the way that IR::post_invoice() expects.
1526 $form->{exchangerate} = $form->format_amount($myconfig, $form->{exchangerate});
1528 for $row (1 .. scalar @{ $form->{invoice_details} }) {
1529 $item = $form->{invoice_details}->[$row - 1];
1531 map { $item->{$_} = $form->format_amount($myconfig, $item->{$_}) } qw(qty sellprice);
1533 map { $form->{"${_}_${row}"} = $item->{$_} } keys %{ $item };
1536 $form->{rowcount} = scalar @{ $form->{invoice_details} };
1538 delete @{$form}{qw(invoice_details paidaccounts storno paid)};
1540 # Restore the payment options from the user input.
1541 map { $form->{$_} = $payments{$_} } keys %payments;
1543 # Get the AP accno (which is normally done by Form::create_links()).
1547 LEFT JOIN chart c ON (at.chart_id = c.id)
1548 WHERE (trans_id = ?)
1549 AND ((c.link = 'AP') OR (c.link LIKE '%:AP') OR (c.link LIKE 'AP:%'))
1550 ORDER BY at.acc_trans_id
1553 ($form->{AP}) = selectfirst_array_query($form, $dbh, $query, conv_i($form->{id}));
1555 # Post the new payments.
1556 $self->post_invoice($myconfig, $form, $dbh, 1);
1558 restore_form($old_form);
1560 my $rc = $dbh->commit();
1563 $main::lxdebug->leave_sub();
1569 $::lxdebug->enter_sub;
1571 my ($self, %params) = @_;
1573 if (!$params{vendor_id} || !$params{invdate}) {
1574 $::lxdebug->leave_sub;
1575 return $params{default};
1578 my $dbh = $::form->get_standard_dbh;
1579 my $query = qq|SELECT ?::date + pt.terms_netto
1581 LEFT JOIN payment_terms pt ON (pt.id = v.payment_id)
1584 my ($duedate) = selectfirst_array_query($::form, $dbh, $query, $params{invdate}, $params{vendor_id});
1586 $duedate ||= $params{default};
1588 $::lxdebug->leave_sub;