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;
52 use SL::DB::MakeModel;
54 use SL::Presenter::Part qw(type_abbreviation classification_abbreviation);
55 use List::Util qw(min);
58 use constant PCLASS_OK => 0;
59 use constant PCLASS_NOTFORSALE => 1;
60 use constant PCLASS_NOTFORPURCHASE => 2;
63 my ($self, $myconfig, $form, $provided_dbh, %params) = @_;
64 $main::lxdebug->enter_sub();
66 my $rc = SL::DB->client->with_transaction(\&_post_invoice, $self, $myconfig, $form, $provided_dbh, %params);
68 $::lxdebug->leave_sub;
73 my ($self, $myconfig, $form, $provided_dbh, %params) = @_;
75 my $payments_only = $params{payments_only};
76 my $dbh = $provided_dbh || SL::DB->client->dbh;
77 my $restricter = SL::HTML::Restrict->create;
79 $form->{defaultcurrency} = $form->get_default_currency($myconfig);
80 my $defaultcurrency = $form->{defaultcurrency};
82 my $ic_cvar_configs = CVar->get_configs(module => 'IC',
85 my ($query, $sth, @values, $project_id);
86 my ($allocated, $taxrate, $taxamount, $taxdiff, $item);
87 my ($amount, $linetotal, $lastinventoryaccno, $lastexpenseaccno);
88 my ($netamount, $invoicediff, $expensediff) = (0, 0, 0);
90 my ($basefactor, $baseqty, @taxaccounts, $totaltax);
92 my $all_units = AM->retrieve_units($myconfig, $form);
95 if (!$payments_only) {
97 &reverse_invoice($dbh, $form);
99 ($form->{id}) = selectrow_query($form, $dbh, qq|SELECT nextval('glid')|);
100 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});
104 if ($form->{currency} eq $defaultcurrency) {
105 $form->{exchangerate} = 1;
107 $exchangerate = $form->check_exchangerate($myconfig, $form->{currency}, $form->{invdate}, 'sell');
110 $form->{exchangerate} = $exchangerate || $form->parse_amount($myconfig, $form->{exchangerate});
111 $form->{exchangerate} = 1 unless ($form->{exchangerate} * 1);
114 my $q_item_unit = qq|SELECT unit FROM parts WHERE id = ?|;
115 my $h_item_unit = prepare_query($form, $dbh, $q_item_unit);
117 $form->get_lists('price_factors' => 'ALL_PRICE_FACTORS');
118 my %price_factors = map { $_->{id} => $_->{factor} } @{ $form->{ALL_PRICE_FACTORS} };
121 my @processed_invoice_ids;
122 for my $i (1 .. $form->{rowcount}) {
123 next unless $form->{"id_$i"};
127 $form->{"qty_$i"} = $form->parse_amount($myconfig, $form->{"qty_$i"});
128 $form->{"qty_$i"} *= -1 if $form->{storno};
130 if ( $::instance_conf->get_inventory_system eq 'periodic') {
131 # inventory account number is overwritten with expense account number, so
132 # never book incoming to inventory account but always to expense account
133 $form->{"inventory_accno_$i"} = $form->{"expense_accno_$i"}
137 if (!$item_units{$form->{"id_$i"}}) {
138 do_statement($form, $h_item_unit, $q_item_unit, $form->{"id_$i"});
139 ($item_units{$form->{"id_$i"}}) = $h_item_unit->fetchrow_array();
142 my $item_unit = $item_units{$form->{"id_$i"}};
144 if (defined($all_units->{$item_unit}->{factor})
145 && ($all_units->{$item_unit}->{factor} ne '')
146 && ($all_units->{$item_unit}->{factor} * 1 != 0)) {
147 $basefactor = $all_units->{$form->{"unit_$i"}}->{factor} / $all_units->{$item_unit}->{factor};
151 $baseqty = $form->{"qty_$i"} * $basefactor;
153 @taxaccounts = split / /, $form->{"taxaccounts_$i"};
158 $form->{"sellprice_$i"} = $form->parse_amount($myconfig, $form->{"sellprice_$i"});
159 (my $fxsellprice = $form->{"sellprice_$i"}) =~ /\.(\d+)/;
161 my $decimalplaces = ($dec > 2) ? $dec : 2;
163 map { $taxrate += $form->{"${_}_rate"} } @taxaccounts;
165 $price_factor = $price_factors{ $form->{"price_factor_id_$i"} } || 1;
166 # copied from IS.pm, with some changes (no decimalplaces corrections here etc)
167 # TODO maybe use PriceTaxCalculation or something like this for backends (IR.pm / IS.pm)
169 # undo discount formatting
170 $form->{"discount_$i"} = $form->parse_amount($myconfig, $form->{"discount_$i"}) / 100;
172 $form->{"sellprice_$i"} = $fxsellprice * (1 - $form->{"discount_$i"});
174 ######################################################################
175 if ($form->{"inventory_accno_$i"}) {
177 $linetotal = $form->round_amount($form->{"sellprice_$i"} * $form->{"qty_$i"} / $price_factor, 2);
179 if ($form->{taxincluded}) {
181 $taxamount = $linetotal * ($taxrate / (1 + $taxrate));
182 $form->{"sellprice_$i"} = $form->{"sellprice_$i"} * (1 / (1 + $taxrate));
185 $taxamount = $linetotal * $taxrate;
188 $netamount += $linetotal;
190 if ($form->round_amount($taxrate, 7) == 0) {
191 if ($form->{taxincluded}) {
192 foreach $item (@taxaccounts) {
194 $form->round_amount($linetotal * $form->{"${item}_rate"} / (1 + abs($form->{"${item}_rate"})), 2);
195 $taxdiff += $taxamount;
196 $form->{amount}{ $form->{id} }{$item} -= $taxamount;
198 $form->{amount}{ $form->{id} }{ $taxaccounts[0] } += $taxdiff;
201 map { $form->{amount}{ $form->{id} }{$_} -= $linetotal * $form->{"${_}_rate"} } @taxaccounts;
205 map { $form->{amount}{ $form->{id} }{$_} -= $taxamount * $form->{"${_}_rate"} / $taxrate } @taxaccounts;
208 # add purchase to inventory, this one is without the tax!
209 $amount = $form->{"sellprice_$i"} * $form->{"qty_$i"} * $form->{exchangerate} / $price_factor;
210 $linetotal = $form->round_amount($form->{"sellprice_$i"} * $form->{"qty_$i"} / $price_factor, 2) * $form->{exchangerate};
211 $linetotal = $form->round_amount($linetotal, 2);
213 # this is the difference for the inventory
214 $invoicediff += ($amount - $linetotal);
216 $form->{amount}{ $form->{id} }{ $form->{"inventory_accno_$i"} } -= $linetotal;
218 # adjust and round sellprice
219 $form->{"sellprice_$i"} = $form->round_amount($form->{"sellprice_$i"} * $form->{exchangerate}, $decimalplaces);
221 $lastinventoryaccno = $form->{"inventory_accno_$i"};
223 next if $payments_only;
225 # update parts table by setting lastcost to current price, don't allow negative values by using abs
226 $query = qq|UPDATE parts SET lastcost = ? WHERE id = ?|;
227 @values = (abs($fxsellprice * $form->{exchangerate} / $basefactor), conv_i($form->{"id_$i"}));
228 do_query($form, $dbh, $query, @values);
230 # check if we sold the item already and
231 # make an entry for the expense and inventory
232 my $taxzone = $form->{taxzone_id} * 1;
234 qq|SELECT i.id, i.qty, i.allocated, i.trans_id, i.base_qty,
235 bg.inventory_accno_id, tc.expense_accno_id AS expense_accno_id, a.transdate
236 FROM invoice i, ar a, parts p, buchungsgruppen bg, taxzone_charts tc
237 WHERE (i.parts_id = p.id)
239 AND ((i.base_qty + i.allocated) > 0)
240 AND (i.trans_id = a.id)
241 AND (p.buchungsgruppen_id = bg.id)
242 AND (tc.buchungsgruppen_id = p.buchungsgruppen_id)
243 AND (tc.taxzone_id = ${taxzone})
245 # ORDER BY transdate guarantees FIFO
247 # sold two items without having bought them yet, example result of query:
248 # id | qty | allocated | trans_id | inventory_accno_id | expense_accno_id | transdate
249 # ---+-----+-----------+----------+--------------------+------------------+------------
250 # 9 | 2 | 0 | 9 | 15 | 151 | 2011-01-05
252 # base_qty + allocated > 0 if article has already been sold but not bought yet
254 # select qty,allocated,base_qty,sellprice from invoice where trans_id = 9;
255 # qty | allocated | base_qty | sellprice
256 # -----+-----------+----------+------------
257 # 2 | 0 | 2 | 1000.00000
259 $sth = prepare_execute_query($form, $dbh, $query, conv_i($form->{"id_$i"}));
261 my $totalqty = $baseqty;
263 while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
264 my $qty = min $totalqty, ($ref->{base_qty} + $ref->{allocated});
265 $linetotal = $form->round_amount(($form->{"sellprice_$i"} * $qty) / $basefactor, 2);
267 if ( $::instance_conf->get_inventory_system eq 'perpetual' ) {
268 # Warenbestandsbuchungen nur bei Bestandsmethode
270 if ($ref->{allocated} < 0) {
272 # we have an entry for it already, adjust amount
273 $form->update_balance($dbh, "acc_trans", "amount",
274 qq| (trans_id = $ref->{trans_id})
275 AND (chart_id = $ref->{inventory_accno_id})
276 AND (transdate = '$ref->{transdate}')|,
279 $form->update_balance($dbh, "acc_trans", "amount",
280 qq| (trans_id = $ref->{trans_id})
281 AND (chart_id = $ref->{expense_accno_id})
282 AND (transdate = '$ref->{transdate}')|,
285 } elsif ($linetotal != 0) {
288 # add entry for inventory, this one is for the sold item
289 $query = qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate, taxkey, tax_id, chart_link) VALUES (?, ?, ?, ?,
294 ORDER BY startdate DESC LIMIT 1),
299 ORDER BY startdate DESC LIMIT 1),
300 (SELECT link FROM chart WHERE id = ?))|;
301 @values = ($ref->{trans_id}, $ref->{inventory_accno_id}, $linetotal, $ref->{transdate}, $ref->{inventory_accno_id}, $ref->{transdate}, $ref->{inventory_accno_id}, $ref->{transdate},
302 $ref->{inventory_accno_id});
303 do_query($form, $dbh, $query, @values);
306 $query = qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate, taxkey, tax_id, chart_link) VALUES (?, ?, ?, ?,
311 ORDER BY startdate DESC LIMIT 1),
316 ORDER BY startdate DESC LIMIT 1),
317 (SELECT link FROM chart WHERE id = ?))|;
318 @values = ($ref->{trans_id}, $ref->{expense_accno_id}, ($linetotal * -1), $ref->{transdate}, $ref->{expense_accno_id}, $ref->{transdate}, $ref->{expense_accno_id}, $ref->{transdate},
319 $ref->{expense_accno_id});
320 do_query($form, $dbh, $query, @values);
324 # update allocated for sold item
325 $form->update_balance($dbh, "invoice", "allocated", qq|id = $ref->{id}|, $qty * -1);
329 last if ($totalqty -= $qty) <= 0;
334 } else { # if ($form->{"inventory_accno_id_$i"})
335 # part doesn't have an inventory_accno_id
336 # lastcost of the part is updated at the end
338 $linetotal = $form->round_amount($form->{"sellprice_$i"} * $form->{"qty_$i"} / $price_factor, 2);
340 if ($form->{taxincluded}) {
341 $taxamount = $linetotal * ($taxrate / (1 + $taxrate));
342 $form->{"sellprice_$i"} = $form->{"sellprice_$i"} * (1 / (1 + $taxrate));
345 $taxamount = $linetotal * $taxrate;
348 $netamount += $linetotal;
350 if ($form->round_amount($taxrate, 7) == 0) {
351 if ($form->{taxincluded}) {
352 foreach $item (@taxaccounts) {
353 $taxamount = $linetotal * $form->{"${item}_rate"} / (1 + abs($form->{"${item}_rate"}));
354 $totaltax += $taxamount;
355 $form->{amount}{ $form->{id} }{$item} -= $taxamount;
358 map { $form->{amount}{ $form->{id} }{$_} -= $linetotal * $form->{"${_}_rate"} } @taxaccounts;
361 map { $form->{amount}{ $form->{id} }{$_} -= $taxamount * $form->{"${_}_rate"} / $taxrate } @taxaccounts;
364 $amount = $form->{"sellprice_$i"} * $form->{"qty_$i"} * $form->{exchangerate} / $price_factor;
365 $linetotal = $form->round_amount($form->{"sellprice_$i"} * $form->{"qty_$i"} / $price_factor, 2) * $form->{exchangerate};
366 $linetotal = $form->round_amount($linetotal, 2);
368 # this is the difference for expense
369 $expensediff += ($amount - $linetotal);
371 # add amount to expense
372 $form->{amount}{ $form->{id} }{ $form->{"expense_accno_$i"} } -= $linetotal;
374 $lastexpenseaccno = $form->{"expense_accno_$i"};
376 # adjust and round sellprice
377 $form->{"sellprice_$i"} = $form->round_amount($form->{"sellprice_$i"} * $form->{exchangerate}, $decimalplaces);
379 next if $payments_only;
382 $query = qq|UPDATE parts SET lastcost = ? WHERE id = ?|;
383 do_query($form, $dbh, $query, $form->{"sellprice_$i"} / $basefactor, conv_i($form->{"id_$i"}));
386 next if $payments_only;
388 CVar->get_non_editable_ic_cvars(form => $form,
391 sub_module => 'invoice',
392 may_converted_from => ['delivery_order_items', 'orderitems', 'invoice']);
394 if (!$form->{"invoice_id_$i"}) {
395 # there is no persistent id, therefore create one with all necessary constraints
396 my $q_invoice_id = qq|SELECT nextval('invoiceid')|;
397 my $h_invoice_id = prepare_query($form, $dbh, $q_invoice_id);
398 do_statement($form, $h_invoice_id, $q_invoice_id);
399 $form->{"invoice_id_$i"} = $h_invoice_id->fetchrow_array();
400 my $q_create_invoice_id = qq|INSERT INTO invoice (id, trans_id, position, parts_id) values (?, ?, ?, ?)|;
401 do_query($form, $dbh, $q_create_invoice_id, conv_i($form->{"invoice_id_$i"}),
402 conv_i($form->{id}), conv_i($position), conv_i($form->{"id_$i"}));
403 $h_invoice_id->finish();
406 # save detail record in invoice table
408 UPDATE invoice SET trans_id = ?, position = ?, parts_id = ?, description = ?, longdescription = ?, qty = ?, base_qty = ?,
409 sellprice = ?, fxsellprice = ?, discount = ?, allocated = ?, unit = ?, deliverydate = ?,
410 project_id = ?, serialnumber = ?, price_factor_id = ?,
411 price_factor = (SELECT factor FROM price_factors WHERE id = ?), marge_price_factor = ?,
412 active_price_source = ?, active_discount_source = ?
416 @values = (conv_i($form->{id}), conv_i($position), conv_i($form->{"id_$i"}),
417 $form->{"description_$i"}, $restricter->process($form->{"longdescription_$i"}), $form->{"qty_$i"} * -1,
418 $baseqty * -1, $form->{"sellprice_$i"}, $fxsellprice, $form->{"discount_$i"}, $allocated,
419 $form->{"unit_$i"}, conv_date($form->{deliverydate}),
420 conv_i($form->{"project_id_$i"}), $form->{"serialnumber_$i"},
421 conv_i($form->{"price_factor_id_$i"}), conv_i($form->{"price_factor_id_$i"}), conv_i($form->{"marge_price_factor_$i"}),
422 $form->{"active_price_source_$i"}, $form->{"active_discount_source_$i"},
423 conv_i($form->{"invoice_id_$i"}));
424 do_query($form, $dbh, $query, @values);
425 push @processed_invoice_ids, $form->{"invoice_id_$i"};
427 CVar->save_custom_variables(module => 'IC',
428 sub_module => 'invoice',
429 trans_id => $form->{"invoice_id_$i"},
430 configs => $ic_cvar_configs,
432 name_prefix => 'ic_',
433 name_postfix => "_$i",
436 # link previous items with invoice items See IS.pm (no credit note -> no invoice item)
437 foreach (qw(delivery_order_items orderitems invoice)) {
438 if (!$form->{useasnew} && $form->{"converted_from_${_}_id_$i"}) {
439 RecordLinks->create_links('dbh' => $dbh,
442 'from_ids' => $form->{"converted_from_${_}_id_$i"},
443 'to_table' => 'invoice',
444 'to_id' => $form->{"invoice_id_$i"},
447 delete $form->{"converted_from_${_}_id_$i"};
451 $h_item_unit->finish();
453 $project_id = conv_i($form->{"globalproject_id"});
455 $form->{datepaid} = $form->{invdate};
457 # all amounts are in natural state, netamount includes the taxes
458 # if tax is included, netamount is rounded to 2 decimal places,
462 for my $i (1 .. $form->{paidaccounts}) {
463 $form->{"paid_$i"} = $form->parse_amount($myconfig, $form->{"paid_$i"});
464 $form->{paid} += $form->{"paid_$i"};
465 $form->{datepaid} = $form->{"datepaid_$i"} if $form->{"datepaid_$i"};
468 my ($tax, $paiddiff) = (0, 0);
470 $netamount = $form->round_amount($netamount, 2);
472 # figure out rounding errors for amount paid and total amount
473 if ($form->{taxincluded}) {
475 $amount = $form->round_amount($netamount * $form->{exchangerate}, 2);
476 $paiddiff = $amount - $netamount * $form->{exchangerate};
477 $netamount = $amount;
479 foreach $item (split / /, $form->{taxaccounts}) {
480 $amount = $form->{amount}{ $form->{id} }{$item} * $form->{exchangerate};
481 $form->{amount}{ $form->{id} }{$item} = $form->round_amount($amount, 2);
483 $amount = $form->{amount}{ $form->{id} }{$item} * -1;
485 $netamount -= $amount;
488 $invoicediff += $paiddiff;
489 $expensediff += $paiddiff;
491 ######## this only applies to tax included
493 # in the sales invoice case rounding errors only have to be corrected for
494 # income accounts, it is enough to add the total rounding error to one of
495 # the income accounts, with the one assigned to the last row being used
496 # (lastinventoryaccno)
498 # in the purchase invoice case rounding errors may be split between
499 # inventory accounts and expense accounts. After rounding, an error of 1
500 # cent is introduced if the total rounding error exceeds 0.005. The total
501 # error is made up of $invoicediff and $expensediff, however, so if both
502 # values are below 0.005, but add up to a total >= 0.005, correcting
503 # lastinventoryaccno and lastexpenseaccno separately has no effect after
504 # rounding. This caused bug 1579. Therefore when the combined total exceeds
505 # 0.005, but neither do individually, the account with the larger value
506 # shall receive the total rounding error, and the next time it is rounded
507 # the 1 cent correction will be introduced.
509 $form->{amount}{ $form->{id} }{$lastinventoryaccno} -= $invoicediff if $lastinventoryaccno;
510 $form->{amount}{ $form->{id} }{$lastexpenseaccno} -= $expensediff if $lastexpenseaccno;
512 if ( (abs($expensediff)+abs($invoicediff)) >= 0.005 and abs($expensediff) < 0.005 and abs($invoicediff) < 0.005 ) {
514 # in total the rounding error adds up to 1 cent effectively, correct the
515 # larger of the two numbers
517 if ( abs($form->{amount}{ $form->{id} }{$lastinventoryaccno}) > abs($form->{amount}{ $form->{id} }{$lastexpenseaccno}) ) {
518 # $invoicediff has already been deducted, now also deduct expensediff
519 $form->{amount}{ $form->{id} }{$lastinventoryaccno} -= $expensediff;
521 # expensediff has already been deducted, now also deduct invoicediff
522 $form->{amount}{ $form->{id} }{$lastexpenseaccno} -= $invoicediff;
527 $amount = $form->round_amount($netamount * $form->{exchangerate}, 2);
528 $paiddiff = $amount - $netamount * $form->{exchangerate};
529 $netamount = $amount;
531 foreach my $item (split / /, $form->{taxaccounts}) {
532 $form->{amount}{ $form->{id} }{$item} = $form->round_amount($form->{amount}{ $form->{id} }{$item}, 2);
533 $amount = $form->round_amount( $form->{amount}{ $form->{id} }{$item} * $form->{exchangerate} * -1, 2);
534 $paiddiff += $amount - $form->{amount}{ $form->{id} }{$item} * $form->{exchangerate} * -1;
535 $form->{amount}{ $form->{id} }{$item} = $form->round_amount($amount * -1, 2);
536 $amount = $form->{amount}{ $form->{id} }{$item} * -1;
541 $form->{amount}{ $form->{id} }{ $form->{AP} } = $netamount + $tax;
544 $form->{paid} = $form->round_amount($form->{paid} * $form->{exchangerate} + $paiddiff, 2) if $form->{paid} != 0;
546 # update exchangerate
548 $form->update_exchangerate($dbh, $form->{currency}, $form->{invdate}, 0, $form->{exchangerate})
549 if ($form->{currency} ne $defaultcurrency) && !$exchangerate;
551 # record acc_trans transactions
552 my $taxdate = $form->{tax_point} || $form->{deliverydate} || $form->{invdate};
553 foreach my $trans_id (keys %{ $form->{amount} }) {
554 foreach my $accno (keys %{ $form->{amount}{$trans_id} }) {
555 $form->{amount}{$trans_id}{$accno} = $form->round_amount($form->{amount}{$trans_id}{$accno}, 2);
558 next if $payments_only || !$form->{amount}{$trans_id}{$accno};
560 $query = qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate, taxkey, project_id, tax_id, chart_link)
561 VALUES (?, (SELECT id FROM chart WHERE accno = ?), ?, ?,
564 WHERE chart_id= (SELECT id
568 ORDER BY startdate DESC LIMIT 1),
572 WHERE chart_id= (SELECT id
576 ORDER BY startdate DESC LIMIT 1),
577 (SELECT link FROM chart WHERE accno = ?))|;
578 @values = ($trans_id, $accno, $form->{amount}{$trans_id}{$accno},
579 conv_date($form->{invdate}), $accno, conv_date($taxdate), $project_id, $accno, conv_date($taxdate), $accno);
580 do_query($form, $dbh, $query, @values);
584 # deduct payment differences from paiddiff
585 for my $i (1 .. $form->{paidaccounts}) {
586 if ($form->{"paid_$i"} != 0) {
587 $amount = $form->round_amount($form->{"paid_$i"} * $form->{exchangerate}, 2);
588 $paiddiff -= $amount - $form->{"paid_$i"} * $form->{exchangerate};
592 # force AP entry if 0
594 $form->{amount}{ $form->{id} }{ $form->{AP} } = $form->{paid} if $form->{amount}{$form->{id}}{$form->{AP}} == 0;
596 my %already_cleared = %{ $params{already_cleared} // {} };
598 # record payments and offsetting AP
599 for my $i (1 .. $form->{paidaccounts}) {
600 if ($form->{"acc_trans_id_$i"}
602 && (SL::DB::Default->get->payments_changeable == 0)) {
606 next if $form->{"paid_$i"} == 0;
608 my ($accno) = split /--/, $form->{"AP_paid_$i"};
609 $form->{"datepaid_$i"} = $form->{invdate} unless ($form->{"datepaid_$i"});
610 $form->{datepaid} = $form->{"datepaid_$i"};
612 $amount = $form->round_amount($form->{"paid_$i"} * $form->{exchangerate} + $paiddiff, 2) * -1;
614 my $new_cleared = !$form->{"acc_trans_id_$i"} ? 'f'
615 : !$already_cleared{$form->{"acc_trans_id_$i"}} ? 'f'
616 : $already_cleared{$form->{"acc_trans_id_$i"}}->{amount} != $form->{"paid_$i"} ? 'f'
617 : $already_cleared{$form->{"acc_trans_id_$i"}}->{accno} != $accno ? 'f'
618 : $already_cleared{$form->{"acc_trans_id_$i"}}->{cleared} ? 't'
622 if ($form->{amount}{ $form->{id} }{ $form->{AP} } != 0) {
623 $query = qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate, taxkey, project_id, cleared, tax_id, chart_link)
624 VALUES (?, (SELECT id FROM chart WHERE accno = ?), ?, ?,
627 WHERE chart_id= (SELECT id
631 ORDER BY startdate DESC LIMIT 1),
635 WHERE chart_id= (SELECT id
639 ORDER BY startdate DESC LIMIT 1),
640 (SELECT link FROM chart WHERE accno = ?))|;
641 @values = (conv_i($form->{id}), $form->{AP}, $amount,
642 $form->{"datepaid_$i"}, $form->{AP}, conv_date($form->{"datepaid_$i"}), $project_id, $new_cleared, $form->{AP}, conv_date($form->{"datepaid_$i"}), $form->{AP});
643 do_query($form, $dbh, $query, @values);
647 my $gldate = (conv_date($form->{"gldate_$i"}))? conv_date($form->{"gldate_$i"}) : conv_date($form->current_date($myconfig));
650 qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate, gldate, source, memo, taxkey, project_id, cleared, tax_id, chart_link)
651 VALUES (?, (SELECT id FROM chart WHERE accno = ?), ?, ?, ?, ?, ?,
654 WHERE chart_id= (SELECT id
655 FROM chart WHERE accno = ?)
657 ORDER BY startdate DESC LIMIT 1),
661 WHERE chart_id= (SELECT id
662 FROM chart WHERE accno = ?)
664 ORDER BY startdate DESC LIMIT 1),
665 (SELECT link FROM chart WHERE accno = ?))|;
666 @values = (conv_i($form->{id}), $accno, $form->{"paid_$i"}, $form->{"datepaid_$i"},
667 $gldate, $form->{"source_$i"}, $form->{"memo_$i"}, $accno, conv_date($form->{"datepaid_$i"}), $project_id, $new_cleared, $accno, conv_date($form->{"datepaid_$i"}), $accno);
668 do_query($form, $dbh, $query, @values);
672 if ($form->{currency} eq $defaultcurrency) {
673 $form->{"exchangerate_$i"} = 1;
675 $exchangerate = $form->check_exchangerate($myconfig, $form->{currency}, $form->{"datepaid_$i"}, 'sell');
676 $form->{"exchangerate_$i"} = $exchangerate || $form->parse_amount($myconfig, $form->{"exchangerate_$i"});
679 # exchangerate difference
680 $form->{fx}{$accno}{ $form->{"datepaid_$i"} } += $form->{"paid_$i"} * ($form->{"exchangerate_$i"} - 1) + $paiddiff;
684 ($form->{"paid_$i"} * $form->{exchangerate}) -
685 ($form->{"paid_$i"} * $form->{"exchangerate_$i"});
687 $form->{fx}{ $form->{fxgain_accno} }{ $form->{"datepaid_$i"} } += $amount;
689 $form->{fx}{ $form->{fxloss_accno} }{ $form->{"datepaid_$i"} } += $amount;
694 # update exchange rate
695 $form->update_exchangerate($dbh, $form->{currency}, $form->{"datepaid_$i"}, 0, $form->{"exchangerate_$i"})
696 if ($form->{currency} ne $defaultcurrency) && !$exchangerate;
699 # record exchange rate differences and gains/losses
700 foreach my $accno (keys %{ $form->{fx} }) {
701 foreach my $transdate (keys %{ $form->{fx}{$accno} }) {
702 $form->{fx}{$accno}{$transdate} = $form->round_amount($form->{fx}{$accno}{$transdate}, 2);
703 next if ($form->{fx}{$accno}{$transdate} == 0);
705 $query = qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate, cleared, fx_transaction, taxkey, project_id, tax_id, chart_link)
706 VALUES (?, (SELECT id FROM chart WHERE accno = ?), ?, ?, '0', '1', 0, ?,
707 (SELECT id FROM tax WHERE taxkey=0 LIMIT 1),
708 (SELECT link FROM chart WHERE accno = ?))|;
709 @values = (conv_i($form->{id}), $accno, $form->{fx}{$accno}{$transdate}, conv_date($transdate), $project_id, $accno);
710 do_query($form, $dbh, $query, @values);
714 IO->set_datepaid(table => 'ap', id => $form->{id}, dbh => $dbh);
716 if ($payments_only) {
717 $query = qq|UPDATE ap SET paid = ? WHERE id = ?|;
718 do_query($form, $dbh, $query, $form->{paid}, conv_i($form->{id}));
719 $form->new_lastmtime('ap');
724 $amount = $netamount + $tax;
726 # set values which could be empty
727 my $taxzone_id = $form->{taxzone_id} * 1;
728 $taxzone_id = SL::DB::Manager::TaxZone->get_default->id unless SL::DB::Manager::TaxZone->find_by(id => $taxzone_id);
730 $form->{invnumber} = $form->{id} unless $form->{invnumber};
733 $query = qq|UPDATE ap SET
734 invnumber = ?, ordnumber = ?, quonumber = ?, transdate = ?,
735 orddate = ?, quodate = ?, vendor_id = ?, amount = ?,
736 netamount = ?, paid = ?, duedate = ?, deliverydate = ?,
737 invoice = ?, taxzone_id = ?, notes = ?, taxincluded = ?,
738 intnotes = ?, storno_id = ?, storno = ?, tax_point = ?,
739 cp_id = ?, employee_id = ?, department_id = ?, delivery_term_id = ?,
740 payment_id = ?, transaction_description = ?,
741 currency_id = (SELECT id FROM currencies WHERE name = ?),
742 globalproject_id = ?, direct_debit = ?
745 $form->{invnumber}, $form->{ordnumber}, $form->{quonumber}, conv_date($form->{invdate}),
746 conv_date($form->{orddate}), conv_date($form->{quodate}), conv_i($form->{vendor_id}), $amount,
747 $netamount, $form->{paid}, conv_date($form->{duedate}), conv_date($form->{deliverydate}),
748 '1', $taxzone_id, $restricter->process($form->{notes}), $form->{taxincluded} ? 't' : 'f',
749 $form->{intnotes}, conv_i($form->{storno_id}), $form->{storno} ? 't' : 'f', conv_date($form->{tax_point}),
750 conv_i($form->{cp_id}), conv_i($form->{employee_id}), conv_i($form->{department_id}), conv_i($form->{delivery_term_id}),
751 conv_i($form->{payment_id}), $form->{transaction_description},
753 conv_i($form->{globalproject_id}),
754 $form->{direct_debit} ? 't' : 'f',
757 do_query($form, $dbh, $query, @values);
759 if ($form->{storno}) {
760 $query = qq|UPDATE ap SET paid = paid + amount WHERE id = ?|;
761 do_query($form, $dbh, $query, conv_i($form->{storno_id}));
763 $query = qq|UPDATE ap SET storno = 't' WHERE id = ?|;
764 do_query($form, $dbh, $query, conv_i($form->{storno_id}));
766 $query = qq!UPDATE ap SET intnotes = ? || intnotes WHERE id = ?!;
767 do_query($form, $dbh, $query, "Rechnung storniert am $form->{invdate} ", conv_i($form->{storno_id}));
769 $query = qq|UPDATE ap SET paid = amount WHERE id = ?|;
770 do_query($form, $dbh, $query, conv_i($form->{id}));
773 $form->new_lastmtime('ap');
775 $form->{name} = $form->{vendor};
776 $form->{name} =~ s/--\Q$form->{vendor_id}\E//;
779 $form->add_shipto($dbh, $form->{id}, "AP");
781 # delete zero entries
782 do_query($form, $dbh, qq|DELETE FROM acc_trans WHERE amount = 0|);
784 Common::webdav_folder($form);
786 # Link this record to the records it was created from order or invoice (storno)
787 foreach (qw(oe ap)) {
788 if ($form->{"convert_from_${_}_ids"}) {
789 RecordLinks->create_links('dbh' => $dbh,
792 'from_ids' => $form->{"convert_from_${_}_ids"},
794 'to_id' => $form->{id},
796 delete $form->{"convert_from_${_}_ids"};
800 my @convert_from_do_ids = map { $_ * 1 } grep { $_ } split m/\s+/, $form->{convert_from_do_ids};
801 if (scalar @convert_from_do_ids) {
802 DO->close_orders('dbh' => $dbh,
803 'ids' => \@convert_from_do_ids);
805 RecordLinks->create_links('dbh' => $dbh,
807 'from_table' => 'delivery_orders',
808 'from_ids' => \@convert_from_do_ids,
810 'to_id' => $form->{id},
813 delete $form->{convert_from_do_ids};
815 ARAP->close_orders_if_billed('dbh' => $dbh,
816 'arap_id' => $form->{id},
819 # search for orphaned invoice items
820 $query = sprintf 'SELECT id FROM invoice WHERE trans_id = ? AND NOT id IN (%s)', join ', ', ("?") x scalar @processed_invoice_ids;
821 @values = (conv_i($form->{id}), map { conv_i($_) } @processed_invoice_ids);
822 my @orphaned_ids = map { $_->{id} } selectall_hashref_query($form, $dbh, $query, @values);
823 if (scalar @orphaned_ids) {
824 # clean up invoice items
825 $query = sprintf 'DELETE FROM invoice WHERE id IN (%s)', join ', ', ("?") x scalar @orphaned_ids;
826 do_query($form, $dbh, $query, @orphaned_ids);
829 if ($form->{draft_id}) {
830 SL::DB::Manager::Draft->delete_all(where => [ id => delete($form->{draft_id}) ]);
833 # safety check datev export
834 if ($::instance_conf->get_datev_check_on_purchase_invoice) {
836 my $datev = SL::DATEV->new(
838 trans_id => $form->{id},
841 $datev->generate_datev_data;
843 if ($datev->errors) {
844 die join "\n", $::locale->text('DATEV check returned errors:'), $datev->errors;
851 sub reverse_invoice {
852 $main::lxdebug->enter_sub();
854 my ($dbh, $form) = @_;
856 # reverse inventory items
858 qq|SELECT i.parts_id, p.part_type, i.qty, i.allocated, i.sellprice
859 FROM invoice i, parts p
860 WHERE (i.parts_id = p.id)
861 AND (i.trans_id = ?)|;
862 my $sth = prepare_execute_query($form, $dbh, $query, conv_i($form->{id}));
866 while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
867 $netamount += $form->round_amount($ref->{sellprice} * $ref->{qty} * -1, 2);
869 next unless $ref->{part_type} eq 'part';
871 # if $ref->{allocated} > 0 than we sold that many items
872 next if ($ref->{allocated} <= 0);
874 # get references for sold items
876 qq|SELECT i.id, i.trans_id, i.allocated, a.transdate
878 WHERE (i.parts_id = ?)
879 AND (i.allocated < 0)
880 AND (i.trans_id = a.id)
881 ORDER BY transdate DESC|;
882 my $sth2 = prepare_execute_query($form, $dbh, $query, $ref->{parts_id});
884 while (my $pthref = $sth2->fetchrow_hashref("NAME_lc")) {
885 my $qty = $ref->{allocated};
886 if (($ref->{allocated} + $pthref->{allocated}) > 0) {
887 $qty = $pthref->{allocated} * -1;
890 my $amount = $form->round_amount($ref->{sellprice} * $qty, 2);
893 $form->update_balance($dbh, "invoice", "allocated", qq|id = $pthref->{id}|, $qty);
895 if ( $::instance_conf->get_inventory_system eq 'perpetual' ) {
897 $form->update_balance($dbh, "acc_trans", "amount",
898 qq| (trans_id = $pthref->{trans_id})
899 AND (chart_id = $ref->{expense_accno_id})
900 AND (transdate = '$pthref->{transdate}')|,
903 $form->update_balance($dbh, "acc_trans", "amount",
904 qq| (trans_id = $pthref->{trans_id})
905 AND (chart_id = $ref->{inventory_accno_id})
906 AND (transdate = '$pthref->{transdate}')|,
910 last if (($ref->{allocated} -= $qty) <= 0);
916 my $id = conv_i($form->{id});
919 $query = qq|DELETE FROM acc_trans WHERE trans_id = ?|;
920 do_query($form, $dbh, $query, $id);
922 $query = qq|DELETE FROM shipto WHERE (trans_id = ?) AND (module = 'AP')|;
923 do_query($form, $dbh, $query, $id);
925 $main::lxdebug->leave_sub();
929 $main::lxdebug->enter_sub();
931 my ($self, $myconfig, $form) = @_;
933 # connect to database
934 my $dbh = SL::DB->client->dbh;
936 SL::DB->client->with_transaction(sub{
938 &reverse_invoice($dbh, $form);
940 my @values = (conv_i($form->{id}));
942 # delete zero entries
943 # wtf? use case for this?
944 $query = qq|DELETE FROM acc_trans WHERE amount = 0|;
945 do_query($form, $dbh, $query);
949 qq|DELETE FROM invoice WHERE trans_id = ?|,
950 qq|DELETE FROM ap WHERE id = ?|,
953 map { do_query($form, $dbh, $_, @values) } @queries;
955 }) or do { die SL::DB->client->error };
960 sub retrieve_invoice {
961 $main::lxdebug->enter_sub();
963 my ($self, $myconfig, $form) = @_;
965 # connect to database
966 my $dbh = SL::DB->client->dbh;
968 my ($query, $sth, $ref, $q_invdate);
971 $q_invdate = qq|, COALESCE((SELECT transdate FROM ar WHERE id = (SELECT MAX(id) FROM ar)), current_date) AS invdate|;
972 if ($form->{vendor_id}) {
973 my $vendor_id = $dbh->quote($form->{vendor_id} * 1);
975 qq|, COALESCE((SELECT transdate FROM ar WHERE id = (SELECT MAX(id) FROM ar)), current_date) +
976 COALESCE((SELECT pt.terms_netto
978 LEFT JOIN payment_terms pt ON (v.payment_id = pt.id)
979 WHERE v.id = $vendor_id),
984 # get default accounts and last invoice number
987 (SELECT c.accno FROM chart c WHERE d.inventory_accno_id = c.id) AS inventory_accno,
988 (SELECT c.accno FROM chart c WHERE d.income_accno_id = c.id) AS income_accno,
989 (SELECT c.accno FROM chart c WHERE d.expense_accno_id = c.id) AS expense_accno,
990 (SELECT c.accno FROM chart c WHERE d.fxgain_accno_id = c.id) AS fxgain_accno,
991 (SELECT c.accno FROM chart c WHERE d.fxloss_accno_id = c.id) AS fxloss_accno
994 $ref = selectfirst_hashref_query($form, $dbh, $query);
995 map { $form->{$_} = $ref->{$_} } keys %$ref;
998 $main::lxdebug->leave_sub();
1004 $query = qq|SELECT cp_id, invnumber, transdate AS invdate, duedate,
1005 orddate, quodate, deliverydate, tax_point, globalproject_id,
1006 ordnumber, quonumber, paid, taxincluded, notes, taxzone_id, storno, gldate,
1008 intnotes, (SELECT cu.name FROM currencies cu WHERE cu.id=ap.currency_id) AS currency, direct_debit,
1009 payment_id, delivery_term_id, transaction_description
1012 $ref = selectfirst_hashref_query($form, $dbh, $query, conv_i($form->{id}));
1013 map { $form->{$_} = $ref->{$_} } keys %$ref;
1014 $form->{mtime} = $form->{itime} if !$form->{mtime};
1015 $form->{lastmtime} = $form->{mtime};
1017 $form->{exchangerate} = $form->get_exchangerate($dbh, $form->{currency}, $form->{invdate}, "sell");
1020 $query = qq|SELECT * FROM shipto WHERE (trans_id = ?) AND (module = 'AP')|;
1021 $ref = selectfirst_hashref_query($form, $dbh, $query, conv_i($form->{id}));
1023 map { $form->{$_} = $ref->{$_} } keys %$ref;
1025 my $transdate = $form->{tax_point} ? $dbh->quote($form->{tax_point}) :$form->{invdate} ? $dbh->quote($form->{invdate}) : "current_date";
1027 my $taxzone_id = $form->{taxzone_id} * 1;
1028 $taxzone_id = SL::DB::Manager::TaxZone->get_default->id unless SL::DB::Manager::TaxZone->find_by(id => $taxzone_id);
1030 # retrieve individual items
1033 c1.accno AS inventory_accno, c1.new_chart_id AS inventory_new_chart, date($transdate) - c1.valid_from AS inventory_valid,
1034 c2.accno AS income_accno, c2.new_chart_id AS income_new_chart, date($transdate) - c2.valid_from AS income_valid,
1035 c3.accno AS expense_accno, c3.new_chart_id AS expense_new_chart, date($transdate) - c3.valid_from AS expense_valid,
1038 i.description, i.longdescription, i.qty, i.fxsellprice AS sellprice, i.parts_id AS id, i.unit, i.deliverydate, i.project_id, i.serialnumber,
1039 i.price_factor_id, i.price_factor, i.marge_price_factor, i.discount, i.active_price_source, i.active_discount_source,
1040 p.partnumber, p.part_type, pr.projectnumber, pg.partsgroup
1041 ,p.classification_id
1044 JOIN parts p ON (i.parts_id = p.id)
1045 LEFT JOIN chart c1 ON ((SELECT inventory_accno_id FROM buchungsgruppen WHERE id = p.buchungsgruppen_id) = c1.id)
1046 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)
1047 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)
1048 LEFT JOIN project pr ON (i.project_id = pr.id)
1049 LEFT JOIN partsgroup pg ON (pg.id = p.partsgroup_id)
1051 WHERE i.trans_id = ?
1053 ORDER BY i.position|;
1054 $sth = prepare_execute_query($form, $dbh, $query, conv_i($form->{id}));
1056 while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
1057 # Retrieve custom variables.
1058 my $cvars = CVar->get_custom_variables(dbh => $dbh,
1060 sub_module => 'invoice',
1061 trans_id => $ref->{invoice_id},
1063 map { $ref->{"ic_cvar_$_->{name}"} = $_->{value} } @{ $cvars };
1065 map({ delete($ref->{$_}); } qw(inventory_accno inventory_new_chart inventory_valid)) if !$ref->{"part_type"} eq 'part';
1067 foreach my $type (qw(inventory income expense)) {
1068 while ($ref->{"${type}_new_chart"} && ($ref->{"${type}_valid"} >=0)) {
1069 my $query = qq|SELECT accno, new_chart_id, date($transdate) - valid_from FROM chart WHERE id = ?|;
1070 @$ref{ map $type.$_, qw(_accno _new_chart _valid) } = selectrow_query($form, $dbh, $query, $ref->{"${type}_new_chart"});
1074 # get tax rates and description
1075 my $accno_id = ($form->{vc} eq "customer") ? $ref->{income_accno} : $ref->{expense_accno};
1077 qq|SELECT c.accno, t.taxdescription, t.rate, t.id as tax_id,
1078 c.accno as taxnumber -- taxnumber is same as accno, but still accessed as taxnumber in code
1080 LEFT JOIN chart c ON (c.id = t.chart_id)
1082 (SELECT tk.tax_id FROM taxkeys tk
1083 WHERE tk.chart_id = (SELECT id FROM chart WHERE accno = ?)
1084 AND (startdate <= $transdate)
1085 ORDER BY startdate DESC
1088 my $stw = prepare_execute_query($form, $dbh, $query, $accno_id);
1089 $ref->{taxaccounts} = "";
1092 while (my $ptr = $stw->fetchrow_hashref("NAME_lc")) {
1093 if (($ptr->{accno} eq "") && ($ptr->{rate} == 0)) {
1098 $ref->{taxaccounts} .= "$ptr->{accno} ";
1100 if (!($form->{taxaccounts} =~ /\Q$ptr->{accno}\E/)) {
1101 $form->{"$ptr->{accno}_rate"} = $ptr->{rate};
1102 $form->{"$ptr->{accno}_description"} = $ptr->{taxdescription};
1103 $form->{"$ptr->{accno}_taxnumber"} = $ptr->{taxnumber};
1104 $form->{"$ptr->{accno}_tax_id"} = $ptr->{tax_id};
1105 $form->{taxaccounts} .= "$ptr->{accno} ";
1110 chop $ref->{taxaccounts};
1111 push @{ $form->{invoice_details} }, $ref;
1116 Common::webdav_folder($form);
1118 $main::lxdebug->leave_sub();
1122 $main::lxdebug->enter_sub();
1124 my ($self, $myconfig, $form, $params) = @_;
1126 $params = $form unless defined $params && ref $params eq "HASH";
1128 # connect to database
1129 my $dbh = SL::DB->client->dbh;
1131 my $dateformat = $myconfig->{dateformat};
1132 $dateformat .= "yy" if $myconfig->{dateformat} !~ /^y/;
1134 my $vid = conv_i($params->{vendor_id});
1135 my $vnr = conv_i($params->{vendornumber});
1138 ($params->{invdate})
1139 ? "to_date(" . $dbh->quote($params->{invdate}) . ", '$dateformat')"
1146 $where .= 'AND v.id = ?';
1150 $where .= 'AND v.vendornumber = ?';
1155 v.id AS vendor_id, v.name AS vendor, v.discount as vendor_discount,
1156 v.creditlimit, v.notes AS intnotes,
1157 v.email, v.cc, v.bcc, v.language_id, v.payment_id, v.delivery_term_id,
1158 v.street, v.zipcode, v.city, v.country, v.taxzone_id, cu.name AS curr, v.direct_debit,
1159 $duedate + COALESCE(pt.terms_netto, 0) AS duedate,
1160 b.discount AS tradediscount, b.description AS business
1162 LEFT JOIN business b ON (b.id = v.business_id)
1163 LEFT JOIN payment_terms pt ON (v.payment_id = pt.id)
1164 LEFT JOIN currencies cu ON (v.currency_id = cu.id)
1166 my $ref = selectfirst_hashref_query($form, $dbh, $query, @values);
1167 map { $params->{$_} = $ref->{$_} } keys %$ref;
1169 # use vendor currency
1170 $form->{currency} = $form->{curr};
1172 $params->{creditremaining} = $params->{creditlimit};
1174 $query = qq|SELECT SUM(amount - paid) FROM ap WHERE vendor_id = ?|;
1175 my ($unpaid_invoices) = selectfirst_array_query($form, $dbh, $query, $vid);
1176 $params->{creditremaining} -= $unpaid_invoices;
1178 $query = qq|SELECT o.amount,
1181 WHERE (e.currency_id = o.currency_id)
1182 AND (e.transdate = o.transdate)) AS exch
1184 WHERE (o.vendor_id = ?) AND (o.quotation = '0') AND (o.closed = '0')|;
1185 my $sth = prepare_execute_query($form, $dbh, $query, $vid);
1186 while (my ($amount, $exch) = $sth->fetchrow_array()) {
1187 $exch = 1 unless $exch;
1188 $params->{creditremaining} -= $amount * $exch;
1192 $main::lxdebug->leave_sub();
1196 $main::lxdebug->enter_sub();
1198 my ($self, $myconfig, $form) = @_;
1200 my $dbh = SL::DB->client->dbh;
1202 my $i = $form->{rowcount};
1204 # don't include assemblies or obsolete parts
1205 my $where = "NOT p.part_type = 'assembly' AND NOT p.obsolete = '1'";
1208 foreach my $table_column (qw(p.partnumber p.description pg.partsgroup)) {
1209 my $field = (split m{\.}, $table_column)[1];
1210 next unless $form->{"${field}_${i}"};
1211 $where .= " AND lower(${table_column}) LIKE lower(?)";
1212 push @values, like($form->{"${field}_${i}"});
1216 if ($form->{"partnumber_$i"} && !$form->{"description_$i"}) {
1217 $where .= qq| OR (NOT p.obsolete = '1' AND p.ean = ? )|;
1218 push @values, $form->{"partnumber_$i"};
1220 # also search hits in makemodels, but only cache the results by id and merge later
1222 SELECT parts_id, model FROM makemodel
1223 LEFT JOIN parts ON parts.id = parts_id
1224 WHERE NOT parts.obsolete AND model ILIKE ? AND (make IS NULL OR make = ?);
1226 my $mm_results = selectall_hashref_query($::form, $dbh, $mm_query, like($form->{"partnumber_$i"}), $::form->{vendor_id});
1227 my @mm_ids = map { $_->{parts_id} } @$mm_results;
1228 push @{$mm_by_id{ $_->{parts_id} } ||= []}, $_ for @$mm_results;
1231 $where .= qq| OR p.id IN (| . join(',', ('?') x @mm_ids) . qq|)|;
1232 push @values, @mm_ids;
1236 # Search for part ID overrides all other criteria.
1237 if ($form->{"id_${i}"}) {
1238 $where = qq|p.id = ?|;
1239 @values = ($form->{"id_${i}"});
1242 if ($form->{"description_$i"}) {
1243 $where .= " ORDER BY p.description";
1245 $where .= " ORDER BY p.partnumber";
1249 if ($form->{type} eq "invoice") {
1250 $transdate = $form->{deliverydate} ? $dbh->quote($form->{deliverydate})
1251 : $form->{invdate} ? $dbh->quote($form->{invdate})
1254 $transdate = $form->{transdate} ? $dbh->quote($form->{transdate}) : "current_date";
1257 my $taxzone_id = $form->{taxzone_id} * 1;
1258 $taxzone_id = SL::DB::Manager::TaxZone->get_default->id unless SL::DB::Manager::TaxZone->find_by(id => $taxzone_id);
1262 p.id, p.partnumber, p.description, p.lastcost AS sellprice, p.listprice,
1263 p.unit, p.part_type, p.onhand, p.formel,
1264 p.notes AS partnotes, p.notes AS longdescription, p.not_discountable,
1267 p.classification_id,
1269 pfac.factor AS price_factor,
1271 c1.accno AS inventory_accno,
1272 c1.new_chart_id AS inventory_new_chart,
1273 date($transdate) - c1.valid_from AS inventory_valid,
1275 c2.accno AS income_accno,
1276 c2.new_chart_id AS income_new_chart,
1277 date($transdate) - c2.valid_from AS income_valid,
1279 c3.accno AS expense_accno,
1280 c3.new_chart_id AS expense_new_chart,
1281 date($transdate) - c3.valid_from AS expense_valid,
1283 pt.used_for_purchase AS used_for_purchase,
1287 LEFT JOIN chart c1 ON
1288 ((SELECT inventory_accno_id
1289 FROM buchungsgruppen
1290 WHERE id = p.buchungsgruppen_id) = c1.id)
1291 LEFT JOIN chart c2 ON
1292 ((SELECT tc.income_accno_id
1293 FROM taxzone_charts tc
1294 WHERE tc.taxzone_id = '$taxzone_id' and tc.buchungsgruppen_id = p.buchungsgruppen_id) = c2.id)
1295 LEFT JOIN chart c3 ON
1296 ((SELECT tc.expense_accno_id
1297 FROM taxzone_charts tc
1298 WHERE tc.taxzone_id = '$taxzone_id' and tc.buchungsgruppen_id = p.buchungsgruppen_id) = c3.id)
1299 LEFT JOIN partsgroup pg ON (pg.id = p.partsgroup_id)
1300 LEFT JOIN part_classifications pt ON (pt.id = p.classification_id)
1301 LEFT JOIN price_factors pfac ON (pfac.id = p.price_factor_id)
1303 my $sth = prepare_execute_query($form, $dbh, $query, @values);
1305 my @translation_queries = ( [ qq|SELECT tr.translation, tr.longdescription
1307 WHERE tr.language_id = ? AND tr.parts_id = ?| ],
1308 [ qq|SELECT tr.translation, tr.longdescription
1310 WHERE tr.language_id IN
1313 WHERE article_code = (SELECT article_code FROM language WHERE id = ?))
1316 map { push @{ $_ }, prepare_query($form, $dbh, $_->[0]) } @translation_queries;
1318 $form->{item_list} = [];
1319 my $has_wrong_pclass = PCLASS_OK;
1320 while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
1322 if ($mm_by_id{$ref->{id}}) {
1323 $ref->{makemodels} = $mm_by_id{$ref->{id}};
1324 push @{ $ref->{matches} ||= [] }, $::locale->text('Model') . ': ' . join ', ', map { $_->{model} } @{ $mm_by_id{$ref->{id}} };
1327 if (($::form->{"partnumber_$i"} ne '') && ($ref->{ean} eq $::form->{"partnumber_$i"})) {
1328 push @{ $ref->{matches} ||= [] }, $::locale->text('EAN') . ': ' . $ref->{ean};
1330 $ref->{type_and_classific} = type_abbreviation($ref->{part_type}) .
1331 classification_abbreviation($ref->{classification_id});
1333 if (! $ref->{used_for_purchase} ) {
1334 $has_wrong_pclass = PCLASS_NOTFORPURCHASE;
1337 # In der Buchungsgruppe ist immer ein Bestandskonto verknuepft, auch wenn
1338 # es sich um eine Dienstleistung handelt. Bei Dienstleistungen muss das
1339 # Buchungskonto also aus dem Ergebnis rausgenommen werden.
1340 if (!$ref->{inventory_accno_id}) {
1341 map({ delete($ref->{"inventory_${_}"}); } qw(accno new_chart valid));
1343 delete($ref->{inventory_accno_id});
1345 # get tax rates and description
1346 my $accno_id = ($form->{vc} eq "customer") ? $ref->{income_accno} : $ref->{expense_accno};
1348 qq|SELECT c.accno, t.taxdescription, t.rate, c.accno as taxnumber, t.id as tax_id
1350 LEFT JOIN chart c on (c.id = t.chart_id)
1358 AND (startdate <= $transdate)
1359 ORDER BY startdate DESC
1362 my $stw = prepare_execute_query($form, $dbh, $query, $accno_id);
1364 $ref->{taxaccounts} = "";
1366 while (my $ptr = $stw->fetchrow_hashref("NAME_lc")) {
1368 if (($ptr->{accno} eq "") && ($ptr->{rate} == 0)) {
1373 $ref->{taxaccounts} .= "$ptr->{accno} ";
1375 if (!($form->{taxaccounts} =~ /\Q$ptr->{accno}\E/)) {
1376 $form->{"$ptr->{accno}_rate"} = $ptr->{rate};
1377 $form->{"$ptr->{accno}_description"} = $ptr->{taxdescription};
1378 $form->{"$ptr->{accno}_taxnumber"} = $ptr->{taxnumber};
1379 $form->{"$ptr->{accno}_tax_id"} = $ptr->{tax_id};
1380 $form->{taxaccounts} .= "$ptr->{accno} ";
1383 if ($form->{language_id}) {
1384 for my $spec (@translation_queries) {
1385 do_statement($form, $spec->[1], $spec->[0], conv_i($form->{language_id}), conv_i($ref->{id}));
1386 my ($translation, $longdescription) = $spec->[1]->fetchrow_array;
1387 next unless $translation;
1388 $ref->{description} = $translation;
1389 $ref->{longdescription} = $longdescription;
1396 chop $ref->{taxaccounts};
1398 $ref->{onhand} *= 1;
1399 push @{ $form->{item_list} }, $ref;
1404 $_->[1]->finish for @translation_queries;
1406 $form->{is_wrong_pclass} = $has_wrong_pclass;
1407 $form->{NOTFORSALE} = PCLASS_NOTFORSALE;
1408 $form->{NOTFORPURCHASE} = PCLASS_NOTFORPURCHASE;
1409 foreach my $item (@{ $form->{item_list} }) {
1410 my $custom_variables = CVar->get_custom_variables(module => 'IC',
1411 trans_id => $item->{id},
1414 $form->{is_wrong_pclass} = PCLASS_OK; # one correct type
1415 map { $item->{"ic_cvar_" . $_->{name} } = $_->{value} } @{ $custom_variables };
1418 $main::lxdebug->leave_sub();
1421 sub vendor_details {
1422 $main::lxdebug->enter_sub();
1424 my ($self, $myconfig, $form, @wanted_vars) = @_;
1426 my $dbh = SL::DB->client->dbh;
1430 # get contact id, set it if nessessary
1431 $form->{cp_id} *= 1;
1433 if ($form->{cp_id}) {
1434 $contact = "AND cp.cp_id = ?";
1435 push @values, $form->{cp_id};
1438 # get rest for the vendor
1439 # fax and phone and email as vendor*
1441 qq|SELECT ct.*, cp.*, ct.notes as vendornotes, phone as vendorphone, fax as vendorfax, email as vendoremail,
1444 LEFT JOIN contacts cp ON (ct.id = cp.cp_cv_id)
1445 LEFT JOIN currencies cu ON (ct.currency_id = cu.id)
1446 WHERE (ct.id = ?) $contact
1449 my $ref = selectfirst_hashref_query($form, $dbh, $query, $form->{vendor_id}, @values);
1451 # remove id,notes (double of vendornotes) and taxincluded before copy back
1452 delete @$ref{qw(id taxincluded notes)};
1454 @wanted_vars = grep({ $_ } @wanted_vars);
1455 if (scalar(@wanted_vars) > 0) {
1457 map({ $h_wanted_vars{$_} = 1; } @wanted_vars);
1458 map({ delete($ref->{$_}) unless ($h_wanted_vars{$_}); } keys(%{$ref}));
1461 map { $form->{$_} = $ref->{$_} } keys %$ref;
1463 my $custom_variables = CVar->get_custom_variables('dbh' => $dbh,
1465 'trans_id' => $form->{vendor_id});
1466 map { $form->{"vc_cvar_$_->{name}"} = $_->{value} } @{ $custom_variables };
1468 if ($form->{cp_id}) {
1469 $custom_variables = CVar->get_custom_variables(dbh => $dbh,
1470 module => 'Contacts',
1471 trans_id => $form->{cp_id});
1472 $form->{"cp_cvar_$_->{name}"} = $_->{value} for @{ $custom_variables };
1475 $form->{cp_greeting} = GenericTranslations->get('dbh' => $dbh,
1476 'translation_type' => 'greetings::' . ($form->{cp_gender} eq 'f' ? 'female' : 'male'),
1477 'allow_fallback' => 1);
1479 $main::lxdebug->leave_sub();
1483 $main::lxdebug->enter_sub();
1485 my ($self, $myconfig, $form) = @_;
1487 my $dbh = SL::DB->client->dbh;
1490 qq|SELECT accno, description, link
1492 WHERE link LIKE '%IC%'
1494 my $sth = prepare_execute_query($query, $dbh, $query);
1496 while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
1497 foreach my $key (split(/:/, $ref->{link})) {
1499 push @{ $form->{IC_links}{$key} },
1500 { accno => $ref->{accno},
1501 description => $ref->{description} };
1507 $main::lxdebug->leave_sub();
1510 sub _delete_payments {
1511 $main::lxdebug->enter_sub();
1513 my ($self, $form, $dbh) = @_;
1515 my @delete_acc_trans_ids;
1517 # Delete old payment entries from acc_trans.
1519 qq|SELECT acc_trans_id
1521 WHERE (trans_id = ?) AND fx_transaction
1525 SELECT at.acc_trans_id
1527 LEFT JOIN chart c ON (at.chart_id = c.id)
1528 WHERE (trans_id = ?) AND (c.link LIKE '%AP_paid%')|;
1529 push @delete_acc_trans_ids, selectall_array_query($form, $dbh, $query, conv_i($form->{id}), conv_i($form->{id}));
1532 qq|SELECT at.acc_trans_id
1534 LEFT JOIN chart c ON (at.chart_id = c.id)
1535 WHERE (trans_id = ?)
1536 AND ((c.link = 'AP') OR (c.link LIKE '%:AP') OR (c.link LIKE 'AP:%'))
1537 ORDER BY at.acc_trans_id
1539 push @delete_acc_trans_ids, selectall_array_query($form, $dbh, $query, conv_i($form->{id}));
1541 if (@delete_acc_trans_ids) {
1542 $query = qq|DELETE FROM acc_trans WHERE acc_trans_id IN (| . join(", ", @delete_acc_trans_ids) . qq|)|;
1543 do_query($form, $dbh, $query);
1546 $main::lxdebug->leave_sub();
1550 my ($self, $myconfig, $form, $locale) = @_;
1551 $main::lxdebug->enter_sub();
1553 my $rc = SL::DB->client->with_transaction(\&_post_payment, $self, $myconfig, $form, $locale);
1555 $::lxdebug->leave_sub;
1560 my ($self, $myconfig, $form, $locale) = @_;
1562 my $dbh = SL::DB->client->dbh;
1564 my (%payments, $old_form, $row, $item, $query, %keep_vars);
1566 $old_form = save_form();
1569 SELECT at.acc_trans_id, at.amount, at.cleared, c.accno
1571 LEFT JOIN chart c ON (at.chart_id = c.id)
1572 WHERE (at.trans_id = ?)
1575 my %already_cleared = selectall_as_map($form, $dbh, $query, 'acc_trans_id', [ qw(amount cleared accno) ], $form->{id});
1577 # Delete all entries in acc_trans from prior payments.
1578 if (SL::DB::Default->get->payments_changeable != 0) {
1579 $self->_delete_payments($form, $dbh);
1582 # Save the new payments the user made before cleaning up $form.
1583 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 };
1585 # Clean up $form so that old content won't tamper the results.
1586 %keep_vars = map { $_, 1 } qw(login password id);
1587 map { delete $form->{$_} unless $keep_vars{$_} } keys %{ $form };
1589 # Retrieve the invoice from the database.
1590 $self->retrieve_invoice($myconfig, $form);
1592 # Set up the content of $form in the way that IR::post_invoice() expects.
1593 $form->{exchangerate} = $form->format_amount($myconfig, $form->{exchangerate});
1595 for $row (1 .. scalar @{ $form->{invoice_details} }) {
1596 $item = $form->{invoice_details}->[$row - 1];
1598 map { $item->{$_} = $form->format_amount($myconfig, $item->{$_}) } qw(qty sellprice);
1600 map { $form->{"${_}_${row}"} = $item->{$_} } keys %{ $item };
1603 $form->{rowcount} = scalar @{ $form->{invoice_details} };
1605 delete @{$form}{qw(invoice_details paidaccounts storno paid)};
1607 # Restore the payment options from the user input.
1608 map { $form->{$_} = $payments{$_} } keys %payments;
1610 # Get the AP accno (which is normally done by Form::create_links()).
1614 LEFT JOIN chart c ON (at.chart_id = c.id)
1615 WHERE (trans_id = ?)
1616 AND ((c.link = 'AP') OR (c.link LIKE '%:AP') OR (c.link LIKE 'AP:%'))
1617 ORDER BY at.acc_trans_id
1620 ($form->{AP}) = selectfirst_array_query($form, $dbh, $query, conv_i($form->{id}));
1622 # Post the new payments.
1623 $self->post_invoice($myconfig, $form, $dbh, payments_only => 1, already_cleared => \%already_cleared);
1625 restore_form($old_form);
1631 $::lxdebug->enter_sub;
1633 my ($self, %params) = @_;
1635 if (!$params{vendor_id} || !$params{invdate}) {
1636 $::lxdebug->leave_sub;
1637 return $params{default};
1640 my $dbh = $::form->get_standard_dbh;
1641 my $query = qq|SELECT ?::date + pt.terms_netto
1643 LEFT JOIN payment_terms pt ON (pt.id = v.payment_id)
1646 my ($duedate) = selectfirst_array_query($::form, $dbh, $query, $params{invdate}, $params{vendor_id});
1648 $duedate ||= $params{default};
1650 $::lxdebug->leave_sub;