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;
50 use List::Util qw(min);
55 $main::lxdebug->enter_sub();
57 my ($self, $myconfig, $form, $provided_dbh, $payments_only) = @_;
59 # connect to database, turn off autocommit
60 my $dbh = $provided_dbh ? $provided_dbh : $form->dbconnect_noauto($myconfig);
61 my $restricter = SL::HTML::Restrict->create;
63 $form->{defaultcurrency} = $form->get_default_currency($myconfig);
64 my $defaultcurrency = $form->{defaultcurrency};
66 my $ic_cvar_configs = CVar->get_configs(module => 'IC',
69 my ($query, $sth, @values, $project_id);
70 my ($allocated, $taxrate, $taxamount, $taxdiff, $item);
71 my ($amount, $linetotal, $lastinventoryaccno, $lastexpenseaccno);
72 my ($netamount, $invoicediff, $expensediff) = (0, 0, 0);
74 my ($basefactor, $baseqty, @taxaccounts, $totaltax);
76 my $all_units = AM->retrieve_units($myconfig, $form);
79 if (!$payments_only) {
81 &reverse_invoice($dbh, $form);
83 ($form->{id}) = selectrow_query($form, $dbh, qq|SELECT nextval('glid')|);
84 do_query($form, $dbh, qq|INSERT INTO ap (id, invnumber, currency_id, taxzone_id) VALUES (?, '', (SELECT id FROM currencies WHERE name=?), ?)|, $form->{id}, $form->{currency}, $form->{taxzone_id});
88 if ($form->{currency} eq $defaultcurrency) {
89 $form->{exchangerate} = 1;
91 $exchangerate = $form->check_exchangerate($myconfig, $form->{currency}, $form->{invdate}, 'sell');
94 $form->{exchangerate} = $exchangerate || $form->parse_amount($myconfig, $form->{exchangerate});
95 $form->{exchangerate} = 1 unless ($form->{exchangerate} * 1);
98 my $q_item_unit = qq|SELECT unit FROM parts WHERE id = ?|;
99 my $h_item_unit = prepare_query($form, $dbh, $q_item_unit);
101 $form->get_lists('price_factors' => 'ALL_PRICE_FACTORS');
102 my %price_factors = map { $_->{id} => $_->{factor} } @{ $form->{ALL_PRICE_FACTORS} };
105 my @processed_invoice_ids;
106 for my $i (1 .. $form->{rowcount}) {
107 next unless $form->{"id_$i"};
109 $form->{"qty_$i"} = $form->parse_amount($myconfig, $form->{"qty_$i"});
110 $form->{"qty_$i"} *= -1 if $form->{storno};
112 if ( $::instance_conf->get_inventory_system eq 'periodic') {
113 # inventory account number is overwritten with expense account number, so
114 # never book incoming to inventory account but always to expense account
115 $form->{"inventory_accno_$i"} = $form->{"expense_accno_$i"}
119 if (!$item_units{$form->{"id_$i"}}) {
120 do_statement($form, $h_item_unit, $q_item_unit, $form->{"id_$i"});
121 ($item_units{$form->{"id_$i"}}) = $h_item_unit->fetchrow_array();
124 my $item_unit = $item_units{$form->{"id_$i"}};
126 if (defined($all_units->{$item_unit}->{factor})
127 && ($all_units->{$item_unit}->{factor} ne '')
128 && ($all_units->{$item_unit}->{factor} * 1 != 0)) {
129 $basefactor = $all_units->{$form->{"unit_$i"}}->{factor} / $all_units->{$item_unit}->{factor};
133 $baseqty = $form->{"qty_$i"} * $basefactor;
135 @taxaccounts = split / /, $form->{"taxaccounts_$i"};
140 $form->{"sellprice_$i"} = $form->parse_amount($myconfig, $form->{"sellprice_$i"});
141 (my $fxsellprice = $form->{"sellprice_$i"}) =~ /\.(\d+)/;
143 my $decimalplaces = ($dec > 2) ? $dec : 2;
145 map { $taxrate += $form->{"${_}_rate"} } @taxaccounts;
147 $price_factor = $price_factors{ $form->{"price_factor_id_$i"} } || 1;
148 # copied from IS.pm, with some changes (no decimalplaces corrections here etc)
149 # TODO maybe use PriceTaxCalculation or something like this for backends (IR.pm / IS.pm)
151 # undo discount formatting
152 $form->{"discount_$i"} = $form->parse_amount($myconfig, $form->{"discount_$i"}) / 100;
154 $form->{"sellprice_$i"} = $fxsellprice * (1 - $form->{"discount_$i"});
156 ######################################################################
157 if ($form->{"inventory_accno_$i"}) {
159 $linetotal = $form->round_amount($form->{"sellprice_$i"} * $form->{"qty_$i"} / $price_factor, 2);
161 if ($form->{taxincluded}) {
163 $taxamount = $linetotal * ($taxrate / (1 + $taxrate));
164 $form->{"sellprice_$i"} = $form->{"sellprice_$i"} * (1 / (1 + $taxrate));
167 $taxamount = $linetotal * $taxrate;
170 $netamount += $linetotal;
172 if ($form->round_amount($taxrate, 7) == 0) {
173 if ($form->{taxincluded}) {
174 foreach $item (@taxaccounts) {
176 $form->round_amount($linetotal * $form->{"${item}_rate"} / (1 + abs($form->{"${item}_rate"})), 2);
177 $taxdiff += $taxamount;
178 $form->{amount}{ $form->{id} }{$item} -= $taxamount;
180 $form->{amount}{ $form->{id} }{ $taxaccounts[0] } += $taxdiff;
183 map { $form->{amount}{ $form->{id} }{$_} -= $linetotal * $form->{"${_}_rate"} } @taxaccounts;
187 map { $form->{amount}{ $form->{id} }{$_} -= $taxamount * $form->{"${_}_rate"} / $taxrate } @taxaccounts;
190 # add purchase to inventory, this one is without the tax!
191 $amount = $form->{"sellprice_$i"} * $form->{"qty_$i"} * $form->{exchangerate} / $price_factor;
192 $linetotal = $form->round_amount($form->{"sellprice_$i"} * $form->{"qty_$i"} / $price_factor, 2) * $form->{exchangerate};
193 $linetotal = $form->round_amount($linetotal, 2);
195 # this is the difference for the inventory
196 $invoicediff += ($amount - $linetotal);
198 $form->{amount}{ $form->{id} }{ $form->{"inventory_accno_$i"} } -= $linetotal;
200 # adjust and round sellprice
201 $form->{"sellprice_$i"} = $form->round_amount($form->{"sellprice_$i"} * $form->{exchangerate}, $decimalplaces);
203 $lastinventoryaccno = $form->{"inventory_accno_$i"};
205 next if $payments_only;
207 # update parts table by setting lastcost to current price, don't allow negative values by using abs
208 $query = qq|UPDATE parts SET lastcost = ? WHERE id = ?|;
209 @values = (abs($fxsellprice * $form->{exchangerate} / $basefactor), conv_i($form->{"id_$i"}));
210 do_query($form, $dbh, $query, @values);
212 # check if we sold the item already and
213 # make an entry for the expense and inventory
214 my $taxzone = $form->{taxzone_id} * 1;
216 qq|SELECT i.id, i.qty, i.allocated, i.trans_id, i.base_qty,
217 bg.inventory_accno_id, tc.expense_accno_id AS expense_accno_id, a.transdate
218 FROM invoice i, ar a, parts p, buchungsgruppen bg, taxzone_charts tc
219 WHERE (i.parts_id = p.id)
221 AND ((i.base_qty + i.allocated) > 0)
222 AND (i.trans_id = a.id)
223 AND (p.buchungsgruppen_id = bg.id)
224 AND (tc.buchungsgruppen_id = p.buchungsgruppen_id)
225 AND (tc.taxzone_id = ${taxzone})
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, chart_link) VALUES (?, ?, ?, ?,
276 ORDER BY startdate DESC LIMIT 1),
281 ORDER BY startdate DESC LIMIT 1),
282 (SELECT 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, chart_link) VALUES (?, ?, ?, ?,
293 ORDER BY startdate DESC LIMIT 1),
298 ORDER BY startdate DESC LIMIT 1),
299 (SELECT 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 if (!$form->{"invoice_id_$i"}) {
371 # there is no persistent id, therefore create one with all necessary constraints
372 my $q_invoice_id = qq|SELECT nextval('invoiceid')|;
373 my $h_invoice_id = prepare_query($form, $dbh, $q_invoice_id);
374 do_statement($form, $h_invoice_id, $q_invoice_id);
375 $form->{"invoice_id_$i"} = $h_invoice_id->fetchrow_array();
376 my $q_create_invoice_id = qq|INSERT INTO invoice (id, trans_id, parts_id) values (?, ?, ?)|;
377 do_query($form, $dbh, $q_create_invoice_id, conv_i($form->{"invoice_id_$i"}), conv_i($form->{id}), conv_i($form->{"id_$i"}));
378 $h_invoice_id->finish();
381 # save detail record in invoice table
383 UPDATE invoice SET trans_id = ?, parts_id = ?, description = ?, longdescription = ?, qty = ?, base_qty = ?,
384 sellprice = ?, fxsellprice = ?, discount = ?, allocated = ?, unit = ?, deliverydate = ?,
385 project_id = ?, serialnumber = ?, price_factor_id = ?,
386 price_factor = (SELECT factor FROM price_factors WHERE id = ?), marge_price_factor = ?,
387 active_price_source = ?, active_discount_source = ?
391 @values = (conv_i($form->{id}), conv_i($form->{"id_$i"}),
392 $form->{"description_$i"}, $restricter->process($form->{"longdescription_$i"}), $form->{"qty_$i"} * -1,
393 $baseqty * -1, $form->{"sellprice_$i"}, $fxsellprice, $form->{"discount_$i"}, $allocated,
394 $form->{"unit_$i"}, conv_date($form->{deliverydate}),
395 conv_i($form->{"project_id_$i"}), $form->{"serialnumber_$i"},
396 conv_i($form->{"price_factor_id_$i"}), conv_i($form->{"price_factor_id_$i"}), conv_i($form->{"marge_price_factor_$i"}),
397 $form->{"active_price_source_$i"}, $form->{"active_discount_source_$i"},
398 conv_i($form->{"invoice_id_$i"}));
399 do_query($form, $dbh, $query, @values);
400 push @processed_invoice_ids, $form->{"invoice_id_$i"};
402 CVar->save_custom_variables(module => 'IC',
403 sub_module => 'invoice',
404 trans_id => $form->{"invoice_id_$i"},
405 configs => $ic_cvar_configs,
407 name_prefix => 'ic_',
408 name_postfix => "_$i",
410 # link previous items with invoice items See IS.pm (no credit note -> no invoice item)
411 foreach (qw(delivery_order_items orderitems)) {
412 if ($form->{"converted_from_${_}_id_$i"}) {
413 RecordLinks->create_links('dbh' => $dbh,
416 'from_ids' => $form->{"converted_from_${_}_id_$i"},
417 'to_table' => 'invoice',
418 'to_id' => $form->{"invoice_id_$i"},
420 delete $form->{"converted_from_${_}_id_$i"};
425 $h_item_unit->finish();
427 $project_id = conv_i($form->{"globalproject_id"});
429 $form->{datepaid} = $form->{invdate};
431 # all amounts are in natural state, netamount includes the taxes
432 # if tax is included, netamount is rounded to 2 decimal places,
436 for my $i (1 .. $form->{paidaccounts}) {
437 $form->{"paid_$i"} = $form->parse_amount($myconfig, $form->{"paid_$i"});
438 $form->{paid} += $form->{"paid_$i"};
439 $form->{datepaid} = $form->{"datepaid_$i"} if $form->{"datepaid_$i"};
442 my ($tax, $paiddiff) = (0, 0);
444 $netamount = $form->round_amount($netamount, 2);
446 # figure out rounding errors for amount paid and total amount
447 if ($form->{taxincluded}) {
449 $amount = $form->round_amount($netamount * $form->{exchangerate}, 2);
450 $paiddiff = $amount - $netamount * $form->{exchangerate};
451 $netamount = $amount;
453 foreach $item (split / /, $form->{taxaccounts}) {
454 $amount = $form->{amount}{ $form->{id} }{$item} * $form->{exchangerate};
455 $form->{amount}{ $form->{id} }{$item} = $form->round_amount($amount, 2);
457 $amount = $form->{amount}{ $form->{id} }{$item} * -1;
459 $netamount -= $amount;
462 $invoicediff += $paiddiff;
463 $expensediff += $paiddiff;
465 ######## this only applies to tax included
467 # in the sales invoice case rounding errors only have to be corrected for
468 # income accounts, it is enough to add the total rounding error to one of
469 # the income accounts, with the one assigned to the last row being used
470 # (lastinventoryaccno)
472 # in the purchase invoice case rounding errors may be split between
473 # inventory accounts and expense accounts. After rounding, an error of 1
474 # cent is introduced if the total rounding error exceeds 0.005. The total
475 # error is made up of $invoicediff and $expensediff, however, so if both
476 # values are below 0.005, but add up to a total >= 0.005, correcting
477 # lastinventoryaccno and lastexpenseaccno separately has no effect after
478 # rounding. This caused bug 1579. Therefore when the combined total exceeds
479 # 0.005, but neither do individually, the account with the larger value
480 # shall receive the total rounding error, and the next time it is rounded
481 # the 1 cent correction will be introduced.
483 $form->{amount}{ $form->{id} }{$lastinventoryaccno} -= $invoicediff if $lastinventoryaccno;
484 $form->{amount}{ $form->{id} }{$lastexpenseaccno} -= $expensediff if $lastexpenseaccno;
486 if ( (abs($expensediff)+abs($invoicediff)) >= 0.005 and abs($expensediff) < 0.005 and abs($invoicediff) < 0.005 ) {
488 # in total the rounding error adds up to 1 cent effectively, correct the
489 # larger of the two numbers
491 if ( abs($form->{amount}{ $form->{id} }{$lastinventoryaccno}) > abs($form->{amount}{ $form->{id} }{$lastexpenseaccno}) ) {
492 # $invoicediff has already been deducted, now also deduct expensediff
493 $form->{amount}{ $form->{id} }{$lastinventoryaccno} -= $expensediff;
495 # expensediff has already been deducted, now also deduct invoicediff
496 $form->{amount}{ $form->{id} }{$lastexpenseaccno} -= $invoicediff;
501 $amount = $form->round_amount($netamount * $form->{exchangerate}, 2);
502 $paiddiff = $amount - $netamount * $form->{exchangerate};
503 $netamount = $amount;
505 foreach my $item (split / /, $form->{taxaccounts}) {
506 $form->{amount}{ $form->{id} }{$item} = $form->round_amount($form->{amount}{ $form->{id} }{$item}, 2);
507 $amount = $form->round_amount( $form->{amount}{ $form->{id} }{$item} * $form->{exchangerate} * -1, 2);
508 $paiddiff += $amount - $form->{amount}{ $form->{id} }{$item} * $form->{exchangerate} * -1;
509 $form->{amount}{ $form->{id} }{$item} = $form->round_amount($amount * -1, 2);
510 $amount = $form->{amount}{ $form->{id} }{$item} * -1;
515 $form->{amount}{ $form->{id} }{ $form->{AP} } = $netamount + $tax;
518 $form->{paid} = $form->round_amount($form->{paid} * $form->{exchangerate} + $paiddiff, 2) if $form->{paid} != 0;
520 # update exchangerate
522 $form->update_exchangerate($dbh, $form->{currency}, $form->{invdate}, 0, $form->{exchangerate})
523 if ($form->{currency} ne $defaultcurrency) && !$exchangerate;
525 # record acc_trans transactions
526 foreach my $trans_id (keys %{ $form->{amount} }) {
527 foreach my $accno (keys %{ $form->{amount}{$trans_id} }) {
528 $form->{amount}{$trans_id}{$accno} = $form->round_amount($form->{amount}{$trans_id}{$accno}, 2);
531 next if $payments_only || !$form->{amount}{$trans_id}{$accno};
533 $query = qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate, taxkey, project_id, tax_id, chart_link)
534 VALUES (?, (SELECT id FROM chart WHERE accno = ?), ?, ?,
537 WHERE chart_id= (SELECT id
541 ORDER BY startdate DESC LIMIT 1),
545 WHERE chart_id= (SELECT id
549 ORDER BY startdate DESC LIMIT 1),
550 (SELECT link FROM chart WHERE accno = ?))|;
551 @values = ($trans_id, $accno, $form->{amount}{$trans_id}{$accno},
552 conv_date($form->{invdate}), $accno, conv_date($form->{invdate}), $project_id, $accno, conv_date($form->{invdate}), $accno);
553 do_query($form, $dbh, $query, @values);
557 # deduct payment differences from paiddiff
558 for my $i (1 .. $form->{paidaccounts}) {
559 if ($form->{"paid_$i"} != 0) {
560 $amount = $form->round_amount($form->{"paid_$i"} * $form->{exchangerate}, 2);
561 $paiddiff -= $amount - $form->{"paid_$i"} * $form->{exchangerate};
565 # force AP entry if 0
567 $form->{amount}{ $form->{id} }{ $form->{AP} } = $form->{paid} if $form->{amount}{$form->{id}}{$form->{AP}} == 0;
569 # record payments and offsetting AP
570 for my $i (1 .. $form->{paidaccounts}) {
571 if ($form->{"acc_trans_id_$i"}
573 && (SL::DB::Default->get->payments_changeable == 0)) {
577 next if $form->{"paid_$i"} == 0;
579 my ($accno) = split /--/, $form->{"AP_paid_$i"};
580 $form->{"datepaid_$i"} = $form->{invdate} unless ($form->{"datepaid_$i"});
581 $form->{datepaid} = $form->{"datepaid_$i"};
583 $amount = $form->round_amount($form->{"paid_$i"} * $form->{exchangerate} + $paiddiff, 2) * -1;
586 if ($form->{amount}{ $form->{id} }{ $form->{AP} } != 0) {
587 $query = qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate, taxkey, project_id, tax_id, chart_link)
588 VALUES (?, (SELECT id FROM chart WHERE accno = ?), ?, ?,
591 WHERE chart_id= (SELECT id
595 ORDER BY startdate DESC LIMIT 1),
599 WHERE chart_id= (SELECT id
603 ORDER BY startdate DESC LIMIT 1),
604 (SELECT link FROM chart WHERE accno = ?))|;
605 @values = (conv_i($form->{id}), $form->{AP}, $amount,
606 $form->{"datepaid_$i"}, $form->{AP}, conv_date($form->{"datepaid_$i"}), $project_id, $form->{AP}, conv_date($form->{"datepaid_$i"}), $form->{AP});
607 do_query($form, $dbh, $query, @values);
611 my $gldate = (conv_date($form->{"gldate_$i"}))? conv_date($form->{"gldate_$i"}) : conv_date($form->current_date($myconfig));
614 qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate, gldate, source, memo, taxkey, project_id, tax_id, chart_link)
615 VALUES (?, (SELECT id FROM chart WHERE accno = ?), ?, ?, ?, ?, ?,
618 WHERE chart_id= (SELECT id
619 FROM chart WHERE accno = ?)
621 ORDER BY startdate DESC LIMIT 1),
625 WHERE chart_id= (SELECT id
626 FROM chart WHERE accno = ?)
628 ORDER BY startdate DESC LIMIT 1),
629 (SELECT link FROM chart WHERE accno = ?))|;
630 @values = (conv_i($form->{id}), $accno, $form->{"paid_$i"}, $form->{"datepaid_$i"},
631 $gldate, $form->{"source_$i"}, $form->{"memo_$i"}, $accno, conv_date($form->{"datepaid_$i"}), $project_id, $accno, conv_date($form->{"datepaid_$i"}), $accno);
632 do_query($form, $dbh, $query, @values);
636 if ($form->{currency} eq $defaultcurrency) {
637 $form->{"exchangerate_$i"} = 1;
639 $exchangerate = $form->check_exchangerate($myconfig, $form->{currency}, $form->{"datepaid_$i"}, 'sell');
640 $form->{"exchangerate_$i"} = $exchangerate || $form->parse_amount($myconfig, $form->{"exchangerate_$i"});
643 # exchangerate difference
644 $form->{fx}{$accno}{ $form->{"datepaid_$i"} } += $form->{"paid_$i"} * ($form->{"exchangerate_$i"} - 1) + $paiddiff;
648 ($form->{"paid_$i"} * $form->{exchangerate}) -
649 ($form->{"paid_$i"} * $form->{"exchangerate_$i"});
651 $form->{fx}{ $form->{fxgain_accno} }{ $form->{"datepaid_$i"} } += $amount;
653 $form->{fx}{ $form->{fxloss_accno} }{ $form->{"datepaid_$i"} } += $amount;
658 # update exchange rate
659 $form->update_exchangerate($dbh, $form->{currency}, $form->{"datepaid_$i"}, 0, $form->{"exchangerate_$i"})
660 if ($form->{currency} ne $defaultcurrency) && !$exchangerate;
663 # record exchange rate differences and gains/losses
664 foreach my $accno (keys %{ $form->{fx} }) {
665 foreach my $transdate (keys %{ $form->{fx}{$accno} }) {
666 $form->{fx}{$accno}{$transdate} = $form->round_amount($form->{fx}{$accno}{$transdate}, 2);
667 next if ($form->{fx}{$accno}{$transdate} == 0);
669 $query = qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate, cleared, fx_transaction, taxkey, project_id, tax_id, chart_link)
670 VALUES (?, (SELECT id FROM chart WHERE accno = ?), ?, ?, '0', '1', 0, ?,
671 (SELECT id FROM tax WHERE taxkey=0 LIMIT 1),
672 (SELECT link FROM chart WHERE accno = ?))|;
673 @values = (conv_i($form->{id}), $accno, $form->{fx}{$accno}{$transdate}, conv_date($transdate), $project_id, $accno);
674 do_query($form, $dbh, $query, @values);
678 IO->set_datepaid(table => 'ap', id => $form->{id}, dbh => $dbh);
680 if ($payments_only) {
681 $query = qq|UPDATE ap SET paid = ? WHERE id = ?|;
682 do_query($form, $dbh, $query, $form->{paid}, conv_i($form->{id}));
684 if (!$provided_dbh) {
689 $main::lxdebug->leave_sub();
693 $amount = $netamount + $tax;
695 # set values which could be empty
696 my $taxzone_id = $form->{taxzone_id} * 1;
697 $taxzone_id = SL::DB::Manager::TaxZone->get_default->id unless SL::DB::Manager::TaxZone->find_by(id => $taxzone_id);
699 $form->{invnumber} = $form->{id} unless $form->{invnumber};
702 $query = qq|UPDATE ap SET
703 invnumber = ?, ordnumber = ?, quonumber = ?, transdate = ?,
704 orddate = ?, quodate = ?, vendor_id = ?, amount = ?,
705 netamount = ?, paid = ?, duedate = ?,
706 invoice = ?, taxzone_id = ?, notes = ?, taxincluded = ?,
707 intnotes = ?, storno_id = ?, storno = ?,
708 cp_id = ?, employee_id = ?, department_id = ?, delivery_term_id = ?,
709 globalproject_id = ?, direct_debit = ?
712 $form->{invnumber}, $form->{ordnumber}, $form->{quonumber}, conv_date($form->{invdate}),
713 conv_date($form->{orddate}), conv_date($form->{quodate}), conv_i($form->{vendor_id}), $amount,
714 $netamount, $form->{paid}, conv_date($form->{duedate}),
715 '1', $taxzone_id, $form->{notes}, $form->{taxincluded} ? 't' : 'f',
716 $form->{intnotes}, conv_i($form->{storno_id}), $form->{storno} ? 't' : 'f',
717 conv_i($form->{cp_id}), conv_i($form->{employee_id}), conv_i($form->{department_id}), conv_i($form->{delivery_term_id}),
718 conv_i($form->{globalproject_id}),
719 $form->{direct_debit} ? 't' : 'f',
722 do_query($form, $dbh, $query, @values);
724 if ($form->{storno}) {
725 $query = qq|UPDATE ap SET paid = paid + amount WHERE id = ?|;
726 do_query($form, $dbh, $query, conv_i($form->{storno_id}));
728 $query = qq|UPDATE ap SET storno = 't' WHERE id = ?|;
729 do_query($form, $dbh, $query, conv_i($form->{storno_id}));
731 $query = qq!UPDATE ap SET intnotes = ? || intnotes WHERE id = ?!;
732 do_query($form, $dbh, $query, "Rechnung storniert am $form->{invdate} ", conv_i($form->{storno_id}));
734 $query = qq|UPDATE ap SET paid = amount WHERE id = ?|;
735 do_query($form, $dbh, $query, conv_i($form->{id}));
739 $form->{name} = $form->{vendor};
740 $form->{name} =~ s/--\Q$form->{vendor_id}\E//;
743 $form->add_shipto($dbh, $form->{id}, "AP");
745 # delete zero entries
746 do_query($form, $dbh, qq|DELETE FROM acc_trans WHERE amount = 0|);
748 Common::webdav_folder($form);
750 # Link this record to the records it was created from.
751 if ($form->{convert_from_oe_ids}) {
752 RecordLinks->create_links('dbh' => $dbh,
754 'from_table' => 'oe',
755 'from_ids' => $form->{convert_from_oe_ids},
757 'to_id' => $form->{id},
759 delete $form->{convert_from_oe_ids};
762 my @convert_from_do_ids = map { $_ * 1 } grep { $_ } split m/\s+/, $form->{convert_from_do_ids};
763 if (scalar @convert_from_do_ids) {
764 DO->close_orders('dbh' => $dbh,
765 'ids' => \@convert_from_do_ids);
767 RecordLinks->create_links('dbh' => $dbh,
769 'from_table' => 'delivery_orders',
770 'from_ids' => \@convert_from_do_ids,
772 'to_id' => $form->{id},
775 delete $form->{convert_from_do_ids};
777 ARAP->close_orders_if_billed('dbh' => $dbh,
778 'arap_id' => $form->{id},
781 # search for orphaned invoice items
782 $query = sprintf 'SELECT id FROM invoice WHERE trans_id = ? AND NOT id IN (%s)', join ', ', ("?") x scalar @processed_invoice_ids;
783 @values = (conv_i($form->{id}), map { conv_i($_) } @processed_invoice_ids);
784 my @orphaned_ids = map { $_->{id} } selectall_hashref_query($form, $dbh, $query, @values);
785 if (scalar @orphaned_ids) {
786 # clean up invoice items
787 $query = sprintf 'DELETE FROM invoice WHERE id IN (%s)', join ', ', ("?") x scalar @orphaned_ids;
788 do_query($form, $dbh, $query, @orphaned_ids);
791 # safety check datev export
792 if ($::instance_conf->get_datev_check_on_purchase_invoice) {
793 my $transdate = $::form->{invdate} ? DateTime->from_lxoffice($::form->{invdate}) : undef;
794 $transdate ||= DateTime->today;
796 my $datev = SL::DATEV->new(
797 exporttype => DATEV_ET_BUCHUNGEN,
798 format => DATEV_FORMAT_KNE,
802 trans_id => $form->{id},
807 if ($datev->errors) {
809 die join "\n", $::locale->text('DATEV check returned errors:'), $datev->errors;
814 if (!$provided_dbh) {
815 $rc = $dbh->commit();
819 $main::lxdebug->leave_sub();
824 sub reverse_invoice {
825 $main::lxdebug->enter_sub();
827 my ($dbh, $form) = @_;
829 # reverse inventory items
831 qq|SELECT i.parts_id, p.inventory_accno_id, p.expense_accno_id, i.qty, i.allocated, i.sellprice
832 FROM invoice i, parts p
833 WHERE (i.parts_id = p.id)
834 AND (i.trans_id = ?)|;
835 my $sth = prepare_execute_query($form, $dbh, $query, conv_i($form->{id}));
839 while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
840 $netamount += $form->round_amount($ref->{sellprice} * $ref->{qty} * -1, 2);
842 next unless $ref->{inventory_accno_id};
844 # if $ref->{allocated} > 0 than we sold that many items
845 next if ($ref->{allocated} <= 0);
847 # get references for sold items
849 qq|SELECT i.id, i.trans_id, i.allocated, a.transdate
851 WHERE (i.parts_id = ?)
852 AND (i.allocated < 0)
853 AND (i.trans_id = a.id)
854 ORDER BY transdate DESC|;
855 my $sth2 = prepare_execute_query($form, $dbh, $query, $ref->{parts_id});
857 while (my $pthref = $sth2->fetchrow_hashref("NAME_lc")) {
858 my $qty = $ref->{allocated};
859 if (($ref->{allocated} + $pthref->{allocated}) > 0) {
860 $qty = $pthref->{allocated} * -1;
863 my $amount = $form->round_amount($ref->{sellprice} * $qty, 2);
866 $form->update_balance($dbh, "invoice", "allocated", qq|id = $pthref->{id}|, $qty);
868 $form->update_balance($dbh, "acc_trans", "amount",
869 qq| (trans_id = $pthref->{trans_id})
870 AND (chart_id = $ref->{expense_accno_id})
871 AND (transdate = '$pthref->{transdate}')|,
874 $form->update_balance($dbh, "acc_trans", "amount",
875 qq| (trans_id = $pthref->{trans_id})
876 AND (chart_id = $ref->{inventory_accno_id})
877 AND (transdate = '$pthref->{transdate}')|,
880 last if (($ref->{allocated} -= $qty) <= 0);
886 my $id = conv_i($form->{id});
889 $query = qq|DELETE FROM acc_trans WHERE trans_id = ?|;
890 do_query($form, $dbh, $query, $id);
892 $query = qq|DELETE FROM shipto WHERE (trans_id = ?) AND (module = 'AP')|;
893 do_query($form, $dbh, $query, $id);
895 $main::lxdebug->leave_sub();
899 $main::lxdebug->enter_sub();
901 my ($self, $myconfig, $form) = @_;
903 # connect to database
904 my $dbh = $form->dbconnect_noauto($myconfig);
906 &reverse_invoice($dbh, $form);
908 my @values = (conv_i($form->{id}));
910 # delete zero entries
911 # wtf? use case for this?
912 $query = qq|DELETE FROM acc_trans WHERE amount = 0|;
913 do_query($form, $dbh, $query);
917 qq|DELETE FROM invoice WHERE trans_id = ?|,
918 qq|DELETE FROM ap WHERE id = ?|,
921 map { do_query($form, $dbh, $_, @values) } @queries;
923 my $rc = $dbh->commit;
926 $main::lxdebug->leave_sub();
931 sub retrieve_invoice {
932 $main::lxdebug->enter_sub();
934 my ($self, $myconfig, $form) = @_;
936 # connect to database
937 my $dbh = $form->dbconnect($myconfig);
939 my ($query, $sth, $ref, $q_invdate);
942 $q_invdate = qq|, COALESCE((SELECT transdate FROM ar WHERE id = (SELECT MAX(id) FROM ar)), current_date) AS invdate|;
943 if ($form->{vendor_id}) {
944 my $vendor_id = $dbh->quote($form->{vendor_id} * 1);
946 qq|, COALESCE((SELECT transdate FROM ar WHERE id = (SELECT MAX(id) FROM ar)), current_date) +
947 COALESCE((SELECT pt.terms_netto
949 LEFT JOIN payment_terms pt ON (v.payment_id = pt.id)
950 WHERE v.id = $vendor_id),
955 # get default accounts and last invoice number
958 (SELECT c.accno FROM chart c WHERE d.inventory_accno_id = c.id) AS inventory_accno,
959 (SELECT c.accno FROM chart c WHERE d.income_accno_id = c.id) AS income_accno,
960 (SELECT c.accno FROM chart c WHERE d.expense_accno_id = c.id) AS expense_accno,
961 (SELECT c.accno FROM chart c WHERE d.fxgain_accno_id = c.id) AS fxgain_accno,
962 (SELECT c.accno FROM chart c WHERE d.fxloss_accno_id = c.id) AS fxloss_accno
965 $ref = selectfirst_hashref_query($form, $dbh, $query);
966 map { $form->{$_} = $ref->{$_} } keys %$ref;
970 $main::lxdebug->leave_sub();
976 $query = qq|SELECT cp_id, invnumber, transdate AS invdate, duedate,
977 orddate, quodate, globalproject_id,
978 ordnumber, quonumber, paid, taxincluded, notes, taxzone_id, storno, gldate,
979 intnotes, (SELECT cu.name FROM currencies cu WHERE cu.id=ap.currency_id) AS currency, direct_debit,
983 $ref = selectfirst_hashref_query($form, $dbh, $query, conv_i($form->{id}));
984 map { $form->{$_} = $ref->{$_} } keys %$ref;
986 $form->{exchangerate} = $form->get_exchangerate($dbh, $form->{currency}, $form->{invdate}, "sell");
989 $query = qq|SELECT * FROM shipto WHERE (trans_id = ?) AND (module = 'AP')|;
990 $ref = selectfirst_hashref_query($form, $dbh, $query, conv_i($form->{id}));
992 map { $form->{$_} = $ref->{$_} } keys %$ref;
994 my $transdate = $form->{invdate} ? $dbh->quote($form->{invdate}) : "current_date";
996 my $taxzone_id = $form->{taxzone_id} * 1;
997 $taxzone_id = SL::DB::Manager::TaxZone->get_default->id unless SL::DB::Manager::TaxZone->find_by(id => $taxzone_id);
999 # retrieve individual items
1002 c1.accno AS inventory_accno, c1.new_chart_id AS inventory_new_chart, date($transdate) - c1.valid_from AS inventory_valid,
1003 c2.accno AS income_accno, c2.new_chart_id AS income_new_chart, date($transdate) - c2.valid_from AS income_valid,
1004 c3.accno AS expense_accno, c3.new_chart_id AS expense_new_chart, date($transdate) - c3.valid_from AS expense_valid,
1007 i.description, i.longdescription, i.qty, i.fxsellprice AS sellprice, i.parts_id AS id, i.unit, i.deliverydate, i.project_id, i.serialnumber,
1008 i.price_factor_id, i.price_factor, i.marge_price_factor, i.discount, i.active_price_source, i.active_discount_source,
1009 p.partnumber, p.inventory_accno_id AS part_inventory_accno_id, pr.projectnumber, pg.partsgroup
1012 JOIN parts p ON (i.parts_id = p.id)
1013 LEFT JOIN chart c1 ON ((SELECT inventory_accno_id FROM buchungsgruppen WHERE id = p.buchungsgruppen_id) = c1.id)
1014 LEFT JOIN chart c2 ON ((SELECT tc.income_accno_id FROM taxzone_charts tc where tc.taxzone_id = '$taxzone_id' and tc.buchungsgruppen_id = p.buchungsgruppen_id) = c2.id)
1015 LEFT JOIN chart c3 ON ((SELECT tc.expense_accno_id FROM taxzone_charts tc where tc.taxzone_id = '$taxzone_id' and tc.buchungsgruppen_id = p.buchungsgruppen_id) = c3.id)
1016 LEFT JOIN project pr ON (i.project_id = pr.id)
1017 LEFT JOIN partsgroup pg ON (pg.id = p.partsgroup_id)
1019 WHERE i.trans_id = ?
1022 $sth = prepare_execute_query($form, $dbh, $query, conv_i($form->{id}));
1024 while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
1025 # Retrieve custom variables.
1026 my $cvars = CVar->get_custom_variables(dbh => $dbh,
1028 sub_module => 'invoice',
1029 trans_id => $ref->{invoice_id},
1031 map { $ref->{"ic_cvar_$_->{name}"} = $_->{value} } @{ $cvars };
1033 map({ delete($ref->{$_}); } qw(inventory_accno inventory_new_chart inventory_valid)) if !$ref->{"part_inventory_accno_id"};
1034 delete($ref->{"part_inventory_accno_id"});
1036 foreach my $type (qw(inventory income expense)) {
1037 while ($ref->{"${type}_new_chart"} && ($ref->{"${type}_valid"} >=0)) {
1038 my $query = qq|SELECT accno, new_chart_id, date($transdate) - valid_from FROM chart WHERE id = ?|;
1039 @$ref{ map $type.$_, qw(_accno _new_chart _valid) } = selectrow_query($form, $dbh, $query, $ref->{"${type}_new_chart"});
1043 # get tax rates and description
1044 my $accno_id = ($form->{vc} eq "customer") ? $ref->{income_accno} : $ref->{expense_accno};
1046 qq|SELECT c.accno, t.taxdescription, t.rate, t.taxnumber FROM tax t
1047 LEFT JOIN chart c ON (c.id = t.chart_id)
1049 (SELECT tk.tax_id FROM taxkeys tk
1050 WHERE tk.chart_id = (SELECT id FROM chart WHERE accno = ?)
1051 AND (startdate <= $transdate)
1052 ORDER BY startdate DESC
1055 my $stw = prepare_execute_query($form, $dbh, $query, $accno_id);
1056 $ref->{taxaccounts} = "";
1059 while (my $ptr = $stw->fetchrow_hashref("NAME_lc")) {
1060 if (($ptr->{accno} eq "") && ($ptr->{rate} == 0)) {
1065 $ref->{taxaccounts} .= "$ptr->{accno} ";
1067 if (!($form->{taxaccounts} =~ /\Q$ptr->{accno}\E/)) {
1068 $form->{"$ptr->{accno}_rate"} = $ptr->{rate};
1069 $form->{"$ptr->{accno}_description"} = $ptr->{taxdescription};
1070 $form->{"$ptr->{accno}_taxnumber"} = $ptr->{taxnumber};
1071 $form->{taxaccounts} .= "$ptr->{accno} ";
1076 chop $ref->{taxaccounts};
1077 push @{ $form->{invoice_details} }, $ref;
1082 Common::webdav_folder($form);
1086 $main::lxdebug->leave_sub();
1090 $main::lxdebug->enter_sub();
1092 my ($self, $myconfig, $form, $params) = @_;
1094 $params = $form unless defined $params && ref $params eq "HASH";
1096 # connect to database
1097 my $dbh = $form->dbconnect($myconfig);
1099 my $dateformat = $myconfig->{dateformat};
1100 $dateformat .= "yy" if $myconfig->{dateformat} !~ /^y/;
1102 my $vid = conv_i($params->{vendor_id});
1103 my $vnr = conv_i($params->{vendornumber});
1106 ($params->{invdate})
1107 ? "to_date(" . $dbh->quote($params->{invdate}) . ", '$dateformat')"
1114 $where .= 'AND v.id = ?';
1118 $where .= 'AND v.vendornumber = ?';
1123 v.id AS vendor_id, v.name AS vendor, v.discount as vendor_discount,
1124 v.creditlimit, v.terms, v.notes AS intnotes,
1125 v.email, v.cc, v.bcc, v.language_id, v.payment_id, v.delivery_term_id,
1126 v.street, v.zipcode, v.city, v.country, v.taxzone_id, cu.name AS curr, v.direct_debit,
1127 $duedate + COALESCE(pt.terms_netto, 0) AS duedate,
1128 b.description AS business
1130 LEFT JOIN business b ON (b.id = v.business_id)
1131 LEFT JOIN payment_terms pt ON (v.payment_id = pt.id)
1132 LEFT JOIN currencies cu ON (v.currency_id = cu.id)
1134 my $ref = selectfirst_hashref_query($form, $dbh, $query, @values);
1135 map { $params->{$_} = $ref->{$_} } keys %$ref;
1137 # use vendor currency
1138 $form->{currency} = $form->{curr};
1140 $params->{creditremaining} = $params->{creditlimit};
1142 $query = qq|SELECT SUM(amount - paid) FROM ap WHERE vendor_id = ?|;
1143 my ($unpaid_invoices) = selectfirst_array_query($form, $dbh, $query, $vid);
1144 $params->{creditremaining} -= $unpaid_invoices;
1146 $query = qq|SELECT o.amount,
1149 WHERE (e.currency_id = o.currency_id)
1150 AND (e.transdate = o.transdate)) AS exch
1152 WHERE (o.vendor_id = ?) AND (o.quotation = '0') AND (o.closed = '0')|;
1153 my $sth = prepare_execute_query($form, $dbh, $query, $vid);
1154 while (my ($amount, $exch) = $sth->fetchrow_array()) {
1155 $exch = 1 unless $exch;
1156 $params->{creditremaining} -= $amount * $exch;
1160 if (!$params->{id} && $params->{type} !~ /_(order|quotation)/) {
1161 # setup last accounts used
1163 qq|SELECT c.id, c.accno, c.description, c.link, c.category
1165 JOIN acc_trans ac ON (ac.chart_id = c.id)
1166 JOIN ap a ON (a.id = ac.trans_id)
1167 WHERE (a.vendor_id = ?)
1168 AND (NOT ((c.link LIKE '%_tax%') OR (c.link LIKE '%_paid%')))
1169 AND (a.id IN (SELECT max(a2.id) FROM ap a2 WHERE a2.vendor_id = ?))|;
1170 my $refs = selectall_hashref_query($form, $dbh, $query, $vid, $vid);
1174 if ($ref->{category} eq 'E') {
1176 my ($tax_id, $rate);
1177 if ($params->{initial_transdate}) {
1178 my $tax_query = qq|SELECT tk.tax_id, t.rate FROM taxkeys tk
1179 LEFT JOIN tax t ON (tk.tax_id = t.id)
1180 WHERE (tk.chart_id = ?) AND (startdate <= ?)
1181 ORDER BY tk.startdate DESC
1183 ($tax_id, $rate) = selectrow_query($form, $dbh, $tax_query, $ref->{id}, $params->{initial_transdate});
1184 $params->{"taxchart_$i"} = "${tax_id}--${rate}";
1187 $params->{"AP_amount_$i"} = "$ref->{accno}--$tax_id";
1190 if ($ref->{category} eq 'L') {
1191 $params->{APselected} = $params->{AP_1} = $ref->{accno};
1194 $params->{rowcount} = $i if ($i && !$params->{type});
1199 $main::lxdebug->leave_sub();
1203 $main::lxdebug->enter_sub();
1205 my ($self, $myconfig, $form) = @_;
1207 # connect to database
1208 my $dbh = $form->dbconnect($myconfig);
1210 my $i = $form->{rowcount};
1212 # don't include assemblies or obsolete parts
1213 my $where = "NOT p.assembly = '1' AND NOT p.obsolete = '1'";
1216 foreach my $table_column (qw(p.partnumber p.description pg.partsgroup)) {
1217 my $field = (split m{\.}, $table_column)[1];
1218 next unless $form->{"${field}_${i}"};
1219 $where .= " AND lower(${table_column}) LIKE lower(?)";
1220 push @values, '%' . $form->{"${field}_${i}"} . '%';
1224 if ($form->{"partnumber_$i"} && !$form->{"description_$i"}) {
1225 $where .= qq| OR (NOT p.obsolete = '1' AND p.ean = ? )|;
1226 push @values, $form->{"partnumber_$i"};
1228 # also search hits in makemodels, but only cache the results by id and merge later
1230 SELECT parts_id, model FROM makemodel
1231 LEFT JOIN parts ON parts.id = parts_id
1232 WHERE NOT parts.obsolete AND model ILIKE ? AND (make IS NULL OR make = ?);
1234 my $mm_results = selectall_hashref_query($::form, $dbh, $mm_query, '%' . $form->{"partnumber_$i"} . '%', $::form->{vendor_id});
1235 my @mm_ids = map { $_->{parts_id} } @$mm_results;
1236 push @{$mm_by_id{ $_->{parts_id} } ||= []}, $_ for @$mm_results;
1239 $where .= qq| OR p.id IN (| . join(',', ('?') x @mm_ids) . qq|)|;
1240 push @values, @mm_ids;
1244 # Search for part ID overrides all other criteria.
1245 if ($form->{"id_${i}"}) {
1246 $where = qq|p.id = ?|;
1247 @values = ($form->{"id_${i}"});
1250 if ($form->{"description_$i"}) {
1251 $where .= " ORDER BY p.description";
1253 $where .= " ORDER BY p.partnumber";
1257 if ($form->{type} eq "invoice") {
1258 $transdate = $form->{deliverydate} ? $dbh->quote($form->{deliverydate})
1259 : $form->{invdate} ? $dbh->quote($form->{invdate})
1262 $transdate = $form->{transdate} ? $dbh->quote($form->{transdate}) : "current_date";
1265 my $taxzone_id = $form->{taxzone_id} * 1;
1266 $taxzone_id = SL::DB::Manager::TaxZone->get_default->id unless SL::DB::Manager::TaxZone->find_by(id => $taxzone_id);
1270 p.id, p.partnumber, p.description, p.lastcost AS sellprice, p.listprice,
1271 p.unit, p.assembly, p.onhand, p.formel,
1272 p.notes AS partnotes, p.notes AS longdescription, p.not_discountable,
1273 p.inventory_accno_id, p.price_factor_id,
1276 pfac.factor AS price_factor,
1278 c1.accno AS inventory_accno,
1279 c1.new_chart_id AS inventory_new_chart,
1280 date($transdate) - c1.valid_from AS inventory_valid,
1282 c2.accno AS income_accno,
1283 c2.new_chart_id AS income_new_chart,
1284 date($transdate) - c2.valid_from AS income_valid,
1286 c3.accno AS expense_accno,
1287 c3.new_chart_id AS expense_new_chart,
1288 date($transdate) - c3.valid_from AS expense_valid,
1293 LEFT JOIN chart c1 ON
1294 ((SELECT inventory_accno_id
1295 FROM buchungsgruppen
1296 WHERE id = p.buchungsgruppen_id) = c1.id)
1297 LEFT JOIN chart c2 ON
1298 ((SELECT tc.income_accno_id
1299 FROM taxzone_charts tc
1300 WHERE tc.taxzone_id = '$taxzone_id' and tc.buchungsgruppen_id = p.buchungsgruppen_id) = c2.id)
1301 LEFT JOIN chart c3 ON
1302 ((SELECT tc.expense_accno_id
1303 FROM taxzone_charts tc
1304 WHERE tc.taxzone_id = '$taxzone_id' and tc.buchungsgruppen_id = p.buchungsgruppen_id) = c3.id)
1305 LEFT JOIN partsgroup pg ON (pg.id = p.partsgroup_id)
1306 LEFT JOIN price_factors pfac ON (pfac.id = p.price_factor_id)
1308 my $sth = prepare_execute_query($form, $dbh, $query, @values);
1310 my @translation_queries = ( [ qq|SELECT tr.translation, tr.longdescription
1312 WHERE tr.language_id = ? AND tr.parts_id = ?| ],
1313 [ qq|SELECT tr.translation, tr.longdescription
1315 WHERE tr.language_id IN
1318 WHERE article_code = (SELECT article_code FROM language WHERE id = ?))
1321 map { push @{ $_ }, prepare_query($form, $dbh, $_->[0]) } @translation_queries;
1323 $form->{item_list} = [];
1324 while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
1326 if ($mm_by_id{$ref->{id}}) {
1327 $ref->{makemodels} = $mm_by_id{$ref->{id}};
1328 push @{ $ref->{matches} ||= [] }, $::locale->text('Model') . ': ' . join ', ', map { $_->{model} } @{ $mm_by_id{$ref->{id}} };
1331 if ($ref->{ean} eq $::form->{"partnumber_$i"}) {
1332 push @{ $ref->{matches} ||= [] }, $::locale->text('EAN') . ': ' . $ref->{ean};
1335 # In der Buchungsgruppe ist immer ein Bestandskonto verknuepft, auch wenn
1336 # es sich um eine Dienstleistung handelt. Bei Dienstleistungen muss das
1337 # Buchungskonto also aus dem Ergebnis rausgenommen werden.
1338 if (!$ref->{inventory_accno_id}) {
1339 map({ delete($ref->{"inventory_${_}"}); } qw(accno new_chart valid));
1341 delete($ref->{inventory_accno_id});
1343 # get tax rates and description
1344 my $accno_id = ($form->{vc} eq "customer") ? $ref->{income_accno} : $ref->{expense_accno};
1346 qq|SELECT c.accno, t.taxdescription, t.rate, t.taxnumber
1348 LEFT JOIN chart c on (c.id = t.chart_id)
1356 AND (startdate <= $transdate)
1357 ORDER BY startdate DESC
1360 my $stw = prepare_execute_query($form, $dbh, $query, $accno_id);
1362 $ref->{taxaccounts} = "";
1364 while (my $ptr = $stw->fetchrow_hashref("NAME_lc")) {
1366 if (($ptr->{accno} eq "") && ($ptr->{rate} == 0)) {
1371 $ref->{taxaccounts} .= "$ptr->{accno} ";
1373 if (!($form->{taxaccounts} =~ /\Q$ptr->{accno}\E/)) {
1374 $form->{"$ptr->{accno}_rate"} = $ptr->{rate};
1375 $form->{"$ptr->{accno}_description"} = $ptr->{taxdescription};
1376 $form->{"$ptr->{accno}_taxnumber"} = $ptr->{taxnumber};
1377 $form->{taxaccounts} .= "$ptr->{accno} ";
1380 if ($form->{language_id}) {
1381 for my $spec (@translation_queries) {
1382 do_statement($form, $spec->[1], $spec->[0], conv_i($form->{language_id}), conv_i($ref->{id}));
1383 my ($translation, $longdescription) = $spec->[1]->fetchrow_array;
1384 next unless $translation;
1385 $ref->{description} = $translation;
1386 $ref->{longdescription} = $longdescription;
1393 chop $ref->{taxaccounts};
1395 $ref->{onhand} *= 1;
1397 push @{ $form->{item_list} }, $ref;
1402 $_->[1]->finish for @translation_queries;
1404 foreach my $item (@{ $form->{item_list} }) {
1405 my $custom_variables = CVar->get_custom_variables(module => 'IC',
1406 trans_id => $item->{id},
1410 map { $item->{"ic_cvar_" . $_->{name} } = $_->{value} } @{ $custom_variables };
1415 $main::lxdebug->leave_sub();
1418 sub vendor_details {
1419 $main::lxdebug->enter_sub();
1421 my ($self, $myconfig, $form, @wanted_vars) = @_;
1423 # connect to database
1424 my $dbh = $form->dbconnect($myconfig);
1428 # get contact id, set it if nessessary
1429 $form->{cp_id} *= 1;
1431 if ($form->{cp_id}) {
1432 $contact = "AND cp.cp_id = ?";
1433 push @values, $form->{cp_id};
1436 # get rest for the vendor
1437 # fax and phone and email as vendor*
1439 qq|SELECT ct.*, cp.*, ct.notes as vendornotes, phone as vendorphone, fax as vendorfax, email as vendoremail,
1442 LEFT JOIN contacts cp ON (ct.id = cp.cp_cv_id)
1443 LEFT JOIN currencies cu ON (ct.currency_id = cu.id)
1444 WHERE (ct.id = ?) $contact
1447 my $ref = selectfirst_hashref_query($form, $dbh, $query, $form->{vendor_id}, @values);
1449 # remove id and taxincluded before copy back
1450 delete @$ref{qw(id taxincluded)};
1452 @wanted_vars = grep({ $_ } @wanted_vars);
1453 if (scalar(@wanted_vars) > 0) {
1455 map({ $h_wanted_vars{$_} = 1; } @wanted_vars);
1456 map({ delete($ref->{$_}) unless ($h_wanted_vars{$_}); } keys(%{$ref}));
1459 map { $form->{$_} = $ref->{$_} } keys %$ref;
1461 my $custom_variables = CVar->get_custom_variables('dbh' => $dbh,
1463 'trans_id' => $form->{vendor_id});
1464 map { $form->{"vc_cvar_$_->{name}"} = $_->{value} } @{ $custom_variables };
1466 $form->{cp_greeting} = GenericTranslations->get('dbh' => $dbh,
1467 'translation_type' => 'greetings::' . ($form->{cp_gender} eq 'f' ? 'female' : 'male'),
1468 'allow_fallback' => 1);
1472 $main::lxdebug->leave_sub();
1476 $main::lxdebug->enter_sub();
1478 my ($self, $myconfig, $form) = @_;
1480 # connect to database
1481 my $dbh = $form->dbconnect($myconfig);
1484 qq|SELECT accno, description, link
1486 WHERE link LIKE '%IC%'
1488 my $sth = prepare_execute_query($query, $dbh, $query);
1490 while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
1491 foreach my $key (split(/:/, $ref->{link})) {
1493 push @{ $form->{IC_links}{$key} },
1494 { accno => $ref->{accno},
1495 description => $ref->{description} };
1503 $main::lxdebug->leave_sub();
1506 sub _delete_payments {
1507 $main::lxdebug->enter_sub();
1509 my ($self, $form, $dbh) = @_;
1511 my @delete_acc_trans_ids;
1513 # Delete old payment entries from acc_trans.
1515 qq|SELECT acc_trans_id
1517 WHERE (trans_id = ?) AND fx_transaction
1521 SELECT at.acc_trans_id
1523 LEFT JOIN chart c ON (at.chart_id = c.id)
1524 WHERE (trans_id = ?) AND (c.link LIKE '%AP_paid%')|;
1525 push @delete_acc_trans_ids, selectall_array_query($form, $dbh, $query, conv_i($form->{id}), conv_i($form->{id}));
1528 qq|SELECT at.acc_trans_id
1530 LEFT JOIN chart c ON (at.chart_id = c.id)
1531 WHERE (trans_id = ?)
1532 AND ((c.link = 'AP') OR (c.link LIKE '%:AP') OR (c.link LIKE 'AP:%'))
1533 ORDER BY at.acc_trans_id
1535 push @delete_acc_trans_ids, selectall_array_query($form, $dbh, $query, conv_i($form->{id}));
1537 if (@delete_acc_trans_ids) {
1538 $query = qq|DELETE FROM acc_trans WHERE acc_trans_id IN (| . join(", ", @delete_acc_trans_ids) . qq|)|;
1539 do_query($form, $dbh, $query);
1542 $main::lxdebug->leave_sub();
1546 $main::lxdebug->enter_sub();
1548 my ($self, $myconfig, $form, $locale) = @_;
1550 # connect to database, turn off autocommit
1551 my $dbh = $form->dbconnect_noauto($myconfig);
1553 my (%payments, $old_form, $row, $item, $query, %keep_vars);
1555 $old_form = save_form();
1557 # Delete all entries in acc_trans from prior payments.
1558 if (SL::DB::Default->get->payments_changeable != 0) {
1559 $self->_delete_payments($form, $dbh);
1562 # Save the new payments the user made before cleaning up $form.
1563 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 };
1565 # Clean up $form so that old content won't tamper the results.
1566 %keep_vars = map { $_, 1 } qw(login password id);
1567 map { delete $form->{$_} unless $keep_vars{$_} } keys %{ $form };
1569 # Retrieve the invoice from the database.
1570 $self->retrieve_invoice($myconfig, $form);
1572 # Set up the content of $form in the way that IR::post_invoice() expects.
1573 $form->{exchangerate} = $form->format_amount($myconfig, $form->{exchangerate});
1575 for $row (1 .. scalar @{ $form->{invoice_details} }) {
1576 $item = $form->{invoice_details}->[$row - 1];
1578 map { $item->{$_} = $form->format_amount($myconfig, $item->{$_}) } qw(qty sellprice);
1580 map { $form->{"${_}_${row}"} = $item->{$_} } keys %{ $item };
1583 $form->{rowcount} = scalar @{ $form->{invoice_details} };
1585 delete @{$form}{qw(invoice_details paidaccounts storno paid)};
1587 # Restore the payment options from the user input.
1588 map { $form->{$_} = $payments{$_} } keys %payments;
1590 # Get the AP accno (which is normally done by Form::create_links()).
1594 LEFT JOIN chart c ON (at.chart_id = c.id)
1595 WHERE (trans_id = ?)
1596 AND ((c.link = 'AP') OR (c.link LIKE '%:AP') OR (c.link LIKE 'AP:%'))
1597 ORDER BY at.acc_trans_id
1600 ($form->{AP}) = selectfirst_array_query($form, $dbh, $query, conv_i($form->{id}));
1602 # Post the new payments.
1603 $self->post_invoice($myconfig, $form, $dbh, 1);
1605 restore_form($old_form);
1607 my $rc = $dbh->commit();
1610 $main::lxdebug->leave_sub();
1616 $::lxdebug->enter_sub;
1618 my ($self, %params) = @_;
1620 if (!$params{vendor_id} || !$params{invdate}) {
1621 $::lxdebug->leave_sub;
1622 return $params{default};
1625 my $dbh = $::form->get_standard_dbh;
1626 my $query = qq|SELECT ?::date + pt.terms_netto
1628 LEFT JOIN payment_terms pt ON (pt.id = v.payment_id)
1631 my ($duedate) = selectfirst_array_query($::form, $dbh, $query, $params{invdate}, $params{vendor_id});
1633 $duedate ||= $params{default};
1635 $::lxdebug->leave_sub;