1 #=====================================================================
4 # Based on SQL-Ledger Version 2.1.9
5 # Web http://www.lx-office.org
7 #=====================================================================
8 # SQL-Ledger Accounting
11 # Author: Dieter Simader
12 # Email: dsimader@sql-ledger.org
13 # Web: http://www.sql-ledger.org
17 # This program is free software; you can redistribute it and/or modify
18 # it under the terms of the GNU General Public License as published by
19 # the Free Software Foundation; either version 2 of the License, or
20 # (at your option) any later version.
22 # This program is distributed in the hope that it will be useful,
23 # but WITHOUT ANY WARRANTY; without even the implied warranty of
24 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
25 # GNU General Public License for more details.
26 # You should have received a copy of the GNU General Public License
27 # along with this program; if not, write to the Free Software
28 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
30 #======================================================================
32 # Inventory received module
34 #======================================================================
42 use SL::DATEV qw(:CONSTANTS);
46 use SL::GenericTranslations;
47 use SL::HTML::Restrict;
53 use List::Util qw(min);
56 use constant PCLASS_OK => 0;
57 use constant PCLASS_NOTFORSALE => 1;
58 use constant PCLASS_NOTFORPURCHASE => 2;
61 my ($self, $myconfig, $form, $provided_dbh, $payments_only) = @_;
62 $main::lxdebug->enter_sub();
64 my $rc = SL::DB->client->with_transaction(\&_post_invoice, $self, $myconfig, $form, $provided_dbh, $payments_only);
66 $::lxdebug->leave_sub;
71 my ($self, $myconfig, $form, $provided_dbh, $payments_only) = @_;
73 my $dbh = $provided_dbh || SL::DB->client->dbh;
74 my $restricter = SL::HTML::Restrict->create;
76 $form->{defaultcurrency} = $form->get_default_currency($myconfig);
77 my $defaultcurrency = $form->{defaultcurrency};
79 my $ic_cvar_configs = CVar->get_configs(module => 'IC',
82 my ($query, $sth, @values, $project_id);
83 my ($allocated, $taxrate, $taxamount, $taxdiff, $item);
84 my ($amount, $linetotal, $lastinventoryaccno, $lastexpenseaccno);
85 my ($netamount, $invoicediff, $expensediff) = (0, 0, 0);
87 my ($basefactor, $baseqty, @taxaccounts, $totaltax);
89 my $all_units = AM->retrieve_units($myconfig, $form);
92 if (!$payments_only) {
94 &reverse_invoice($dbh, $form);
96 ($form->{id}) = selectrow_query($form, $dbh, qq|SELECT nextval('glid')|);
97 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});
101 if ($form->{currency} eq $defaultcurrency) {
102 $form->{exchangerate} = 1;
104 $exchangerate = $form->check_exchangerate($myconfig, $form->{currency}, $form->{invdate}, 'sell');
107 $form->{exchangerate} = $exchangerate || $form->parse_amount($myconfig, $form->{exchangerate});
108 $form->{exchangerate} = 1 unless ($form->{exchangerate} * 1);
111 my $q_item_unit = qq|SELECT unit FROM parts WHERE id = ?|;
112 my $h_item_unit = prepare_query($form, $dbh, $q_item_unit);
114 $form->get_lists('price_factors' => 'ALL_PRICE_FACTORS');
115 my %price_factors = map { $_->{id} => $_->{factor} } @{ $form->{ALL_PRICE_FACTORS} };
118 my @processed_invoice_ids;
119 for my $i (1 .. $form->{rowcount}) {
120 next unless $form->{"id_$i"};
124 $form->{"qty_$i"} = $form->parse_amount($myconfig, $form->{"qty_$i"});
125 $form->{"qty_$i"} *= -1 if $form->{storno};
127 if ( $::instance_conf->get_inventory_system eq 'periodic') {
128 # inventory account number is overwritten with expense account number, so
129 # never book incoming to inventory account but always to expense account
130 $form->{"inventory_accno_$i"} = $form->{"expense_accno_$i"}
134 if (!$item_units{$form->{"id_$i"}}) {
135 do_statement($form, $h_item_unit, $q_item_unit, $form->{"id_$i"});
136 ($item_units{$form->{"id_$i"}}) = $h_item_unit->fetchrow_array();
139 my $item_unit = $item_units{$form->{"id_$i"}};
141 if (defined($all_units->{$item_unit}->{factor})
142 && ($all_units->{$item_unit}->{factor} ne '')
143 && ($all_units->{$item_unit}->{factor} * 1 != 0)) {
144 $basefactor = $all_units->{$form->{"unit_$i"}}->{factor} / $all_units->{$item_unit}->{factor};
148 $baseqty = $form->{"qty_$i"} * $basefactor;
150 @taxaccounts = split / /, $form->{"taxaccounts_$i"};
155 $form->{"sellprice_$i"} = $form->parse_amount($myconfig, $form->{"sellprice_$i"});
156 (my $fxsellprice = $form->{"sellprice_$i"}) =~ /\.(\d+)/;
158 my $decimalplaces = ($dec > 2) ? $dec : 2;
160 map { $taxrate += $form->{"${_}_rate"} } @taxaccounts;
162 $price_factor = $price_factors{ $form->{"price_factor_id_$i"} } || 1;
163 # copied from IS.pm, with some changes (no decimalplaces corrections here etc)
164 # TODO maybe use PriceTaxCalculation or something like this for backends (IR.pm / IS.pm)
166 # undo discount formatting
167 $form->{"discount_$i"} = $form->parse_amount($myconfig, $form->{"discount_$i"}) / 100;
169 $form->{"sellprice_$i"} = $fxsellprice * (1 - $form->{"discount_$i"});
171 ######################################################################
172 if ($form->{"inventory_accno_$i"}) {
174 $linetotal = $form->round_amount($form->{"sellprice_$i"} * $form->{"qty_$i"} / $price_factor, 2);
176 if ($form->{taxincluded}) {
178 $taxamount = $linetotal * ($taxrate / (1 + $taxrate));
179 $form->{"sellprice_$i"} = $form->{"sellprice_$i"} * (1 / (1 + $taxrate));
182 $taxamount = $linetotal * $taxrate;
185 $netamount += $linetotal;
187 if ($form->round_amount($taxrate, 7) == 0) {
188 if ($form->{taxincluded}) {
189 foreach $item (@taxaccounts) {
191 $form->round_amount($linetotal * $form->{"${item}_rate"} / (1 + abs($form->{"${item}_rate"})), 2);
192 $taxdiff += $taxamount;
193 $form->{amount}{ $form->{id} }{$item} -= $taxamount;
195 $form->{amount}{ $form->{id} }{ $taxaccounts[0] } += $taxdiff;
198 map { $form->{amount}{ $form->{id} }{$_} -= $linetotal * $form->{"${_}_rate"} } @taxaccounts;
202 map { $form->{amount}{ $form->{id} }{$_} -= $taxamount * $form->{"${_}_rate"} / $taxrate } @taxaccounts;
205 # add purchase to inventory, this one is without the tax!
206 $amount = $form->{"sellprice_$i"} * $form->{"qty_$i"} * $form->{exchangerate} / $price_factor;
207 $linetotal = $form->round_amount($form->{"sellprice_$i"} * $form->{"qty_$i"} / $price_factor, 2) * $form->{exchangerate};
208 $linetotal = $form->round_amount($linetotal, 2);
210 # this is the difference for the inventory
211 $invoicediff += ($amount - $linetotal);
213 $form->{amount}{ $form->{id} }{ $form->{"inventory_accno_$i"} } -= $linetotal;
215 # adjust and round sellprice
216 $form->{"sellprice_$i"} = $form->round_amount($form->{"sellprice_$i"} * $form->{exchangerate}, $decimalplaces);
218 $lastinventoryaccno = $form->{"inventory_accno_$i"};
220 next if $payments_only;
222 # update parts table by setting lastcost to current price, don't allow negative values by using abs
223 $query = qq|UPDATE parts SET lastcost = ? WHERE id = ?|;
224 @values = (abs($fxsellprice * $form->{exchangerate} / $basefactor), conv_i($form->{"id_$i"}));
225 do_query($form, $dbh, $query, @values);
227 # check if we sold the item already and
228 # make an entry for the expense and inventory
229 my $taxzone = $form->{taxzone_id} * 1;
231 qq|SELECT i.id, i.qty, i.allocated, i.trans_id, i.base_qty,
232 bg.inventory_accno_id, tc.expense_accno_id AS expense_accno_id, a.transdate
233 FROM invoice i, ar a, parts p, buchungsgruppen bg, taxzone_charts tc
234 WHERE (i.parts_id = p.id)
236 AND ((i.base_qty + i.allocated) > 0)
237 AND (i.trans_id = a.id)
238 AND (p.buchungsgruppen_id = bg.id)
239 AND (tc.buchungsgruppen_id = p.buchungsgruppen_id)
240 AND (tc.taxzone_id = ${taxzone})
242 # ORDER BY transdate guarantees FIFO
244 # sold two items without having bought them yet, example result of query:
245 # id | qty | allocated | trans_id | inventory_accno_id | expense_accno_id | transdate
246 # ---+-----+-----------+----------+--------------------+------------------+------------
247 # 9 | 2 | 0 | 9 | 15 | 151 | 2011-01-05
249 # base_qty + allocated > 0 if article has already been sold but not bought yet
251 # select qty,allocated,base_qty,sellprice from invoice where trans_id = 9;
252 # qty | allocated | base_qty | sellprice
253 # -----+-----------+----------+------------
254 # 2 | 0 | 2 | 1000.00000
256 $sth = prepare_execute_query($form, $dbh, $query, conv_i($form->{"id_$i"}));
258 my $totalqty = $baseqty;
260 while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
261 my $qty = min $totalqty, ($ref->{base_qty} + $ref->{allocated});
262 $linetotal = $form->round_amount(($form->{"sellprice_$i"} * $qty) / $basefactor, 2);
264 if ( $::instance_conf->get_inventory_system eq 'perpetual' ) {
265 # Warenbestandsbuchungen nur bei Bestandsmethode
267 if ($ref->{allocated} < 0) {
269 # we have an entry for it already, adjust amount
270 $form->update_balance($dbh, "acc_trans", "amount",
271 qq| (trans_id = $ref->{trans_id})
272 AND (chart_id = $ref->{inventory_accno_id})
273 AND (transdate = '$ref->{transdate}')|,
276 $form->update_balance($dbh, "acc_trans", "amount",
277 qq| (trans_id = $ref->{trans_id})
278 AND (chart_id = $ref->{expense_accno_id})
279 AND (transdate = '$ref->{transdate}')|,
282 } elsif ($linetotal != 0) {
285 # add entry for inventory, this one is for the sold item
286 $query = qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate, taxkey, tax_id, chart_link) VALUES (?, ?, ?, ?,
291 ORDER BY startdate DESC LIMIT 1),
296 ORDER BY startdate DESC LIMIT 1),
297 (SELECT link FROM chart WHERE id = ?))|;
298 @values = ($ref->{trans_id}, $ref->{inventory_accno_id}, $linetotal, $ref->{transdate}, $ref->{inventory_accno_id}, $ref->{transdate}, $ref->{inventory_accno_id}, $ref->{transdate},
299 $ref->{inventory_accno_id});
300 do_query($form, $dbh, $query, @values);
303 $query = qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate, taxkey, tax_id, chart_link) VALUES (?, ?, ?, ?,
308 ORDER BY startdate DESC LIMIT 1),
313 ORDER BY startdate DESC LIMIT 1),
314 (SELECT link FROM chart WHERE id = ?))|;
315 @values = ($ref->{trans_id}, $ref->{expense_accno_id}, ($linetotal * -1), $ref->{transdate}, $ref->{expense_accno_id}, $ref->{transdate}, $ref->{expense_accno_id}, $ref->{transdate},
316 $ref->{expense_accno_id});
317 do_query($form, $dbh, $query, @values);
321 # update allocated for sold item
322 $form->update_balance($dbh, "invoice", "allocated", qq|id = $ref->{id}|, $qty * -1);
326 last if ($totalqty -= $qty) <= 0;
331 } else { # if ($form->{"inventory_accno_id_$i"})
332 # part doesn't have an inventory_accno_id
333 # lastcost of the part is updated at the end
335 $linetotal = $form->round_amount($form->{"sellprice_$i"} * $form->{"qty_$i"} / $price_factor, 2);
337 if ($form->{taxincluded}) {
338 $taxamount = $linetotal * ($taxrate / (1 + $taxrate));
339 $form->{"sellprice_$i"} = $form->{"sellprice_$i"} * (1 / (1 + $taxrate));
342 $taxamount = $linetotal * $taxrate;
345 $netamount += $linetotal;
347 if ($form->round_amount($taxrate, 7) == 0) {
348 if ($form->{taxincluded}) {
349 foreach $item (@taxaccounts) {
350 $taxamount = $linetotal * $form->{"${item}_rate"} / (1 + abs($form->{"${item}_rate"}));
351 $totaltax += $taxamount;
352 $form->{amount}{ $form->{id} }{$item} -= $taxamount;
355 map { $form->{amount}{ $form->{id} }{$_} -= $linetotal * $form->{"${_}_rate"} } @taxaccounts;
358 map { $form->{amount}{ $form->{id} }{$_} -= $taxamount * $form->{"${_}_rate"} / $taxrate } @taxaccounts;
361 $amount = $form->{"sellprice_$i"} * $form->{"qty_$i"} * $form->{exchangerate} / $price_factor;
362 $linetotal = $form->round_amount($form->{"sellprice_$i"} * $form->{"qty_$i"} / $price_factor, 2) * $form->{exchangerate};
363 $linetotal = $form->round_amount($linetotal, 2);
365 # this is the difference for expense
366 $expensediff += ($amount - $linetotal);
368 # add amount to expense
369 $form->{amount}{ $form->{id} }{ $form->{"expense_accno_$i"} } -= $linetotal;
371 $lastexpenseaccno = $form->{"expense_accno_$i"};
373 # adjust and round sellprice
374 $form->{"sellprice_$i"} = $form->round_amount($form->{"sellprice_$i"} * $form->{exchangerate}, $decimalplaces);
376 next if $payments_only;
379 $query = qq|UPDATE parts SET lastcost = ? WHERE id = ?|;
380 do_query($form, $dbh, $query, $form->{"sellprice_$i"} / $basefactor, conv_i($form->{"id_$i"}));
383 next if $payments_only;
385 CVar->get_non_editable_ic_cvars(form => $form,
388 sub_module => 'invoice',
389 may_converted_from => ['delivery_order_items', 'orderitems', 'invoice']);
391 if (!$form->{"invoice_id_$i"}) {
392 # there is no persistent id, therefore create one with all necessary constraints
393 my $q_invoice_id = qq|SELECT nextval('invoiceid')|;
394 my $h_invoice_id = prepare_query($form, $dbh, $q_invoice_id);
395 do_statement($form, $h_invoice_id, $q_invoice_id);
396 $form->{"invoice_id_$i"} = $h_invoice_id->fetchrow_array();
397 my $q_create_invoice_id = qq|INSERT INTO invoice (id, trans_id, position, parts_id) values (?, ?, ?, ?)|;
398 do_query($form, $dbh, $q_create_invoice_id, conv_i($form->{"invoice_id_$i"}),
399 conv_i($form->{id}), conv_i($position), conv_i($form->{"id_$i"}));
400 $h_invoice_id->finish();
403 # save detail record in invoice table
405 UPDATE invoice SET trans_id = ?, position = ?, parts_id = ?, description = ?, longdescription = ?, qty = ?, base_qty = ?,
406 sellprice = ?, fxsellprice = ?, discount = ?, allocated = ?, unit = ?, deliverydate = ?,
407 project_id = ?, serialnumber = ?, price_factor_id = ?,
408 price_factor = (SELECT factor FROM price_factors WHERE id = ?), marge_price_factor = ?,
409 active_price_source = ?, active_discount_source = ?
413 @values = (conv_i($form->{id}), conv_i($position), conv_i($form->{"id_$i"}),
414 $form->{"description_$i"}, $restricter->process($form->{"longdescription_$i"}), $form->{"qty_$i"} * -1,
415 $baseqty * -1, $form->{"sellprice_$i"}, $fxsellprice, $form->{"discount_$i"}, $allocated,
416 $form->{"unit_$i"}, conv_date($form->{deliverydate}),
417 conv_i($form->{"project_id_$i"}), $form->{"serialnumber_$i"},
418 conv_i($form->{"price_factor_id_$i"}), conv_i($form->{"price_factor_id_$i"}), conv_i($form->{"marge_price_factor_$i"}),
419 $form->{"active_price_source_$i"}, $form->{"active_discount_source_$i"},
420 conv_i($form->{"invoice_id_$i"}));
421 do_query($form, $dbh, $query, @values);
422 push @processed_invoice_ids, $form->{"invoice_id_$i"};
424 CVar->save_custom_variables(module => 'IC',
425 sub_module => 'invoice',
426 trans_id => $form->{"invoice_id_$i"},
427 configs => $ic_cvar_configs,
429 name_prefix => 'ic_',
430 name_postfix => "_$i",
433 # link previous items with invoice items See IS.pm (no credit note -> no invoice item)
434 foreach (qw(delivery_order_items orderitems invoice)) {
435 if (!$form->{useasnew} && $form->{"converted_from_${_}_id_$i"}) {
436 RecordLinks->create_links('dbh' => $dbh,
439 'from_ids' => $form->{"converted_from_${_}_id_$i"},
440 'to_table' => 'invoice',
441 'to_id' => $form->{"invoice_id_$i"},
444 delete $form->{"converted_from_${_}_id_$i"};
448 $h_item_unit->finish();
450 $project_id = conv_i($form->{"globalproject_id"});
452 $form->{datepaid} = $form->{invdate};
454 # all amounts are in natural state, netamount includes the taxes
455 # if tax is included, netamount is rounded to 2 decimal places,
459 for my $i (1 .. $form->{paidaccounts}) {
460 $form->{"paid_$i"} = $form->parse_amount($myconfig, $form->{"paid_$i"});
461 $form->{paid} += $form->{"paid_$i"};
462 $form->{datepaid} = $form->{"datepaid_$i"} if $form->{"datepaid_$i"};
465 my ($tax, $paiddiff) = (0, 0);
467 $netamount = $form->round_amount($netamount, 2);
469 # figure out rounding errors for amount paid and total amount
470 if ($form->{taxincluded}) {
472 $amount = $form->round_amount($netamount * $form->{exchangerate}, 2);
473 $paiddiff = $amount - $netamount * $form->{exchangerate};
474 $netamount = $amount;
476 foreach $item (split / /, $form->{taxaccounts}) {
477 $amount = $form->{amount}{ $form->{id} }{$item} * $form->{exchangerate};
478 $form->{amount}{ $form->{id} }{$item} = $form->round_amount($amount, 2);
480 $amount = $form->{amount}{ $form->{id} }{$item} * -1;
482 $netamount -= $amount;
485 $invoicediff += $paiddiff;
486 $expensediff += $paiddiff;
488 ######## this only applies to tax included
490 # in the sales invoice case rounding errors only have to be corrected for
491 # income accounts, it is enough to add the total rounding error to one of
492 # the income accounts, with the one assigned to the last row being used
493 # (lastinventoryaccno)
495 # in the purchase invoice case rounding errors may be split between
496 # inventory accounts and expense accounts. After rounding, an error of 1
497 # cent is introduced if the total rounding error exceeds 0.005. The total
498 # error is made up of $invoicediff and $expensediff, however, so if both
499 # values are below 0.005, but add up to a total >= 0.005, correcting
500 # lastinventoryaccno and lastexpenseaccno separately has no effect after
501 # rounding. This caused bug 1579. Therefore when the combined total exceeds
502 # 0.005, but neither do individually, the account with the larger value
503 # shall receive the total rounding error, and the next time it is rounded
504 # the 1 cent correction will be introduced.
506 $form->{amount}{ $form->{id} }{$lastinventoryaccno} -= $invoicediff if $lastinventoryaccno;
507 $form->{amount}{ $form->{id} }{$lastexpenseaccno} -= $expensediff if $lastexpenseaccno;
509 if ( (abs($expensediff)+abs($invoicediff)) >= 0.005 and abs($expensediff) < 0.005 and abs($invoicediff) < 0.005 ) {
511 # in total the rounding error adds up to 1 cent effectively, correct the
512 # larger of the two numbers
514 if ( abs($form->{amount}{ $form->{id} }{$lastinventoryaccno}) > abs($form->{amount}{ $form->{id} }{$lastexpenseaccno}) ) {
515 # $invoicediff has already been deducted, now also deduct expensediff
516 $form->{amount}{ $form->{id} }{$lastinventoryaccno} -= $expensediff;
518 # expensediff has already been deducted, now also deduct invoicediff
519 $form->{amount}{ $form->{id} }{$lastexpenseaccno} -= $invoicediff;
524 $amount = $form->round_amount($netamount * $form->{exchangerate}, 2);
525 $paiddiff = $amount - $netamount * $form->{exchangerate};
526 $netamount = $amount;
528 foreach my $item (split / /, $form->{taxaccounts}) {
529 $form->{amount}{ $form->{id} }{$item} = $form->round_amount($form->{amount}{ $form->{id} }{$item}, 2);
530 $amount = $form->round_amount( $form->{amount}{ $form->{id} }{$item} * $form->{exchangerate} * -1, 2);
531 $paiddiff += $amount - $form->{amount}{ $form->{id} }{$item} * $form->{exchangerate} * -1;
532 $form->{amount}{ $form->{id} }{$item} = $form->round_amount($amount * -1, 2);
533 $amount = $form->{amount}{ $form->{id} }{$item} * -1;
538 $form->{amount}{ $form->{id} }{ $form->{AP} } = $netamount + $tax;
541 $form->{paid} = $form->round_amount($form->{paid} * $form->{exchangerate} + $paiddiff, 2) if $form->{paid} != 0;
543 # update exchangerate
545 $form->update_exchangerate($dbh, $form->{currency}, $form->{invdate}, 0, $form->{exchangerate})
546 if ($form->{currency} ne $defaultcurrency) && !$exchangerate;
548 # record acc_trans transactions
549 foreach my $trans_id (keys %{ $form->{amount} }) {
550 foreach my $accno (keys %{ $form->{amount}{$trans_id} }) {
551 $form->{amount}{$trans_id}{$accno} = $form->round_amount($form->{amount}{$trans_id}{$accno}, 2);
554 next if $payments_only || !$form->{amount}{$trans_id}{$accno};
556 $query = qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate, taxkey, project_id, tax_id, chart_link)
557 VALUES (?, (SELECT id FROM chart WHERE accno = ?), ?, ?,
560 WHERE chart_id= (SELECT id
564 ORDER BY startdate DESC LIMIT 1),
568 WHERE chart_id= (SELECT id
572 ORDER BY startdate DESC LIMIT 1),
573 (SELECT link FROM chart WHERE accno = ?))|;
574 @values = ($trans_id, $accno, $form->{amount}{$trans_id}{$accno},
575 conv_date($form->{invdate}), $accno, conv_date($form->{invdate}), $project_id, $accno, conv_date($form->{invdate}), $accno);
576 do_query($form, $dbh, $query, @values);
580 # deduct payment differences from paiddiff
581 for my $i (1 .. $form->{paidaccounts}) {
582 if ($form->{"paid_$i"} != 0) {
583 $amount = $form->round_amount($form->{"paid_$i"} * $form->{exchangerate}, 2);
584 $paiddiff -= $amount - $form->{"paid_$i"} * $form->{exchangerate};
588 # force AP entry if 0
590 $form->{amount}{ $form->{id} }{ $form->{AP} } = $form->{paid} if $form->{amount}{$form->{id}}{$form->{AP}} == 0;
592 # record payments and offsetting AP
593 for my $i (1 .. $form->{paidaccounts}) {
594 if ($form->{"acc_trans_id_$i"}
596 && (SL::DB::Default->get->payments_changeable == 0)) {
600 next if $form->{"paid_$i"} == 0;
602 my ($accno) = split /--/, $form->{"AP_paid_$i"};
603 $form->{"datepaid_$i"} = $form->{invdate} unless ($form->{"datepaid_$i"});
604 $form->{datepaid} = $form->{"datepaid_$i"};
606 $amount = $form->round_amount($form->{"paid_$i"} * $form->{exchangerate} + $paiddiff, 2) * -1;
609 if ($form->{amount}{ $form->{id} }{ $form->{AP} } != 0) {
610 $query = qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate, taxkey, project_id, tax_id, chart_link)
611 VALUES (?, (SELECT id FROM chart WHERE accno = ?), ?, ?,
614 WHERE chart_id= (SELECT id
618 ORDER BY startdate DESC LIMIT 1),
622 WHERE chart_id= (SELECT id
626 ORDER BY startdate DESC LIMIT 1),
627 (SELECT link FROM chart WHERE accno = ?))|;
628 @values = (conv_i($form->{id}), $form->{AP}, $amount,
629 $form->{"datepaid_$i"}, $form->{AP}, conv_date($form->{"datepaid_$i"}), $project_id, $form->{AP}, conv_date($form->{"datepaid_$i"}), $form->{AP});
630 do_query($form, $dbh, $query, @values);
634 my $gldate = (conv_date($form->{"gldate_$i"}))? conv_date($form->{"gldate_$i"}) : conv_date($form->current_date($myconfig));
637 qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate, gldate, source, memo, taxkey, project_id, tax_id, chart_link)
638 VALUES (?, (SELECT id FROM chart WHERE accno = ?), ?, ?, ?, ?, ?,
641 WHERE chart_id= (SELECT id
642 FROM chart WHERE accno = ?)
644 ORDER BY startdate DESC LIMIT 1),
648 WHERE chart_id= (SELECT id
649 FROM chart WHERE accno = ?)
651 ORDER BY startdate DESC LIMIT 1),
652 (SELECT link FROM chart WHERE accno = ?))|;
653 @values = (conv_i($form->{id}), $accno, $form->{"paid_$i"}, $form->{"datepaid_$i"},
654 $gldate, $form->{"source_$i"}, $form->{"memo_$i"}, $accno, conv_date($form->{"datepaid_$i"}), $project_id, $accno, conv_date($form->{"datepaid_$i"}), $accno);
655 do_query($form, $dbh, $query, @values);
659 if ($form->{currency} eq $defaultcurrency) {
660 $form->{"exchangerate_$i"} = 1;
662 $exchangerate = $form->check_exchangerate($myconfig, $form->{currency}, $form->{"datepaid_$i"}, 'sell');
663 $form->{"exchangerate_$i"} = $exchangerate || $form->parse_amount($myconfig, $form->{"exchangerate_$i"});
666 # exchangerate difference
667 $form->{fx}{$accno}{ $form->{"datepaid_$i"} } += $form->{"paid_$i"} * ($form->{"exchangerate_$i"} - 1) + $paiddiff;
671 ($form->{"paid_$i"} * $form->{exchangerate}) -
672 ($form->{"paid_$i"} * $form->{"exchangerate_$i"});
674 $form->{fx}{ $form->{fxgain_accno} }{ $form->{"datepaid_$i"} } += $amount;
676 $form->{fx}{ $form->{fxloss_accno} }{ $form->{"datepaid_$i"} } += $amount;
681 # update exchange rate
682 $form->update_exchangerate($dbh, $form->{currency}, $form->{"datepaid_$i"}, 0, $form->{"exchangerate_$i"})
683 if ($form->{currency} ne $defaultcurrency) && !$exchangerate;
686 # record exchange rate differences and gains/losses
687 foreach my $accno (keys %{ $form->{fx} }) {
688 foreach my $transdate (keys %{ $form->{fx}{$accno} }) {
689 $form->{fx}{$accno}{$transdate} = $form->round_amount($form->{fx}{$accno}{$transdate}, 2);
690 next if ($form->{fx}{$accno}{$transdate} == 0);
692 $query = qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate, cleared, fx_transaction, taxkey, project_id, tax_id, chart_link)
693 VALUES (?, (SELECT id FROM chart WHERE accno = ?), ?, ?, '0', '1', 0, ?,
694 (SELECT id FROM tax WHERE taxkey=0 LIMIT 1),
695 (SELECT link FROM chart WHERE accno = ?))|;
696 @values = (conv_i($form->{id}), $accno, $form->{fx}{$accno}{$transdate}, conv_date($transdate), $project_id, $accno);
697 do_query($form, $dbh, $query, @values);
701 IO->set_datepaid(table => 'ap', id => $form->{id}, dbh => $dbh);
703 if ($payments_only) {
704 $query = qq|UPDATE ap SET paid = ? WHERE id = ?|;
705 do_query($form, $dbh, $query, $form->{paid}, conv_i($form->{id}));
706 $form->new_lastmtime('ap');
711 $amount = $netamount + $tax;
713 # set values which could be empty
714 my $taxzone_id = $form->{taxzone_id} * 1;
715 $taxzone_id = SL::DB::Manager::TaxZone->get_default->id unless SL::DB::Manager::TaxZone->find_by(id => $taxzone_id);
717 $form->{invnumber} = $form->{id} unless $form->{invnumber};
720 $query = qq|UPDATE ap SET
721 invnumber = ?, ordnumber = ?, quonumber = ?, transdate = ?,
722 orddate = ?, quodate = ?, vendor_id = ?, amount = ?,
723 netamount = ?, paid = ?, duedate = ?,
724 invoice = ?, taxzone_id = ?, notes = ?, taxincluded = ?,
725 intnotes = ?, storno_id = ?, storno = ?,
726 cp_id = ?, employee_id = ?, department_id = ?, delivery_term_id = ?,
727 currency_id = (SELECT id FROM currencies WHERE name = ?),
728 globalproject_id = ?, direct_debit = ?
731 $form->{invnumber}, $form->{ordnumber}, $form->{quonumber}, conv_date($form->{invdate}),
732 conv_date($form->{orddate}), conv_date($form->{quodate}), conv_i($form->{vendor_id}), $amount,
733 $netamount, $form->{paid}, conv_date($form->{duedate}),
734 '1', $taxzone_id, $restricter->process($form->{notes}), $form->{taxincluded} ? 't' : 'f',
735 $form->{intnotes}, conv_i($form->{storno_id}), $form->{storno} ? 't' : 'f',
736 conv_i($form->{cp_id}), conv_i($form->{employee_id}), conv_i($form->{department_id}), conv_i($form->{delivery_term_id}),
738 conv_i($form->{globalproject_id}),
739 $form->{direct_debit} ? 't' : 'f',
742 do_query($form, $dbh, $query, @values);
744 if ($form->{storno}) {
745 $query = qq|UPDATE ap SET paid = paid + amount WHERE id = ?|;
746 do_query($form, $dbh, $query, conv_i($form->{storno_id}));
748 $query = qq|UPDATE ap SET storno = 't' WHERE id = ?|;
749 do_query($form, $dbh, $query, conv_i($form->{storno_id}));
751 $query = qq!UPDATE ap SET intnotes = ? || intnotes WHERE id = ?!;
752 do_query($form, $dbh, $query, "Rechnung storniert am $form->{invdate} ", conv_i($form->{storno_id}));
754 $query = qq|UPDATE ap SET paid = amount WHERE id = ?|;
755 do_query($form, $dbh, $query, conv_i($form->{id}));
758 $form->new_lastmtime('ap');
760 $form->{name} = $form->{vendor};
761 $form->{name} =~ s/--\Q$form->{vendor_id}\E//;
764 $form->add_shipto($dbh, $form->{id}, "AP");
766 # delete zero entries
767 do_query($form, $dbh, qq|DELETE FROM acc_trans WHERE amount = 0|);
769 Common::webdav_folder($form);
771 # Link this record to the records it was created from order or invoice (storno)
772 foreach (qw(oe ap)) {
773 if ($form->{"convert_from_${_}_ids"}) {
774 RecordLinks->create_links('dbh' => $dbh,
777 'from_ids' => $form->{"convert_from_${_}_ids"},
779 'to_id' => $form->{id},
781 delete $form->{"convert_from_${_}_ids"};
785 my @convert_from_do_ids = map { $_ * 1 } grep { $_ } split m/\s+/, $form->{convert_from_do_ids};
786 if (scalar @convert_from_do_ids) {
787 DO->close_orders('dbh' => $dbh,
788 'ids' => \@convert_from_do_ids);
790 RecordLinks->create_links('dbh' => $dbh,
792 'from_table' => 'delivery_orders',
793 'from_ids' => \@convert_from_do_ids,
795 'to_id' => $form->{id},
798 delete $form->{convert_from_do_ids};
800 ARAP->close_orders_if_billed('dbh' => $dbh,
801 'arap_id' => $form->{id},
804 # search for orphaned invoice items
805 $query = sprintf 'SELECT id FROM invoice WHERE trans_id = ? AND NOT id IN (%s)', join ', ', ("?") x scalar @processed_invoice_ids;
806 @values = (conv_i($form->{id}), map { conv_i($_) } @processed_invoice_ids);
807 my @orphaned_ids = map { $_->{id} } selectall_hashref_query($form, $dbh, $query, @values);
808 if (scalar @orphaned_ids) {
809 # clean up invoice items
810 $query = sprintf 'DELETE FROM invoice WHERE id IN (%s)', join ', ', ("?") x scalar @orphaned_ids;
811 do_query($form, $dbh, $query, @orphaned_ids);
814 if ($form->{draft_id}) {
815 SL::DB::Manager::Draft->delete_all(where => [ id => delete($form->{draft_id}) ]);
818 # safety check datev export
819 if ($::instance_conf->get_datev_check_on_purchase_invoice) {
820 # if we need department for kostenstelle in DATEV check
821 $form->{department} = SL::DB::Manager::Department->find_by(id => $form->{department_id})->description if $form->{department_id};
822 my $transdate = $::form->{invdate} ? DateTime->from_lxoffice($::form->{invdate}) : undef;
823 $transdate ||= DateTime->today;
825 my $datev = SL::DATEV->new(
826 exporttype => DATEV_ET_BUCHUNGEN,
827 format => DATEV_FORMAT_KNE,
829 trans_id => $form->{id},
834 if ($datev->errors) {
835 die join "\n", $::locale->text('DATEV check returned errors:'), $datev->errors;
842 sub reverse_invoice {
843 $main::lxdebug->enter_sub();
845 my ($dbh, $form) = @_;
847 # reverse inventory items
849 qq|SELECT i.parts_id, p.part_type, i.qty, i.allocated, i.sellprice
850 FROM invoice i, parts p
851 WHERE (i.parts_id = p.id)
852 AND (i.trans_id = ?)|;
853 my $sth = prepare_execute_query($form, $dbh, $query, conv_i($form->{id}));
857 while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
858 $netamount += $form->round_amount($ref->{sellprice} * $ref->{qty} * -1, 2);
860 next unless $ref->{part_type} eq 'part';
862 # if $ref->{allocated} > 0 than we sold that many items
863 next if ($ref->{allocated} <= 0);
865 # get references for sold items
867 qq|SELECT i.id, i.trans_id, i.allocated, a.transdate
869 WHERE (i.parts_id = ?)
870 AND (i.allocated < 0)
871 AND (i.trans_id = a.id)
872 ORDER BY transdate DESC|;
873 my $sth2 = prepare_execute_query($form, $dbh, $query, $ref->{parts_id});
875 while (my $pthref = $sth2->fetchrow_hashref("NAME_lc")) {
876 my $qty = $ref->{allocated};
877 if (($ref->{allocated} + $pthref->{allocated}) > 0) {
878 $qty = $pthref->{allocated} * -1;
881 my $amount = $form->round_amount($ref->{sellprice} * $qty, 2);
884 $form->update_balance($dbh, "invoice", "allocated", qq|id = $pthref->{id}|, $qty);
886 if ( $::instance_conf->get_inventory_system eq 'perpetual' ) {
888 $form->update_balance($dbh, "acc_trans", "amount",
889 qq| (trans_id = $pthref->{trans_id})
890 AND (chart_id = $ref->{expense_accno_id})
891 AND (transdate = '$pthref->{transdate}')|,
894 $form->update_balance($dbh, "acc_trans", "amount",
895 qq| (trans_id = $pthref->{trans_id})
896 AND (chart_id = $ref->{inventory_accno_id})
897 AND (transdate = '$pthref->{transdate}')|,
901 last if (($ref->{allocated} -= $qty) <= 0);
907 my $id = conv_i($form->{id});
910 $query = qq|DELETE FROM acc_trans WHERE trans_id = ?|;
911 do_query($form, $dbh, $query, $id);
913 $query = qq|DELETE FROM shipto WHERE (trans_id = ?) AND (module = 'AP')|;
914 do_query($form, $dbh, $query, $id);
916 $main::lxdebug->leave_sub();
920 $main::lxdebug->enter_sub();
922 my ($self, $myconfig, $form) = @_;
924 # connect to database
925 my $dbh = SL::DB->client->dbh;
927 SL::DB->client->with_transaction(sub{
929 &reverse_invoice($dbh, $form);
931 my @values = (conv_i($form->{id}));
933 # delete zero entries
934 # wtf? use case for this?
935 $query = qq|DELETE FROM acc_trans WHERE amount = 0|;
936 do_query($form, $dbh, $query);
940 qq|DELETE FROM invoice WHERE trans_id = ?|,
941 qq|DELETE FROM ap WHERE id = ?|,
944 map { do_query($form, $dbh, $_, @values) } @queries;
946 }) or do { die SL::DB->client->error };
951 sub retrieve_invoice {
952 $main::lxdebug->enter_sub();
954 my ($self, $myconfig, $form) = @_;
956 # connect to database
957 my $dbh = SL::DB->client->dbh;
959 my ($query, $sth, $ref, $q_invdate);
962 $q_invdate = qq|, COALESCE((SELECT transdate FROM ar WHERE id = (SELECT MAX(id) FROM ar)), current_date) AS invdate|;
963 if ($form->{vendor_id}) {
964 my $vendor_id = $dbh->quote($form->{vendor_id} * 1);
966 qq|, COALESCE((SELECT transdate FROM ar WHERE id = (SELECT MAX(id) FROM ar)), current_date) +
967 COALESCE((SELECT pt.terms_netto
969 LEFT JOIN payment_terms pt ON (v.payment_id = pt.id)
970 WHERE v.id = $vendor_id),
975 # get default accounts and last invoice number
978 (SELECT c.accno FROM chart c WHERE d.inventory_accno_id = c.id) AS inventory_accno,
979 (SELECT c.accno FROM chart c WHERE d.income_accno_id = c.id) AS income_accno,
980 (SELECT c.accno FROM chart c WHERE d.expense_accno_id = c.id) AS expense_accno,
981 (SELECT c.accno FROM chart c WHERE d.fxgain_accno_id = c.id) AS fxgain_accno,
982 (SELECT c.accno FROM chart c WHERE d.fxloss_accno_id = c.id) AS fxloss_accno
985 $ref = selectfirst_hashref_query($form, $dbh, $query);
986 map { $form->{$_} = $ref->{$_} } keys %$ref;
989 $main::lxdebug->leave_sub();
995 $query = qq|SELECT cp_id, invnumber, transdate AS invdate, duedate,
996 orddate, quodate, globalproject_id,
997 ordnumber, quonumber, paid, taxincluded, notes, taxzone_id, storno, gldate,
999 intnotes, (SELECT cu.name FROM currencies cu WHERE cu.id=ap.currency_id) AS currency, direct_debit,
1003 $ref = selectfirst_hashref_query($form, $dbh, $query, conv_i($form->{id}));
1004 map { $form->{$_} = $ref->{$_} } keys %$ref;
1005 $form->{mtime} = $form->{itime} if !$form->{mtime};
1006 $form->{lastmtime} = $form->{mtime};
1008 $form->{exchangerate} = $form->get_exchangerate($dbh, $form->{currency}, $form->{invdate}, "sell");
1011 $query = qq|SELECT * FROM shipto WHERE (trans_id = ?) AND (module = 'AP')|;
1012 $ref = selectfirst_hashref_query($form, $dbh, $query, conv_i($form->{id}));
1014 map { $form->{$_} = $ref->{$_} } keys %$ref;
1016 my $transdate = $form->{invdate} ? $dbh->quote($form->{invdate}) : "current_date";
1018 my $taxzone_id = $form->{taxzone_id} * 1;
1019 $taxzone_id = SL::DB::Manager::TaxZone->get_default->id unless SL::DB::Manager::TaxZone->find_by(id => $taxzone_id);
1021 # retrieve individual items
1024 c1.accno AS inventory_accno, c1.new_chart_id AS inventory_new_chart, date($transdate) - c1.valid_from AS inventory_valid,
1025 c2.accno AS income_accno, c2.new_chart_id AS income_new_chart, date($transdate) - c2.valid_from AS income_valid,
1026 c3.accno AS expense_accno, c3.new_chart_id AS expense_new_chart, date($transdate) - c3.valid_from AS expense_valid,
1029 i.description, i.longdescription, i.qty, i.fxsellprice AS sellprice, i.parts_id AS id, i.unit, i.deliverydate, i.project_id, i.serialnumber,
1030 i.price_factor_id, i.price_factor, i.marge_price_factor, i.discount, i.active_price_source, i.active_discount_source,
1031 p.partnumber, p.part_type, pr.projectnumber, pg.partsgroup
1032 ,p.classification_id
1035 JOIN parts p ON (i.parts_id = p.id)
1036 LEFT JOIN chart c1 ON ((SELECT inventory_accno_id FROM buchungsgruppen WHERE id = p.buchungsgruppen_id) = c1.id)
1037 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)
1038 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)
1039 LEFT JOIN project pr ON (i.project_id = pr.id)
1040 LEFT JOIN partsgroup pg ON (pg.id = p.partsgroup_id)
1042 WHERE i.trans_id = ?
1044 ORDER BY i.position|;
1045 $sth = prepare_execute_query($form, $dbh, $query, conv_i($form->{id}));
1047 while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
1048 # Retrieve custom variables.
1049 my $cvars = CVar->get_custom_variables(dbh => $dbh,
1051 sub_module => 'invoice',
1052 trans_id => $ref->{invoice_id},
1054 map { $ref->{"ic_cvar_$_->{name}"} = $_->{value} } @{ $cvars };
1056 map({ delete($ref->{$_}); } qw(inventory_accno inventory_new_chart inventory_valid)) if !$ref->{"part_type"} eq 'part';
1058 foreach my $type (qw(inventory income expense)) {
1059 while ($ref->{"${type}_new_chart"} && ($ref->{"${type}_valid"} >=0)) {
1060 my $query = qq|SELECT accno, new_chart_id, date($transdate) - valid_from FROM chart WHERE id = ?|;
1061 @$ref{ map $type.$_, qw(_accno _new_chart _valid) } = selectrow_query($form, $dbh, $query, $ref->{"${type}_new_chart"});
1065 # get tax rates and description
1066 my $accno_id = ($form->{vc} eq "customer") ? $ref->{income_accno} : $ref->{expense_accno};
1068 qq|SELECT c.accno, t.taxdescription, t.rate, t.taxnumber FROM tax t
1069 LEFT JOIN chart c ON (c.id = t.chart_id)
1071 (SELECT tk.tax_id FROM taxkeys tk
1072 WHERE tk.chart_id = (SELECT id FROM chart WHERE accno = ?)
1073 AND (startdate <= $transdate)
1074 ORDER BY startdate DESC
1077 my $stw = prepare_execute_query($form, $dbh, $query, $accno_id);
1078 $ref->{taxaccounts} = "";
1081 while (my $ptr = $stw->fetchrow_hashref("NAME_lc")) {
1082 if (($ptr->{accno} eq "") && ($ptr->{rate} == 0)) {
1087 $ref->{taxaccounts} .= "$ptr->{accno} ";
1089 if (!($form->{taxaccounts} =~ /\Q$ptr->{accno}\E/)) {
1090 $form->{"$ptr->{accno}_rate"} = $ptr->{rate};
1091 $form->{"$ptr->{accno}_description"} = $ptr->{taxdescription};
1092 $form->{"$ptr->{accno}_taxnumber"} = $ptr->{taxnumber};
1093 $form->{taxaccounts} .= "$ptr->{accno} ";
1098 chop $ref->{taxaccounts};
1099 push @{ $form->{invoice_details} }, $ref;
1104 Common::webdav_folder($form);
1106 $main::lxdebug->leave_sub();
1110 $main::lxdebug->enter_sub();
1112 my ($self, $myconfig, $form, $params) = @_;
1114 $params = $form unless defined $params && ref $params eq "HASH";
1116 # connect to database
1117 my $dbh = SL::DB->client->dbh;
1119 my $dateformat = $myconfig->{dateformat};
1120 $dateformat .= "yy" if $myconfig->{dateformat} !~ /^y/;
1122 my $vid = conv_i($params->{vendor_id});
1123 my $vnr = conv_i($params->{vendornumber});
1126 ($params->{invdate})
1127 ? "to_date(" . $dbh->quote($params->{invdate}) . ", '$dateformat')"
1134 $where .= 'AND v.id = ?';
1138 $where .= 'AND v.vendornumber = ?';
1143 v.id AS vendor_id, v.name AS vendor, v.discount as vendor_discount,
1144 v.creditlimit, v.notes AS intnotes,
1145 v.email, v.cc, v.bcc, v.language_id, v.payment_id, v.delivery_term_id,
1146 v.street, v.zipcode, v.city, v.country, v.taxzone_id, cu.name AS curr, v.direct_debit,
1147 $duedate + COALESCE(pt.terms_netto, 0) AS duedate,
1148 b.discount AS tradediscount, b.description AS business
1150 LEFT JOIN business b ON (b.id = v.business_id)
1151 LEFT JOIN payment_terms pt ON (v.payment_id = pt.id)
1152 LEFT JOIN currencies cu ON (v.currency_id = cu.id)
1154 my $ref = selectfirst_hashref_query($form, $dbh, $query, @values);
1155 map { $params->{$_} = $ref->{$_} } keys %$ref;
1157 # use vendor currency
1158 $form->{currency} = $form->{curr};
1160 $params->{creditremaining} = $params->{creditlimit};
1162 $query = qq|SELECT SUM(amount - paid) FROM ap WHERE vendor_id = ?|;
1163 my ($unpaid_invoices) = selectfirst_array_query($form, $dbh, $query, $vid);
1164 $params->{creditremaining} -= $unpaid_invoices;
1166 $query = qq|SELECT o.amount,
1169 WHERE (e.currency_id = o.currency_id)
1170 AND (e.transdate = o.transdate)) AS exch
1172 WHERE (o.vendor_id = ?) AND (o.quotation = '0') AND (o.closed = '0')|;
1173 my $sth = prepare_execute_query($form, $dbh, $query, $vid);
1174 while (my ($amount, $exch) = $sth->fetchrow_array()) {
1175 $exch = 1 unless $exch;
1176 $params->{creditremaining} -= $amount * $exch;
1180 $main::lxdebug->leave_sub();
1184 $main::lxdebug->enter_sub();
1186 my ($self, $myconfig, $form) = @_;
1188 my $dbh = SL::DB->client->dbh;
1190 my $i = $form->{rowcount};
1192 # don't include assemblies or obsolete parts
1193 my $where = "NOT p.part_type = 'assembly' AND NOT p.obsolete = '1'";
1196 foreach my $table_column (qw(p.partnumber p.description pg.partsgroup)) {
1197 my $field = (split m{\.}, $table_column)[1];
1198 next unless $form->{"${field}_${i}"};
1199 $where .= " AND lower(${table_column}) LIKE lower(?)";
1200 push @values, like($form->{"${field}_${i}"});
1204 if ($form->{"partnumber_$i"} && !$form->{"description_$i"}) {
1205 $where .= qq| OR (NOT p.obsolete = '1' AND p.ean = ? )|;
1206 push @values, $form->{"partnumber_$i"};
1208 # also search hits in makemodels, but only cache the results by id and merge later
1210 SELECT parts_id, model FROM makemodel
1211 LEFT JOIN parts ON parts.id = parts_id
1212 WHERE NOT parts.obsolete AND model ILIKE ? AND (make IS NULL OR make = ?);
1214 my $mm_results = selectall_hashref_query($::form, $dbh, $mm_query, like($form->{"partnumber_$i"}), $::form->{vendor_id});
1215 my @mm_ids = map { $_->{parts_id} } @$mm_results;
1216 push @{$mm_by_id{ $_->{parts_id} } ||= []}, $_ for @$mm_results;
1219 $where .= qq| OR p.id IN (| . join(',', ('?') x @mm_ids) . qq|)|;
1220 push @values, @mm_ids;
1224 # Search for part ID overrides all other criteria.
1225 if ($form->{"id_${i}"}) {
1226 $where = qq|p.id = ?|;
1227 @values = ($form->{"id_${i}"});
1230 if ($form->{"description_$i"}) {
1231 $where .= " ORDER BY p.description";
1233 $where .= " ORDER BY p.partnumber";
1237 if ($form->{type} eq "invoice") {
1238 $transdate = $form->{deliverydate} ? $dbh->quote($form->{deliverydate})
1239 : $form->{invdate} ? $dbh->quote($form->{invdate})
1242 $transdate = $form->{transdate} ? $dbh->quote($form->{transdate}) : "current_date";
1245 my $taxzone_id = $form->{taxzone_id} * 1;
1246 $taxzone_id = SL::DB::Manager::TaxZone->get_default->id unless SL::DB::Manager::TaxZone->find_by(id => $taxzone_id);
1250 p.id, p.partnumber, p.description, p.lastcost AS sellprice, p.listprice,
1251 p.unit, p.part_type, p.onhand, p.formel,
1252 p.notes AS partnotes, p.notes AS longdescription, p.not_discountable,
1255 p.classification_id,
1257 pfac.factor AS price_factor,
1259 c1.accno AS inventory_accno,
1260 c1.new_chart_id AS inventory_new_chart,
1261 date($transdate) - c1.valid_from AS inventory_valid,
1263 c2.accno AS income_accno,
1264 c2.new_chart_id AS income_new_chart,
1265 date($transdate) - c2.valid_from AS income_valid,
1267 c3.accno AS expense_accno,
1268 c3.new_chart_id AS expense_new_chart,
1269 date($transdate) - c3.valid_from AS expense_valid,
1271 pt.used_for_purchase AS used_for_purchase,
1275 LEFT JOIN chart c1 ON
1276 ((SELECT inventory_accno_id
1277 FROM buchungsgruppen
1278 WHERE id = p.buchungsgruppen_id) = c1.id)
1279 LEFT JOIN chart c2 ON
1280 ((SELECT tc.income_accno_id
1281 FROM taxzone_charts tc
1282 WHERE tc.taxzone_id = '$taxzone_id' and tc.buchungsgruppen_id = p.buchungsgruppen_id) = c2.id)
1283 LEFT JOIN chart c3 ON
1284 ((SELECT tc.expense_accno_id
1285 FROM taxzone_charts tc
1286 WHERE tc.taxzone_id = '$taxzone_id' and tc.buchungsgruppen_id = p.buchungsgruppen_id) = c3.id)
1287 LEFT JOIN partsgroup pg ON (pg.id = p.partsgroup_id)
1288 LEFT JOIN part_classifications pt ON (pt.id = p.classification_id)
1289 LEFT JOIN price_factors pfac ON (pfac.id = p.price_factor_id)
1291 my $sth = prepare_execute_query($form, $dbh, $query, @values);
1293 my @translation_queries = ( [ qq|SELECT tr.translation, tr.longdescription
1295 WHERE tr.language_id = ? AND tr.parts_id = ?| ],
1296 [ qq|SELECT tr.translation, tr.longdescription
1298 WHERE tr.language_id IN
1301 WHERE article_code = (SELECT article_code FROM language WHERE id = ?))
1304 map { push @{ $_ }, prepare_query($form, $dbh, $_->[0]) } @translation_queries;
1306 $form->{item_list} = [];
1307 my $has_wrong_pclass = PCLASS_OK;
1308 while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
1310 if ($mm_by_id{$ref->{id}}) {
1311 $ref->{makemodels} = $mm_by_id{$ref->{id}};
1312 push @{ $ref->{matches} ||= [] }, $::locale->text('Model') . ': ' . join ', ', map { $_->{model} } @{ $mm_by_id{$ref->{id}} };
1315 if (($::form->{"partnumber_$i"} ne '') && ($ref->{ean} eq $::form->{"partnumber_$i"})) {
1316 push @{ $ref->{matches} ||= [] }, $::locale->text('EAN') . ': ' . $ref->{ean};
1318 $ref->{type_and_classific} = $::request->presenter->type_abbreviation($ref->{part_type}).
1319 $::request->presenter->classification_abbreviation($ref->{classification_id});
1321 if (! $ref->{used_for_purchase} ) {
1322 $has_wrong_pclass = PCLASS_NOTFORPURCHASE;
1325 # In der Buchungsgruppe ist immer ein Bestandskonto verknuepft, auch wenn
1326 # es sich um eine Dienstleistung handelt. Bei Dienstleistungen muss das
1327 # Buchungskonto also aus dem Ergebnis rausgenommen werden.
1328 if (!$ref->{inventory_accno_id}) {
1329 map({ delete($ref->{"inventory_${_}"}); } qw(accno new_chart valid));
1331 delete($ref->{inventory_accno_id});
1333 # get tax rates and description
1334 my $accno_id = ($form->{vc} eq "customer") ? $ref->{income_accno} : $ref->{expense_accno};
1336 qq|SELECT c.accno, t.taxdescription, t.rate, t.taxnumber
1338 LEFT JOIN chart c on (c.id = t.chart_id)
1346 AND (startdate <= $transdate)
1347 ORDER BY startdate DESC
1350 my $stw = prepare_execute_query($form, $dbh, $query, $accno_id);
1352 $ref->{taxaccounts} = "";
1354 while (my $ptr = $stw->fetchrow_hashref("NAME_lc")) {
1356 if (($ptr->{accno} eq "") && ($ptr->{rate} == 0)) {
1361 $ref->{taxaccounts} .= "$ptr->{accno} ";
1363 if (!($form->{taxaccounts} =~ /\Q$ptr->{accno}\E/)) {
1364 $form->{"$ptr->{accno}_rate"} = $ptr->{rate};
1365 $form->{"$ptr->{accno}_description"} = $ptr->{taxdescription};
1366 $form->{"$ptr->{accno}_taxnumber"} = $ptr->{taxnumber};
1367 $form->{taxaccounts} .= "$ptr->{accno} ";
1370 if ($form->{language_id}) {
1371 for my $spec (@translation_queries) {
1372 do_statement($form, $spec->[1], $spec->[0], conv_i($form->{language_id}), conv_i($ref->{id}));
1373 my ($translation, $longdescription) = $spec->[1]->fetchrow_array;
1374 next unless $translation;
1375 $ref->{description} = $translation;
1376 $ref->{longdescription} = $longdescription;
1383 chop $ref->{taxaccounts};
1385 $ref->{onhand} *= 1;
1387 push @{ $form->{item_list} }, $ref;
1392 $_->[1]->finish for @translation_queries;
1394 $form->{is_wrong_pclass} = $has_wrong_pclass;
1395 $form->{NOTFORSALE} = PCLASS_NOTFORSALE;
1396 $form->{NOTFORPURCHASE} = PCLASS_NOTFORPURCHASE;
1397 foreach my $item (@{ $form->{item_list} }) {
1398 my $custom_variables = CVar->get_custom_variables(module => 'IC',
1399 trans_id => $item->{id},
1402 $form->{is_wrong_pclass} = PCLASS_OK; # one correct type
1403 map { $item->{"ic_cvar_" . $_->{name} } = $_->{value} } @{ $custom_variables };
1406 $main::lxdebug->leave_sub();
1409 sub vendor_details {
1410 $main::lxdebug->enter_sub();
1412 my ($self, $myconfig, $form, @wanted_vars) = @_;
1414 my $dbh = SL::DB->client->dbh;
1418 # get contact id, set it if nessessary
1419 $form->{cp_id} *= 1;
1421 if ($form->{cp_id}) {
1422 $contact = "AND cp.cp_id = ?";
1423 push @values, $form->{cp_id};
1426 # get rest for the vendor
1427 # fax and phone and email as vendor*
1429 qq|SELECT ct.*, cp.*, ct.notes as vendornotes, phone as vendorphone, fax as vendorfax, email as vendoremail,
1432 LEFT JOIN contacts cp ON (ct.id = cp.cp_cv_id)
1433 LEFT JOIN currencies cu ON (ct.currency_id = cu.id)
1434 WHERE (ct.id = ?) $contact
1437 my $ref = selectfirst_hashref_query($form, $dbh, $query, $form->{vendor_id}, @values);
1439 # remove id,notes (double of vendornotes) and taxincluded before copy back
1440 delete @$ref{qw(id taxincluded notes)};
1442 @wanted_vars = grep({ $_ } @wanted_vars);
1443 if (scalar(@wanted_vars) > 0) {
1445 map({ $h_wanted_vars{$_} = 1; } @wanted_vars);
1446 map({ delete($ref->{$_}) unless ($h_wanted_vars{$_}); } keys(%{$ref}));
1449 map { $form->{$_} = $ref->{$_} } keys %$ref;
1451 my $custom_variables = CVar->get_custom_variables('dbh' => $dbh,
1453 'trans_id' => $form->{vendor_id});
1454 map { $form->{"vc_cvar_$_->{name}"} = $_->{value} } @{ $custom_variables };
1456 $form->{cp_greeting} = GenericTranslations->get('dbh' => $dbh,
1457 'translation_type' => 'greetings::' . ($form->{cp_gender} eq 'f' ? 'female' : 'male'),
1458 'allow_fallback' => 1);
1460 $main::lxdebug->leave_sub();
1464 $main::lxdebug->enter_sub();
1466 my ($self, $myconfig, $form) = @_;
1468 my $dbh = SL::DB->client->dbh;
1471 qq|SELECT accno, description, link
1473 WHERE link LIKE '%IC%'
1475 my $sth = prepare_execute_query($query, $dbh, $query);
1477 while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
1478 foreach my $key (split(/:/, $ref->{link})) {
1480 push @{ $form->{IC_links}{$key} },
1481 { accno => $ref->{accno},
1482 description => $ref->{description} };
1488 $main::lxdebug->leave_sub();
1491 sub _delete_payments {
1492 $main::lxdebug->enter_sub();
1494 my ($self, $form, $dbh) = @_;
1496 my @delete_acc_trans_ids;
1498 # Delete old payment entries from acc_trans.
1500 qq|SELECT acc_trans_id
1502 WHERE (trans_id = ?) AND fx_transaction
1506 SELECT at.acc_trans_id
1508 LEFT JOIN chart c ON (at.chart_id = c.id)
1509 WHERE (trans_id = ?) AND (c.link LIKE '%AP_paid%')|;
1510 push @delete_acc_trans_ids, selectall_array_query($form, $dbh, $query, conv_i($form->{id}), conv_i($form->{id}));
1513 qq|SELECT at.acc_trans_id
1515 LEFT JOIN chart c ON (at.chart_id = c.id)
1516 WHERE (trans_id = ?)
1517 AND ((c.link = 'AP') OR (c.link LIKE '%:AP') OR (c.link LIKE 'AP:%'))
1518 ORDER BY at.acc_trans_id
1520 push @delete_acc_trans_ids, selectall_array_query($form, $dbh, $query, conv_i($form->{id}));
1522 if (@delete_acc_trans_ids) {
1523 $query = qq|DELETE FROM acc_trans WHERE acc_trans_id IN (| . join(", ", @delete_acc_trans_ids) . qq|)|;
1524 do_query($form, $dbh, $query);
1527 $main::lxdebug->leave_sub();
1531 my ($self, $myconfig, $form, $locale) = @_;
1532 $main::lxdebug->enter_sub();
1534 my $rc = SL::DB->client->with_transaction(\&_post_payment, $self, $myconfig, $form, $locale);
1536 $::lxdebug->leave_sub;
1541 my ($self, $myconfig, $form, $locale) = @_;
1543 my $dbh = SL::DB->client->dbh;
1545 my (%payments, $old_form, $row, $item, $query, %keep_vars);
1547 $old_form = save_form();
1549 # Delete all entries in acc_trans from prior payments.
1550 if (SL::DB::Default->get->payments_changeable != 0) {
1551 $self->_delete_payments($form, $dbh);
1554 # Save the new payments the user made before cleaning up $form.
1555 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 };
1557 # Clean up $form so that old content won't tamper the results.
1558 %keep_vars = map { $_, 1 } qw(login password id);
1559 map { delete $form->{$_} unless $keep_vars{$_} } keys %{ $form };
1561 # Retrieve the invoice from the database.
1562 $self->retrieve_invoice($myconfig, $form);
1564 # Set up the content of $form in the way that IR::post_invoice() expects.
1565 $form->{exchangerate} = $form->format_amount($myconfig, $form->{exchangerate});
1567 for $row (1 .. scalar @{ $form->{invoice_details} }) {
1568 $item = $form->{invoice_details}->[$row - 1];
1570 map { $item->{$_} = $form->format_amount($myconfig, $item->{$_}) } qw(qty sellprice);
1572 map { $form->{"${_}_${row}"} = $item->{$_} } keys %{ $item };
1575 $form->{rowcount} = scalar @{ $form->{invoice_details} };
1577 delete @{$form}{qw(invoice_details paidaccounts storno paid)};
1579 # Restore the payment options from the user input.
1580 map { $form->{$_} = $payments{$_} } keys %payments;
1582 # Get the AP accno (which is normally done by Form::create_links()).
1586 LEFT JOIN chart c ON (at.chart_id = c.id)
1587 WHERE (trans_id = ?)
1588 AND ((c.link = 'AP') OR (c.link LIKE '%:AP') OR (c.link LIKE 'AP:%'))
1589 ORDER BY at.acc_trans_id
1592 ($form->{AP}) = selectfirst_array_query($form, $dbh, $query, conv_i($form->{id}));
1594 # Post the new payments.
1595 $self->post_invoice($myconfig, $form, $dbh, 1);
1597 restore_form($old_form);
1603 $::lxdebug->enter_sub;
1605 my ($self, %params) = @_;
1607 if (!$params{vendor_id} || !$params{invdate}) {
1608 $::lxdebug->leave_sub;
1609 return $params{default};
1612 my $dbh = $::form->get_standard_dbh;
1613 my $query = qq|SELECT ?::date + pt.terms_netto
1615 LEFT JOIN payment_terms pt ON (pt.id = v.payment_id)
1618 my ($duedate) = selectfirst_array_query($::form, $dbh, $query, $params{invdate}, $params{vendor_id});
1620 $duedate ||= $params{default};
1622 $::lxdebug->leave_sub;