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., 51 Franklin Street, Fifth Floor, Boston,
30 #======================================================================
32 # Inventory received module
34 #======================================================================
42 use SL::DATEV qw(:CONSTANTS);
46 use SL::GenericTranslations;
47 use SL::HTML::Restrict;
53 use SL::Presenter::Part qw(type_abbreviation classification_abbreviation);
54 use List::Util qw(min);
57 use constant PCLASS_OK => 0;
58 use constant PCLASS_NOTFORSALE => 1;
59 use constant PCLASS_NOTFORPURCHASE => 2;
62 my ($self, $myconfig, $form, $provided_dbh, $payments_only) = @_;
63 $main::lxdebug->enter_sub();
65 my $rc = SL::DB->client->with_transaction(\&_post_invoice, $self, $myconfig, $form, $provided_dbh, $payments_only);
67 $::lxdebug->leave_sub;
72 my ($self, $myconfig, $form, $provided_dbh, $payments_only) = @_;
74 my $dbh = $provided_dbh || SL::DB->client->dbh;
75 my $restricter = SL::HTML::Restrict->create;
77 $form->{defaultcurrency} = $form->get_default_currency($myconfig);
78 my $defaultcurrency = $form->{defaultcurrency};
80 my $ic_cvar_configs = CVar->get_configs(module => 'IC',
83 my ($query, $sth, @values, $project_id);
84 my ($allocated, $taxrate, $taxamount, $taxdiff, $item);
85 my ($amount, $linetotal, $lastinventoryaccno, $lastexpenseaccno);
86 my ($netamount, $invoicediff, $expensediff) = (0, 0, 0);
88 my ($basefactor, $baseqty, @taxaccounts, $totaltax);
90 my $all_units = AM->retrieve_units($myconfig, $form);
93 if (!$payments_only) {
95 &reverse_invoice($dbh, $form);
97 ($form->{id}) = selectrow_query($form, $dbh, qq|SELECT nextval('glid')|);
98 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});
102 if ($form->{currency} eq $defaultcurrency) {
103 $form->{exchangerate} = 1;
105 $exchangerate = $form->check_exchangerate($myconfig, $form->{currency}, $form->{invdate}, 'sell');
108 $form->{exchangerate} = $exchangerate || $form->parse_amount($myconfig, $form->{exchangerate});
109 $form->{exchangerate} = 1 unless ($form->{exchangerate} * 1);
112 my $q_item_unit = qq|SELECT unit FROM parts WHERE id = ?|;
113 my $h_item_unit = prepare_query($form, $dbh, $q_item_unit);
115 $form->get_lists('price_factors' => 'ALL_PRICE_FACTORS');
116 my %price_factors = map { $_->{id} => $_->{factor} } @{ $form->{ALL_PRICE_FACTORS} };
119 my @processed_invoice_ids;
120 for my $i (1 .. $form->{rowcount}) {
121 next unless $form->{"id_$i"};
125 $form->{"qty_$i"} = $form->parse_amount($myconfig, $form->{"qty_$i"});
126 $form->{"qty_$i"} *= -1 if $form->{storno};
128 if ( $::instance_conf->get_inventory_system eq 'periodic') {
129 # inventory account number is overwritten with expense account number, so
130 # never book incoming to inventory account but always to expense account
131 $form->{"inventory_accno_$i"} = $form->{"expense_accno_$i"}
135 if (!$item_units{$form->{"id_$i"}}) {
136 do_statement($form, $h_item_unit, $q_item_unit, $form->{"id_$i"});
137 ($item_units{$form->{"id_$i"}}) = $h_item_unit->fetchrow_array();
140 my $item_unit = $item_units{$form->{"id_$i"}};
142 if (defined($all_units->{$item_unit}->{factor})
143 && ($all_units->{$item_unit}->{factor} ne '')
144 && ($all_units->{$item_unit}->{factor} * 1 != 0)) {
145 $basefactor = $all_units->{$form->{"unit_$i"}}->{factor} / $all_units->{$item_unit}->{factor};
149 $baseqty = $form->{"qty_$i"} * $basefactor;
151 @taxaccounts = split / /, $form->{"taxaccounts_$i"};
156 $form->{"sellprice_$i"} = $form->parse_amount($myconfig, $form->{"sellprice_$i"});
157 (my $fxsellprice = $form->{"sellprice_$i"}) =~ /\.(\d+)/;
159 my $decimalplaces = ($dec > 2) ? $dec : 2;
161 map { $taxrate += $form->{"${_}_rate"} } @taxaccounts;
163 $price_factor = $price_factors{ $form->{"price_factor_id_$i"} } || 1;
164 # copied from IS.pm, with some changes (no decimalplaces corrections here etc)
165 # TODO maybe use PriceTaxCalculation or something like this for backends (IR.pm / IS.pm)
167 # undo discount formatting
168 $form->{"discount_$i"} = $form->parse_amount($myconfig, $form->{"discount_$i"}) / 100;
170 $form->{"sellprice_$i"} = $fxsellprice * (1 - $form->{"discount_$i"});
172 ######################################################################
173 if ($form->{"inventory_accno_$i"}) {
175 $linetotal = $form->round_amount($form->{"sellprice_$i"} * $form->{"qty_$i"} / $price_factor, 2);
177 if ($form->{taxincluded}) {
179 $taxamount = $linetotal * ($taxrate / (1 + $taxrate));
180 $form->{"sellprice_$i"} = $form->{"sellprice_$i"} * (1 / (1 + $taxrate));
183 $taxamount = $linetotal * $taxrate;
186 $netamount += $linetotal;
188 if ($form->round_amount($taxrate, 7) == 0) {
189 if ($form->{taxincluded}) {
190 foreach $item (@taxaccounts) {
192 $form->round_amount($linetotal * $form->{"${item}_rate"} / (1 + abs($form->{"${item}_rate"})), 2);
193 $taxdiff += $taxamount;
194 $form->{amount}{ $form->{id} }{$item} -= $taxamount;
196 $form->{amount}{ $form->{id} }{ $taxaccounts[0] } += $taxdiff;
199 map { $form->{amount}{ $form->{id} }{$_} -= $linetotal * $form->{"${_}_rate"} } @taxaccounts;
203 map { $form->{amount}{ $form->{id} }{$_} -= $taxamount * $form->{"${_}_rate"} / $taxrate } @taxaccounts;
206 # add purchase to inventory, this one is without the tax!
207 $amount = $form->{"sellprice_$i"} * $form->{"qty_$i"} * $form->{exchangerate} / $price_factor;
208 $linetotal = $form->round_amount($form->{"sellprice_$i"} * $form->{"qty_$i"} / $price_factor, 2) * $form->{exchangerate};
209 $linetotal = $form->round_amount($linetotal, 2);
211 # this is the difference for the inventory
212 $invoicediff += ($amount - $linetotal);
214 $form->{amount}{ $form->{id} }{ $form->{"inventory_accno_$i"} } -= $linetotal;
216 # adjust and round sellprice
217 $form->{"sellprice_$i"} = $form->round_amount($form->{"sellprice_$i"} * $form->{exchangerate}, $decimalplaces);
219 $lastinventoryaccno = $form->{"inventory_accno_$i"};
221 next if $payments_only;
223 # update parts table by setting lastcost to current price, don't allow negative values by using abs
224 $query = qq|UPDATE parts SET lastcost = ? WHERE id = ?|;
225 @values = (abs($fxsellprice * $form->{exchangerate} / $basefactor), conv_i($form->{"id_$i"}));
226 do_query($form, $dbh, $query, @values);
228 # check if we sold the item already and
229 # make an entry for the expense and inventory
230 my $taxzone = $form->{taxzone_id} * 1;
232 qq|SELECT i.id, i.qty, i.allocated, i.trans_id, i.base_qty,
233 bg.inventory_accno_id, tc.expense_accno_id AS expense_accno_id, a.transdate
234 FROM invoice i, ar a, parts p, buchungsgruppen bg, taxzone_charts tc
235 WHERE (i.parts_id = p.id)
237 AND ((i.base_qty + i.allocated) > 0)
238 AND (i.trans_id = a.id)
239 AND (p.buchungsgruppen_id = bg.id)
240 AND (tc.buchungsgruppen_id = p.buchungsgruppen_id)
241 AND (tc.taxzone_id = ${taxzone})
243 # ORDER BY transdate guarantees FIFO
245 # sold two items without having bought them yet, example result of query:
246 # id | qty | allocated | trans_id | inventory_accno_id | expense_accno_id | transdate
247 # ---+-----+-----------+----------+--------------------+------------------+------------
248 # 9 | 2 | 0 | 9 | 15 | 151 | 2011-01-05
250 # base_qty + allocated > 0 if article has already been sold but not bought yet
252 # select qty,allocated,base_qty,sellprice from invoice where trans_id = 9;
253 # qty | allocated | base_qty | sellprice
254 # -----+-----------+----------+------------
255 # 2 | 0 | 2 | 1000.00000
257 $sth = prepare_execute_query($form, $dbh, $query, conv_i($form->{"id_$i"}));
259 my $totalqty = $baseqty;
261 while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
262 my $qty = min $totalqty, ($ref->{base_qty} + $ref->{allocated});
263 $linetotal = $form->round_amount(($form->{"sellprice_$i"} * $qty) / $basefactor, 2);
265 if ( $::instance_conf->get_inventory_system eq 'perpetual' ) {
266 # Warenbestandsbuchungen nur bei Bestandsmethode
268 if ($ref->{allocated} < 0) {
270 # we have an entry for it already, adjust amount
271 $form->update_balance($dbh, "acc_trans", "amount",
272 qq| (trans_id = $ref->{trans_id})
273 AND (chart_id = $ref->{inventory_accno_id})
274 AND (transdate = '$ref->{transdate}')|,
277 $form->update_balance($dbh, "acc_trans", "amount",
278 qq| (trans_id = $ref->{trans_id})
279 AND (chart_id = $ref->{expense_accno_id})
280 AND (transdate = '$ref->{transdate}')|,
283 } elsif ($linetotal != 0) {
286 # add entry for inventory, this one is for the sold item
287 $query = qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate, taxkey, tax_id, chart_link) VALUES (?, ?, ?, ?,
292 ORDER BY startdate DESC LIMIT 1),
297 ORDER BY startdate DESC LIMIT 1),
298 (SELECT link FROM chart WHERE id = ?))|;
299 @values = ($ref->{trans_id}, $ref->{inventory_accno_id}, $linetotal, $ref->{transdate}, $ref->{inventory_accno_id}, $ref->{transdate}, $ref->{inventory_accno_id}, $ref->{transdate},
300 $ref->{inventory_accno_id});
301 do_query($form, $dbh, $query, @values);
304 $query = qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate, taxkey, tax_id, chart_link) VALUES (?, ?, ?, ?,
309 ORDER BY startdate DESC LIMIT 1),
314 ORDER BY startdate DESC LIMIT 1),
315 (SELECT link FROM chart WHERE id = ?))|;
316 @values = ($ref->{trans_id}, $ref->{expense_accno_id}, ($linetotal * -1), $ref->{transdate}, $ref->{expense_accno_id}, $ref->{transdate}, $ref->{expense_accno_id}, $ref->{transdate},
317 $ref->{expense_accno_id});
318 do_query($form, $dbh, $query, @values);
322 # update allocated for sold item
323 $form->update_balance($dbh, "invoice", "allocated", qq|id = $ref->{id}|, $qty * -1);
327 last if ($totalqty -= $qty) <= 0;
332 } else { # if ($form->{"inventory_accno_id_$i"})
333 # part doesn't have an inventory_accno_id
334 # lastcost of the part is updated at the end
336 $linetotal = $form->round_amount($form->{"sellprice_$i"} * $form->{"qty_$i"} / $price_factor, 2);
338 if ($form->{taxincluded}) {
339 $taxamount = $linetotal * ($taxrate / (1 + $taxrate));
340 $form->{"sellprice_$i"} = $form->{"sellprice_$i"} * (1 / (1 + $taxrate));
343 $taxamount = $linetotal * $taxrate;
346 $netamount += $linetotal;
348 if ($form->round_amount($taxrate, 7) == 0) {
349 if ($form->{taxincluded}) {
350 foreach $item (@taxaccounts) {
351 $taxamount = $linetotal * $form->{"${item}_rate"} / (1 + abs($form->{"${item}_rate"}));
352 $totaltax += $taxamount;
353 $form->{amount}{ $form->{id} }{$item} -= $taxamount;
356 map { $form->{amount}{ $form->{id} }{$_} -= $linetotal * $form->{"${_}_rate"} } @taxaccounts;
359 map { $form->{amount}{ $form->{id} }{$_} -= $taxamount * $form->{"${_}_rate"} / $taxrate } @taxaccounts;
362 $amount = $form->{"sellprice_$i"} * $form->{"qty_$i"} * $form->{exchangerate} / $price_factor;
363 $linetotal = $form->round_amount($form->{"sellprice_$i"} * $form->{"qty_$i"} / $price_factor, 2) * $form->{exchangerate};
364 $linetotal = $form->round_amount($linetotal, 2);
366 # this is the difference for expense
367 $expensediff += ($amount - $linetotal);
369 # add amount to expense
370 $form->{amount}{ $form->{id} }{ $form->{"expense_accno_$i"} } -= $linetotal;
372 $lastexpenseaccno = $form->{"expense_accno_$i"};
374 # adjust and round sellprice
375 $form->{"sellprice_$i"} = $form->round_amount($form->{"sellprice_$i"} * $form->{exchangerate}, $decimalplaces);
377 next if $payments_only;
380 $query = qq|UPDATE parts SET lastcost = ? WHERE id = ?|;
381 do_query($form, $dbh, $query, $form->{"sellprice_$i"} / $basefactor, conv_i($form->{"id_$i"}));
384 next if $payments_only;
386 CVar->get_non_editable_ic_cvars(form => $form,
389 sub_module => 'invoice',
390 may_converted_from => ['delivery_order_items', 'orderitems', 'invoice']);
392 if (!$form->{"invoice_id_$i"}) {
393 # there is no persistent id, therefore create one with all necessary constraints
394 my $q_invoice_id = qq|SELECT nextval('invoiceid')|;
395 my $h_invoice_id = prepare_query($form, $dbh, $q_invoice_id);
396 do_statement($form, $h_invoice_id, $q_invoice_id);
397 $form->{"invoice_id_$i"} = $h_invoice_id->fetchrow_array();
398 my $q_create_invoice_id = qq|INSERT INTO invoice (id, trans_id, position, parts_id) values (?, ?, ?, ?)|;
399 do_query($form, $dbh, $q_create_invoice_id, conv_i($form->{"invoice_id_$i"}),
400 conv_i($form->{id}), conv_i($position), conv_i($form->{"id_$i"}));
401 $h_invoice_id->finish();
404 # save detail record in invoice table
406 UPDATE invoice SET trans_id = ?, position = ?, parts_id = ?, description = ?, longdescription = ?, qty = ?, base_qty = ?,
407 sellprice = ?, fxsellprice = ?, discount = ?, allocated = ?, unit = ?, deliverydate = ?,
408 project_id = ?, serialnumber = ?, price_factor_id = ?,
409 price_factor = (SELECT factor FROM price_factors WHERE id = ?), marge_price_factor = ?,
410 active_price_source = ?, active_discount_source = ?
414 @values = (conv_i($form->{id}), conv_i($position), conv_i($form->{"id_$i"}),
415 $form->{"description_$i"}, $restricter->process($form->{"longdescription_$i"}), $form->{"qty_$i"} * -1,
416 $baseqty * -1, $form->{"sellprice_$i"}, $fxsellprice, $form->{"discount_$i"}, $allocated,
417 $form->{"unit_$i"}, conv_date($form->{deliverydate}),
418 conv_i($form->{"project_id_$i"}), $form->{"serialnumber_$i"},
419 conv_i($form->{"price_factor_id_$i"}), conv_i($form->{"price_factor_id_$i"}), conv_i($form->{"marge_price_factor_$i"}),
420 $form->{"active_price_source_$i"}, $form->{"active_discount_source_$i"},
421 conv_i($form->{"invoice_id_$i"}));
422 do_query($form, $dbh, $query, @values);
423 push @processed_invoice_ids, $form->{"invoice_id_$i"};
425 CVar->save_custom_variables(module => 'IC',
426 sub_module => 'invoice',
427 trans_id => $form->{"invoice_id_$i"},
428 configs => $ic_cvar_configs,
430 name_prefix => 'ic_',
431 name_postfix => "_$i",
434 # link previous items with invoice items See IS.pm (no credit note -> no invoice item)
435 foreach (qw(delivery_order_items orderitems invoice)) {
436 if (!$form->{useasnew} && $form->{"converted_from_${_}_id_$i"}) {
437 RecordLinks->create_links('dbh' => $dbh,
440 'from_ids' => $form->{"converted_from_${_}_id_$i"},
441 'to_table' => 'invoice',
442 'to_id' => $form->{"invoice_id_$i"},
445 delete $form->{"converted_from_${_}_id_$i"};
449 $h_item_unit->finish();
451 $project_id = conv_i($form->{"globalproject_id"});
453 $form->{datepaid} = $form->{invdate};
455 # all amounts are in natural state, netamount includes the taxes
456 # if tax is included, netamount is rounded to 2 decimal places,
460 for my $i (1 .. $form->{paidaccounts}) {
461 $form->{"paid_$i"} = $form->parse_amount($myconfig, $form->{"paid_$i"});
462 $form->{paid} += $form->{"paid_$i"};
463 $form->{datepaid} = $form->{"datepaid_$i"} if $form->{"datepaid_$i"};
466 my ($tax, $paiddiff) = (0, 0);
468 $netamount = $form->round_amount($netamount, 2);
470 # figure out rounding errors for amount paid and total amount
471 if ($form->{taxincluded}) {
473 $amount = $form->round_amount($netamount * $form->{exchangerate}, 2);
474 $paiddiff = $amount - $netamount * $form->{exchangerate};
475 $netamount = $amount;
477 foreach $item (split / /, $form->{taxaccounts}) {
478 $amount = $form->{amount}{ $form->{id} }{$item} * $form->{exchangerate};
479 $form->{amount}{ $form->{id} }{$item} = $form->round_amount($amount, 2);
481 $amount = $form->{amount}{ $form->{id} }{$item} * -1;
483 $netamount -= $amount;
486 $invoicediff += $paiddiff;
487 $expensediff += $paiddiff;
489 ######## this only applies to tax included
491 # in the sales invoice case rounding errors only have to be corrected for
492 # income accounts, it is enough to add the total rounding error to one of
493 # the income accounts, with the one assigned to the last row being used
494 # (lastinventoryaccno)
496 # in the purchase invoice case rounding errors may be split between
497 # inventory accounts and expense accounts. After rounding, an error of 1
498 # cent is introduced if the total rounding error exceeds 0.005. The total
499 # error is made up of $invoicediff and $expensediff, however, so if both
500 # values are below 0.005, but add up to a total >= 0.005, correcting
501 # lastinventoryaccno and lastexpenseaccno separately has no effect after
502 # rounding. This caused bug 1579. Therefore when the combined total exceeds
503 # 0.005, but neither do individually, the account with the larger value
504 # shall receive the total rounding error, and the next time it is rounded
505 # the 1 cent correction will be introduced.
507 $form->{amount}{ $form->{id} }{$lastinventoryaccno} -= $invoicediff if $lastinventoryaccno;
508 $form->{amount}{ $form->{id} }{$lastexpenseaccno} -= $expensediff if $lastexpenseaccno;
510 if ( (abs($expensediff)+abs($invoicediff)) >= 0.005 and abs($expensediff) < 0.005 and abs($invoicediff) < 0.005 ) {
512 # in total the rounding error adds up to 1 cent effectively, correct the
513 # larger of the two numbers
515 if ( abs($form->{amount}{ $form->{id} }{$lastinventoryaccno}) > abs($form->{amount}{ $form->{id} }{$lastexpenseaccno}) ) {
516 # $invoicediff has already been deducted, now also deduct expensediff
517 $form->{amount}{ $form->{id} }{$lastinventoryaccno} -= $expensediff;
519 # expensediff has already been deducted, now also deduct invoicediff
520 $form->{amount}{ $form->{id} }{$lastexpenseaccno} -= $invoicediff;
525 $amount = $form->round_amount($netamount * $form->{exchangerate}, 2);
526 $paiddiff = $amount - $netamount * $form->{exchangerate};
527 $netamount = $amount;
529 foreach my $item (split / /, $form->{taxaccounts}) {
530 $form->{amount}{ $form->{id} }{$item} = $form->round_amount($form->{amount}{ $form->{id} }{$item}, 2);
531 $amount = $form->round_amount( $form->{amount}{ $form->{id} }{$item} * $form->{exchangerate} * -1, 2);
532 $paiddiff += $amount - $form->{amount}{ $form->{id} }{$item} * $form->{exchangerate} * -1;
533 $form->{amount}{ $form->{id} }{$item} = $form->round_amount($amount * -1, 2);
534 $amount = $form->{amount}{ $form->{id} }{$item} * -1;
539 $form->{amount}{ $form->{id} }{ $form->{AP} } = $netamount + $tax;
542 $form->{paid} = $form->round_amount($form->{paid} * $form->{exchangerate} + $paiddiff, 2) if $form->{paid} != 0;
544 # update exchangerate
546 $form->update_exchangerate($dbh, $form->{currency}, $form->{invdate}, 0, $form->{exchangerate})
547 if ($form->{currency} ne $defaultcurrency) && !$exchangerate;
549 # record acc_trans transactions
550 foreach my $trans_id (keys %{ $form->{amount} }) {
551 foreach my $accno (keys %{ $form->{amount}{$trans_id} }) {
552 $form->{amount}{$trans_id}{$accno} = $form->round_amount($form->{amount}{$trans_id}{$accno}, 2);
555 next if $payments_only || !$form->{amount}{$trans_id}{$accno};
557 $query = qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate, taxkey, project_id, tax_id, chart_link)
558 VALUES (?, (SELECT id FROM chart WHERE accno = ?), ?, ?,
561 WHERE chart_id= (SELECT id
565 ORDER BY startdate DESC LIMIT 1),
569 WHERE chart_id= (SELECT id
573 ORDER BY startdate DESC LIMIT 1),
574 (SELECT link FROM chart WHERE accno = ?))|;
575 @values = ($trans_id, $accno, $form->{amount}{$trans_id}{$accno},
576 conv_date($form->{invdate}), $accno, conv_date($form->{invdate}), $project_id, $accno, conv_date($form->{invdate}), $accno);
577 do_query($form, $dbh, $query, @values);
581 # deduct payment differences from paiddiff
582 for my $i (1 .. $form->{paidaccounts}) {
583 if ($form->{"paid_$i"} != 0) {
584 $amount = $form->round_amount($form->{"paid_$i"} * $form->{exchangerate}, 2);
585 $paiddiff -= $amount - $form->{"paid_$i"} * $form->{exchangerate};
589 # force AP entry if 0
591 $form->{amount}{ $form->{id} }{ $form->{AP} } = $form->{paid} if $form->{amount}{$form->{id}}{$form->{AP}} == 0;
593 # record payments and offsetting AP
594 for my $i (1 .. $form->{paidaccounts}) {
595 if ($form->{"acc_trans_id_$i"}
597 && (SL::DB::Default->get->payments_changeable == 0)) {
601 next if $form->{"paid_$i"} == 0;
603 my ($accno) = split /--/, $form->{"AP_paid_$i"};
604 $form->{"datepaid_$i"} = $form->{invdate} unless ($form->{"datepaid_$i"});
605 $form->{datepaid} = $form->{"datepaid_$i"};
607 $amount = $form->round_amount($form->{"paid_$i"} * $form->{exchangerate} + $paiddiff, 2) * -1;
610 if ($form->{amount}{ $form->{id} }{ $form->{AP} } != 0) {
611 $query = qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate, taxkey, project_id, tax_id, chart_link)
612 VALUES (?, (SELECT id FROM chart WHERE accno = ?), ?, ?,
615 WHERE chart_id= (SELECT id
619 ORDER BY startdate DESC LIMIT 1),
623 WHERE chart_id= (SELECT id
627 ORDER BY startdate DESC LIMIT 1),
628 (SELECT link FROM chart WHERE accno = ?))|;
629 @values = (conv_i($form->{id}), $form->{AP}, $amount,
630 $form->{"datepaid_$i"}, $form->{AP}, conv_date($form->{"datepaid_$i"}), $project_id, $form->{AP}, conv_date($form->{"datepaid_$i"}), $form->{AP});
631 do_query($form, $dbh, $query, @values);
635 my $gldate = (conv_date($form->{"gldate_$i"}))? conv_date($form->{"gldate_$i"}) : conv_date($form->current_date($myconfig));
638 qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate, gldate, source, memo, taxkey, project_id, tax_id, chart_link)
639 VALUES (?, (SELECT id FROM chart WHERE accno = ?), ?, ?, ?, ?, ?,
642 WHERE chart_id= (SELECT id
643 FROM chart WHERE accno = ?)
645 ORDER BY startdate DESC LIMIT 1),
649 WHERE chart_id= (SELECT id
650 FROM chart WHERE accno = ?)
652 ORDER BY startdate DESC LIMIT 1),
653 (SELECT link FROM chart WHERE accno = ?))|;
654 @values = (conv_i($form->{id}), $accno, $form->{"paid_$i"}, $form->{"datepaid_$i"},
655 $gldate, $form->{"source_$i"}, $form->{"memo_$i"}, $accno, conv_date($form->{"datepaid_$i"}), $project_id, $accno, conv_date($form->{"datepaid_$i"}), $accno);
656 do_query($form, $dbh, $query, @values);
660 if ($form->{currency} eq $defaultcurrency) {
661 $form->{"exchangerate_$i"} = 1;
663 $exchangerate = $form->check_exchangerate($myconfig, $form->{currency}, $form->{"datepaid_$i"}, 'sell');
664 $form->{"exchangerate_$i"} = $exchangerate || $form->parse_amount($myconfig, $form->{"exchangerate_$i"});
667 # exchangerate difference
668 $form->{fx}{$accno}{ $form->{"datepaid_$i"} } += $form->{"paid_$i"} * ($form->{"exchangerate_$i"} - 1) + $paiddiff;
672 ($form->{"paid_$i"} * $form->{exchangerate}) -
673 ($form->{"paid_$i"} * $form->{"exchangerate_$i"});
675 $form->{fx}{ $form->{fxgain_accno} }{ $form->{"datepaid_$i"} } += $amount;
677 $form->{fx}{ $form->{fxloss_accno} }{ $form->{"datepaid_$i"} } += $amount;
682 # update exchange rate
683 $form->update_exchangerate($dbh, $form->{currency}, $form->{"datepaid_$i"}, 0, $form->{"exchangerate_$i"})
684 if ($form->{currency} ne $defaultcurrency) && !$exchangerate;
687 # record exchange rate differences and gains/losses
688 foreach my $accno (keys %{ $form->{fx} }) {
689 foreach my $transdate (keys %{ $form->{fx}{$accno} }) {
690 $form->{fx}{$accno}{$transdate} = $form->round_amount($form->{fx}{$accno}{$transdate}, 2);
691 next if ($form->{fx}{$accno}{$transdate} == 0);
693 $query = qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate, cleared, fx_transaction, taxkey, project_id, tax_id, chart_link)
694 VALUES (?, (SELECT id FROM chart WHERE accno = ?), ?, ?, '0', '1', 0, ?,
695 (SELECT id FROM tax WHERE taxkey=0 LIMIT 1),
696 (SELECT link FROM chart WHERE accno = ?))|;
697 @values = (conv_i($form->{id}), $accno, $form->{fx}{$accno}{$transdate}, conv_date($transdate), $project_id, $accno);
698 do_query($form, $dbh, $query, @values);
702 IO->set_datepaid(table => 'ap', id => $form->{id}, dbh => $dbh);
704 if ($payments_only) {
705 $query = qq|UPDATE ap SET paid = ? WHERE id = ?|;
706 do_query($form, $dbh, $query, $form->{paid}, conv_i($form->{id}));
707 $form->new_lastmtime('ap');
712 $amount = $netamount + $tax;
714 # set values which could be empty
715 my $taxzone_id = $form->{taxzone_id} * 1;
716 $taxzone_id = SL::DB::Manager::TaxZone->get_default->id unless SL::DB::Manager::TaxZone->find_by(id => $taxzone_id);
718 $form->{invnumber} = $form->{id} unless $form->{invnumber};
721 $query = qq|UPDATE ap SET
722 invnumber = ?, ordnumber = ?, quonumber = ?, transdate = ?,
723 orddate = ?, quodate = ?, vendor_id = ?, amount = ?,
724 netamount = ?, paid = ?, duedate = ?,
725 invoice = ?, taxzone_id = ?, notes = ?, taxincluded = ?,
726 intnotes = ?, storno_id = ?, storno = ?,
727 cp_id = ?, employee_id = ?, department_id = ?, delivery_term_id = ?,
728 currency_id = (SELECT id FROM currencies WHERE name = ?),
729 globalproject_id = ?, direct_debit = ?
732 $form->{invnumber}, $form->{ordnumber}, $form->{quonumber}, conv_date($form->{invdate}),
733 conv_date($form->{orddate}), conv_date($form->{quodate}), conv_i($form->{vendor_id}), $amount,
734 $netamount, $form->{paid}, conv_date($form->{duedate}),
735 '1', $taxzone_id, $restricter->process($form->{notes}), $form->{taxincluded} ? 't' : 'f',
736 $form->{intnotes}, conv_i($form->{storno_id}), $form->{storno} ? 't' : 'f',
737 conv_i($form->{cp_id}), conv_i($form->{employee_id}), conv_i($form->{department_id}), conv_i($form->{delivery_term_id}),
739 conv_i($form->{globalproject_id}),
740 $form->{direct_debit} ? 't' : 'f',
743 do_query($form, $dbh, $query, @values);
745 if ($form->{storno}) {
746 $query = qq|UPDATE ap SET paid = paid + amount WHERE id = ?|;
747 do_query($form, $dbh, $query, conv_i($form->{storno_id}));
749 $query = qq|UPDATE ap SET storno = 't' WHERE id = ?|;
750 do_query($form, $dbh, $query, conv_i($form->{storno_id}));
752 $query = qq!UPDATE ap SET intnotes = ? || intnotes WHERE id = ?!;
753 do_query($form, $dbh, $query, "Rechnung storniert am $form->{invdate} ", conv_i($form->{storno_id}));
755 $query = qq|UPDATE ap SET paid = amount WHERE id = ?|;
756 do_query($form, $dbh, $query, conv_i($form->{id}));
759 $form->new_lastmtime('ap');
761 $form->{name} = $form->{vendor};
762 $form->{name} =~ s/--\Q$form->{vendor_id}\E//;
765 $form->add_shipto($dbh, $form->{id}, "AP");
767 # delete zero entries
768 do_query($form, $dbh, qq|DELETE FROM acc_trans WHERE amount = 0|);
770 Common::webdav_folder($form);
772 # Link this record to the records it was created from order or invoice (storno)
773 foreach (qw(oe ap)) {
774 if ($form->{"convert_from_${_}_ids"}) {
775 RecordLinks->create_links('dbh' => $dbh,
778 'from_ids' => $form->{"convert_from_${_}_ids"},
780 'to_id' => $form->{id},
782 delete $form->{"convert_from_${_}_ids"};
786 my @convert_from_do_ids = map { $_ * 1 } grep { $_ } split m/\s+/, $form->{convert_from_do_ids};
787 if (scalar @convert_from_do_ids) {
788 DO->close_orders('dbh' => $dbh,
789 'ids' => \@convert_from_do_ids);
791 RecordLinks->create_links('dbh' => $dbh,
793 'from_table' => 'delivery_orders',
794 'from_ids' => \@convert_from_do_ids,
796 'to_id' => $form->{id},
799 delete $form->{convert_from_do_ids};
801 ARAP->close_orders_if_billed('dbh' => $dbh,
802 'arap_id' => $form->{id},
805 # search for orphaned invoice items
806 $query = sprintf 'SELECT id FROM invoice WHERE trans_id = ? AND NOT id IN (%s)', join ', ', ("?") x scalar @processed_invoice_ids;
807 @values = (conv_i($form->{id}), map { conv_i($_) } @processed_invoice_ids);
808 my @orphaned_ids = map { $_->{id} } selectall_hashref_query($form, $dbh, $query, @values);
809 if (scalar @orphaned_ids) {
810 # clean up invoice items
811 $query = sprintf 'DELETE FROM invoice WHERE id IN (%s)', join ', ', ("?") x scalar @orphaned_ids;
812 do_query($form, $dbh, $query, @orphaned_ids);
815 if ($form->{draft_id}) {
816 SL::DB::Manager::Draft->delete_all(where => [ id => delete($form->{draft_id}) ]);
819 # safety check datev export
820 if ($::instance_conf->get_datev_check_on_purchase_invoice) {
822 my $datev = SL::DATEV->new(
824 trans_id => $form->{id},
827 $datev->generate_datev_data;
829 if ($datev->errors) {
830 die join "\n", $::locale->text('DATEV check returned errors:'), $datev->errors;
837 sub reverse_invoice {
838 $main::lxdebug->enter_sub();
840 my ($dbh, $form) = @_;
842 # reverse inventory items
844 qq|SELECT i.parts_id, p.part_type, i.qty, i.allocated, i.sellprice
845 FROM invoice i, parts p
846 WHERE (i.parts_id = p.id)
847 AND (i.trans_id = ?)|;
848 my $sth = prepare_execute_query($form, $dbh, $query, conv_i($form->{id}));
852 while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
853 $netamount += $form->round_amount($ref->{sellprice} * $ref->{qty} * -1, 2);
855 next unless $ref->{part_type} eq 'part';
857 # if $ref->{allocated} > 0 than we sold that many items
858 next if ($ref->{allocated} <= 0);
860 # get references for sold items
862 qq|SELECT i.id, i.trans_id, i.allocated, a.transdate
864 WHERE (i.parts_id = ?)
865 AND (i.allocated < 0)
866 AND (i.trans_id = a.id)
867 ORDER BY transdate DESC|;
868 my $sth2 = prepare_execute_query($form, $dbh, $query, $ref->{parts_id});
870 while (my $pthref = $sth2->fetchrow_hashref("NAME_lc")) {
871 my $qty = $ref->{allocated};
872 if (($ref->{allocated} + $pthref->{allocated}) > 0) {
873 $qty = $pthref->{allocated} * -1;
876 my $amount = $form->round_amount($ref->{sellprice} * $qty, 2);
879 $form->update_balance($dbh, "invoice", "allocated", qq|id = $pthref->{id}|, $qty);
881 if ( $::instance_conf->get_inventory_system eq 'perpetual' ) {
883 $form->update_balance($dbh, "acc_trans", "amount",
884 qq| (trans_id = $pthref->{trans_id})
885 AND (chart_id = $ref->{expense_accno_id})
886 AND (transdate = '$pthref->{transdate}')|,
889 $form->update_balance($dbh, "acc_trans", "amount",
890 qq| (trans_id = $pthref->{trans_id})
891 AND (chart_id = $ref->{inventory_accno_id})
892 AND (transdate = '$pthref->{transdate}')|,
896 last if (($ref->{allocated} -= $qty) <= 0);
902 my $id = conv_i($form->{id});
905 $query = qq|DELETE FROM acc_trans WHERE trans_id = ?|;
906 do_query($form, $dbh, $query, $id);
908 $query = qq|DELETE FROM shipto WHERE (trans_id = ?) AND (module = 'AP')|;
909 do_query($form, $dbh, $query, $id);
911 $main::lxdebug->leave_sub();
915 $main::lxdebug->enter_sub();
917 my ($self, $myconfig, $form) = @_;
919 # connect to database
920 my $dbh = SL::DB->client->dbh;
922 SL::DB->client->with_transaction(sub{
924 &reverse_invoice($dbh, $form);
926 my @values = (conv_i($form->{id}));
928 # delete zero entries
929 # wtf? use case for this?
930 $query = qq|DELETE FROM acc_trans WHERE amount = 0|;
931 do_query($form, $dbh, $query);
935 qq|DELETE FROM invoice WHERE trans_id = ?|,
936 qq|DELETE FROM ap WHERE id = ?|,
939 map { do_query($form, $dbh, $_, @values) } @queries;
941 }) or do { die SL::DB->client->error };
946 sub retrieve_invoice {
947 $main::lxdebug->enter_sub();
949 my ($self, $myconfig, $form) = @_;
951 # connect to database
952 my $dbh = SL::DB->client->dbh;
954 my ($query, $sth, $ref, $q_invdate);
957 $q_invdate = qq|, COALESCE((SELECT transdate FROM ar WHERE id = (SELECT MAX(id) FROM ar)), current_date) AS invdate|;
958 if ($form->{vendor_id}) {
959 my $vendor_id = $dbh->quote($form->{vendor_id} * 1);
961 qq|, COALESCE((SELECT transdate FROM ar WHERE id = (SELECT MAX(id) FROM ar)), current_date) +
962 COALESCE((SELECT pt.terms_netto
964 LEFT JOIN payment_terms pt ON (v.payment_id = pt.id)
965 WHERE v.id = $vendor_id),
970 # get default accounts and last invoice number
973 (SELECT c.accno FROM chart c WHERE d.inventory_accno_id = c.id) AS inventory_accno,
974 (SELECT c.accno FROM chart c WHERE d.income_accno_id = c.id) AS income_accno,
975 (SELECT c.accno FROM chart c WHERE d.expense_accno_id = c.id) AS expense_accno,
976 (SELECT c.accno FROM chart c WHERE d.fxgain_accno_id = c.id) AS fxgain_accno,
977 (SELECT c.accno FROM chart c WHERE d.fxloss_accno_id = c.id) AS fxloss_accno
980 $ref = selectfirst_hashref_query($form, $dbh, $query);
981 map { $form->{$_} = $ref->{$_} } keys %$ref;
984 $main::lxdebug->leave_sub();
990 $query = qq|SELECT cp_id, invnumber, transdate AS invdate, duedate,
991 orddate, quodate, globalproject_id,
992 ordnumber, quonumber, paid, taxincluded, notes, taxzone_id, storno, gldate,
994 intnotes, (SELECT cu.name FROM currencies cu WHERE cu.id=ap.currency_id) AS currency, direct_debit,
998 $ref = selectfirst_hashref_query($form, $dbh, $query, conv_i($form->{id}));
999 map { $form->{$_} = $ref->{$_} } keys %$ref;
1000 $form->{mtime} = $form->{itime} if !$form->{mtime};
1001 $form->{lastmtime} = $form->{mtime};
1003 $form->{exchangerate} = $form->get_exchangerate($dbh, $form->{currency}, $form->{invdate}, "sell");
1006 $query = qq|SELECT * FROM shipto WHERE (trans_id = ?) AND (module = 'AP')|;
1007 $ref = selectfirst_hashref_query($form, $dbh, $query, conv_i($form->{id}));
1009 map { $form->{$_} = $ref->{$_} } keys %$ref;
1011 my $transdate = $form->{invdate} ? $dbh->quote($form->{invdate}) : "current_date";
1013 my $taxzone_id = $form->{taxzone_id} * 1;
1014 $taxzone_id = SL::DB::Manager::TaxZone->get_default->id unless SL::DB::Manager::TaxZone->find_by(id => $taxzone_id);
1016 # retrieve individual items
1019 c1.accno AS inventory_accno, c1.new_chart_id AS inventory_new_chart, date($transdate) - c1.valid_from AS inventory_valid,
1020 c2.accno AS income_accno, c2.new_chart_id AS income_new_chart, date($transdate) - c2.valid_from AS income_valid,
1021 c3.accno AS expense_accno, c3.new_chart_id AS expense_new_chart, date($transdate) - c3.valid_from AS expense_valid,
1024 i.description, i.longdescription, i.qty, i.fxsellprice AS sellprice, i.parts_id AS id, i.unit, i.deliverydate, i.project_id, i.serialnumber,
1025 i.price_factor_id, i.price_factor, i.marge_price_factor, i.discount, i.active_price_source, i.active_discount_source,
1026 p.partnumber, p.part_type, pr.projectnumber, pg.partsgroup
1027 ,p.classification_id
1030 JOIN parts p ON (i.parts_id = p.id)
1031 LEFT JOIN chart c1 ON ((SELECT inventory_accno_id FROM buchungsgruppen WHERE id = p.buchungsgruppen_id) = c1.id)
1032 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)
1033 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)
1034 LEFT JOIN project pr ON (i.project_id = pr.id)
1035 LEFT JOIN partsgroup pg ON (pg.id = p.partsgroup_id)
1037 WHERE i.trans_id = ?
1039 ORDER BY i.position|;
1040 $sth = prepare_execute_query($form, $dbh, $query, conv_i($form->{id}));
1042 while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
1043 # Retrieve custom variables.
1044 my $cvars = CVar->get_custom_variables(dbh => $dbh,
1046 sub_module => 'invoice',
1047 trans_id => $ref->{invoice_id},
1049 map { $ref->{"ic_cvar_$_->{name}"} = $_->{value} } @{ $cvars };
1051 map({ delete($ref->{$_}); } qw(inventory_accno inventory_new_chart inventory_valid)) if !$ref->{"part_type"} eq 'part';
1053 foreach my $type (qw(inventory income expense)) {
1054 while ($ref->{"${type}_new_chart"} && ($ref->{"${type}_valid"} >=0)) {
1055 my $query = qq|SELECT accno, new_chart_id, date($transdate) - valid_from FROM chart WHERE id = ?|;
1056 @$ref{ map $type.$_, qw(_accno _new_chart _valid) } = selectrow_query($form, $dbh, $query, $ref->{"${type}_new_chart"});
1060 # get tax rates and description
1061 my $accno_id = ($form->{vc} eq "customer") ? $ref->{income_accno} : $ref->{expense_accno};
1063 qq|SELECT c.accno, t.taxdescription, t.rate, t.taxnumber FROM tax t
1064 LEFT JOIN chart c ON (c.id = t.chart_id)
1066 (SELECT tk.tax_id FROM taxkeys tk
1067 WHERE tk.chart_id = (SELECT id FROM chart WHERE accno = ?)
1068 AND (startdate <= $transdate)
1069 ORDER BY startdate DESC
1072 my $stw = prepare_execute_query($form, $dbh, $query, $accno_id);
1073 $ref->{taxaccounts} = "";
1076 while (my $ptr = $stw->fetchrow_hashref("NAME_lc")) {
1077 if (($ptr->{accno} eq "") && ($ptr->{rate} == 0)) {
1082 $ref->{taxaccounts} .= "$ptr->{accno} ";
1084 if (!($form->{taxaccounts} =~ /\Q$ptr->{accno}\E/)) {
1085 $form->{"$ptr->{accno}_rate"} = $ptr->{rate};
1086 $form->{"$ptr->{accno}_description"} = $ptr->{taxdescription};
1087 $form->{"$ptr->{accno}_taxnumber"} = $ptr->{taxnumber};
1088 $form->{taxaccounts} .= "$ptr->{accno} ";
1093 chop $ref->{taxaccounts};
1094 push @{ $form->{invoice_details} }, $ref;
1099 Common::webdav_folder($form);
1101 $main::lxdebug->leave_sub();
1105 $main::lxdebug->enter_sub();
1107 my ($self, $myconfig, $form, $params) = @_;
1109 $params = $form unless defined $params && ref $params eq "HASH";
1111 # connect to database
1112 my $dbh = SL::DB->client->dbh;
1114 my $dateformat = $myconfig->{dateformat};
1115 $dateformat .= "yy" if $myconfig->{dateformat} !~ /^y/;
1117 my $vid = conv_i($params->{vendor_id});
1118 my $vnr = conv_i($params->{vendornumber});
1121 ($params->{invdate})
1122 ? "to_date(" . $dbh->quote($params->{invdate}) . ", '$dateformat')"
1129 $where .= 'AND v.id = ?';
1133 $where .= 'AND v.vendornumber = ?';
1138 v.id AS vendor_id, v.name AS vendor, v.discount as vendor_discount,
1139 v.creditlimit, v.notes AS intnotes,
1140 v.email, v.cc, v.bcc, v.language_id, v.payment_id, v.delivery_term_id,
1141 v.street, v.zipcode, v.city, v.country, v.taxzone_id, cu.name AS curr, v.direct_debit,
1142 $duedate + COALESCE(pt.terms_netto, 0) AS duedate,
1143 b.discount AS tradediscount, b.description AS business
1145 LEFT JOIN business b ON (b.id = v.business_id)
1146 LEFT JOIN payment_terms pt ON (v.payment_id = pt.id)
1147 LEFT JOIN currencies cu ON (v.currency_id = cu.id)
1149 my $ref = selectfirst_hashref_query($form, $dbh, $query, @values);
1150 map { $params->{$_} = $ref->{$_} } keys %$ref;
1152 # use vendor currency
1153 $form->{currency} = $form->{curr};
1155 $params->{creditremaining} = $params->{creditlimit};
1157 $query = qq|SELECT SUM(amount - paid) FROM ap WHERE vendor_id = ?|;
1158 my ($unpaid_invoices) = selectfirst_array_query($form, $dbh, $query, $vid);
1159 $params->{creditremaining} -= $unpaid_invoices;
1161 $query = qq|SELECT o.amount,
1164 WHERE (e.currency_id = o.currency_id)
1165 AND (e.transdate = o.transdate)) AS exch
1167 WHERE (o.vendor_id = ?) AND (o.quotation = '0') AND (o.closed = '0')|;
1168 my $sth = prepare_execute_query($form, $dbh, $query, $vid);
1169 while (my ($amount, $exch) = $sth->fetchrow_array()) {
1170 $exch = 1 unless $exch;
1171 $params->{creditremaining} -= $amount * $exch;
1175 $main::lxdebug->leave_sub();
1179 $main::lxdebug->enter_sub();
1181 my ($self, $myconfig, $form) = @_;
1183 my $dbh = SL::DB->client->dbh;
1185 my $i = $form->{rowcount};
1187 # don't include assemblies or obsolete parts
1188 my $where = "NOT p.part_type = 'assembly' AND NOT p.obsolete = '1'";
1191 foreach my $table_column (qw(p.partnumber p.description pg.partsgroup)) {
1192 my $field = (split m{\.}, $table_column)[1];
1193 next unless $form->{"${field}_${i}"};
1194 $where .= " AND lower(${table_column}) LIKE lower(?)";
1195 push @values, like($form->{"${field}_${i}"});
1199 if ($form->{"partnumber_$i"} && !$form->{"description_$i"}) {
1200 $where .= qq| OR (NOT p.obsolete = '1' AND p.ean = ? )|;
1201 push @values, $form->{"partnumber_$i"};
1203 # also search hits in makemodels, but only cache the results by id and merge later
1205 SELECT parts_id, model FROM makemodel
1206 LEFT JOIN parts ON parts.id = parts_id
1207 WHERE NOT parts.obsolete AND model ILIKE ? AND (make IS NULL OR make = ?);
1209 my $mm_results = selectall_hashref_query($::form, $dbh, $mm_query, like($form->{"partnumber_$i"}), $::form->{vendor_id});
1210 my @mm_ids = map { $_->{parts_id} } @$mm_results;
1211 push @{$mm_by_id{ $_->{parts_id} } ||= []}, $_ for @$mm_results;
1214 $where .= qq| OR p.id IN (| . join(',', ('?') x @mm_ids) . qq|)|;
1215 push @values, @mm_ids;
1219 # Search for part ID overrides all other criteria.
1220 if ($form->{"id_${i}"}) {
1221 $where = qq|p.id = ?|;
1222 @values = ($form->{"id_${i}"});
1225 if ($form->{"description_$i"}) {
1226 $where .= " ORDER BY p.description";
1228 $where .= " ORDER BY p.partnumber";
1232 if ($form->{type} eq "invoice") {
1233 $transdate = $form->{deliverydate} ? $dbh->quote($form->{deliverydate})
1234 : $form->{invdate} ? $dbh->quote($form->{invdate})
1237 $transdate = $form->{transdate} ? $dbh->quote($form->{transdate}) : "current_date";
1240 my $taxzone_id = $form->{taxzone_id} * 1;
1241 $taxzone_id = SL::DB::Manager::TaxZone->get_default->id unless SL::DB::Manager::TaxZone->find_by(id => $taxzone_id);
1245 p.id, p.partnumber, p.description, p.lastcost AS sellprice, p.listprice,
1246 p.unit, p.part_type, p.onhand, p.formel,
1247 p.notes AS partnotes, p.notes AS longdescription, p.not_discountable,
1250 p.classification_id,
1252 pfac.factor AS price_factor,
1254 c1.accno AS inventory_accno,
1255 c1.new_chart_id AS inventory_new_chart,
1256 date($transdate) - c1.valid_from AS inventory_valid,
1258 c2.accno AS income_accno,
1259 c2.new_chart_id AS income_new_chart,
1260 date($transdate) - c2.valid_from AS income_valid,
1262 c3.accno AS expense_accno,
1263 c3.new_chart_id AS expense_new_chart,
1264 date($transdate) - c3.valid_from AS expense_valid,
1266 pt.used_for_purchase AS used_for_purchase,
1270 LEFT JOIN chart c1 ON
1271 ((SELECT inventory_accno_id
1272 FROM buchungsgruppen
1273 WHERE id = p.buchungsgruppen_id) = c1.id)
1274 LEFT JOIN chart c2 ON
1275 ((SELECT tc.income_accno_id
1276 FROM taxzone_charts tc
1277 WHERE tc.taxzone_id = '$taxzone_id' and tc.buchungsgruppen_id = p.buchungsgruppen_id) = c2.id)
1278 LEFT JOIN chart c3 ON
1279 ((SELECT tc.expense_accno_id
1280 FROM taxzone_charts tc
1281 WHERE tc.taxzone_id = '$taxzone_id' and tc.buchungsgruppen_id = p.buchungsgruppen_id) = c3.id)
1282 LEFT JOIN partsgroup pg ON (pg.id = p.partsgroup_id)
1283 LEFT JOIN part_classifications pt ON (pt.id = p.classification_id)
1284 LEFT JOIN price_factors pfac ON (pfac.id = p.price_factor_id)
1286 my $sth = prepare_execute_query($form, $dbh, $query, @values);
1288 my @translation_queries = ( [ qq|SELECT tr.translation, tr.longdescription
1290 WHERE tr.language_id = ? AND tr.parts_id = ?| ],
1291 [ qq|SELECT tr.translation, tr.longdescription
1293 WHERE tr.language_id IN
1296 WHERE article_code = (SELECT article_code FROM language WHERE id = ?))
1299 map { push @{ $_ }, prepare_query($form, $dbh, $_->[0]) } @translation_queries;
1301 $form->{item_list} = [];
1302 my $has_wrong_pclass = PCLASS_OK;
1303 while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
1305 if ($mm_by_id{$ref->{id}}) {
1306 $ref->{makemodels} = $mm_by_id{$ref->{id}};
1307 push @{ $ref->{matches} ||= [] }, $::locale->text('Model') . ': ' . join ', ', map { $_->{model} } @{ $mm_by_id{$ref->{id}} };
1310 if (($::form->{"partnumber_$i"} ne '') && ($ref->{ean} eq $::form->{"partnumber_$i"})) {
1311 push @{ $ref->{matches} ||= [] }, $::locale->text('EAN') . ': ' . $ref->{ean};
1313 $ref->{type_and_classific} = type_abbreviation($ref->{part_type}) .
1314 classification_abbreviation($ref->{classification_id});
1316 if (! $ref->{used_for_purchase} ) {
1317 $has_wrong_pclass = PCLASS_NOTFORPURCHASE;
1320 # In der Buchungsgruppe ist immer ein Bestandskonto verknuepft, auch wenn
1321 # es sich um eine Dienstleistung handelt. Bei Dienstleistungen muss das
1322 # Buchungskonto also aus dem Ergebnis rausgenommen werden.
1323 if (!$ref->{inventory_accno_id}) {
1324 map({ delete($ref->{"inventory_${_}"}); } qw(accno new_chart valid));
1326 delete($ref->{inventory_accno_id});
1328 # get tax rates and description
1329 my $accno_id = ($form->{vc} eq "customer") ? $ref->{income_accno} : $ref->{expense_accno};
1331 qq|SELECT c.accno, t.taxdescription, t.rate, t.taxnumber
1333 LEFT JOIN chart c on (c.id = t.chart_id)
1341 AND (startdate <= $transdate)
1342 ORDER BY startdate DESC
1345 my $stw = prepare_execute_query($form, $dbh, $query, $accno_id);
1347 $ref->{taxaccounts} = "";
1349 while (my $ptr = $stw->fetchrow_hashref("NAME_lc")) {
1351 if (($ptr->{accno} eq "") && ($ptr->{rate} == 0)) {
1356 $ref->{taxaccounts} .= "$ptr->{accno} ";
1358 if (!($form->{taxaccounts} =~ /\Q$ptr->{accno}\E/)) {
1359 $form->{"$ptr->{accno}_rate"} = $ptr->{rate};
1360 $form->{"$ptr->{accno}_description"} = $ptr->{taxdescription};
1361 $form->{"$ptr->{accno}_taxnumber"} = $ptr->{taxnumber};
1362 $form->{taxaccounts} .= "$ptr->{accno} ";
1365 if ($form->{language_id}) {
1366 for my $spec (@translation_queries) {
1367 do_statement($form, $spec->[1], $spec->[0], conv_i($form->{language_id}), conv_i($ref->{id}));
1368 my ($translation, $longdescription) = $spec->[1]->fetchrow_array;
1369 next unless $translation;
1370 $ref->{description} = $translation;
1371 $ref->{longdescription} = $longdescription;
1378 chop $ref->{taxaccounts};
1380 $ref->{onhand} *= 1;
1382 push @{ $form->{item_list} }, $ref;
1387 $_->[1]->finish for @translation_queries;
1389 $form->{is_wrong_pclass} = $has_wrong_pclass;
1390 $form->{NOTFORSALE} = PCLASS_NOTFORSALE;
1391 $form->{NOTFORPURCHASE} = PCLASS_NOTFORPURCHASE;
1392 foreach my $item (@{ $form->{item_list} }) {
1393 my $custom_variables = CVar->get_custom_variables(module => 'IC',
1394 trans_id => $item->{id},
1397 $form->{is_wrong_pclass} = PCLASS_OK; # one correct type
1398 map { $item->{"ic_cvar_" . $_->{name} } = $_->{value} } @{ $custom_variables };
1401 $main::lxdebug->leave_sub();
1404 sub vendor_details {
1405 $main::lxdebug->enter_sub();
1407 my ($self, $myconfig, $form, @wanted_vars) = @_;
1409 my $dbh = SL::DB->client->dbh;
1413 # get contact id, set it if nessessary
1414 $form->{cp_id} *= 1;
1416 if ($form->{cp_id}) {
1417 $contact = "AND cp.cp_id = ?";
1418 push @values, $form->{cp_id};
1421 # get rest for the vendor
1422 # fax and phone and email as vendor*
1424 qq|SELECT ct.*, cp.*, ct.notes as vendornotes, phone as vendorphone, fax as vendorfax, email as vendoremail,
1427 LEFT JOIN contacts cp ON (ct.id = cp.cp_cv_id)
1428 LEFT JOIN currencies cu ON (ct.currency_id = cu.id)
1429 WHERE (ct.id = ?) $contact
1432 my $ref = selectfirst_hashref_query($form, $dbh, $query, $form->{vendor_id}, @values);
1434 # remove id,notes (double of vendornotes) and taxincluded before copy back
1435 delete @$ref{qw(id taxincluded notes)};
1437 @wanted_vars = grep({ $_ } @wanted_vars);
1438 if (scalar(@wanted_vars) > 0) {
1440 map({ $h_wanted_vars{$_} = 1; } @wanted_vars);
1441 map({ delete($ref->{$_}) unless ($h_wanted_vars{$_}); } keys(%{$ref}));
1444 map { $form->{$_} = $ref->{$_} } keys %$ref;
1446 my $custom_variables = CVar->get_custom_variables('dbh' => $dbh,
1448 'trans_id' => $form->{vendor_id});
1449 map { $form->{"vc_cvar_$_->{name}"} = $_->{value} } @{ $custom_variables };
1451 if ($form->{cp_id}) {
1452 $custom_variables = CVar->get_custom_variables(dbh => $dbh,
1453 module => 'Contacts',
1454 trans_id => $form->{cp_id});
1455 $form->{"cp_cvar_$_->{name}"} = $_->{value} for @{ $custom_variables };
1458 $form->{cp_greeting} = GenericTranslations->get('dbh' => $dbh,
1459 'translation_type' => 'greetings::' . ($form->{cp_gender} eq 'f' ? 'female' : 'male'),
1460 'allow_fallback' => 1);
1462 $main::lxdebug->leave_sub();
1466 $main::lxdebug->enter_sub();
1468 my ($self, $myconfig, $form) = @_;
1470 my $dbh = SL::DB->client->dbh;
1473 qq|SELECT accno, description, link
1475 WHERE link LIKE '%IC%'
1477 my $sth = prepare_execute_query($query, $dbh, $query);
1479 while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
1480 foreach my $key (split(/:/, $ref->{link})) {
1482 push @{ $form->{IC_links}{$key} },
1483 { accno => $ref->{accno},
1484 description => $ref->{description} };
1490 $main::lxdebug->leave_sub();
1493 sub _delete_payments {
1494 $main::lxdebug->enter_sub();
1496 my ($self, $form, $dbh) = @_;
1498 my @delete_acc_trans_ids;
1500 # Delete old payment entries from acc_trans.
1502 qq|SELECT acc_trans_id
1504 WHERE (trans_id = ?) AND fx_transaction
1508 SELECT at.acc_trans_id
1510 LEFT JOIN chart c ON (at.chart_id = c.id)
1511 WHERE (trans_id = ?) AND (c.link LIKE '%AP_paid%')|;
1512 push @delete_acc_trans_ids, selectall_array_query($form, $dbh, $query, conv_i($form->{id}), conv_i($form->{id}));
1515 qq|SELECT at.acc_trans_id
1517 LEFT JOIN chart c ON (at.chart_id = c.id)
1518 WHERE (trans_id = ?)
1519 AND ((c.link = 'AP') OR (c.link LIKE '%:AP') OR (c.link LIKE 'AP:%'))
1520 ORDER BY at.acc_trans_id
1522 push @delete_acc_trans_ids, selectall_array_query($form, $dbh, $query, conv_i($form->{id}));
1524 if (@delete_acc_trans_ids) {
1525 $query = qq|DELETE FROM acc_trans WHERE acc_trans_id IN (| . join(", ", @delete_acc_trans_ids) . qq|)|;
1526 do_query($form, $dbh, $query);
1529 $main::lxdebug->leave_sub();
1533 my ($self, $myconfig, $form, $locale) = @_;
1534 $main::lxdebug->enter_sub();
1536 my $rc = SL::DB->client->with_transaction(\&_post_payment, $self, $myconfig, $form, $locale);
1538 $::lxdebug->leave_sub;
1543 my ($self, $myconfig, $form, $locale) = @_;
1545 my $dbh = SL::DB->client->dbh;
1547 my (%payments, $old_form, $row, $item, $query, %keep_vars);
1549 $old_form = save_form();
1551 # Delete all entries in acc_trans from prior payments.
1552 if (SL::DB::Default->get->payments_changeable != 0) {
1553 $self->_delete_payments($form, $dbh);
1556 # Save the new payments the user made before cleaning up $form.
1557 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 };
1559 # Clean up $form so that old content won't tamper the results.
1560 %keep_vars = map { $_, 1 } qw(login password id);
1561 map { delete $form->{$_} unless $keep_vars{$_} } keys %{ $form };
1563 # Retrieve the invoice from the database.
1564 $self->retrieve_invoice($myconfig, $form);
1566 # Set up the content of $form in the way that IR::post_invoice() expects.
1567 $form->{exchangerate} = $form->format_amount($myconfig, $form->{exchangerate});
1569 for $row (1 .. scalar @{ $form->{invoice_details} }) {
1570 $item = $form->{invoice_details}->[$row - 1];
1572 map { $item->{$_} = $form->format_amount($myconfig, $item->{$_}) } qw(qty sellprice);
1574 map { $form->{"${_}_${row}"} = $item->{$_} } keys %{ $item };
1577 $form->{rowcount} = scalar @{ $form->{invoice_details} };
1579 delete @{$form}{qw(invoice_details paidaccounts storno paid)};
1581 # Restore the payment options from the user input.
1582 map { $form->{$_} = $payments{$_} } keys %payments;
1584 # Get the AP accno (which is normally done by Form::create_links()).
1588 LEFT JOIN chart c ON (at.chart_id = c.id)
1589 WHERE (trans_id = ?)
1590 AND ((c.link = 'AP') OR (c.link LIKE '%:AP') OR (c.link LIKE 'AP:%'))
1591 ORDER BY at.acc_trans_id
1594 ($form->{AP}) = selectfirst_array_query($form, $dbh, $query, conv_i($form->{id}));
1596 # Post the new payments.
1597 $self->post_invoice($myconfig, $form, $dbh, 1);
1599 restore_form($old_form);
1605 $::lxdebug->enter_sub;
1607 my ($self, %params) = @_;
1609 if (!$params{vendor_id} || !$params{invdate}) {
1610 $::lxdebug->leave_sub;
1611 return $params{default};
1614 my $dbh = $::form->get_standard_dbh;
1615 my $query = qq|SELECT ?::date + pt.terms_netto
1617 LEFT JOIN payment_terms pt ON (pt.id = v.payment_id)
1620 my ($duedate) = selectfirst_array_query($::form, $dbh, $query, $params{invdate}, $params{vendor_id});
1622 $duedate ||= $params{default};
1624 $::lxdebug->leave_sub;