1 #=====================================================================
4 # Based on SQL-Ledger Version 2.1.9
5 # Web http://www.lx-office.org
7 #=====================================================================
8 # SQL-Ledger Accounting
11 # Author: Dieter Simader
12 # Email: dsimader@sql-ledger.org
13 # Web: http://www.sql-ledger.org
17 # This program is free software; you can redistribute it and/or modify
18 # it under the terms of the GNU General Public License as published by
19 # the Free Software Foundation; either version 2 of the License, or
20 # (at your option) any later version.
22 # This program is distributed in the hope that it will be useful,
23 # but WITHOUT ANY WARRANTY; without even the implied warranty of
24 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
25 # GNU General Public License for more details.
26 # You should have received a copy of the GNU General Public License
27 # along with this program; if not, write to the Free Software
28 # Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
29 #======================================================================
31 # Inventory received module
33 #======================================================================
41 use SL::DATEV qw(:CONSTANTS);
44 use SL::GenericTranslations;
48 use List::Util qw(min);
53 $main::lxdebug->enter_sub();
55 my ($self, $myconfig, $form, $provided_dbh, $payments_only) = @_;
57 # connect to database, turn off autocommit
58 my $dbh = $provided_dbh ? $provided_dbh : $form->dbconnect_noauto($myconfig);
59 $form->{defaultcurrency} = $form->get_default_currency($myconfig);
60 my $defaultcurrency = $form->{defaultcurrency};
62 my $ic_cvar_configs = CVar->get_configs(module => 'IC',
65 my ($query, $sth, @values, $project_id);
66 my ($allocated, $taxrate, $taxamount, $taxdiff, $item);
67 my ($amount, $linetotal, $lastinventoryaccno, $lastexpenseaccno);
68 my ($netamount, $invoicediff, $expensediff) = (0, 0, 0);
70 my ($basefactor, $baseqty, @taxaccounts, $totaltax);
72 my $all_units = AM->retrieve_units($myconfig, $form);
75 if (!$payments_only) {
77 &reverse_invoice($dbh, $form);
79 ($form->{id}) = selectrow_query($form, $dbh, qq|SELECT nextval('glid')|);
80 do_query($form, $dbh, qq|INSERT INTO ap (id, invnumber, curr) VALUES (?, '', (SELECT id FROM currencies WHERE curr=?))|, $form->{id}, $form->{currency});
84 if ($form->{currency} eq $defaultcurrency) {
85 $form->{exchangerate} = 1;
87 $exchangerate = $form->check_exchangerate($myconfig, $form->{currency}, $form->{invdate}, 'sell');
90 $form->{exchangerate} = $exchangerate || $form->parse_amount($myconfig, $form->{exchangerate});
91 $form->{exchangerate} = 1 unless ($form->{exchangerate} * 1);
94 my $q_item_unit = qq|SELECT unit FROM parts WHERE id = ?|;
95 my $h_item_unit = prepare_query($form, $dbh, $q_item_unit);
97 $form->get_lists('price_factors' => 'ALL_PRICE_FACTORS');
98 my %price_factors = map { $_->{id} => $_->{factor} } @{ $form->{ALL_PRICE_FACTORS} };
101 for my $i (1 .. $form->{rowcount}) {
102 next unless $form->{"id_$i"};
104 $form->{"qty_$i"} = $form->parse_amount($myconfig, $form->{"qty_$i"});
105 $form->{"qty_$i"} *= -1 if $form->{storno};
107 if ( $::instance_conf->get_inventory_system eq 'periodic') {
108 # inventory account number is overwritten with expense account number, so
109 # never book incoming to inventory account but always to expense account
110 $form->{"inventory_accno_$i"} = $form->{"expense_accno_$i"}
114 if (!$item_units{$form->{"id_$i"}}) {
115 do_statement($form, $h_item_unit, $q_item_unit, $form->{"id_$i"});
116 ($item_units{$form->{"id_$i"}}) = $h_item_unit->fetchrow_array();
119 my $item_unit = $item_units{$form->{"id_$i"}};
121 if (defined($all_units->{$item_unit}->{factor})
122 && ($all_units->{$item_unit}->{factor} ne '')
123 && ($all_units->{$item_unit}->{factor} * 1 != 0)) {
124 $basefactor = $all_units->{$form->{"unit_$i"}}->{factor} / $all_units->{$item_unit}->{factor};
128 $baseqty = $form->{"qty_$i"} * $basefactor;
130 @taxaccounts = split / /, $form->{"taxaccounts_$i"};
135 $form->{"sellprice_$i"} = $form->parse_amount($myconfig, $form->{"sellprice_$i"});
136 (my $fxsellprice = $form->{"sellprice_$i"}) =~ /\.(\d+)/;
138 my $decimalplaces = ($dec > 2) ? $dec : 2;
140 map { $taxrate += $form->{"${_}_rate"} } @taxaccounts;
142 $price_factor = $price_factors{ $form->{"price_factor_id_$i"} } || 1;
143 #####################################################################
144 # das ist aus IS.pm kopiert. schlimm. jb 7.10.2009
145 # ich würde mir wünschen, dass diese vier stellen zusammengefasst werden
146 # ... vier stellen = (einkauf + verkauf) * (maske + backend)
147 # ansonsten stolpert man immer wieder viermal statt einmal heftig
148 # und auch das undo discount formatting ist nicht besonders wartungsfreundlich
150 # keine ahnung wofür das in IS.pm gemacht wird:
151 # my ($dec) = ($fxsellprice =~ /\.(\d+)/);
152 # $dec = length $dec;
153 # my $decimalplaces = ($dec > 2) ? $dec : 2;
155 # undo discount formatting
156 $form->{"discount_$i"} = $form->parse_amount($myconfig, $form->{"discount_$i"}) / 100;
158 $form->{"sellprice_$i"} = $fxsellprice * (1 - $form->{"discount_$i"});
160 ######################################################################
161 if ($form->{"inventory_accno_$i"}) {
163 $linetotal = $form->round_amount($form->{"sellprice_$i"} * $form->{"qty_$i"} / $price_factor, 2);
165 if ($form->{taxincluded}) {
167 $taxamount = $linetotal * ($taxrate / (1 + $taxrate));
168 $form->{"sellprice_$i"} = $form->{"sellprice_$i"} * (1 / (1 + $taxrate));
171 $taxamount = $linetotal * $taxrate;
174 $netamount += $linetotal;
176 if ($form->round_amount($taxrate, 7) == 0) {
177 if ($form->{taxincluded}) {
178 foreach $item (@taxaccounts) {
180 $form->round_amount($linetotal * $form->{"${item}_rate"} / (1 + abs($form->{"${item}_rate"})), 2);
181 $taxdiff += $taxamount;
182 $form->{amount}{ $form->{id} }{$item} -= $taxamount;
184 $form->{amount}{ $form->{id} }{ $taxaccounts[0] } += $taxdiff;
187 map { $form->{amount}{ $form->{id} }{$_} -= $linetotal * $form->{"${_}_rate"} } @taxaccounts;
191 map { $form->{amount}{ $form->{id} }{$_} -= $taxamount * $form->{"${_}_rate"} / $taxrate } @taxaccounts;
194 # add purchase to inventory, this one is without the tax!
195 $amount = $form->{"sellprice_$i"} * $form->{"qty_$i"} * $form->{exchangerate} / $price_factor;
196 $linetotal = $form->round_amount($form->{"sellprice_$i"} * $form->{"qty_$i"} / $price_factor, 2) * $form->{exchangerate};
197 $linetotal = $form->round_amount($linetotal, 2);
199 # this is the difference for the inventory
200 $invoicediff += ($amount - $linetotal);
202 $form->{amount}{ $form->{id} }{ $form->{"inventory_accno_$i"} } -= $linetotal;
204 # adjust and round sellprice
205 $form->{"sellprice_$i"} = $form->round_amount($form->{"sellprice_$i"} * $form->{exchangerate}, $decimalplaces);
207 $lastinventoryaccno = $form->{"inventory_accno_$i"};
209 next if $payments_only;
211 # update parts table by setting lastcost to current price, don't allow negative values by using abs
212 $query = qq|UPDATE parts SET lastcost = ? WHERE id = ?|;
213 @values = (abs($form->{"sellprice_$i"} / $basefactor), conv_i($form->{"id_$i"}));
214 do_query($form, $dbh, $query, @values);
216 # check if we sold the item already and
217 # make an entry for the expense and inventory
219 qq|SELECT i.id, i.qty, i.allocated, i.trans_id, i.base_qty,
220 p.inventory_accno_id, p.expense_accno_id, a.transdate
221 FROM invoice i, ar a, parts p
222 WHERE (i.parts_id = p.id)
224 AND ((i.base_qty + i.allocated) > 0)
225 AND (i.trans_id = a.id)
227 # ORDER BY transdate guarantees FIFO
229 # sold two items without having bought them yet, example result of query:
230 # id | qty | allocated | trans_id | inventory_accno_id | expense_accno_id | transdate
231 # ---+-----+-----------+----------+--------------------+------------------+------------
232 # 9 | 2 | 0 | 9 | 15 | 151 | 2011-01-05
234 # base_qty + allocated > 0 if article has already been sold but not bought yet
236 # select qty,allocated,base_qty,sellprice from invoice where trans_id = 9;
237 # qty | allocated | base_qty | sellprice
238 # -----+-----------+----------+------------
239 # 2 | 0 | 2 | 1000.00000
241 $sth = prepare_execute_query($form, $dbh, $query, conv_i($form->{"id_$i"}));
243 my $totalqty = $baseqty;
245 while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
246 my $qty = min $totalqty, ($ref->{base_qty} + $ref->{allocated});
247 $linetotal = $form->round_amount(($form->{"sellprice_$i"} * $qty) / $basefactor, 2);
249 if ( $::instance_conf->get_inventory_system eq 'perpetual' ) {
250 # Warenbestandsbuchungen nur bei Bestandsmethode
252 if ($ref->{allocated} < 0) {
254 # we have an entry for it already, adjust amount
255 $form->update_balance($dbh, "acc_trans", "amount",
256 qq| (trans_id = $ref->{trans_id})
257 AND (chart_id = $ref->{inventory_accno_id})
258 AND (transdate = '$ref->{transdate}')|,
261 $form->update_balance($dbh, "acc_trans", "amount",
262 qq| (trans_id = $ref->{trans_id})
263 AND (chart_id = $ref->{expense_accno_id})
264 AND (transdate = '$ref->{transdate}')|,
267 } elsif ($linetotal != 0) {
270 # add entry for inventory, this one is for the sold item
271 $query = qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate, taxkey, tax_id) VALUES (?, ?, ?, ?,
276 ORDER BY startdate DESC LIMIT 1),
281 ORDER BY startdate DESC LIMIT 1),
282 (SELECT chart_link FROM chart WHERE id = ?))|;
283 @values = ($ref->{trans_id}, $ref->{inventory_accno_id}, $linetotal, $ref->{transdate}, $ref->{inventory_accno_id}, $ref->{transdate}, $ref->{inventory_accno_id}, $ref->{transdate},
284 $ref->{inventory_accno_id});
285 do_query($form, $dbh, $query, @values);
288 $query = qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate, taxkey, tax_id) VALUES (?, ?, ?, ?,
293 ORDER BY startdate DESC LIMIT 1),
298 ORDER BY startdate DESC LIMIT 1),
299 (SELECT chart_link FROM chart WHERE id = ?))|;
300 @values = ($ref->{trans_id}, $ref->{expense_accno_id}, ($linetotal * -1), $ref->{transdate}, $ref->{expense_accno_id}, $ref->{transdate}, $ref->{expense_accno_id}, $ref->{transdate},
301 $ref->{expense_accno_id});
302 do_query($form, $dbh, $query, @values);
306 # update allocated for sold item
307 $form->update_balance($dbh, "invoice", "allocated", qq|id = $ref->{id}|, $qty * -1);
311 last if ($totalqty -= $qty) <= 0;
316 } else { # if ($form->{"inventory_accno_id_$i"})
317 # part doesn't have an inventory_accno_id
318 # lastcost of the part is updated at the end
320 $linetotal = $form->round_amount($form->{"sellprice_$i"} * $form->{"qty_$i"} / $price_factor, 2);
322 if ($form->{taxincluded}) {
323 $taxamount = $linetotal * ($taxrate / (1 + $taxrate));
324 $form->{"sellprice_$i"} = $form->{"sellprice_$i"} * (1 / (1 + $taxrate));
327 $taxamount = $linetotal * $taxrate;
330 $netamount += $linetotal;
332 if ($form->round_amount($taxrate, 7) == 0) {
333 if ($form->{taxincluded}) {
334 foreach $item (@taxaccounts) {
335 $taxamount = $linetotal * $form->{"${item}_rate"} / (1 + abs($form->{"${item}_rate"}));
336 $totaltax += $taxamount;
337 $form->{amount}{ $form->{id} }{$item} -= $taxamount;
340 map { $form->{amount}{ $form->{id} }{$_} -= $linetotal * $form->{"${_}_rate"} } @taxaccounts;
343 map { $form->{amount}{ $form->{id} }{$_} -= $taxamount * $form->{"${_}_rate"} / $taxrate } @taxaccounts;
346 $amount = $form->{"sellprice_$i"} * $form->{"qty_$i"} * $form->{exchangerate} / $price_factor;
347 $linetotal = $form->round_amount($form->{"sellprice_$i"} * $form->{"qty_$i"} / $price_factor, 2) * $form->{exchangerate};
348 $linetotal = $form->round_amount($linetotal, 2);
350 # this is the difference for expense
351 $expensediff += ($amount - $linetotal);
353 # add amount to expense
354 $form->{amount}{ $form->{id} }{ $form->{"expense_accno_$i"} } -= $linetotal;
356 $lastexpenseaccno = $form->{"expense_accno_$i"};
358 # adjust and round sellprice
359 $form->{"sellprice_$i"} = $form->round_amount($form->{"sellprice_$i"} * $form->{exchangerate}, $decimalplaces);
361 next if $payments_only;
364 $query = qq|UPDATE parts SET lastcost = ? WHERE id = ?|;
365 do_query($form, $dbh, $query, $form->{"sellprice_$i"} / $basefactor, conv_i($form->{"id_$i"}));
368 next if $payments_only;
370 # save detail record in invoice table
371 my ($invoice_id) = selectfirst_array_query($form, $dbh, qq|SELECT nextval('invoiceid')|);
374 qq|INSERT INTO invoice (id, trans_id, parts_id, description, longdescription, qty, base_qty,
375 sellprice, fxsellprice, discount, allocated, unit, deliverydate,
376 project_id, serialnumber, price_factor_id, price_factor, marge_price_factor)
377 VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, (SELECT factor FROM price_factors WHERE id = ?), ?)|;
378 @values = ($invoice_id, conv_i($form->{id}), conv_i($form->{"id_$i"}),
379 $form->{"description_$i"}, $form->{"longdescription_$i"}, $form->{"qty_$i"} * -1,
380 $baseqty * -1, $form->{"sellprice_$i"}, $fxsellprice, $form->{"discount_$i"}, $allocated,
381 $form->{"unit_$i"}, conv_date($form->{deliverydate}),
382 conv_i($form->{"project_id_$i"}), $form->{"serialnumber_$i"},
383 conv_i($form->{"price_factor_id_$i"}), conv_i($form->{"price_factor_id_$i"}), conv_i($form->{"marge_price_factor_$i"}));
384 do_query($form, $dbh, $query, @values);
386 CVar->save_custom_variables(module => 'IC',
387 sub_module => 'invoice',
388 trans_id => $invoice_id,
389 configs => $ic_cvar_configs,
391 name_prefix => 'ic_',
392 name_postfix => "_$i",
396 $h_item_unit->finish();
398 $project_id = conv_i($form->{"globalproject_id"});
400 $form->{datepaid} = $form->{invdate};
402 # all amounts are in natural state, netamount includes the taxes
403 # if tax is included, netamount is rounded to 2 decimal places,
407 for my $i (1 .. $form->{paidaccounts}) {
408 $form->{"paid_$i"} = $form->parse_amount($myconfig, $form->{"paid_$i"});
409 $form->{paid} += $form->{"paid_$i"};
410 $form->{datepaid} = $form->{"datepaid_$i"} if $form->{"datepaid_$i"};
413 my ($tax, $paiddiff) = (0, 0);
415 $netamount = $form->round_amount($netamount, 2);
417 # figure out rounding errors for amount paid and total amount
418 if ($form->{taxincluded}) {
420 $amount = $form->round_amount($netamount * $form->{exchangerate}, 2);
421 $paiddiff = $amount - $netamount * $form->{exchangerate};
422 $netamount = $amount;
424 foreach $item (split / /, $form->{taxaccounts}) {
425 $amount = $form->{amount}{ $form->{id} }{$item} * $form->{exchangerate};
426 $form->{amount}{ $form->{id} }{$item} = $form->round_amount($amount, 2);
428 $amount = $form->{amount}{ $form->{id} }{$item} * -1;
430 $netamount -= $amount;
433 $invoicediff += $paiddiff;
434 $expensediff += $paiddiff;
436 ######## this only applies to tax included
438 # in the sales invoice case rounding errors only have to be corrected for
439 # income accounts, it is enough to add the total rounding error to one of
440 # the income accounts, with the one assigned to the last row being used
441 # (lastinventoryaccno)
443 # in the purchase invoice case rounding errors may be split between
444 # inventory accounts and expense accounts. After rounding, an error of 1
445 # cent is introduced if the total rounding error exceeds 0.005. The total
446 # error is made up of $invoicediff and $expensediff, however, so if both
447 # values are below 0.005, but add up to a total >= 0.005, correcting
448 # lastinventoryaccno and lastexpenseaccno separately has no effect after
449 # rounding. This caused bug 1579. Therefore when the combined total exceeds
450 # 0.005, but neither do individually, the account with the larger value
451 # shall receive the total rounding error, and the next time it is rounded
452 # the 1 cent correction will be introduced.
454 $form->{amount}{ $form->{id} }{$lastinventoryaccno} -= $invoicediff if $lastinventoryaccno;
455 $form->{amount}{ $form->{id} }{$lastexpenseaccno} -= $expensediff if $lastexpenseaccno;
457 if ( (abs($expensediff)+abs($invoicediff)) >= 0.005 and abs($expensediff) < 0.005 and abs($invoicediff) < 0.005 ) {
459 # in total the rounding error adds up to 1 cent effectively, correct the
460 # larger of the two numbers
462 if ( abs($form->{amount}{ $form->{id} }{$lastinventoryaccno}) > abs($form->{amount}{ $form->{id} }{$lastexpenseaccno}) ) {
463 # $invoicediff has already been deducted, now also deduct expensediff
464 $form->{amount}{ $form->{id} }{$lastinventoryaccno} -= $expensediff;
466 # expensediff has already been deducted, now also deduct invoicediff
467 $form->{amount}{ $form->{id} }{$lastexpenseaccno} -= $invoicediff;
472 $amount = $form->round_amount($netamount * $form->{exchangerate}, 2);
473 $paiddiff = $amount - $netamount * $form->{exchangerate};
474 $netamount = $amount;
476 foreach my $item (split / /, $form->{taxaccounts}) {
477 $form->{amount}{ $form->{id} }{$item} = $form->round_amount($form->{amount}{ $form->{id} }{$item}, 2);
478 $amount = $form->round_amount( $form->{amount}{ $form->{id} }{$item} * $form->{exchangerate} * -1, 2);
479 $paiddiff += $amount - $form->{amount}{ $form->{id} }{$item} * $form->{exchangerate} * -1;
480 $form->{amount}{ $form->{id} }{$item} = $form->round_amount($amount * -1, 2);
481 $amount = $form->{amount}{ $form->{id} }{$item} * -1;
486 $form->{amount}{ $form->{id} }{ $form->{AP} } = $netamount + $tax;
489 $form->{paid} = $form->round_amount($form->{paid} * $form->{exchangerate} + $paiddiff, 2) if $form->{paid} != 0;
491 # update exchangerate
493 $form->update_exchangerate($dbh, $form->{currency}, $form->{invdate}, 0, $form->{exchangerate})
494 if ($form->{currency} ne $defaultcurrency) && !$exchangerate;
496 # record acc_trans transactions
497 foreach my $trans_id (keys %{ $form->{amount} }) {
498 foreach my $accno (keys %{ $form->{amount}{$trans_id} }) {
499 $form->{amount}{$trans_id}{$accno} = $form->round_amount($form->{amount}{$trans_id}{$accno}, 2);
502 next if $payments_only || !$form->{amount}{$trans_id}{$accno};
504 $query = qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate, taxkey, project_id, tax_id, chart_link)
505 VALUES (?, (SELECT id FROM chart WHERE accno = ?), ?, ?,
508 WHERE chart_id= (SELECT id
512 ORDER BY startdate DESC LIMIT 1),
516 WHERE chart_id= (SELECT id
520 ORDER BY startdate DESC LIMIT 1),
521 (SELECT link FROM chart WHERE accno = ?))|;
522 @values = ($trans_id, $accno, $form->{amount}{$trans_id}{$accno},
523 conv_date($form->{invdate}), $accno, conv_date($form->{invdate}), $project_id, $accno, conv_date($form->{invdate}), $accno);
524 do_query($form, $dbh, $query, @values);
528 # deduct payment differences from paiddiff
529 for my $i (1 .. $form->{paidaccounts}) {
530 if ($form->{"paid_$i"} != 0) {
531 $amount = $form->round_amount($form->{"paid_$i"} * $form->{exchangerate}, 2);
532 $paiddiff -= $amount - $form->{"paid_$i"} * $form->{exchangerate};
536 # force AP entry if 0
538 $form->{amount}{ $form->{id} }{ $form->{AP} } = $form->{paid} if $form->{amount}{$form->{id}}{$form->{AP}} == 0;
540 # record payments and offsetting AP
541 for my $i (1 .. $form->{paidaccounts}) {
542 if ($form->{"acc_trans_id_$i"}
544 && (SL::DB::Default->get->payments_changeable == 0)) {
548 next if $form->{"paid_$i"} == 0;
550 my ($accno) = split /--/, $form->{"AP_paid_$i"};
551 $form->{"datepaid_$i"} = $form->{invdate} unless ($form->{"datepaid_$i"});
552 $form->{datepaid} = $form->{"datepaid_$i"};
554 $amount = $form->round_amount($form->{"paid_$i"} * $form->{exchangerate} + $paiddiff, 2) * -1;
557 if ($form->{amount}{ $form->{id} }{ $form->{AP} } != 0) {
558 $query = qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate, taxkey, project_id, tax_id, chart_link)
559 VALUES (?, (SELECT id FROM chart WHERE accno = ?), ?, ?,
562 WHERE chart_id= (SELECT id
566 ORDER BY startdate DESC LIMIT 1),
570 WHERE chart_id= (SELECT id
574 ORDER BY startdate DESC LIMIT 1),
575 (SELECT link FROM chart WHERE accno = ?))|;
576 @values = (conv_i($form->{id}), $form->{AP}, $amount,
577 $form->{"datepaid_$i"}, $form->{AP}, conv_date($form->{"datepaid_$i"}), $project_id, $form->{AP}, conv_date($form->{"datepaid_$i"}), $form->{AP});
578 do_query($form, $dbh, $query, @values);
582 my $gldate = (conv_date($form->{"gldate_$i"}))? conv_date($form->{"gldate_$i"}) : conv_date($form->current_date($myconfig));
585 qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate, gldate, source, memo, taxkey, project_id, tax_id, chart_link)
586 VALUES (?, (SELECT id FROM chart WHERE accno = ?), ?, ?, ?, ?, ?,
589 WHERE chart_id= (SELECT id
590 FROM chart WHERE accno = ?)
592 ORDER BY startdate DESC LIMIT 1),
596 WHERE chart_id= (SELECT id
597 FROM chart WHERE accno = ?)
599 ORDER BY startdate DESC LIMIT 1),
600 (SELECT link FROM chart WHERE accno = ?))|;
601 @values = (conv_i($form->{id}), $accno, $form->{"paid_$i"}, $form->{"datepaid_$i"},
602 $gldate, $form->{"source_$i"}, $form->{"memo_$i"}, $accno, conv_date($form->{"datepaid_$i"}), $project_id, $accno, conv_date($form->{"datepaid_$i"}), $accno);
603 do_query($form, $dbh, $query, @values);
607 if ($form->{currency} eq $defaultcurrency) {
608 $form->{"exchangerate_$i"} = 1;
610 $exchangerate = $form->check_exchangerate($myconfig, $form->{currency}, $form->{"datepaid_$i"}, 'sell');
611 $form->{"exchangerate_$i"} = $exchangerate || $form->parse_amount($myconfig, $form->{"exchangerate_$i"});
614 # exchangerate difference
615 $form->{fx}{$accno}{ $form->{"datepaid_$i"} } += $form->{"paid_$i"} * ($form->{"exchangerate_$i"} - 1) + $paiddiff;
619 ($form->{"paid_$i"} * $form->{exchangerate}) -
620 ($form->{"paid_$i"} * $form->{"exchangerate_$i"});
622 $form->{fx}{ $form->{fxgain_accno} }{ $form->{"datepaid_$i"} } += $amount;
624 $form->{fx}{ $form->{fxloss_accno} }{ $form->{"datepaid_$i"} } += $amount;
629 # update exchange rate
630 $form->update_exchangerate($dbh, $form->{currency}, $form->{"datepaid_$i"}, 0, $form->{"exchangerate_$i"})
631 if ($form->{currency} ne $defaultcurrency) && !$exchangerate;
634 # record exchange rate differences and gains/losses
635 foreach my $accno (keys %{ $form->{fx} }) {
636 foreach my $transdate (keys %{ $form->{fx}{$accno} }) {
637 $form->{fx}{$accno}{$transdate} = $form->round_amount($form->{fx}{$accno}{$transdate}, 2);
638 next if ($form->{fx}{$accno}{$transdate} == 0);
640 $query = qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate, cleared, fx_transaction, taxkey, project_id, tax_id, chart_link)
641 VALUES (?, (SELECT id FROM chart WHERE accno = ?), ?, ?, '0', '1', 0, ?,
642 (SELECT id FROM tax WHERE taxkey=0 LIMIT 1),
643 (SELECT link FROM chart WHERE accno = ?))|;
644 @values = (conv_i($form->{id}), $accno, $form->{fx}{$accno}{$transdate}, conv_date($transdate), $project_id, $accno);
645 do_query($form, $dbh, $query, @values);
649 IO->set_datepaid(table => 'ap', id => $form->{id}, dbh => $dbh);
651 if ($payments_only) {
652 $query = qq|UPDATE ap SET paid = ? WHERE id = ?|;
653 do_query($form, $dbh, $query, $form->{paid}, conv_i($form->{id}));
655 if (!$provided_dbh) {
660 $main::lxdebug->leave_sub();
664 $amount = $netamount + $tax;
666 # set values which could be empty
667 my $taxzone_id = $form->{taxzone_id} * 1;
669 # Seit neuestem wird die department_id schon übergeben UND $form->department nicht mehr
670 # korrekt zusammengebaut. Sehr wahrscheinlich beim Umstieg auf T8 kaputt gegangen
671 # Ich lass den Code von 2005 erstmal noch stehen ;-) jb 03-2011
672 # copy & paste von IS.pm
673 if (!$form->{department_id}){
674 $form->{department_id} = (split /--/, $form->{department})[1];
676 $form->{invnumber} = $form->{id} unless $form->{invnumber};
678 $taxzone_id = 0 if (3 < $taxzone_id) || (0 > $taxzone_id);
681 $query = qq|UPDATE ap SET
682 invnumber = ?, ordnumber = ?, quonumber = ?, transdate = ?,
683 orddate = ?, quodate = ?, vendor_id = ?, amount = ?,
684 netamount = ?, paid = ?, duedate = ?,
685 invoice = ?, taxzone_id = ?, notes = ?, taxincluded = ?,
686 intnotes = ?, storno_id = ?, storno = ?,
687 cp_id = ?, employee_id = ?, department_id = ?,
688 globalproject_id = ?, direct_debit = ?
691 $form->{invnumber}, $form->{ordnumber}, $form->{quonumber}, conv_date($form->{invdate}),
692 conv_date($form->{orddate}), conv_date($form->{quodate}), conv_i($form->{vendor_id}), $amount,
693 $netamount, $form->{paid}, conv_date($form->{duedate}),
694 '1', $taxzone_id, $form->{notes}, $form->{taxincluded} ? 't' : 'f',
695 $form->{intnotes}, conv_i($form->{storno_id}), $form->{storno} ? 't' : 'f',
696 conv_i($form->{cp_id}), conv_i($form->{employee_id}), conv_i($form->{department_id}),
697 conv_i($form->{globalproject_id}),
698 $form->{direct_debit} ? 't' : 'f',
701 do_query($form, $dbh, $query, @values);
703 if ($form->{storno}) {
704 $query = qq|UPDATE ap SET paid = paid + amount WHERE id = ?|;
705 do_query($form, $dbh, $query, conv_i($form->{storno_id}));
707 $query = qq|UPDATE ap SET storno = 't' WHERE id = ?|;
708 do_query($form, $dbh, $query, conv_i($form->{storno_id}));
710 $query = qq!UPDATE ap SET intnotes = ? || intnotes WHERE id = ?!;
711 do_query($form, $dbh, $query, "Rechnung storniert am $form->{invdate} ", conv_i($form->{storno_id}));
713 $query = qq|UPDATE ap SET paid = amount WHERE id = ?|;
714 do_query($form, $dbh, $query, conv_i($form->{id}));
719 $form->{name} = $form->{vendor};
720 $form->{name} =~ s/--\Q$form->{vendor_id}\E//;
721 $form->add_shipto($dbh, $form->{id}, "AP");
723 # delete zero entries
724 do_query($form, $dbh, qq|DELETE FROM acc_trans WHERE amount = 0|);
726 Common::webdav_folder($form);
728 # Link this record to the records it was created from.
729 RecordLinks->create_links('dbh' => $dbh,
731 'from_table' => 'oe',
732 'from_ids' => $form->{convert_from_oe_ids},
734 'to_id' => $form->{id},
736 delete $form->{convert_from_oe_ids};
738 my @convert_from_do_ids = map { $_ * 1 } grep { $_ } split m/\s+/, $form->{convert_from_do_ids};
739 if (scalar @convert_from_do_ids) {
740 DO->close_orders('dbh' => $dbh,
741 'ids' => \@convert_from_do_ids);
743 RecordLinks->create_links('dbh' => $dbh,
745 'from_table' => 'delivery_orders',
746 'from_ids' => \@convert_from_do_ids,
748 'to_id' => $form->{id},
751 delete $form->{convert_from_do_ids};
753 ARAP->close_orders_if_billed('dbh' => $dbh,
754 'arap_id' => $form->{id},
757 # safety check datev export
758 if ($::instance_conf->get_datev_check_on_purchase_invoice) {
759 my $transdate = $::form->{invdate} ? DateTime->from_lxoffice($::form->{invdate}) : undef;
760 $transdate ||= DateTime->today;
762 my $datev = SL::DATEV->new(
763 exporttype => DATEV_ET_BUCHUNGEN,
764 format => DATEV_FORMAT_KNE,
772 if ($datev->errors) {
774 die join "\n", $::locale->text('DATEV check returned errors:'), $datev->errors;
779 if (!$provided_dbh) {
780 $rc = $dbh->commit();
784 $main::lxdebug->leave_sub();
789 sub reverse_invoice {
790 $main::lxdebug->enter_sub();
792 my ($dbh, $form) = @_;
794 # reverse inventory items
796 qq|SELECT i.parts_id, p.inventory_accno_id, p.expense_accno_id, i.qty, i.allocated, i.sellprice
797 FROM invoice i, parts p
798 WHERE (i.parts_id = p.id)
799 AND (i.trans_id = ?)|;
800 my $sth = prepare_execute_query($form, $dbh, $query, conv_i($form->{id}));
804 while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
805 $netamount += $form->round_amount($ref->{sellprice} * $ref->{qty} * -1, 2);
807 next unless $ref->{inventory_accno_id};
809 # if $ref->{allocated} > 0 than we sold that many items
810 next if ($ref->{allocated} <= 0);
812 # get references for sold items
814 qq|SELECT i.id, i.trans_id, i.allocated, a.transdate
816 WHERE (i.parts_id = ?)
817 AND (i.allocated < 0)
818 AND (i.trans_id = a.id)
819 ORDER BY transdate DESC|;
820 my $sth2 = prepare_execute_query($form, $dbh, $query, $ref->{parts_id});
822 while (my $pthref = $sth2->fetchrow_hashref("NAME_lc")) {
823 my $qty = $ref->{allocated};
824 if (($ref->{allocated} + $pthref->{allocated}) > 0) {
825 $qty = $pthref->{allocated} * -1;
828 my $amount = $form->round_amount($ref->{sellprice} * $qty, 2);
831 $form->update_balance($dbh, "invoice", "allocated", qq|id = $pthref->{id}|, $qty);
833 $form->update_balance($dbh, "acc_trans", "amount",
834 qq| (trans_id = $pthref->{trans_id})
835 AND (chart_id = $ref->{expense_accno_id})
836 AND (transdate = '$pthref->{transdate}')|,
839 $form->update_balance($dbh, "acc_trans", "amount",
840 qq| (trans_id = $pthref->{trans_id})
841 AND (chart_id = $ref->{inventory_accno_id})
842 AND (transdate = '$pthref->{transdate}')|,
845 last if (($ref->{allocated} -= $qty) <= 0);
851 my $id = conv_i($form->{id});
854 $query = qq|DELETE FROM acc_trans WHERE trans_id = ?|;
855 do_query($form, $dbh, $query, $id);
857 # delete invoice entries
858 $query = qq|DELETE FROM invoice WHERE trans_id = ?|;
859 do_query($form, $dbh, $query, $id);
861 $query = qq|DELETE FROM shipto WHERE (trans_id = ?) AND (module = 'AP')|;
862 do_query($form, $dbh, $query, $id);
864 $main::lxdebug->leave_sub();
868 $main::lxdebug->enter_sub();
870 my ($self, $myconfig, $form) = @_;
872 # connect to database
873 my $dbh = $form->dbconnect_noauto($myconfig);
875 &reverse_invoice($dbh, $form);
877 # delete zero entries
878 $query = qq|DELETE FROM acc_trans WHERE amount = 0|;
879 do_query($form, $dbh, $query);
882 $query = qq|DELETE FROM ap WHERE id = ?|;
883 do_query($form, $dbh, $query, conv_i($form->{id}));
885 my $rc = $dbh->commit;
888 $main::lxdebug->leave_sub();
893 sub retrieve_invoice {
894 $main::lxdebug->enter_sub();
896 my ($self, $myconfig, $form) = @_;
898 # connect to database
899 my $dbh = $form->dbconnect($myconfig);
901 my ($query, $sth, $ref, $q_invdate);
904 $q_invdate = qq|, COALESCE((SELECT transdate FROM ar WHERE id = (SELECT MAX(id) FROM ar)), current_date) AS invdate|;
905 if ($form->{vendor_id}) {
906 my $vendor_id = $dbh->quote($form->{vendor_id} * 1);
908 qq|, COALESCE((SELECT transdate FROM ar WHERE id = (SELECT MAX(id) FROM ar)), current_date) +
909 COALESCE((SELECT pt.terms_netto
911 LEFT JOIN payment_terms pt ON (v.payment_id = pt.id)
912 WHERE v.id = $vendor_id),
917 # get default accounts and last invoice number
920 (SELECT c.accno FROM chart c WHERE d.inventory_accno_id = c.id) AS inventory_accno,
921 (SELECT c.accno FROM chart c WHERE d.income_accno_id = c.id) AS income_accno,
922 (SELECT c.accno FROM chart c WHERE d.expense_accno_id = c.id) AS expense_accno,
923 (SELECT c.accno FROM chart c WHERE d.fxgain_accno_id = c.id) AS fxgain_accno,
924 (SELECT c.accno FROM chart c WHERE d.fxloss_accno_id = c.id) AS fxloss_accno
927 $ref = selectfirst_hashref_query($form, $dbh, $query);
928 map { $form->{$_} = $ref->{$_} } keys %$ref;
932 $main::lxdebug->leave_sub();
938 $query = qq|SELECT cp_id, invnumber, transdate AS invdate, duedate,
939 orddate, quodate, globalproject_id,
940 ordnumber, quonumber, paid, taxincluded, notes, taxzone_id, storno, gldate,
941 intnotes, (SELECT cu.curr FROM currencies cu WHERE cu.id=ap.curr) AS currency, direct_debit
944 $ref = selectfirst_hashref_query($form, $dbh, $query, conv_i($form->{id}));
945 map { $form->{$_} = $ref->{$_} } keys %$ref;
947 $form->{exchangerate} = $form->get_exchangerate($dbh, $form->{currency}, $form->{invdate}, "sell");
950 $query = qq|SELECT * FROM shipto WHERE (trans_id = ?) AND (module = 'AP')|;
951 $ref = selectfirst_hashref_query($form, $dbh, $query, conv_i($form->{id}));
953 map { $form->{$_} = $ref->{$_} } keys %$ref;
955 my $transdate = $form->{invdate} ? $dbh->quote($form->{invdate}) : "current_date";
956 my $taxzone_id = $form->{taxzone_id} * 1;
958 $taxzone_id = 0 if ((3 < $taxzone_id) || (0 > $taxzone_id));
960 # retrieve individual items
963 c1.accno AS inventory_accno, c1.new_chart_id AS inventory_new_chart, date($transdate) - c1.valid_from AS inventory_valid,
964 c2.accno AS income_accno, c2.new_chart_id AS income_new_chart, date($transdate) - c2.valid_from AS income_valid,
965 c3.accno AS expense_accno, c3.new_chart_id AS expense_new_chart, date($transdate) - c3.valid_from AS expense_valid,
968 i.description, i.longdescription, i.qty, i.fxsellprice AS sellprice, i.parts_id AS id, i.unit, i.deliverydate, i.project_id, i.serialnumber,
969 i.price_factor_id, i.price_factor, i.marge_price_factor, i.discount,
970 p.partnumber, p.inventory_accno_id AS part_inventory_accno_id, p.bin, pr.projectnumber, pg.partsgroup
973 JOIN parts p ON (i.parts_id = p.id)
974 LEFT JOIN chart c1 ON ((SELECT inventory_accno_id FROM buchungsgruppen WHERE id = p.buchungsgruppen_id) = c1.id)
975 LEFT JOIN chart c2 ON ((SELECT income_accno_id_${taxzone_id} FROM buchungsgruppen WHERE id = p.buchungsgruppen_id) = c2.id)
976 LEFT JOIN chart c3 ON ((SELECT expense_accno_id_${taxzone_id} FROM buchungsgruppen WHERE id = p.buchungsgruppen_id) = c3.id)
977 LEFT JOIN project pr ON (i.project_id = pr.id)
978 LEFT JOIN partsgroup pg ON (pg.id = p.partsgroup_id)
983 $sth = prepare_execute_query($form, $dbh, $query, conv_i($form->{id}));
985 while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
986 # Retrieve custom variables.
987 my $cvars = CVar->get_custom_variables(dbh => $dbh,
989 sub_module => 'invoice',
990 trans_id => $ref->{invoice_id},
992 map { $ref->{"ic_cvar_$_->{name}"} = $_->{value} } @{ $cvars };
993 delete $ref->{invoice_id};
995 map({ delete($ref->{$_}); } qw(inventory_accno inventory_new_chart inventory_valid)) if !$ref->{"part_inventory_accno_id"};
996 delete($ref->{"part_inventory_accno_id"});
998 foreach my $type (qw(inventory income expense)) {
999 while ($ref->{"${type}_new_chart"} && ($ref->{"${type}_valid"} >=0)) {
1000 my $query = qq|SELECT accno, new_chart_id, date($transdate) - valid_from FROM chart WHERE id = ?|;
1001 @$ref{ map $type.$_, qw(_accno _new_chart _valid) } = selectrow_query($form, $dbh, $query, $ref->{"${type}_new_chart"});
1005 # get tax rates and description
1006 my $accno_id = ($form->{vc} eq "customer") ? $ref->{income_accno} : $ref->{expense_accno};
1008 qq|SELECT c.accno, t.taxdescription, t.rate, t.taxnumber FROM tax t
1009 LEFT JOIN chart c ON (c.id = t.chart_id)
1011 (SELECT tk.tax_id FROM taxkeys tk
1012 WHERE tk.chart_id = (SELECT id FROM chart WHERE accno = ?)
1013 AND (startdate <= $transdate)
1014 ORDER BY startdate DESC
1017 my $stw = prepare_execute_query($form, $dbh, $query, $accno_id);
1018 $ref->{taxaccounts} = "";
1021 while (my $ptr = $stw->fetchrow_hashref("NAME_lc")) {
1022 if (($ptr->{accno} eq "") && ($ptr->{rate} == 0)) {
1027 $ref->{taxaccounts} .= "$ptr->{accno} ";
1029 if (!($form->{taxaccounts} =~ /\Q$ptr->{accno}\E/)) {
1030 $form->{"$ptr->{accno}_rate"} = $ptr->{rate};
1031 $form->{"$ptr->{accno}_description"} = $ptr->{taxdescription};
1032 $form->{"$ptr->{accno}_taxnumber"} = $ptr->{taxnumber};
1033 $form->{taxaccounts} .= "$ptr->{accno} ";
1038 chop $ref->{taxaccounts};
1039 push @{ $form->{invoice_details} }, $ref;
1044 Common::webdav_folder($form);
1048 $main::lxdebug->leave_sub();
1052 $main::lxdebug->enter_sub();
1054 my ($self, $myconfig, $form, $params) = @_;
1056 $params = $form unless defined $params && ref $params eq "HASH";
1058 # connect to database
1059 my $dbh = $form->dbconnect($myconfig);
1061 my $dateformat = $myconfig->{dateformat};
1062 $dateformat .= "yy" if $myconfig->{dateformat} !~ /^y/;
1064 my $vid = conv_i($params->{vendor_id});
1065 my $vnr = conv_i($params->{vendornumber});
1068 ($params->{invdate})
1069 ? "to_date(" . $dbh->quote($params->{invdate}) . ", '$dateformat')"
1076 $where .= 'AND v.id = ?';
1080 $where .= 'AND v.vendornumber = ?';
1085 v.id AS vendor_id, v.name AS vendor, v.discount as vendor_discount,
1086 v.creditlimit, v.terms, v.notes AS intnotes,
1087 v.email, v.cc, v.bcc, v.language_id, v.payment_id,
1088 v.street, v.zipcode, v.city, v.country, v.taxzone_id, (SELECT cu.curr FROM currencies cu WHERE cu.id=v.curr) AS curr, v.direct_debit,
1089 $duedate + COALESCE(pt.terms_netto, 0) AS duedate,
1090 b.description AS business
1092 LEFT JOIN business b ON (b.id = v.business_id)
1093 LEFT JOIN payment_terms pt ON (v.payment_id = pt.id)
1095 my $ref = selectfirst_hashref_query($form, $dbh, $query, @values);
1096 map { $params->{$_} = $ref->{$_} } keys %$ref;
1098 # use vendor currency
1099 $form->{currency} = $form->{curr};
1101 $params->{creditremaining} = $params->{creditlimit};
1103 $query = qq|SELECT SUM(amount - paid) FROM ap WHERE vendor_id = ?|;
1104 my ($unpaid_invoices) = selectfirst_array_query($form, $dbh, $query, $vid);
1105 $params->{creditremaining} -= $unpaid_invoices;
1107 $query = qq|SELECT o.amount,
1110 WHERE (e.curr = o.curr)
1111 AND (e.transdate = o.transdate)) AS exch
1113 WHERE (o.vendor_id = ?) AND (o.quotation = '0') AND (o.closed = '0')|;
1114 my $sth = prepare_execute_query($form, $dbh, $query, $vid);
1115 while (my ($amount, $exch) = $sth->fetchrow_array()) {
1116 $exch = 1 unless $exch;
1117 $params->{creditremaining} -= $amount * $exch;
1121 # get shipto if we do not convert an order or invoice
1122 if (!$params->{shipto}) {
1123 delete @{$params}{qw(shiptoname shiptostreet shiptozipcode shiptocity shiptocountry shiptocontact shiptophone shiptofax shiptoemail)};
1125 $query = qq|SELECT * FROM shipto WHERE (trans_id = ?) AND (module= 'CT')|;
1126 $ref = selectfirst_hashref_query($form, $dbh, $query, $vid);
1127 @{$params}{keys %$ref} = @{$ref}{keys %$ref};
1128 map { $params->{$_} = $ref->{$_} } keys %$ref;
1131 if (!$params->{id} && $params->{type} !~ /_(order|quotation)/) {
1132 # setup last accounts used
1134 qq|SELECT c.id, c.accno, c.description, c.link, c.category
1136 JOIN acc_trans ac ON (ac.chart_id = c.id)
1137 JOIN ap a ON (a.id = ac.trans_id)
1138 WHERE (a.vendor_id = ?)
1139 AND (NOT ((c.link LIKE '%_tax%') OR (c.link LIKE '%_paid%')))
1140 AND (a.id IN (SELECT max(a2.id) FROM ap a2 WHERE a2.vendor_id = ?))|;
1141 my $refs = selectall_hashref_query($form, $dbh, $query, $vid, $vid);
1145 if ($ref->{category} eq 'E') {
1147 my ($tax_id, $rate);
1148 if ($params->{initial_transdate}) {
1149 my $tax_query = qq|SELECT tk.tax_id, t.rate FROM taxkeys tk
1150 LEFT JOIN tax t ON (tk.tax_id = t.id)
1151 WHERE (tk.chart_id = ?) AND (startdate <= ?)
1152 ORDER BY tk.startdate DESC
1154 ($tax_id, $rate) = selectrow_query($form, $dbh, $tax_query, $ref->{id}, $params->{initial_transdate});
1155 $params->{"taxchart_$i"} = "${tax_id}--${rate}";
1158 $params->{"AP_amount_$i"} = "$ref->{accno}--$tax_id";
1161 if ($ref->{category} eq 'L') {
1162 $params->{APselected} = $params->{AP_1} = $ref->{accno};
1165 $params->{rowcount} = $i if ($i && !$params->{type});
1170 $main::lxdebug->leave_sub();
1174 $main::lxdebug->enter_sub();
1176 my ($self, $myconfig, $form) = @_;
1178 # connect to database
1179 my $dbh = $form->dbconnect($myconfig);
1181 my $i = $form->{rowcount};
1183 # don't include assemblies or obsolete parts
1184 my $where = "NOT p.assembly = '1' AND NOT p.obsolete = '1'";
1187 foreach my $table_column (qw(p.partnumber p.description pg.partsgroup)) {
1188 my $field = (split m{\.}, $table_column)[1];
1189 next unless $form->{"${field}_${i}"};
1190 $where .= " AND lower(${table_column}) LIKE lower(?)";
1191 push @values, '%' . $form->{"${field}_${i}"} . '%';
1193 #Es soll auch nach EAN gesucht werden, ohne Einschränkung durch Beschreibung
1194 if ($form->{"partnumber_$i"} && !$form->{"description_$i"}) {
1195 $where .= qq| OR (NOT p.obsolete = '1' AND p.ean = ? )|;
1196 push @values, $form->{"partnumber_$i"};
1199 # Search for part ID overrides all other criteria.
1200 if ($form->{"id_${i}"}) {
1201 $where = qq|p.id = ?|;
1202 @values = ($form->{"id_${i}"});
1205 if ($form->{"description_$i"}) {
1206 $where .= " ORDER BY p.description";
1208 $where .= " ORDER BY p.partnumber";
1212 if ($form->{type} eq "invoice") {
1213 $transdate = $form->{invdate} ? $dbh->quote($form->{invdate}) : "current_date";
1215 $transdate = $form->{transdate} ? $dbh->quote($form->{transdate}) : "current_date";
1218 my $taxzone_id = $form->{taxzone_id} * 1;
1219 $taxzone_id = 0 if ((3 < $taxzone_id) || (0 > $taxzone_id));
1223 p.id, p.partnumber, p.description, p.lastcost AS sellprice, p.listprice,
1224 p.unit, p.assembly, p.bin, p.onhand, p.formel,
1225 p.notes AS partnotes, p.notes AS longdescription, p.not_discountable,
1226 p.inventory_accno_id, p.price_factor_id,
1228 pfac.factor AS price_factor,
1230 c1.accno AS inventory_accno,
1231 c1.new_chart_id AS inventory_new_chart,
1232 date($transdate) - c1.valid_from AS inventory_valid,
1234 c2.accno AS income_accno,
1235 c2.new_chart_id AS income_new_chart,
1236 date($transdate) - c2.valid_from AS income_valid,
1238 c3.accno AS expense_accno,
1239 c3.new_chart_id AS expense_new_chart,
1240 date($transdate) - c3.valid_from AS expense_valid,
1245 LEFT JOIN chart c1 ON
1246 ((SELECT inventory_accno_id
1247 FROM buchungsgruppen
1248 WHERE id = p.buchungsgruppen_id) = c1.id)
1249 LEFT JOIN chart c2 ON
1250 ((SELECT income_accno_id_${taxzone_id}
1251 FROM buchungsgruppen
1252 WHERE id = p.buchungsgruppen_id) = c2.id)
1253 LEFT JOIN chart c3 ON
1254 ((SELECT expense_accno_id_${taxzone_id}
1255 FROM buchungsgruppen
1256 WHERE id = p.buchungsgruppen_id) = c3.id)
1257 LEFT JOIN partsgroup pg ON (pg.id = p.partsgroup_id)
1258 LEFT JOIN price_factors pfac ON (pfac.id = p.price_factor_id)
1260 my $sth = prepare_execute_query($form, $dbh, $query, @values);
1262 my @translation_queries = ( [ qq|SELECT tr.translation, tr.longdescription
1264 WHERE tr.language_id = ? AND tr.parts_id = ?| ],
1265 [ qq|SELECT tr.translation, tr.longdescription
1267 WHERE tr.language_id IN
1270 WHERE article_code = (SELECT article_code FROM language WHERE id = ?))
1273 map { push @{ $_ }, prepare_query($form, $dbh, $_->[0]) } @translation_queries;
1275 $form->{item_list} = [];
1276 while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
1278 # In der Buchungsgruppe ist immer ein Bestandskonto verknuepft, auch wenn
1279 # es sich um eine Dienstleistung handelt. Bei Dienstleistungen muss das
1280 # Buchungskonto also aus dem Ergebnis rausgenommen werden.
1281 if (!$ref->{inventory_accno_id}) {
1282 map({ delete($ref->{"inventory_${_}"}); } qw(accno new_chart valid));
1284 delete($ref->{inventory_accno_id});
1286 # get tax rates and description
1287 my $accno_id = ($form->{vc} eq "customer") ? $ref->{income_accno} : $ref->{expense_accno};
1289 qq|SELECT c.accno, t.taxdescription, t.rate, t.taxnumber
1291 LEFT JOIN chart c on (c.id = t.chart_id)
1299 AND (startdate <= $transdate)
1300 ORDER BY startdate DESC
1303 my $stw = prepare_execute_query($form, $dbh, $query, $accno_id);
1305 $ref->{taxaccounts} = "";
1307 while (my $ptr = $stw->fetchrow_hashref("NAME_lc")) {
1309 if (($ptr->{accno} eq "") && ($ptr->{rate} == 0)) {
1314 $ref->{taxaccounts} .= "$ptr->{accno} ";
1316 if (!($form->{taxaccounts} =~ /\Q$ptr->{accno}\E/)) {
1317 $form->{"$ptr->{accno}_rate"} = $ptr->{rate};
1318 $form->{"$ptr->{accno}_description"} = $ptr->{taxdescription};
1319 $form->{"$ptr->{accno}_taxnumber"} = $ptr->{taxnumber};
1320 $form->{taxaccounts} .= "$ptr->{accno} ";
1323 if ($form->{language_id}) {
1324 for my $spec (@translation_queries) {
1325 do_statement($form, $spec->[1], $spec->[0], conv_i($form->{language_id}), conv_i($ref->{id}));
1326 my ($translation, $longdescription) = $spec->[1]->fetchrow_array;
1327 next unless $translation;
1328 $ref->{description} = $translation;
1329 $ref->{longdescription} = $longdescription;
1336 chop $ref->{taxaccounts};
1338 $ref->{onhand} *= 1;
1340 push @{ $form->{item_list} }, $ref;
1345 $_->[1]->finish for @translation_queries;
1347 foreach my $item (@{ $form->{item_list} }) {
1348 my $custom_variables = CVar->get_custom_variables(module => 'IC',
1349 trans_id => $item->{id},
1353 map { $item->{"ic_cvar_" . $_->{name} } = $_->{value} } @{ $custom_variables };
1358 $main::lxdebug->leave_sub();
1361 sub vendor_details {
1362 $main::lxdebug->enter_sub();
1364 my ($self, $myconfig, $form, @wanted_vars) = @_;
1366 # connect to database
1367 my $dbh = $form->dbconnect($myconfig);
1371 # get contact id, set it if nessessary
1372 $form->{cp_id} *= 1;
1374 if ($form->{cp_id}) {
1375 $contact = "AND cp.cp_id = ?";
1376 push @values, $form->{cp_id};
1379 # get rest for the vendor
1380 # fax and phone and email as vendor*
1382 qq|SELECT ct.*, cp.*, ct.notes as vendornotes, phone as vendorphone, fax as vendorfax, email as vendoremail,
1383 (SELECT cu.curr FROM currencies cu WHERE cu.id=ct.curr) AS currency
1385 LEFT JOIN contacts cp ON (ct.id = cp.cp_cv_id)
1386 WHERE (ct.id = ?) $contact
1389 my $ref = selectfirst_hashref_query($form, $dbh, $query, $form->{vendor_id}, @values);
1391 # remove id and taxincluded before copy back
1392 delete @$ref{qw(id taxincluded)};
1394 @wanted_vars = grep({ $_ } @wanted_vars);
1395 if (scalar(@wanted_vars) > 0) {
1397 map({ $h_wanted_vars{$_} = 1; } @wanted_vars);
1398 map({ delete($ref->{$_}) unless ($h_wanted_vars{$_}); } keys(%{$ref}));
1401 map { $form->{$_} = $ref->{$_} } keys %$ref;
1403 my $custom_variables = CVar->get_custom_variables('dbh' => $dbh,
1405 'trans_id' => $form->{vendor_id});
1406 map { $form->{"vc_cvar_$_->{name}"} = $_->{value} } @{ $custom_variables };
1408 $form->{cp_greeting} = GenericTranslations->get('dbh' => $dbh,
1409 'translation_type' => 'greetings::' . ($form->{cp_gender} eq 'f' ? 'female' : 'male'),
1410 'allow_fallback' => 1);
1414 $main::lxdebug->leave_sub();
1418 $main::lxdebug->enter_sub();
1420 my ($self, $myconfig, $form) = @_;
1422 # connect to database
1423 my $dbh = $form->dbconnect($myconfig);
1426 qq|SELECT accno, description, link
1428 WHERE link LIKE '%IC%'
1430 my $sth = prepare_execute_query($query, $dbh, $query);
1432 while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
1433 foreach my $key (split(/:/, $ref->{link})) {
1435 push @{ $form->{IC_links}{$key} },
1436 { accno => $ref->{accno},
1437 description => $ref->{description} };
1445 $main::lxdebug->leave_sub();
1448 sub _delete_payments {
1449 $main::lxdebug->enter_sub();
1451 my ($self, $form, $dbh) = @_;
1453 my @delete_acc_trans_ids;
1455 # Delete old payment entries from acc_trans.
1457 qq|SELECT acc_trans_id
1459 WHERE (trans_id = ?) AND fx_transaction
1463 SELECT at.acc_trans_id
1465 LEFT JOIN chart c ON (at.chart_id = c.id)
1466 WHERE (trans_id = ?) AND (c.link LIKE '%AP_paid%')|;
1467 push @delete_acc_trans_ids, selectall_array_query($form, $dbh, $query, conv_i($form->{id}), conv_i($form->{id}));
1470 qq|SELECT at.acc_trans_id
1472 LEFT JOIN chart c ON (at.chart_id = c.id)
1473 WHERE (trans_id = ?)
1474 AND ((c.link = 'AP') OR (c.link LIKE '%:AP') OR (c.link LIKE 'AP:%'))
1475 ORDER BY at.acc_trans_id
1477 push @delete_acc_trans_ids, selectall_array_query($form, $dbh, $query, conv_i($form->{id}));
1479 if (@delete_acc_trans_ids) {
1480 $query = qq|DELETE FROM acc_trans WHERE acc_trans_id IN (| . join(", ", @delete_acc_trans_ids) . qq|)|;
1481 do_query($form, $dbh, $query);
1484 $main::lxdebug->leave_sub();
1488 $main::lxdebug->enter_sub();
1490 my ($self, $myconfig, $form, $locale) = @_;
1492 # connect to database, turn off autocommit
1493 my $dbh = $form->dbconnect_noauto($myconfig);
1495 my (%payments, $old_form, $row, $item, $query, %keep_vars);
1497 $old_form = save_form();
1499 # Delete all entries in acc_trans from prior payments.
1500 if (SL::DB::Default->get->payments_changeable != 0) {
1501 $self->_delete_payments($form, $dbh);
1504 # Save the new payments the user made before cleaning up $form.
1505 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 };
1507 # Clean up $form so that old content won't tamper the results.
1508 %keep_vars = map { $_, 1 } qw(login password id);
1509 map { delete $form->{$_} unless $keep_vars{$_} } keys %{ $form };
1511 # Retrieve the invoice from the database.
1512 $self->retrieve_invoice($myconfig, $form);
1514 # Set up the content of $form in the way that IR::post_invoice() expects.
1515 $form->{exchangerate} = $form->format_amount($myconfig, $form->{exchangerate});
1517 for $row (1 .. scalar @{ $form->{invoice_details} }) {
1518 $item = $form->{invoice_details}->[$row - 1];
1520 map { $item->{$_} = $form->format_amount($myconfig, $item->{$_}) } qw(qty sellprice);
1522 map { $form->{"${_}_${row}"} = $item->{$_} } keys %{ $item };
1525 $form->{rowcount} = scalar @{ $form->{invoice_details} };
1527 delete @{$form}{qw(invoice_details paidaccounts storno paid)};
1529 # Restore the payment options from the user input.
1530 map { $form->{$_} = $payments{$_} } keys %payments;
1532 # Get the AP accno (which is normally done by Form::create_links()).
1536 LEFT JOIN chart c ON (at.chart_id = c.id)
1537 WHERE (trans_id = ?)
1538 AND ((c.link = 'AP') OR (c.link LIKE '%:AP') OR (c.link LIKE 'AP:%'))
1539 ORDER BY at.acc_trans_id
1542 ($form->{AP}) = selectfirst_array_query($form, $dbh, $query, conv_i($form->{id}));
1544 # Post the new payments.
1545 $self->post_invoice($myconfig, $form, $dbh, 1);
1547 restore_form($old_form);
1549 my $rc = $dbh->commit();
1552 $main::lxdebug->leave_sub();
1558 $::lxdebug->enter_sub;
1560 my ($self, %params) = @_;
1562 if (!$params{vendor_id} || !$params{invdate}) {
1563 $::lxdebug->leave_sub;
1564 return $params{default};
1567 my $dbh = $::form->get_standard_dbh;
1568 my $query = qq|SELECT ?::date + pt.terms_netto
1570 LEFT JOIN payment_terms pt ON (pt.id = v.payment_id)
1573 my ($duedate) = selectfirst_array_query($::form, $dbh, $query, $params{invdate}, $params{vendor_id});
1575 $duedate ||= $params{default};
1577 $::lxdebug->leave_sub;