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);
45 use SL::GenericTranslations;
46 use SL::HTML::Restrict;
52 use List::Util qw(min);
55 use constant PCLASS_OK => 0;
56 use constant PCLASS_NOTFORSALE => 1;
57 use constant PCLASS_NOTFORPURCHASE => 2;
60 my ($self, $myconfig, $form, $provided_dbh, $payments_only) = @_;
61 $main::lxdebug->enter_sub();
63 my $rc = SL::DB->client->with_transaction(\&_post_invoice, $self, $myconfig, $form, $provided_dbh, $payments_only);
65 $::lxdebug->leave_sub;
70 my ($self, $myconfig, $form, $provided_dbh, $payments_only) = @_;
72 my $dbh = $provided_dbh || SL::DB->client->dbh;
73 my $restricter = SL::HTML::Restrict->create;
75 $form->{defaultcurrency} = $form->get_default_currency($myconfig);
76 my $defaultcurrency = $form->{defaultcurrency};
78 my $ic_cvar_configs = CVar->get_configs(module => 'IC',
81 my ($query, $sth, @values, $project_id);
82 my ($allocated, $taxrate, $taxamount, $taxdiff, $item);
83 my ($amount, $linetotal, $lastinventoryaccno, $lastexpenseaccno);
84 my ($netamount, $invoicediff, $expensediff) = (0, 0, 0);
86 my ($basefactor, $baseqty, @taxaccounts, $totaltax);
88 my $all_units = AM->retrieve_units($myconfig, $form);
91 if (!$payments_only) {
93 &reverse_invoice($dbh, $form);
95 ($form->{id}) = selectrow_query($form, $dbh, qq|SELECT nextval('glid')|);
96 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});
100 if ($form->{currency} eq $defaultcurrency) {
101 $form->{exchangerate} = 1;
103 $exchangerate = $form->check_exchangerate($myconfig, $form->{currency}, $form->{invdate}, 'sell');
106 $form->{exchangerate} = $exchangerate || $form->parse_amount($myconfig, $form->{exchangerate});
107 $form->{exchangerate} = 1 unless ($form->{exchangerate} * 1);
110 my $q_item_unit = qq|SELECT unit FROM parts WHERE id = ?|;
111 my $h_item_unit = prepare_query($form, $dbh, $q_item_unit);
113 $form->get_lists('price_factors' => 'ALL_PRICE_FACTORS');
114 my %price_factors = map { $_->{id} => $_->{factor} } @{ $form->{ALL_PRICE_FACTORS} };
117 my @processed_invoice_ids;
118 for my $i (1 .. $form->{rowcount}) {
119 next unless $form->{"id_$i"};
123 $form->{"qty_$i"} = $form->parse_amount($myconfig, $form->{"qty_$i"});
124 $form->{"qty_$i"} *= -1 if $form->{storno};
126 if ( $::instance_conf->get_inventory_system eq 'periodic') {
127 # inventory account number is overwritten with expense account number, so
128 # never book incoming to inventory account but always to expense account
129 $form->{"inventory_accno_$i"} = $form->{"expense_accno_$i"}
133 if (!$item_units{$form->{"id_$i"}}) {
134 do_statement($form, $h_item_unit, $q_item_unit, $form->{"id_$i"});
135 ($item_units{$form->{"id_$i"}}) = $h_item_unit->fetchrow_array();
138 my $item_unit = $item_units{$form->{"id_$i"}};
140 if (defined($all_units->{$item_unit}->{factor})
141 && ($all_units->{$item_unit}->{factor} ne '')
142 && ($all_units->{$item_unit}->{factor} * 1 != 0)) {
143 $basefactor = $all_units->{$form->{"unit_$i"}}->{factor} / $all_units->{$item_unit}->{factor};
147 $baseqty = $form->{"qty_$i"} * $basefactor;
149 @taxaccounts = split / /, $form->{"taxaccounts_$i"};
154 $form->{"sellprice_$i"} = $form->parse_amount($myconfig, $form->{"sellprice_$i"});
155 (my $fxsellprice = $form->{"sellprice_$i"}) =~ /\.(\d+)/;
157 my $decimalplaces = ($dec > 2) ? $dec : 2;
159 map { $taxrate += $form->{"${_}_rate"} } @taxaccounts;
161 $price_factor = $price_factors{ $form->{"price_factor_id_$i"} } || 1;
162 # copied from IS.pm, with some changes (no decimalplaces corrections here etc)
163 # TODO maybe use PriceTaxCalculation or something like this for backends (IR.pm / IS.pm)
165 # undo discount formatting
166 $form->{"discount_$i"} = $form->parse_amount($myconfig, $form->{"discount_$i"}) / 100;
168 $form->{"sellprice_$i"} = $fxsellprice * (1 - $form->{"discount_$i"});
170 ######################################################################
171 if ($form->{"inventory_accno_$i"}) {
173 $linetotal = $form->round_amount($form->{"sellprice_$i"} * $form->{"qty_$i"} / $price_factor, 2);
175 if ($form->{taxincluded}) {
177 $taxamount = $linetotal * ($taxrate / (1 + $taxrate));
178 $form->{"sellprice_$i"} = $form->{"sellprice_$i"} * (1 / (1 + $taxrate));
181 $taxamount = $linetotal * $taxrate;
184 $netamount += $linetotal;
186 if ($form->round_amount($taxrate, 7) == 0) {
187 if ($form->{taxincluded}) {
188 foreach $item (@taxaccounts) {
190 $form->round_amount($linetotal * $form->{"${item}_rate"} / (1 + abs($form->{"${item}_rate"})), 2);
191 $taxdiff += $taxamount;
192 $form->{amount}{ $form->{id} }{$item} -= $taxamount;
194 $form->{amount}{ $form->{id} }{ $taxaccounts[0] } += $taxdiff;
197 map { $form->{amount}{ $form->{id} }{$_} -= $linetotal * $form->{"${_}_rate"} } @taxaccounts;
201 map { $form->{amount}{ $form->{id} }{$_} -= $taxamount * $form->{"${_}_rate"} / $taxrate } @taxaccounts;
204 # add purchase to inventory, this one is without the tax!
205 $amount = $form->{"sellprice_$i"} * $form->{"qty_$i"} * $form->{exchangerate} / $price_factor;
206 $linetotal = $form->round_amount($form->{"sellprice_$i"} * $form->{"qty_$i"} / $price_factor, 2) * $form->{exchangerate};
207 $linetotal = $form->round_amount($linetotal, 2);
209 # this is the difference for the inventory
210 $invoicediff += ($amount - $linetotal);
212 $form->{amount}{ $form->{id} }{ $form->{"inventory_accno_$i"} } -= $linetotal;
214 # adjust and round sellprice
215 $form->{"sellprice_$i"} = $form->round_amount($form->{"sellprice_$i"} * $form->{exchangerate}, $decimalplaces);
217 $lastinventoryaccno = $form->{"inventory_accno_$i"};
219 next if $payments_only;
221 # update parts table by setting lastcost to current price, don't allow negative values by using abs
222 $query = qq|UPDATE parts SET lastcost = ? WHERE id = ?|;
223 @values = (abs($fxsellprice * $form->{exchangerate} / $basefactor), conv_i($form->{"id_$i"}));
224 do_query($form, $dbh, $query, @values);
226 # check if we sold the item already and
227 # make an entry for the expense and inventory
228 my $taxzone = $form->{taxzone_id} * 1;
230 qq|SELECT i.id, i.qty, i.allocated, i.trans_id, i.base_qty,
231 bg.inventory_accno_id, tc.expense_accno_id AS expense_accno_id, a.transdate
232 FROM invoice i, ar a, parts p, buchungsgruppen bg, taxzone_charts tc
233 WHERE (i.parts_id = p.id)
235 AND ((i.base_qty + i.allocated) > 0)
236 AND (i.trans_id = a.id)
237 AND (p.buchungsgruppen_id = bg.id)
238 AND (tc.buchungsgruppen_id = p.buchungsgruppen_id)
239 AND (tc.taxzone_id = ${taxzone})
241 # ORDER BY transdate guarantees FIFO
243 # sold two items without having bought them yet, example result of query:
244 # id | qty | allocated | trans_id | inventory_accno_id | expense_accno_id | transdate
245 # ---+-----+-----------+----------+--------------------+------------------+------------
246 # 9 | 2 | 0 | 9 | 15 | 151 | 2011-01-05
248 # base_qty + allocated > 0 if article has already been sold but not bought yet
250 # select qty,allocated,base_qty,sellprice from invoice where trans_id = 9;
251 # qty | allocated | base_qty | sellprice
252 # -----+-----------+----------+------------
253 # 2 | 0 | 2 | 1000.00000
255 $sth = prepare_execute_query($form, $dbh, $query, conv_i($form->{"id_$i"}));
257 my $totalqty = $baseqty;
259 while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
260 my $qty = min $totalqty, ($ref->{base_qty} + $ref->{allocated});
261 $linetotal = $form->round_amount(($form->{"sellprice_$i"} * $qty) / $basefactor, 2);
263 if ( $::instance_conf->get_inventory_system eq 'perpetual' ) {
264 # Warenbestandsbuchungen nur bei Bestandsmethode
266 if ($ref->{allocated} < 0) {
268 # we have an entry for it already, adjust amount
269 $form->update_balance($dbh, "acc_trans", "amount",
270 qq| (trans_id = $ref->{trans_id})
271 AND (chart_id = $ref->{inventory_accno_id})
272 AND (transdate = '$ref->{transdate}')|,
275 $form->update_balance($dbh, "acc_trans", "amount",
276 qq| (trans_id = $ref->{trans_id})
277 AND (chart_id = $ref->{expense_accno_id})
278 AND (transdate = '$ref->{transdate}')|,
281 } elsif ($linetotal != 0) {
284 # add entry for inventory, this one is for the sold item
285 $query = qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate, taxkey, tax_id, chart_link) VALUES (?, ?, ?, ?,
290 ORDER BY startdate DESC LIMIT 1),
295 ORDER BY startdate DESC LIMIT 1),
296 (SELECT link FROM chart WHERE id = ?))|;
297 @values = ($ref->{trans_id}, $ref->{inventory_accno_id}, $linetotal, $ref->{transdate}, $ref->{inventory_accno_id}, $ref->{transdate}, $ref->{inventory_accno_id}, $ref->{transdate},
298 $ref->{inventory_accno_id});
299 do_query($form, $dbh, $query, @values);
302 $query = qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate, taxkey, tax_id, chart_link) VALUES (?, ?, ?, ?,
307 ORDER BY startdate DESC LIMIT 1),
312 ORDER BY startdate DESC LIMIT 1),
313 (SELECT link FROM chart WHERE id = ?))|;
314 @values = ($ref->{trans_id}, $ref->{expense_accno_id}, ($linetotal * -1), $ref->{transdate}, $ref->{expense_accno_id}, $ref->{transdate}, $ref->{expense_accno_id}, $ref->{transdate},
315 $ref->{expense_accno_id});
316 do_query($form, $dbh, $query, @values);
320 # update allocated for sold item
321 $form->update_balance($dbh, "invoice", "allocated", qq|id = $ref->{id}|, $qty * -1);
325 last if ($totalqty -= $qty) <= 0;
330 } else { # if ($form->{"inventory_accno_id_$i"})
331 # part doesn't have an inventory_accno_id
332 # lastcost of the part is updated at the end
334 $linetotal = $form->round_amount($form->{"sellprice_$i"} * $form->{"qty_$i"} / $price_factor, 2);
336 if ($form->{taxincluded}) {
337 $taxamount = $linetotal * ($taxrate / (1 + $taxrate));
338 $form->{"sellprice_$i"} = $form->{"sellprice_$i"} * (1 / (1 + $taxrate));
341 $taxamount = $linetotal * $taxrate;
344 $netamount += $linetotal;
346 if ($form->round_amount($taxrate, 7) == 0) {
347 if ($form->{taxincluded}) {
348 foreach $item (@taxaccounts) {
349 $taxamount = $linetotal * $form->{"${item}_rate"} / (1 + abs($form->{"${item}_rate"}));
350 $totaltax += $taxamount;
351 $form->{amount}{ $form->{id} }{$item} -= $taxamount;
354 map { $form->{amount}{ $form->{id} }{$_} -= $linetotal * $form->{"${_}_rate"} } @taxaccounts;
357 map { $form->{amount}{ $form->{id} }{$_} -= $taxamount * $form->{"${_}_rate"} / $taxrate } @taxaccounts;
360 $amount = $form->{"sellprice_$i"} * $form->{"qty_$i"} * $form->{exchangerate} / $price_factor;
361 $linetotal = $form->round_amount($form->{"sellprice_$i"} * $form->{"qty_$i"} / $price_factor, 2) * $form->{exchangerate};
362 $linetotal = $form->round_amount($linetotal, 2);
364 # this is the difference for expense
365 $expensediff += ($amount - $linetotal);
367 # add amount to expense
368 $form->{amount}{ $form->{id} }{ $form->{"expense_accno_$i"} } -= $linetotal;
370 $lastexpenseaccno = $form->{"expense_accno_$i"};
372 # adjust and round sellprice
373 $form->{"sellprice_$i"} = $form->round_amount($form->{"sellprice_$i"} * $form->{exchangerate}, $decimalplaces);
375 next if $payments_only;
378 $query = qq|UPDATE parts SET lastcost = ? WHERE id = ?|;
379 do_query($form, $dbh, $query, $form->{"sellprice_$i"} / $basefactor, conv_i($form->{"id_$i"}));
382 next if $payments_only;
384 CVar->get_non_editable_ic_cvars(form => $form,
387 sub_module => 'invoice',
388 may_converted_from => ['delivery_order_items', 'orderitems', 'invoice']);
390 if (!$form->{"invoice_id_$i"}) {
391 # there is no persistent id, therefore create one with all necessary constraints
392 my $q_invoice_id = qq|SELECT nextval('invoiceid')|;
393 my $h_invoice_id = prepare_query($form, $dbh, $q_invoice_id);
394 do_statement($form, $h_invoice_id, $q_invoice_id);
395 $form->{"invoice_id_$i"} = $h_invoice_id->fetchrow_array();
396 my $q_create_invoice_id = qq|INSERT INTO invoice (id, trans_id, position, parts_id) values (?, ?, ?, ?)|;
397 do_query($form, $dbh, $q_create_invoice_id, conv_i($form->{"invoice_id_$i"}),
398 conv_i($form->{id}), conv_i($position), conv_i($form->{"id_$i"}));
399 $h_invoice_id->finish();
402 # save detail record in invoice table
404 UPDATE invoice SET trans_id = ?, position = ?, parts_id = ?, description = ?, longdescription = ?, qty = ?, base_qty = ?,
405 sellprice = ?, fxsellprice = ?, discount = ?, allocated = ?, unit = ?, deliverydate = ?,
406 project_id = ?, serialnumber = ?, price_factor_id = ?,
407 price_factor = (SELECT factor FROM price_factors WHERE id = ?), marge_price_factor = ?,
408 active_price_source = ?, active_discount_source = ?
412 @values = (conv_i($form->{id}), conv_i($position), conv_i($form->{"id_$i"}),
413 $form->{"description_$i"}, $restricter->process($form->{"longdescription_$i"}), $form->{"qty_$i"} * -1,
414 $baseqty * -1, $form->{"sellprice_$i"}, $fxsellprice, $form->{"discount_$i"}, $allocated,
415 $form->{"unit_$i"}, conv_date($form->{deliverydate}),
416 conv_i($form->{"project_id_$i"}), $form->{"serialnumber_$i"},
417 conv_i($form->{"price_factor_id_$i"}), conv_i($form->{"price_factor_id_$i"}), conv_i($form->{"marge_price_factor_$i"}),
418 $form->{"active_price_source_$i"}, $form->{"active_discount_source_$i"},
419 conv_i($form->{"invoice_id_$i"}));
420 do_query($form, $dbh, $query, @values);
421 push @processed_invoice_ids, $form->{"invoice_id_$i"};
423 CVar->save_custom_variables(module => 'IC',
424 sub_module => 'invoice',
425 trans_id => $form->{"invoice_id_$i"},
426 configs => $ic_cvar_configs,
428 name_prefix => 'ic_',
429 name_postfix => "_$i",
432 # link previous items with invoice items See IS.pm (no credit note -> no invoice item)
433 foreach (qw(delivery_order_items orderitems invoice)) {
434 if (!$form->{useasnew} && $form->{"converted_from_${_}_id_$i"}) {
435 RecordLinks->create_links('dbh' => $dbh,
438 'from_ids' => $form->{"converted_from_${_}_id_$i"},
439 'to_table' => 'invoice',
440 'to_id' => $form->{"invoice_id_$i"},
443 delete $form->{"converted_from_${_}_id_$i"};
447 $h_item_unit->finish();
449 $project_id = conv_i($form->{"globalproject_id"});
451 $form->{datepaid} = $form->{invdate};
453 # all amounts are in natural state, netamount includes the taxes
454 # if tax is included, netamount is rounded to 2 decimal places,
458 for my $i (1 .. $form->{paidaccounts}) {
459 $form->{"paid_$i"} = $form->parse_amount($myconfig, $form->{"paid_$i"});
460 $form->{paid} += $form->{"paid_$i"};
461 $form->{datepaid} = $form->{"datepaid_$i"} if $form->{"datepaid_$i"};
464 my ($tax, $paiddiff) = (0, 0);
466 $netamount = $form->round_amount($netamount, 2);
468 # figure out rounding errors for amount paid and total amount
469 if ($form->{taxincluded}) {
471 $amount = $form->round_amount($netamount * $form->{exchangerate}, 2);
472 $paiddiff = $amount - $netamount * $form->{exchangerate};
473 $netamount = $amount;
475 foreach $item (split / /, $form->{taxaccounts}) {
476 $amount = $form->{amount}{ $form->{id} }{$item} * $form->{exchangerate};
477 $form->{amount}{ $form->{id} }{$item} = $form->round_amount($amount, 2);
479 $amount = $form->{amount}{ $form->{id} }{$item} * -1;
481 $netamount -= $amount;
484 $invoicediff += $paiddiff;
485 $expensediff += $paiddiff;
487 ######## this only applies to tax included
489 # in the sales invoice case rounding errors only have to be corrected for
490 # income accounts, it is enough to add the total rounding error to one of
491 # the income accounts, with the one assigned to the last row being used
492 # (lastinventoryaccno)
494 # in the purchase invoice case rounding errors may be split between
495 # inventory accounts and expense accounts. After rounding, an error of 1
496 # cent is introduced if the total rounding error exceeds 0.005. The total
497 # error is made up of $invoicediff and $expensediff, however, so if both
498 # values are below 0.005, but add up to a total >= 0.005, correcting
499 # lastinventoryaccno and lastexpenseaccno separately has no effect after
500 # rounding. This caused bug 1579. Therefore when the combined total exceeds
501 # 0.005, but neither do individually, the account with the larger value
502 # shall receive the total rounding error, and the next time it is rounded
503 # the 1 cent correction will be introduced.
505 $form->{amount}{ $form->{id} }{$lastinventoryaccno} -= $invoicediff if $lastinventoryaccno;
506 $form->{amount}{ $form->{id} }{$lastexpenseaccno} -= $expensediff if $lastexpenseaccno;
508 if ( (abs($expensediff)+abs($invoicediff)) >= 0.005 and abs($expensediff) < 0.005 and abs($invoicediff) < 0.005 ) {
510 # in total the rounding error adds up to 1 cent effectively, correct the
511 # larger of the two numbers
513 if ( abs($form->{amount}{ $form->{id} }{$lastinventoryaccno}) > abs($form->{amount}{ $form->{id} }{$lastexpenseaccno}) ) {
514 # $invoicediff has already been deducted, now also deduct expensediff
515 $form->{amount}{ $form->{id} }{$lastinventoryaccno} -= $expensediff;
517 # expensediff has already been deducted, now also deduct invoicediff
518 $form->{amount}{ $form->{id} }{$lastexpenseaccno} -= $invoicediff;
523 $amount = $form->round_amount($netamount * $form->{exchangerate}, 2);
524 $paiddiff = $amount - $netamount * $form->{exchangerate};
525 $netamount = $amount;
527 foreach my $item (split / /, $form->{taxaccounts}) {
528 $form->{amount}{ $form->{id} }{$item} = $form->round_amount($form->{amount}{ $form->{id} }{$item}, 2);
529 $amount = $form->round_amount( $form->{amount}{ $form->{id} }{$item} * $form->{exchangerate} * -1, 2);
530 $paiddiff += $amount - $form->{amount}{ $form->{id} }{$item} * $form->{exchangerate} * -1;
531 $form->{amount}{ $form->{id} }{$item} = $form->round_amount($amount * -1, 2);
532 $amount = $form->{amount}{ $form->{id} }{$item} * -1;
537 $form->{amount}{ $form->{id} }{ $form->{AP} } = $netamount + $tax;
540 $form->{paid} = $form->round_amount($form->{paid} * $form->{exchangerate} + $paiddiff, 2) if $form->{paid} != 0;
542 # update exchangerate
544 $form->update_exchangerate($dbh, $form->{currency}, $form->{invdate}, 0, $form->{exchangerate})
545 if ($form->{currency} ne $defaultcurrency) && !$exchangerate;
547 # record acc_trans transactions
548 foreach my $trans_id (keys %{ $form->{amount} }) {
549 foreach my $accno (keys %{ $form->{amount}{$trans_id} }) {
550 $form->{amount}{$trans_id}{$accno} = $form->round_amount($form->{amount}{$trans_id}{$accno}, 2);
553 next if $payments_only || !$form->{amount}{$trans_id}{$accno};
555 $query = qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate, taxkey, project_id, tax_id, chart_link)
556 VALUES (?, (SELECT id FROM chart WHERE accno = ?), ?, ?,
559 WHERE chart_id= (SELECT id
563 ORDER BY startdate DESC LIMIT 1),
567 WHERE chart_id= (SELECT id
571 ORDER BY startdate DESC LIMIT 1),
572 (SELECT link FROM chart WHERE accno = ?))|;
573 @values = ($trans_id, $accno, $form->{amount}{$trans_id}{$accno},
574 conv_date($form->{invdate}), $accno, conv_date($form->{invdate}), $project_id, $accno, conv_date($form->{invdate}), $accno);
575 do_query($form, $dbh, $query, @values);
579 # deduct payment differences from paiddiff
580 for my $i (1 .. $form->{paidaccounts}) {
581 if ($form->{"paid_$i"} != 0) {
582 $amount = $form->round_amount($form->{"paid_$i"} * $form->{exchangerate}, 2);
583 $paiddiff -= $amount - $form->{"paid_$i"} * $form->{exchangerate};
587 # force AP entry if 0
589 $form->{amount}{ $form->{id} }{ $form->{AP} } = $form->{paid} if $form->{amount}{$form->{id}}{$form->{AP}} == 0;
591 # record payments and offsetting AP
592 for my $i (1 .. $form->{paidaccounts}) {
593 if ($form->{"acc_trans_id_$i"}
595 && (SL::DB::Default->get->payments_changeable == 0)) {
599 next if $form->{"paid_$i"} == 0;
601 my ($accno) = split /--/, $form->{"AP_paid_$i"};
602 $form->{"datepaid_$i"} = $form->{invdate} unless ($form->{"datepaid_$i"});
603 $form->{datepaid} = $form->{"datepaid_$i"};
605 $amount = $form->round_amount($form->{"paid_$i"} * $form->{exchangerate} + $paiddiff, 2) * -1;
608 if ($form->{amount}{ $form->{id} }{ $form->{AP} } != 0) {
609 $query = qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate, taxkey, project_id, tax_id, chart_link)
610 VALUES (?, (SELECT id FROM chart WHERE accno = ?), ?, ?,
613 WHERE chart_id= (SELECT id
617 ORDER BY startdate DESC LIMIT 1),
621 WHERE chart_id= (SELECT id
625 ORDER BY startdate DESC LIMIT 1),
626 (SELECT link FROM chart WHERE accno = ?))|;
627 @values = (conv_i($form->{id}), $form->{AP}, $amount,
628 $form->{"datepaid_$i"}, $form->{AP}, conv_date($form->{"datepaid_$i"}), $project_id, $form->{AP}, conv_date($form->{"datepaid_$i"}), $form->{AP});
629 do_query($form, $dbh, $query, @values);
633 my $gldate = (conv_date($form->{"gldate_$i"}))? conv_date($form->{"gldate_$i"}) : conv_date($form->current_date($myconfig));
636 qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate, gldate, source, memo, taxkey, project_id, tax_id, chart_link)
637 VALUES (?, (SELECT id FROM chart WHERE accno = ?), ?, ?, ?, ?, ?,
640 WHERE chart_id= (SELECT id
641 FROM chart WHERE accno = ?)
643 ORDER BY startdate DESC LIMIT 1),
647 WHERE chart_id= (SELECT id
648 FROM chart WHERE accno = ?)
650 ORDER BY startdate DESC LIMIT 1),
651 (SELECT link FROM chart WHERE accno = ?))|;
652 @values = (conv_i($form->{id}), $accno, $form->{"paid_$i"}, $form->{"datepaid_$i"},
653 $gldate, $form->{"source_$i"}, $form->{"memo_$i"}, $accno, conv_date($form->{"datepaid_$i"}), $project_id, $accno, conv_date($form->{"datepaid_$i"}), $accno);
654 do_query($form, $dbh, $query, @values);
658 if ($form->{currency} eq $defaultcurrency) {
659 $form->{"exchangerate_$i"} = 1;
661 $exchangerate = $form->check_exchangerate($myconfig, $form->{currency}, $form->{"datepaid_$i"}, 'sell');
662 $form->{"exchangerate_$i"} = $exchangerate || $form->parse_amount($myconfig, $form->{"exchangerate_$i"});
665 # exchangerate difference
666 $form->{fx}{$accno}{ $form->{"datepaid_$i"} } += $form->{"paid_$i"} * ($form->{"exchangerate_$i"} - 1) + $paiddiff;
670 ($form->{"paid_$i"} * $form->{exchangerate}) -
671 ($form->{"paid_$i"} * $form->{"exchangerate_$i"});
673 $form->{fx}{ $form->{fxgain_accno} }{ $form->{"datepaid_$i"} } += $amount;
675 $form->{fx}{ $form->{fxloss_accno} }{ $form->{"datepaid_$i"} } += $amount;
680 # update exchange rate
681 $form->update_exchangerate($dbh, $form->{currency}, $form->{"datepaid_$i"}, 0, $form->{"exchangerate_$i"})
682 if ($form->{currency} ne $defaultcurrency) && !$exchangerate;
685 # record exchange rate differences and gains/losses
686 foreach my $accno (keys %{ $form->{fx} }) {
687 foreach my $transdate (keys %{ $form->{fx}{$accno} }) {
688 $form->{fx}{$accno}{$transdate} = $form->round_amount($form->{fx}{$accno}{$transdate}, 2);
689 next if ($form->{fx}{$accno}{$transdate} == 0);
691 $query = qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate, cleared, fx_transaction, taxkey, project_id, tax_id, chart_link)
692 VALUES (?, (SELECT id FROM chart WHERE accno = ?), ?, ?, '0', '1', 0, ?,
693 (SELECT id FROM tax WHERE taxkey=0 LIMIT 1),
694 (SELECT link FROM chart WHERE accno = ?))|;
695 @values = (conv_i($form->{id}), $accno, $form->{fx}{$accno}{$transdate}, conv_date($transdate), $project_id, $accno);
696 do_query($form, $dbh, $query, @values);
700 IO->set_datepaid(table => 'ap', id => $form->{id}, dbh => $dbh);
702 if ($payments_only) {
703 $query = qq|UPDATE ap SET paid = ? WHERE id = ?|;
704 do_query($form, $dbh, $query, $form->{paid}, conv_i($form->{id}));
705 $form->new_lastmtime('ap');
710 $amount = $netamount + $tax;
712 # set values which could be empty
713 my $taxzone_id = $form->{taxzone_id} * 1;
714 $taxzone_id = SL::DB::Manager::TaxZone->get_default->id unless SL::DB::Manager::TaxZone->find_by(id => $taxzone_id);
716 $form->{invnumber} = $form->{id} unless $form->{invnumber};
719 $query = qq|UPDATE ap SET
720 invnumber = ?, ordnumber = ?, quonumber = ?, transdate = ?,
721 orddate = ?, quodate = ?, vendor_id = ?, amount = ?,
722 netamount = ?, paid = ?, duedate = ?,
723 invoice = ?, taxzone_id = ?, notes = ?, taxincluded = ?,
724 intnotes = ?, storno_id = ?, storno = ?,
725 cp_id = ?, employee_id = ?, department_id = ?, delivery_term_id = ?,
726 currency_id = (SELECT id FROM currencies WHERE name = ?),
727 globalproject_id = ?, direct_debit = ?
730 $form->{invnumber}, $form->{ordnumber}, $form->{quonumber}, conv_date($form->{invdate}),
731 conv_date($form->{orddate}), conv_date($form->{quodate}), conv_i($form->{vendor_id}), $amount,
732 $netamount, $form->{paid}, conv_date($form->{duedate}),
733 '1', $taxzone_id, $restricter->process($form->{notes}), $form->{taxincluded} ? 't' : 'f',
734 $form->{intnotes}, conv_i($form->{storno_id}), $form->{storno} ? 't' : 'f',
735 conv_i($form->{cp_id}), conv_i($form->{employee_id}), conv_i($form->{department_id}), conv_i($form->{delivery_term_id}),
737 conv_i($form->{globalproject_id}),
738 $form->{direct_debit} ? 't' : 'f',
741 do_query($form, $dbh, $query, @values);
743 if ($form->{storno}) {
744 $query = qq|UPDATE ap SET paid = paid + amount WHERE id = ?|;
745 do_query($form, $dbh, $query, conv_i($form->{storno_id}));
747 $query = qq|UPDATE ap SET storno = 't' WHERE id = ?|;
748 do_query($form, $dbh, $query, conv_i($form->{storno_id}));
750 $query = qq!UPDATE ap SET intnotes = ? || intnotes WHERE id = ?!;
751 do_query($form, $dbh, $query, "Rechnung storniert am $form->{invdate} ", conv_i($form->{storno_id}));
753 $query = qq|UPDATE ap SET paid = amount WHERE id = ?|;
754 do_query($form, $dbh, $query, conv_i($form->{id}));
757 $form->new_lastmtime('ap');
759 $form->{name} = $form->{vendor};
760 $form->{name} =~ s/--\Q$form->{vendor_id}\E//;
763 $form->add_shipto($dbh, $form->{id}, "AP");
765 # delete zero entries
766 do_query($form, $dbh, qq|DELETE FROM acc_trans WHERE amount = 0|);
768 Common::webdav_folder($form);
770 # Link this record to the records it was created from order or invoice (storno)
771 foreach (qw(oe ap)) {
772 if ($form->{"convert_from_${_}_ids"}) {
773 RecordLinks->create_links('dbh' => $dbh,
776 'from_ids' => $form->{"convert_from_${_}_ids"},
778 'to_id' => $form->{id},
780 delete $form->{"convert_from_${_}_ids"};
784 my @convert_from_do_ids = map { $_ * 1 } grep { $_ } split m/\s+/, $form->{convert_from_do_ids};
785 if (scalar @convert_from_do_ids) {
786 DO->close_orders('dbh' => $dbh,
787 'ids' => \@convert_from_do_ids);
789 RecordLinks->create_links('dbh' => $dbh,
791 'from_table' => 'delivery_orders',
792 'from_ids' => \@convert_from_do_ids,
794 'to_id' => $form->{id},
797 delete $form->{convert_from_do_ids};
799 ARAP->close_orders_if_billed('dbh' => $dbh,
800 'arap_id' => $form->{id},
803 # search for orphaned invoice items
804 $query = sprintf 'SELECT id FROM invoice WHERE trans_id = ? AND NOT id IN (%s)', join ', ', ("?") x scalar @processed_invoice_ids;
805 @values = (conv_i($form->{id}), map { conv_i($_) } @processed_invoice_ids);
806 my @orphaned_ids = map { $_->{id} } selectall_hashref_query($form, $dbh, $query, @values);
807 if (scalar @orphaned_ids) {
808 # clean up invoice items
809 $query = sprintf 'DELETE FROM invoice WHERE id IN (%s)', join ', ', ("?") x scalar @orphaned_ids;
810 do_query($form, $dbh, $query, @orphaned_ids);
813 # safety check datev export
814 if ($::instance_conf->get_datev_check_on_purchase_invoice) {
815 # if we need department for kostenstelle in DATEV check
816 $form->{department} = SL::DB::Manager::Department->find_by(id => $form->{department_id})->description if $form->{department_id};
817 my $transdate = $::form->{invdate} ? DateTime->from_lxoffice($::form->{invdate}) : undef;
818 $transdate ||= DateTime->today;
820 my $datev = SL::DATEV->new(
821 exporttype => DATEV_ET_BUCHUNGEN,
822 format => DATEV_FORMAT_KNE,
824 trans_id => $form->{id},
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} = $::request->presenter->type_abbreviation($ref->{part_type}).
1314 $::request->presenter->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 $form->{cp_greeting} = GenericTranslations->get('dbh' => $dbh,
1452 'translation_type' => 'greetings::' . ($form->{cp_gender} eq 'f' ? 'female' : 'male'),
1453 'allow_fallback' => 1);
1455 $main::lxdebug->leave_sub();
1459 $main::lxdebug->enter_sub();
1461 my ($self, $myconfig, $form) = @_;
1463 my $dbh = SL::DB->client->dbh;
1466 qq|SELECT accno, description, link
1468 WHERE link LIKE '%IC%'
1470 my $sth = prepare_execute_query($query, $dbh, $query);
1472 while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
1473 foreach my $key (split(/:/, $ref->{link})) {
1475 push @{ $form->{IC_links}{$key} },
1476 { accno => $ref->{accno},
1477 description => $ref->{description} };
1483 $main::lxdebug->leave_sub();
1486 sub _delete_payments {
1487 $main::lxdebug->enter_sub();
1489 my ($self, $form, $dbh) = @_;
1491 my @delete_acc_trans_ids;
1493 # Delete old payment entries from acc_trans.
1495 qq|SELECT acc_trans_id
1497 WHERE (trans_id = ?) AND fx_transaction
1501 SELECT at.acc_trans_id
1503 LEFT JOIN chart c ON (at.chart_id = c.id)
1504 WHERE (trans_id = ?) AND (c.link LIKE '%AP_paid%')|;
1505 push @delete_acc_trans_ids, selectall_array_query($form, $dbh, $query, conv_i($form->{id}), conv_i($form->{id}));
1508 qq|SELECT at.acc_trans_id
1510 LEFT JOIN chart c ON (at.chart_id = c.id)
1511 WHERE (trans_id = ?)
1512 AND ((c.link = 'AP') OR (c.link LIKE '%:AP') OR (c.link LIKE 'AP:%'))
1513 ORDER BY at.acc_trans_id
1515 push @delete_acc_trans_ids, selectall_array_query($form, $dbh, $query, conv_i($form->{id}));
1517 if (@delete_acc_trans_ids) {
1518 $query = qq|DELETE FROM acc_trans WHERE acc_trans_id IN (| . join(", ", @delete_acc_trans_ids) . qq|)|;
1519 do_query($form, $dbh, $query);
1522 $main::lxdebug->leave_sub();
1526 my ($self, $myconfig, $form, $locale) = @_;
1527 $main::lxdebug->enter_sub();
1529 my $rc = SL::DB->client->with_transaction(\&_post_payment, $self, $myconfig, $form, $locale);
1531 $::lxdebug->leave_sub;
1536 my ($self, $myconfig, $form, $locale) = @_;
1538 my $dbh = SL::DB->client->dbh;
1540 my (%payments, $old_form, $row, $item, $query, %keep_vars);
1542 $old_form = save_form();
1544 # Delete all entries in acc_trans from prior payments.
1545 if (SL::DB::Default->get->payments_changeable != 0) {
1546 $self->_delete_payments($form, $dbh);
1549 # Save the new payments the user made before cleaning up $form.
1550 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 };
1552 # Clean up $form so that old content won't tamper the results.
1553 %keep_vars = map { $_, 1 } qw(login password id);
1554 map { delete $form->{$_} unless $keep_vars{$_} } keys %{ $form };
1556 # Retrieve the invoice from the database.
1557 $self->retrieve_invoice($myconfig, $form);
1559 # Set up the content of $form in the way that IR::post_invoice() expects.
1560 $form->{exchangerate} = $form->format_amount($myconfig, $form->{exchangerate});
1562 for $row (1 .. scalar @{ $form->{invoice_details} }) {
1563 $item = $form->{invoice_details}->[$row - 1];
1565 map { $item->{$_} = $form->format_amount($myconfig, $item->{$_}) } qw(qty sellprice);
1567 map { $form->{"${_}_${row}"} = $item->{$_} } keys %{ $item };
1570 $form->{rowcount} = scalar @{ $form->{invoice_details} };
1572 delete @{$form}{qw(invoice_details paidaccounts storno paid)};
1574 # Restore the payment options from the user input.
1575 map { $form->{$_} = $payments{$_} } keys %payments;
1577 # Get the AP accno (which is normally done by Form::create_links()).
1581 LEFT JOIN chart c ON (at.chart_id = c.id)
1582 WHERE (trans_id = ?)
1583 AND ((c.link = 'AP') OR (c.link LIKE '%:AP') OR (c.link LIKE 'AP:%'))
1584 ORDER BY at.acc_trans_id
1587 ($form->{AP}) = selectfirst_array_query($form, $dbh, $query, conv_i($form->{id}));
1589 # Post the new payments.
1590 $self->post_invoice($myconfig, $form, $dbh, 1);
1592 restore_form($old_form);
1598 $::lxdebug->enter_sub;
1600 my ($self, %params) = @_;
1602 if (!$params{vendor_id} || !$params{invdate}) {
1603 $::lxdebug->leave_sub;
1604 return $params{default};
1607 my $dbh = $::form->get_standard_dbh;
1608 my $query = qq|SELECT ?::date + pt.terms_netto
1610 LEFT JOIN payment_terms pt ON (pt.id = v.payment_id)
1613 my ($duedate) = selectfirst_array_query($::form, $dbh, $query, $params{invdate}, $params{vendor_id});
1615 $duedate ||= $params{default};
1617 $::lxdebug->leave_sub;