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, $payments_only) = @_;
64 $main::lxdebug->enter_sub();
66 my $rc = SL::DB->client->with_transaction(\&_post_invoice, $self, $myconfig, $form, $provided_dbh, $payments_only);
68 $::lxdebug->leave_sub;
73 my ($self, $myconfig, $form, $provided_dbh, $payments_only) = @_;
75 my $dbh = $provided_dbh || SL::DB->client->dbh;
76 my $restricter = SL::HTML::Restrict->create;
78 $form->{defaultcurrency} = $form->get_default_currency($myconfig);
79 my $defaultcurrency = $form->{defaultcurrency};
81 my $ic_cvar_configs = CVar->get_configs(module => 'IC',
84 my ($query, $sth, @values, $project_id);
85 my ($allocated, $taxrate, $taxamount, $taxdiff, $item);
86 my ($amount, $linetotal, $lastinventoryaccno, $lastexpenseaccno);
87 my ($netamount, $invoicediff, $expensediff) = (0, 0, 0);
89 my ($basefactor, $baseqty, @taxaccounts, $totaltax);
91 my $all_units = AM->retrieve_units($myconfig, $form);
94 if (!$payments_only) {
96 &reverse_invoice($dbh, $form);
98 ($form->{id}) = selectrow_query($form, $dbh, qq|SELECT nextval('glid')|);
99 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});
103 if ($form->{currency} eq $defaultcurrency) {
104 $form->{exchangerate} = 1;
106 $exchangerate = $form->check_exchangerate($myconfig, $form->{currency}, $form->{invdate}, 'sell');
109 $form->{exchangerate} = $exchangerate || $form->parse_amount($myconfig, $form->{exchangerate});
110 $form->{exchangerate} = 1 unless ($form->{exchangerate} * 1);
113 my $q_item_unit = qq|SELECT unit FROM parts WHERE id = ?|;
114 my $h_item_unit = prepare_query($form, $dbh, $q_item_unit);
116 $form->get_lists('price_factors' => 'ALL_PRICE_FACTORS');
117 my %price_factors = map { $_->{id} => $_->{factor} } @{ $form->{ALL_PRICE_FACTORS} };
120 my @processed_invoice_ids;
121 for my $i (1 .. $form->{rowcount}) {
122 next unless $form->{"id_$i"};
126 $form->{"qty_$i"} = $form->parse_amount($myconfig, $form->{"qty_$i"});
127 $form->{"qty_$i"} *= -1 if $form->{storno};
129 if ( $::instance_conf->get_inventory_system eq 'periodic') {
130 # inventory account number is overwritten with expense account number, so
131 # never book incoming to inventory account but always to expense account
132 $form->{"inventory_accno_$i"} = $form->{"expense_accno_$i"}
136 if (!$item_units{$form->{"id_$i"}}) {
137 do_statement($form, $h_item_unit, $q_item_unit, $form->{"id_$i"});
138 ($item_units{$form->{"id_$i"}}) = $h_item_unit->fetchrow_array();
141 my $item_unit = $item_units{$form->{"id_$i"}};
143 if (defined($all_units->{$item_unit}->{factor})
144 && ($all_units->{$item_unit}->{factor} ne '')
145 && ($all_units->{$item_unit}->{factor} * 1 != 0)) {
146 $basefactor = $all_units->{$form->{"unit_$i"}}->{factor} / $all_units->{$item_unit}->{factor};
150 $baseqty = $form->{"qty_$i"} * $basefactor;
152 @taxaccounts = split / /, $form->{"taxaccounts_$i"};
157 $form->{"sellprice_$i"} = $form->parse_amount($myconfig, $form->{"sellprice_$i"});
158 (my $fxsellprice = $form->{"sellprice_$i"}) =~ /\.(\d+)/;
160 my $decimalplaces = ($dec > 2) ? $dec : 2;
162 map { $taxrate += $form->{"${_}_rate"} } @taxaccounts;
164 $price_factor = $price_factors{ $form->{"price_factor_id_$i"} } || 1;
165 # copied from IS.pm, with some changes (no decimalplaces corrections here etc)
166 # TODO maybe use PriceTaxCalculation or something like this for backends (IR.pm / IS.pm)
168 # undo discount formatting
169 $form->{"discount_$i"} = $form->parse_amount($myconfig, $form->{"discount_$i"}) / 100;
171 $form->{"sellprice_$i"} = $fxsellprice * (1 - $form->{"discount_$i"});
173 ######################################################################
174 if ($form->{"inventory_accno_$i"}) {
176 $linetotal = $form->round_amount($form->{"sellprice_$i"} * $form->{"qty_$i"} / $price_factor, 2);
178 if ($form->{taxincluded}) {
180 $taxamount = $linetotal * ($taxrate / (1 + $taxrate));
181 $form->{"sellprice_$i"} = $form->{"sellprice_$i"} * (1 / (1 + $taxrate));
184 $taxamount = $linetotal * $taxrate;
187 $netamount += $linetotal;
189 if ($form->round_amount($taxrate, 7) == 0) {
190 if ($form->{taxincluded}) {
191 foreach $item (@taxaccounts) {
193 $form->round_amount($linetotal * $form->{"${item}_rate"} / (1 + abs($form->{"${item}_rate"})), 2);
194 $taxdiff += $taxamount;
195 $form->{amount}{ $form->{id} }{$item} -= $taxamount;
197 $form->{amount}{ $form->{id} }{ $taxaccounts[0] } += $taxdiff;
200 map { $form->{amount}{ $form->{id} }{$_} -= $linetotal * $form->{"${_}_rate"} } @taxaccounts;
204 map { $form->{amount}{ $form->{id} }{$_} -= $taxamount * $form->{"${_}_rate"} / $taxrate } @taxaccounts;
207 # add purchase to inventory, this one is without the tax!
208 $amount = $form->{"sellprice_$i"} * $form->{"qty_$i"} * $form->{exchangerate} / $price_factor;
209 $linetotal = $form->round_amount($form->{"sellprice_$i"} * $form->{"qty_$i"} / $price_factor, 2) * $form->{exchangerate};
210 $linetotal = $form->round_amount($linetotal, 2);
212 # this is the difference for the inventory
213 $invoicediff += ($amount - $linetotal);
215 $form->{amount}{ $form->{id} }{ $form->{"inventory_accno_$i"} } -= $linetotal;
217 # adjust and round sellprice
218 $form->{"sellprice_$i"} = $form->round_amount($form->{"sellprice_$i"} * $form->{exchangerate}, $decimalplaces);
220 $lastinventoryaccno = $form->{"inventory_accno_$i"};
222 next if $payments_only;
224 # update parts table by setting lastcost to current price, don't allow negative values by using abs
225 $query = qq|UPDATE parts SET lastcost = ? WHERE id = ?|;
226 @values = (abs($fxsellprice * $form->{exchangerate} / $basefactor), conv_i($form->{"id_$i"}));
227 do_query($form, $dbh, $query, @values);
229 # check if we sold the item already and
230 # make an entry for the expense and inventory
231 my $taxzone = $form->{taxzone_id} * 1;
233 qq|SELECT i.id, i.qty, i.allocated, i.trans_id, i.base_qty,
234 bg.inventory_accno_id, tc.expense_accno_id AS expense_accno_id, a.transdate
235 FROM invoice i, ar a, parts p, buchungsgruppen bg, taxzone_charts tc
236 WHERE (i.parts_id = p.id)
238 AND ((i.base_qty + i.allocated) > 0)
239 AND (i.trans_id = a.id)
240 AND (p.buchungsgruppen_id = bg.id)
241 AND (tc.buchungsgruppen_id = p.buchungsgruppen_id)
242 AND (tc.taxzone_id = ${taxzone})
244 # ORDER BY transdate guarantees FIFO
246 # sold two items without having bought them yet, example result of query:
247 # id | qty | allocated | trans_id | inventory_accno_id | expense_accno_id | transdate
248 # ---+-----+-----------+----------+--------------------+------------------+------------
249 # 9 | 2 | 0 | 9 | 15 | 151 | 2011-01-05
251 # base_qty + allocated > 0 if article has already been sold but not bought yet
253 # select qty,allocated,base_qty,sellprice from invoice where trans_id = 9;
254 # qty | allocated | base_qty | sellprice
255 # -----+-----------+----------+------------
256 # 2 | 0 | 2 | 1000.00000
258 $sth = prepare_execute_query($form, $dbh, $query, conv_i($form->{"id_$i"}));
260 my $totalqty = $baseqty;
262 while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
263 my $qty = min $totalqty, ($ref->{base_qty} + $ref->{allocated});
264 $linetotal = $form->round_amount(($form->{"sellprice_$i"} * $qty) / $basefactor, 2);
266 if ( $::instance_conf->get_inventory_system eq 'perpetual' ) {
267 # Warenbestandsbuchungen nur bei Bestandsmethode
269 if ($ref->{allocated} < 0) {
271 # we have an entry for it already, adjust amount
272 $form->update_balance($dbh, "acc_trans", "amount",
273 qq| (trans_id = $ref->{trans_id})
274 AND (chart_id = $ref->{inventory_accno_id})
275 AND (transdate = '$ref->{transdate}')|,
278 $form->update_balance($dbh, "acc_trans", "amount",
279 qq| (trans_id = $ref->{trans_id})
280 AND (chart_id = $ref->{expense_accno_id})
281 AND (transdate = '$ref->{transdate}')|,
284 } elsif ($linetotal != 0) {
287 # add entry for inventory, this one is for the sold item
288 $query = qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate, taxkey, tax_id, chart_link) VALUES (?, ?, ?, ?,
293 ORDER BY startdate DESC LIMIT 1),
298 ORDER BY startdate DESC LIMIT 1),
299 (SELECT link FROM chart WHERE id = ?))|;
300 @values = ($ref->{trans_id}, $ref->{inventory_accno_id}, $linetotal, $ref->{transdate}, $ref->{inventory_accno_id}, $ref->{transdate}, $ref->{inventory_accno_id}, $ref->{transdate},
301 $ref->{inventory_accno_id});
302 do_query($form, $dbh, $query, @values);
305 $query = qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate, taxkey, tax_id, chart_link) VALUES (?, ?, ?, ?,
310 ORDER BY startdate DESC LIMIT 1),
315 ORDER BY startdate DESC LIMIT 1),
316 (SELECT link FROM chart WHERE id = ?))|;
317 @values = ($ref->{trans_id}, $ref->{expense_accno_id}, ($linetotal * -1), $ref->{transdate}, $ref->{expense_accno_id}, $ref->{transdate}, $ref->{expense_accno_id}, $ref->{transdate},
318 $ref->{expense_accno_id});
319 do_query($form, $dbh, $query, @values);
323 # update allocated for sold item
324 $form->update_balance($dbh, "invoice", "allocated", qq|id = $ref->{id}|, $qty * -1);
328 last if ($totalqty -= $qty) <= 0;
333 } else { # if ($form->{"inventory_accno_id_$i"})
334 # part doesn't have an inventory_accno_id
335 # lastcost of the part is updated at the end
337 $linetotal = $form->round_amount($form->{"sellprice_$i"} * $form->{"qty_$i"} / $price_factor, 2);
339 if ($form->{taxincluded}) {
340 $taxamount = $linetotal * ($taxrate / (1 + $taxrate));
341 $form->{"sellprice_$i"} = $form->{"sellprice_$i"} * (1 / (1 + $taxrate));
344 $taxamount = $linetotal * $taxrate;
347 $netamount += $linetotal;
349 if ($form->round_amount($taxrate, 7) == 0) {
350 if ($form->{taxincluded}) {
351 foreach $item (@taxaccounts) {
352 $taxamount = $linetotal * $form->{"${item}_rate"} / (1 + abs($form->{"${item}_rate"}));
353 $totaltax += $taxamount;
354 $form->{amount}{ $form->{id} }{$item} -= $taxamount;
357 map { $form->{amount}{ $form->{id} }{$_} -= $linetotal * $form->{"${_}_rate"} } @taxaccounts;
360 map { $form->{amount}{ $form->{id} }{$_} -= $taxamount * $form->{"${_}_rate"} / $taxrate } @taxaccounts;
363 $amount = $form->{"sellprice_$i"} * $form->{"qty_$i"} * $form->{exchangerate} / $price_factor;
364 $linetotal = $form->round_amount($form->{"sellprice_$i"} * $form->{"qty_$i"} / $price_factor, 2) * $form->{exchangerate};
365 $linetotal = $form->round_amount($linetotal, 2);
367 # this is the difference for expense
368 $expensediff += ($amount - $linetotal);
370 # add amount to expense
371 $form->{amount}{ $form->{id} }{ $form->{"expense_accno_$i"} } -= $linetotal;
373 $lastexpenseaccno = $form->{"expense_accno_$i"};
375 # adjust and round sellprice
376 $form->{"sellprice_$i"} = $form->round_amount($form->{"sellprice_$i"} * $form->{exchangerate}, $decimalplaces);
378 next if $payments_only;
381 $query = qq|UPDATE parts SET lastcost = ? WHERE id = ?|;
382 do_query($form, $dbh, $query, $form->{"sellprice_$i"} / $basefactor, conv_i($form->{"id_$i"}));
385 next if $payments_only;
387 CVar->get_non_editable_ic_cvars(form => $form,
390 sub_module => 'invoice',
391 may_converted_from => ['delivery_order_items', 'orderitems', 'invoice']);
393 if (!$form->{"invoice_id_$i"}) {
394 # there is no persistent id, therefore create one with all necessary constraints
395 my $q_invoice_id = qq|SELECT nextval('invoiceid')|;
396 my $h_invoice_id = prepare_query($form, $dbh, $q_invoice_id);
397 do_statement($form, $h_invoice_id, $q_invoice_id);
398 $form->{"invoice_id_$i"} = $h_invoice_id->fetchrow_array();
399 my $q_create_invoice_id = qq|INSERT INTO invoice (id, trans_id, position, parts_id) values (?, ?, ?, ?)|;
400 do_query($form, $dbh, $q_create_invoice_id, conv_i($form->{"invoice_id_$i"}),
401 conv_i($form->{id}), conv_i($position), conv_i($form->{"id_$i"}));
402 $h_invoice_id->finish();
405 # save detail record in invoice table
407 UPDATE invoice SET trans_id = ?, position = ?, parts_id = ?, description = ?, longdescription = ?, qty = ?, base_qty = ?,
408 sellprice = ?, fxsellprice = ?, discount = ?, allocated = ?, unit = ?, deliverydate = ?,
409 project_id = ?, serialnumber = ?, price_factor_id = ?,
410 price_factor = (SELECT factor FROM price_factors WHERE id = ?), marge_price_factor = ?,
411 active_price_source = ?, active_discount_source = ?
415 @values = (conv_i($form->{id}), conv_i($position), conv_i($form->{"id_$i"}),
416 $form->{"description_$i"}, $restricter->process($form->{"longdescription_$i"}), $form->{"qty_$i"} * -1,
417 $baseqty * -1, $form->{"sellprice_$i"}, $fxsellprice, $form->{"discount_$i"}, $allocated,
418 $form->{"unit_$i"}, conv_date($form->{deliverydate}),
419 conv_i($form->{"project_id_$i"}), $form->{"serialnumber_$i"},
420 conv_i($form->{"price_factor_id_$i"}), conv_i($form->{"price_factor_id_$i"}), conv_i($form->{"marge_price_factor_$i"}),
421 $form->{"active_price_source_$i"}, $form->{"active_discount_source_$i"},
422 conv_i($form->{"invoice_id_$i"}));
423 do_query($form, $dbh, $query, @values);
424 push @processed_invoice_ids, $form->{"invoice_id_$i"};
426 CVar->save_custom_variables(module => 'IC',
427 sub_module => 'invoice',
428 trans_id => $form->{"invoice_id_$i"},
429 configs => $ic_cvar_configs,
431 name_prefix => 'ic_',
432 name_postfix => "_$i",
435 # link previous items with invoice items See IS.pm (no credit note -> no invoice item)
436 foreach (qw(delivery_order_items orderitems invoice)) {
437 if (!$form->{useasnew} && $form->{"converted_from_${_}_id_$i"}) {
438 RecordLinks->create_links('dbh' => $dbh,
441 'from_ids' => $form->{"converted_from_${_}_id_$i"},
442 'to_table' => 'invoice',
443 'to_id' => $form->{"invoice_id_$i"},
446 delete $form->{"converted_from_${_}_id_$i"};
450 $h_item_unit->finish();
452 $project_id = conv_i($form->{"globalproject_id"});
454 $form->{datepaid} = $form->{invdate};
456 # all amounts are in natural state, netamount includes the taxes
457 # if tax is included, netamount is rounded to 2 decimal places,
461 for my $i (1 .. $form->{paidaccounts}) {
462 $form->{"paid_$i"} = $form->parse_amount($myconfig, $form->{"paid_$i"});
463 $form->{paid} += $form->{"paid_$i"};
464 $form->{datepaid} = $form->{"datepaid_$i"} if $form->{"datepaid_$i"};
467 my ($tax, $paiddiff) = (0, 0);
469 $netamount = $form->round_amount($netamount, 2);
471 # figure out rounding errors for amount paid and total amount
472 if ($form->{taxincluded}) {
474 $amount = $form->round_amount($netamount * $form->{exchangerate}, 2);
475 $paiddiff = $amount - $netamount * $form->{exchangerate};
476 $netamount = $amount;
478 foreach $item (split / /, $form->{taxaccounts}) {
479 $amount = $form->{amount}{ $form->{id} }{$item} * $form->{exchangerate};
480 $form->{amount}{ $form->{id} }{$item} = $form->round_amount($amount, 2);
482 $amount = $form->{amount}{ $form->{id} }{$item} * -1;
484 $netamount -= $amount;
487 $invoicediff += $paiddiff;
488 $expensediff += $paiddiff;
490 ######## this only applies to tax included
492 # in the sales invoice case rounding errors only have to be corrected for
493 # income accounts, it is enough to add the total rounding error to one of
494 # the income accounts, with the one assigned to the last row being used
495 # (lastinventoryaccno)
497 # in the purchase invoice case rounding errors may be split between
498 # inventory accounts and expense accounts. After rounding, an error of 1
499 # cent is introduced if the total rounding error exceeds 0.005. The total
500 # error is made up of $invoicediff and $expensediff, however, so if both
501 # values are below 0.005, but add up to a total >= 0.005, correcting
502 # lastinventoryaccno and lastexpenseaccno separately has no effect after
503 # rounding. This caused bug 1579. Therefore when the combined total exceeds
504 # 0.005, but neither do individually, the account with the larger value
505 # shall receive the total rounding error, and the next time it is rounded
506 # the 1 cent correction will be introduced.
508 $form->{amount}{ $form->{id} }{$lastinventoryaccno} -= $invoicediff if $lastinventoryaccno;
509 $form->{amount}{ $form->{id} }{$lastexpenseaccno} -= $expensediff if $lastexpenseaccno;
511 if ( (abs($expensediff)+abs($invoicediff)) >= 0.005 and abs($expensediff) < 0.005 and abs($invoicediff) < 0.005 ) {
513 # in total the rounding error adds up to 1 cent effectively, correct the
514 # larger of the two numbers
516 if ( abs($form->{amount}{ $form->{id} }{$lastinventoryaccno}) > abs($form->{amount}{ $form->{id} }{$lastexpenseaccno}) ) {
517 # $invoicediff has already been deducted, now also deduct expensediff
518 $form->{amount}{ $form->{id} }{$lastinventoryaccno} -= $expensediff;
520 # expensediff has already been deducted, now also deduct invoicediff
521 $form->{amount}{ $form->{id} }{$lastexpenseaccno} -= $invoicediff;
526 $amount = $form->round_amount($netamount * $form->{exchangerate}, 2);
527 $paiddiff = $amount - $netamount * $form->{exchangerate};
528 $netamount = $amount;
530 foreach my $item (split / /, $form->{taxaccounts}) {
531 $form->{amount}{ $form->{id} }{$item} = $form->round_amount($form->{amount}{ $form->{id} }{$item}, 2);
532 $amount = $form->round_amount( $form->{amount}{ $form->{id} }{$item} * $form->{exchangerate} * -1, 2);
533 $paiddiff += $amount - $form->{amount}{ $form->{id} }{$item} * $form->{exchangerate} * -1;
534 $form->{amount}{ $form->{id} }{$item} = $form->round_amount($amount * -1, 2);
535 $amount = $form->{amount}{ $form->{id} }{$item} * -1;
540 $form->{amount}{ $form->{id} }{ $form->{AP} } = $netamount + $tax;
543 $form->{paid} = $form->round_amount($form->{paid} * $form->{exchangerate} + $paiddiff, 2) if $form->{paid} != 0;
545 # update exchangerate
547 $form->update_exchangerate($dbh, $form->{currency}, $form->{invdate}, 0, $form->{exchangerate})
548 if ($form->{currency} ne $defaultcurrency) && !$exchangerate;
550 # record acc_trans transactions
551 foreach my $trans_id (keys %{ $form->{amount} }) {
552 foreach my $accno (keys %{ $form->{amount}{$trans_id} }) {
553 $form->{amount}{$trans_id}{$accno} = $form->round_amount($form->{amount}{$trans_id}{$accno}, 2);
556 next if $payments_only || !$form->{amount}{$trans_id}{$accno};
558 $query = qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate, taxkey, project_id, tax_id, chart_link)
559 VALUES (?, (SELECT id FROM chart WHERE accno = ?), ?, ?,
562 WHERE chart_id= (SELECT id
566 ORDER BY startdate DESC LIMIT 1),
570 WHERE chart_id= (SELECT id
574 ORDER BY startdate DESC LIMIT 1),
575 (SELECT link FROM chart WHERE accno = ?))|;
576 @values = ($trans_id, $accno, $form->{amount}{$trans_id}{$accno},
577 conv_date($form->{invdate}), $accno, conv_date($form->{invdate}), $project_id, $accno, conv_date($form->{invdate}), $accno);
578 do_query($form, $dbh, $query, @values);
582 # deduct payment differences from paiddiff
583 for my $i (1 .. $form->{paidaccounts}) {
584 if ($form->{"paid_$i"} != 0) {
585 $amount = $form->round_amount($form->{"paid_$i"} * $form->{exchangerate}, 2);
586 $paiddiff -= $amount - $form->{"paid_$i"} * $form->{exchangerate};
590 # force AP entry if 0
592 $form->{amount}{ $form->{id} }{ $form->{AP} } = $form->{paid} if $form->{amount}{$form->{id}}{$form->{AP}} == 0;
594 # record payments and offsetting AP
595 for my $i (1 .. $form->{paidaccounts}) {
596 if ($form->{"acc_trans_id_$i"}
598 && (SL::DB::Default->get->payments_changeable == 0)) {
602 next if $form->{"paid_$i"} == 0;
604 my ($accno) = split /--/, $form->{"AP_paid_$i"};
605 $form->{"datepaid_$i"} = $form->{invdate} unless ($form->{"datepaid_$i"});
606 $form->{datepaid} = $form->{"datepaid_$i"};
608 $amount = $form->round_amount($form->{"paid_$i"} * $form->{exchangerate} + $paiddiff, 2) * -1;
611 if ($form->{amount}{ $form->{id} }{ $form->{AP} } != 0) {
612 $query = qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate, taxkey, project_id, tax_id, chart_link)
613 VALUES (?, (SELECT id FROM chart WHERE accno = ?), ?, ?,
616 WHERE chart_id= (SELECT id
620 ORDER BY startdate DESC LIMIT 1),
624 WHERE chart_id= (SELECT id
628 ORDER BY startdate DESC LIMIT 1),
629 (SELECT link FROM chart WHERE accno = ?))|;
630 @values = (conv_i($form->{id}), $form->{AP}, $amount,
631 $form->{"datepaid_$i"}, $form->{AP}, conv_date($form->{"datepaid_$i"}), $project_id, $form->{AP}, conv_date($form->{"datepaid_$i"}), $form->{AP});
632 do_query($form, $dbh, $query, @values);
636 my $gldate = (conv_date($form->{"gldate_$i"}))? conv_date($form->{"gldate_$i"}) : conv_date($form->current_date($myconfig));
639 qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate, gldate, source, memo, taxkey, project_id, tax_id, chart_link)
640 VALUES (?, (SELECT id FROM chart WHERE accno = ?), ?, ?, ?, ?, ?,
643 WHERE chart_id= (SELECT id
644 FROM chart WHERE accno = ?)
646 ORDER BY startdate DESC LIMIT 1),
650 WHERE chart_id= (SELECT id
651 FROM chart WHERE accno = ?)
653 ORDER BY startdate DESC LIMIT 1),
654 (SELECT link FROM chart WHERE accno = ?))|;
655 @values = (conv_i($form->{id}), $accno, $form->{"paid_$i"}, $form->{"datepaid_$i"},
656 $gldate, $form->{"source_$i"}, $form->{"memo_$i"}, $accno, conv_date($form->{"datepaid_$i"}), $project_id, $accno, conv_date($form->{"datepaid_$i"}), $accno);
657 do_query($form, $dbh, $query, @values);
661 if ($form->{currency} eq $defaultcurrency) {
662 $form->{"exchangerate_$i"} = 1;
664 $exchangerate = $form->check_exchangerate($myconfig, $form->{currency}, $form->{"datepaid_$i"}, 'sell');
665 $form->{"exchangerate_$i"} = $exchangerate || $form->parse_amount($myconfig, $form->{"exchangerate_$i"});
668 # exchangerate difference
669 $form->{fx}{$accno}{ $form->{"datepaid_$i"} } += $form->{"paid_$i"} * ($form->{"exchangerate_$i"} - 1) + $paiddiff;
673 ($form->{"paid_$i"} * $form->{exchangerate}) -
674 ($form->{"paid_$i"} * $form->{"exchangerate_$i"});
676 $form->{fx}{ $form->{fxgain_accno} }{ $form->{"datepaid_$i"} } += $amount;
678 $form->{fx}{ $form->{fxloss_accno} }{ $form->{"datepaid_$i"} } += $amount;
683 # update exchange rate
684 $form->update_exchangerate($dbh, $form->{currency}, $form->{"datepaid_$i"}, 0, $form->{"exchangerate_$i"})
685 if ($form->{currency} ne $defaultcurrency) && !$exchangerate;
688 # record exchange rate differences and gains/losses
689 foreach my $accno (keys %{ $form->{fx} }) {
690 foreach my $transdate (keys %{ $form->{fx}{$accno} }) {
691 $form->{fx}{$accno}{$transdate} = $form->round_amount($form->{fx}{$accno}{$transdate}, 2);
692 next if ($form->{fx}{$accno}{$transdate} == 0);
694 $query = qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate, cleared, fx_transaction, taxkey, project_id, tax_id, chart_link)
695 VALUES (?, (SELECT id FROM chart WHERE accno = ?), ?, ?, '0', '1', 0, ?,
696 (SELECT id FROM tax WHERE taxkey=0 LIMIT 1),
697 (SELECT link FROM chart WHERE accno = ?))|;
698 @values = (conv_i($form->{id}), $accno, $form->{fx}{$accno}{$transdate}, conv_date($transdate), $project_id, $accno);
699 do_query($form, $dbh, $query, @values);
703 IO->set_datepaid(table => 'ap', id => $form->{id}, dbh => $dbh);
705 if ($payments_only) {
706 $query = qq|UPDATE ap SET paid = ? WHERE id = ?|;
707 do_query($form, $dbh, $query, $form->{paid}, conv_i($form->{id}));
708 $form->new_lastmtime('ap');
713 $amount = $netamount + $tax;
715 # set values which could be empty
716 my $taxzone_id = $form->{taxzone_id} * 1;
717 $taxzone_id = SL::DB::Manager::TaxZone->get_default->id unless SL::DB::Manager::TaxZone->find_by(id => $taxzone_id);
719 $form->{invnumber} = $form->{id} unless $form->{invnumber};
722 $query = qq|UPDATE ap SET
723 invnumber = ?, ordnumber = ?, quonumber = ?, transdate = ?,
724 orddate = ?, quodate = ?, vendor_id = ?, amount = ?,
725 netamount = ?, paid = ?, duedate = ?,
726 invoice = ?, taxzone_id = ?, notes = ?, taxincluded = ?,
727 intnotes = ?, storno_id = ?, storno = ?,
728 cp_id = ?, employee_id = ?, department_id = ?, delivery_term_id = ?,
729 currency_id = (SELECT id FROM currencies WHERE name = ?),
730 globalproject_id = ?, direct_debit = ?
733 $form->{invnumber}, $form->{ordnumber}, $form->{quonumber}, conv_date($form->{invdate}),
734 conv_date($form->{orddate}), conv_date($form->{quodate}), conv_i($form->{vendor_id}), $amount,
735 $netamount, $form->{paid}, conv_date($form->{duedate}),
736 '1', $taxzone_id, $restricter->process($form->{notes}), $form->{taxincluded} ? 't' : 'f',
737 $form->{intnotes}, conv_i($form->{storno_id}), $form->{storno} ? 't' : 'f',
738 conv_i($form->{cp_id}), conv_i($form->{employee_id}), conv_i($form->{department_id}), conv_i($form->{delivery_term_id}),
740 conv_i($form->{globalproject_id}),
741 $form->{direct_debit} ? 't' : 'f',
744 do_query($form, $dbh, $query, @values);
746 if ($form->{storno}) {
747 $query = qq|UPDATE ap SET paid = paid + amount WHERE id = ?|;
748 do_query($form, $dbh, $query, conv_i($form->{storno_id}));
750 $query = qq|UPDATE ap SET storno = 't' WHERE id = ?|;
751 do_query($form, $dbh, $query, conv_i($form->{storno_id}));
753 $query = qq!UPDATE ap SET intnotes = ? || intnotes WHERE id = ?!;
754 do_query($form, $dbh, $query, "Rechnung storniert am $form->{invdate} ", conv_i($form->{storno_id}));
756 $query = qq|UPDATE ap SET paid = amount WHERE id = ?|;
757 do_query($form, $dbh, $query, conv_i($form->{id}));
760 $form->new_lastmtime('ap');
762 $form->{name} = $form->{vendor};
763 $form->{name} =~ s/--\Q$form->{vendor_id}\E//;
766 $form->add_shipto($dbh, $form->{id}, "AP");
768 # delete zero entries
769 do_query($form, $dbh, qq|DELETE FROM acc_trans WHERE amount = 0|);
771 Common::webdav_folder($form);
773 # Link this record to the records it was created from order or invoice (storno)
774 foreach (qw(oe ap)) {
775 if ($form->{"convert_from_${_}_ids"}) {
776 RecordLinks->create_links('dbh' => $dbh,
779 'from_ids' => $form->{"convert_from_${_}_ids"},
781 'to_id' => $form->{id},
783 delete $form->{"convert_from_${_}_ids"};
787 my @convert_from_do_ids = map { $_ * 1 } grep { $_ } split m/\s+/, $form->{convert_from_do_ids};
788 if (scalar @convert_from_do_ids) {
789 DO->close_orders('dbh' => $dbh,
790 'ids' => \@convert_from_do_ids);
792 RecordLinks->create_links('dbh' => $dbh,
794 'from_table' => 'delivery_orders',
795 'from_ids' => \@convert_from_do_ids,
797 'to_id' => $form->{id},
800 delete $form->{convert_from_do_ids};
802 ARAP->close_orders_if_billed('dbh' => $dbh,
803 'arap_id' => $form->{id},
806 # search for orphaned invoice items
807 $query = sprintf 'SELECT id FROM invoice WHERE trans_id = ? AND NOT id IN (%s)', join ', ', ("?") x scalar @processed_invoice_ids;
808 @values = (conv_i($form->{id}), map { conv_i($_) } @processed_invoice_ids);
809 my @orphaned_ids = map { $_->{id} } selectall_hashref_query($form, $dbh, $query, @values);
810 if (scalar @orphaned_ids) {
811 # clean up invoice items
812 $query = sprintf 'DELETE FROM invoice WHERE id IN (%s)', join ', ', ("?") x scalar @orphaned_ids;
813 do_query($form, $dbh, $query, @orphaned_ids);
816 if ($form->{draft_id}) {
817 SL::DB::Manager::Draft->delete_all(where => [ id => delete($form->{draft_id}) ]);
820 # safety check datev export
821 if ($::instance_conf->get_datev_check_on_purchase_invoice) {
823 my $datev = SL::DATEV->new(
825 trans_id => $form->{id},
828 $datev->generate_datev_data;
830 if ($datev->errors) {
831 die join "\n", $::locale->text('DATEV check returned errors:'), $datev->errors;
838 sub reverse_invoice {
839 $main::lxdebug->enter_sub();
841 my ($dbh, $form) = @_;
843 # reverse inventory items
845 qq|SELECT i.parts_id, p.part_type, i.qty, i.allocated, i.sellprice
846 FROM invoice i, parts p
847 WHERE (i.parts_id = p.id)
848 AND (i.trans_id = ?)|;
849 my $sth = prepare_execute_query($form, $dbh, $query, conv_i($form->{id}));
853 while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
854 $netamount += $form->round_amount($ref->{sellprice} * $ref->{qty} * -1, 2);
856 next unless $ref->{part_type} eq 'part';
858 # if $ref->{allocated} > 0 than we sold that many items
859 next if ($ref->{allocated} <= 0);
861 # get references for sold items
863 qq|SELECT i.id, i.trans_id, i.allocated, a.transdate
865 WHERE (i.parts_id = ?)
866 AND (i.allocated < 0)
867 AND (i.trans_id = a.id)
868 ORDER BY transdate DESC|;
869 my $sth2 = prepare_execute_query($form, $dbh, $query, $ref->{parts_id});
871 while (my $pthref = $sth2->fetchrow_hashref("NAME_lc")) {
872 my $qty = $ref->{allocated};
873 if (($ref->{allocated} + $pthref->{allocated}) > 0) {
874 $qty = $pthref->{allocated} * -1;
877 my $amount = $form->round_amount($ref->{sellprice} * $qty, 2);
880 $form->update_balance($dbh, "invoice", "allocated", qq|id = $pthref->{id}|, $qty);
882 if ( $::instance_conf->get_inventory_system eq 'perpetual' ) {
884 $form->update_balance($dbh, "acc_trans", "amount",
885 qq| (trans_id = $pthref->{trans_id})
886 AND (chart_id = $ref->{expense_accno_id})
887 AND (transdate = '$pthref->{transdate}')|,
890 $form->update_balance($dbh, "acc_trans", "amount",
891 qq| (trans_id = $pthref->{trans_id})
892 AND (chart_id = $ref->{inventory_accno_id})
893 AND (transdate = '$pthref->{transdate}')|,
897 last if (($ref->{allocated} -= $qty) <= 0);
903 my $id = conv_i($form->{id});
906 $query = qq|DELETE FROM acc_trans WHERE trans_id = ?|;
907 do_query($form, $dbh, $query, $id);
909 $query = qq|DELETE FROM shipto WHERE (trans_id = ?) AND (module = 'AP')|;
910 do_query($form, $dbh, $query, $id);
912 $main::lxdebug->leave_sub();
916 $main::lxdebug->enter_sub();
918 my ($self, $myconfig, $form) = @_;
920 # connect to database
921 my $dbh = SL::DB->client->dbh;
923 SL::DB->client->with_transaction(sub{
925 &reverse_invoice($dbh, $form);
927 my @values = (conv_i($form->{id}));
929 # delete zero entries
930 # wtf? use case for this?
931 $query = qq|DELETE FROM acc_trans WHERE amount = 0|;
932 do_query($form, $dbh, $query);
936 qq|DELETE FROM invoice WHERE trans_id = ?|,
937 qq|DELETE FROM ap WHERE id = ?|,
940 map { do_query($form, $dbh, $_, @values) } @queries;
942 }) or do { die SL::DB->client->error };
947 sub retrieve_invoice {
948 $main::lxdebug->enter_sub();
950 my ($self, $myconfig, $form) = @_;
952 # connect to database
953 my $dbh = SL::DB->client->dbh;
955 my ($query, $sth, $ref, $q_invdate);
958 $q_invdate = qq|, COALESCE((SELECT transdate FROM ar WHERE id = (SELECT MAX(id) FROM ar)), current_date) AS invdate|;
959 if ($form->{vendor_id}) {
960 my $vendor_id = $dbh->quote($form->{vendor_id} * 1);
962 qq|, COALESCE((SELECT transdate FROM ar WHERE id = (SELECT MAX(id) FROM ar)), current_date) +
963 COALESCE((SELECT pt.terms_netto
965 LEFT JOIN payment_terms pt ON (v.payment_id = pt.id)
966 WHERE v.id = $vendor_id),
971 # get default accounts and last invoice number
974 (SELECT c.accno FROM chart c WHERE d.inventory_accno_id = c.id) AS inventory_accno,
975 (SELECT c.accno FROM chart c WHERE d.income_accno_id = c.id) AS income_accno,
976 (SELECT c.accno FROM chart c WHERE d.expense_accno_id = c.id) AS expense_accno,
977 (SELECT c.accno FROM chart c WHERE d.fxgain_accno_id = c.id) AS fxgain_accno,
978 (SELECT c.accno FROM chart c WHERE d.fxloss_accno_id = c.id) AS fxloss_accno
981 $ref = selectfirst_hashref_query($form, $dbh, $query);
982 map { $form->{$_} = $ref->{$_} } keys %$ref;
985 $main::lxdebug->leave_sub();
991 $query = qq|SELECT cp_id, invnumber, transdate AS invdate, duedate,
992 orddate, quodate, globalproject_id,
993 ordnumber, quonumber, paid, taxincluded, notes, taxzone_id, storno, gldate,
995 intnotes, (SELECT cu.name FROM currencies cu WHERE cu.id=ap.currency_id) AS currency, direct_debit,
999 $ref = selectfirst_hashref_query($form, $dbh, $query, conv_i($form->{id}));
1000 map { $form->{$_} = $ref->{$_} } keys %$ref;
1001 $form->{mtime} = $form->{itime} if !$form->{mtime};
1002 $form->{lastmtime} = $form->{mtime};
1004 $form->{exchangerate} = $form->get_exchangerate($dbh, $form->{currency}, $form->{invdate}, "sell");
1007 $query = qq|SELECT * FROM shipto WHERE (trans_id = ?) AND (module = 'AP')|;
1008 $ref = selectfirst_hashref_query($form, $dbh, $query, conv_i($form->{id}));
1010 map { $form->{$_} = $ref->{$_} } keys %$ref;
1012 my $transdate = $form->{invdate} ? $dbh->quote($form->{invdate}) : "current_date";
1014 my $taxzone_id = $form->{taxzone_id} * 1;
1015 $taxzone_id = SL::DB::Manager::TaxZone->get_default->id unless SL::DB::Manager::TaxZone->find_by(id => $taxzone_id);
1017 # retrieve individual items
1020 c1.accno AS inventory_accno, c1.new_chart_id AS inventory_new_chart, date($transdate) - c1.valid_from AS inventory_valid,
1021 c2.accno AS income_accno, c2.new_chart_id AS income_new_chart, date($transdate) - c2.valid_from AS income_valid,
1022 c3.accno AS expense_accno, c3.new_chart_id AS expense_new_chart, date($transdate) - c3.valid_from AS expense_valid,
1025 i.description, i.longdescription, i.qty, i.fxsellprice AS sellprice, i.parts_id AS id, i.unit, i.deliverydate, i.project_id, i.serialnumber,
1026 i.price_factor_id, i.price_factor, i.marge_price_factor, i.discount, i.active_price_source, i.active_discount_source,
1027 p.partnumber, p.part_type, pr.projectnumber, pg.partsgroup
1028 ,p.classification_id
1031 JOIN parts p ON (i.parts_id = p.id)
1032 LEFT JOIN chart c1 ON ((SELECT inventory_accno_id FROM buchungsgruppen WHERE id = p.buchungsgruppen_id) = c1.id)
1033 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)
1034 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)
1035 LEFT JOIN project pr ON (i.project_id = pr.id)
1036 LEFT JOIN partsgroup pg ON (pg.id = p.partsgroup_id)
1038 WHERE i.trans_id = ?
1040 ORDER BY i.position|;
1041 $sth = prepare_execute_query($form, $dbh, $query, conv_i($form->{id}));
1043 while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
1044 # Retrieve custom variables.
1045 my $cvars = CVar->get_custom_variables(dbh => $dbh,
1047 sub_module => 'invoice',
1048 trans_id => $ref->{invoice_id},
1050 map { $ref->{"ic_cvar_$_->{name}"} = $_->{value} } @{ $cvars };
1052 map({ delete($ref->{$_}); } qw(inventory_accno inventory_new_chart inventory_valid)) if !$ref->{"part_type"} eq 'part';
1054 foreach my $type (qw(inventory income expense)) {
1055 while ($ref->{"${type}_new_chart"} && ($ref->{"${type}_valid"} >=0)) {
1056 my $query = qq|SELECT accno, new_chart_id, date($transdate) - valid_from FROM chart WHERE id = ?|;
1057 @$ref{ map $type.$_, qw(_accno _new_chart _valid) } = selectrow_query($form, $dbh, $query, $ref->{"${type}_new_chart"});
1061 # get tax rates and description
1062 my $accno_id = ($form->{vc} eq "customer") ? $ref->{income_accno} : $ref->{expense_accno};
1064 qq|SELECT c.accno, t.taxdescription, t.rate, t.taxnumber FROM tax t
1065 LEFT JOIN chart c ON (c.id = t.chart_id)
1067 (SELECT tk.tax_id FROM taxkeys tk
1068 WHERE tk.chart_id = (SELECT id FROM chart WHERE accno = ?)
1069 AND (startdate <= $transdate)
1070 ORDER BY startdate DESC
1073 my $stw = prepare_execute_query($form, $dbh, $query, $accno_id);
1074 $ref->{taxaccounts} = "";
1077 while (my $ptr = $stw->fetchrow_hashref("NAME_lc")) {
1078 if (($ptr->{accno} eq "") && ($ptr->{rate} == 0)) {
1083 $ref->{taxaccounts} .= "$ptr->{accno} ";
1085 if (!($form->{taxaccounts} =~ /\Q$ptr->{accno}\E/)) {
1086 $form->{"$ptr->{accno}_rate"} = $ptr->{rate};
1087 $form->{"$ptr->{accno}_description"} = $ptr->{taxdescription};
1088 $form->{"$ptr->{accno}_taxnumber"} = $ptr->{taxnumber};
1089 $form->{taxaccounts} .= "$ptr->{accno} ";
1094 chop $ref->{taxaccounts};
1095 push @{ $form->{invoice_details} }, $ref;
1100 Common::webdav_folder($form);
1102 $main::lxdebug->leave_sub();
1106 $main::lxdebug->enter_sub();
1108 my ($self, $myconfig, $form, $params) = @_;
1110 $params = $form unless defined $params && ref $params eq "HASH";
1112 # connect to database
1113 my $dbh = SL::DB->client->dbh;
1115 my $dateformat = $myconfig->{dateformat};
1116 $dateformat .= "yy" if $myconfig->{dateformat} !~ /^y/;
1118 my $vid = conv_i($params->{vendor_id});
1119 my $vnr = conv_i($params->{vendornumber});
1122 ($params->{invdate})
1123 ? "to_date(" . $dbh->quote($params->{invdate}) . ", '$dateformat')"
1130 $where .= 'AND v.id = ?';
1134 $where .= 'AND v.vendornumber = ?';
1139 v.id AS vendor_id, v.name AS vendor, v.discount as vendor_discount,
1140 v.creditlimit, v.notes AS intnotes,
1141 v.email, v.cc, v.bcc, v.language_id, v.payment_id, v.delivery_term_id,
1142 v.street, v.zipcode, v.city, v.country, v.taxzone_id, cu.name AS curr, v.direct_debit,
1143 $duedate + COALESCE(pt.terms_netto, 0) AS duedate,
1144 b.discount AS tradediscount, b.description AS business
1146 LEFT JOIN business b ON (b.id = v.business_id)
1147 LEFT JOIN payment_terms pt ON (v.payment_id = pt.id)
1148 LEFT JOIN currencies cu ON (v.currency_id = cu.id)
1150 my $ref = selectfirst_hashref_query($form, $dbh, $query, @values);
1151 map { $params->{$_} = $ref->{$_} } keys %$ref;
1153 # use vendor currency
1154 $form->{currency} = $form->{curr};
1156 $params->{creditremaining} = $params->{creditlimit};
1158 $query = qq|SELECT SUM(amount - paid) FROM ap WHERE vendor_id = ?|;
1159 my ($unpaid_invoices) = selectfirst_array_query($form, $dbh, $query, $vid);
1160 $params->{creditremaining} -= $unpaid_invoices;
1162 $query = qq|SELECT o.amount,
1165 WHERE (e.currency_id = o.currency_id)
1166 AND (e.transdate = o.transdate)) AS exch
1168 WHERE (o.vendor_id = ?) AND (o.quotation = '0') AND (o.closed = '0')|;
1169 my $sth = prepare_execute_query($form, $dbh, $query, $vid);
1170 while (my ($amount, $exch) = $sth->fetchrow_array()) {
1171 $exch = 1 unless $exch;
1172 $params->{creditremaining} -= $amount * $exch;
1176 $main::lxdebug->leave_sub();
1180 $main::lxdebug->enter_sub();
1182 my ($self, $myconfig, $form) = @_;
1184 my $dbh = SL::DB->client->dbh;
1186 my $i = $form->{rowcount};
1188 # don't include assemblies or obsolete parts
1189 my $where = "NOT p.part_type = 'assembly' AND NOT p.obsolete = '1'";
1192 foreach my $table_column (qw(p.partnumber p.description pg.partsgroup)) {
1193 my $field = (split m{\.}, $table_column)[1];
1194 next unless $form->{"${field}_${i}"};
1195 $where .= " AND lower(${table_column}) LIKE lower(?)";
1196 push @values, like($form->{"${field}_${i}"});
1200 if ($form->{"partnumber_$i"} && !$form->{"description_$i"}) {
1201 $where .= qq| OR (NOT p.obsolete = '1' AND p.ean = ? )|;
1202 push @values, $form->{"partnumber_$i"};
1204 # also search hits in makemodels, but only cache the results by id and merge later
1206 SELECT parts_id, model FROM makemodel
1207 LEFT JOIN parts ON parts.id = parts_id
1208 WHERE NOT parts.obsolete AND model ILIKE ? AND (make IS NULL OR make = ?);
1210 my $mm_results = selectall_hashref_query($::form, $dbh, $mm_query, like($form->{"partnumber_$i"}), $::form->{vendor_id});
1211 my @mm_ids = map { $_->{parts_id} } @$mm_results;
1212 push @{$mm_by_id{ $_->{parts_id} } ||= []}, $_ for @$mm_results;
1215 $where .= qq| OR p.id IN (| . join(',', ('?') x @mm_ids) . qq|)|;
1216 push @values, @mm_ids;
1220 # Search for part ID overrides all other criteria.
1221 if ($form->{"id_${i}"}) {
1222 $where = qq|p.id = ?|;
1223 @values = ($form->{"id_${i}"});
1226 if ($form->{"description_$i"}) {
1227 $where .= " ORDER BY p.description";
1229 $where .= " ORDER BY p.partnumber";
1233 if ($form->{type} eq "invoice") {
1234 $transdate = $form->{deliverydate} ? $dbh->quote($form->{deliverydate})
1235 : $form->{invdate} ? $dbh->quote($form->{invdate})
1238 $transdate = $form->{transdate} ? $dbh->quote($form->{transdate}) : "current_date";
1241 my $taxzone_id = $form->{taxzone_id} * 1;
1242 $taxzone_id = SL::DB::Manager::TaxZone->get_default->id unless SL::DB::Manager::TaxZone->find_by(id => $taxzone_id);
1246 p.id, p.partnumber, p.description, p.lastcost AS sellprice, p.listprice,
1247 p.unit, p.part_type, p.onhand, p.formel,
1248 p.notes AS partnotes, p.notes AS longdescription, p.not_discountable,
1251 p.classification_id,
1253 pfac.factor AS price_factor,
1255 c1.accno AS inventory_accno,
1256 c1.new_chart_id AS inventory_new_chart,
1257 date($transdate) - c1.valid_from AS inventory_valid,
1259 c2.accno AS income_accno,
1260 c2.new_chart_id AS income_new_chart,
1261 date($transdate) - c2.valid_from AS income_valid,
1263 c3.accno AS expense_accno,
1264 c3.new_chart_id AS expense_new_chart,
1265 date($transdate) - c3.valid_from AS expense_valid,
1267 pt.used_for_purchase AS used_for_purchase,
1271 LEFT JOIN chart c1 ON
1272 ((SELECT inventory_accno_id
1273 FROM buchungsgruppen
1274 WHERE id = p.buchungsgruppen_id) = c1.id)
1275 LEFT JOIN chart c2 ON
1276 ((SELECT tc.income_accno_id
1277 FROM taxzone_charts tc
1278 WHERE tc.taxzone_id = '$taxzone_id' and tc.buchungsgruppen_id = p.buchungsgruppen_id) = c2.id)
1279 LEFT JOIN chart c3 ON
1280 ((SELECT tc.expense_accno_id
1281 FROM taxzone_charts tc
1282 WHERE tc.taxzone_id = '$taxzone_id' and tc.buchungsgruppen_id = p.buchungsgruppen_id) = c3.id)
1283 LEFT JOIN partsgroup pg ON (pg.id = p.partsgroup_id)
1284 LEFT JOIN part_classifications pt ON (pt.id = p.classification_id)
1285 LEFT JOIN price_factors pfac ON (pfac.id = p.price_factor_id)
1287 my $sth = prepare_execute_query($form, $dbh, $query, @values);
1289 my @translation_queries = ( [ qq|SELECT tr.translation, tr.longdescription
1291 WHERE tr.language_id = ? AND tr.parts_id = ?| ],
1292 [ qq|SELECT tr.translation, tr.longdescription
1294 WHERE tr.language_id IN
1297 WHERE article_code = (SELECT article_code FROM language WHERE id = ?))
1300 map { push @{ $_ }, prepare_query($form, $dbh, $_->[0]) } @translation_queries;
1302 $form->{item_list} = [];
1303 my $has_wrong_pclass = PCLASS_OK;
1304 while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
1306 if ($mm_by_id{$ref->{id}}) {
1307 $ref->{makemodels} = $mm_by_id{$ref->{id}};
1308 push @{ $ref->{matches} ||= [] }, $::locale->text('Model') . ': ' . join ', ', map { $_->{model} } @{ $mm_by_id{$ref->{id}} };
1311 if (($::form->{"partnumber_$i"} ne '') && ($ref->{ean} eq $::form->{"partnumber_$i"})) {
1312 push @{ $ref->{matches} ||= [] }, $::locale->text('EAN') . ': ' . $ref->{ean};
1314 $ref->{type_and_classific} = type_abbreviation($ref->{part_type}) .
1315 classification_abbreviation($ref->{classification_id});
1317 if (! $ref->{used_for_purchase} ) {
1318 $has_wrong_pclass = PCLASS_NOTFORPURCHASE;
1321 # In der Buchungsgruppe ist immer ein Bestandskonto verknuepft, auch wenn
1322 # es sich um eine Dienstleistung handelt. Bei Dienstleistungen muss das
1323 # Buchungskonto also aus dem Ergebnis rausgenommen werden.
1324 if (!$ref->{inventory_accno_id}) {
1325 map({ delete($ref->{"inventory_${_}"}); } qw(accno new_chart valid));
1327 delete($ref->{inventory_accno_id});
1329 # get tax rates and description
1330 my $accno_id = ($form->{vc} eq "customer") ? $ref->{income_accno} : $ref->{expense_accno};
1332 qq|SELECT c.accno, t.taxdescription, t.rate, t.taxnumber
1334 LEFT JOIN chart c on (c.id = t.chart_id)
1342 AND (startdate <= $transdate)
1343 ORDER BY startdate DESC
1346 my $stw = prepare_execute_query($form, $dbh, $query, $accno_id);
1348 $ref->{taxaccounts} = "";
1350 while (my $ptr = $stw->fetchrow_hashref("NAME_lc")) {
1352 if (($ptr->{accno} eq "") && ($ptr->{rate} == 0)) {
1357 $ref->{taxaccounts} .= "$ptr->{accno} ";
1359 if (!($form->{taxaccounts} =~ /\Q$ptr->{accno}\E/)) {
1360 $form->{"$ptr->{accno}_rate"} = $ptr->{rate};
1361 $form->{"$ptr->{accno}_description"} = $ptr->{taxdescription};
1362 $form->{"$ptr->{accno}_taxnumber"} = $ptr->{taxnumber};
1363 $form->{taxaccounts} .= "$ptr->{accno} ";
1366 if ($form->{language_id}) {
1367 for my $spec (@translation_queries) {
1368 do_statement($form, $spec->[1], $spec->[0], conv_i($form->{language_id}), conv_i($ref->{id}));
1369 my ($translation, $longdescription) = $spec->[1]->fetchrow_array;
1370 next unless $translation;
1371 $ref->{description} = $translation;
1372 $ref->{longdescription} = $longdescription;
1379 chop $ref->{taxaccounts};
1381 $ref->{onhand} *= 1;
1382 push @{ $form->{item_list} }, $ref;
1387 $_->[1]->finish for @translation_queries;
1389 $form->{is_wrong_pclass} = $has_wrong_pclass;
1390 $form->{NOTFORSALE} = PCLASS_NOTFORSALE;
1391 $form->{NOTFORPURCHASE} = PCLASS_NOTFORPURCHASE;
1392 foreach my $item (@{ $form->{item_list} }) {
1393 my $custom_variables = CVar->get_custom_variables(module => 'IC',
1394 trans_id => $item->{id},
1397 $form->{is_wrong_pclass} = PCLASS_OK; # one correct type
1398 map { $item->{"ic_cvar_" . $_->{name} } = $_->{value} } @{ $custom_variables };
1401 $main::lxdebug->leave_sub();
1404 sub vendor_details {
1405 $main::lxdebug->enter_sub();
1407 my ($self, $myconfig, $form, @wanted_vars) = @_;
1409 my $dbh = SL::DB->client->dbh;
1413 # get contact id, set it if nessessary
1414 $form->{cp_id} *= 1;
1416 if ($form->{cp_id}) {
1417 $contact = "AND cp.cp_id = ?";
1418 push @values, $form->{cp_id};
1421 # get rest for the vendor
1422 # fax and phone and email as vendor*
1424 qq|SELECT ct.*, cp.*, ct.notes as vendornotes, phone as vendorphone, fax as vendorfax, email as vendoremail,
1427 LEFT JOIN contacts cp ON (ct.id = cp.cp_cv_id)
1428 LEFT JOIN currencies cu ON (ct.currency_id = cu.id)
1429 WHERE (ct.id = ?) $contact
1432 my $ref = selectfirst_hashref_query($form, $dbh, $query, $form->{vendor_id}, @values);
1434 # remove id,notes (double of vendornotes) and taxincluded before copy back
1435 delete @$ref{qw(id taxincluded notes)};
1437 @wanted_vars = grep({ $_ } @wanted_vars);
1438 if (scalar(@wanted_vars) > 0) {
1440 map({ $h_wanted_vars{$_} = 1; } @wanted_vars);
1441 map({ delete($ref->{$_}) unless ($h_wanted_vars{$_}); } keys(%{$ref}));
1444 map { $form->{$_} = $ref->{$_} } keys %$ref;
1446 my $custom_variables = CVar->get_custom_variables('dbh' => $dbh,
1448 'trans_id' => $form->{vendor_id});
1449 map { $form->{"vc_cvar_$_->{name}"} = $_->{value} } @{ $custom_variables };
1451 if ($form->{cp_id}) {
1452 $custom_variables = CVar->get_custom_variables(dbh => $dbh,
1453 module => 'Contacts',
1454 trans_id => $form->{cp_id});
1455 $form->{"cp_cvar_$_->{name}"} = $_->{value} for @{ $custom_variables };
1458 $form->{cp_greeting} = GenericTranslations->get('dbh' => $dbh,
1459 'translation_type' => 'greetings::' . ($form->{cp_gender} eq 'f' ? 'female' : 'male'),
1460 'allow_fallback' => 1);
1462 $main::lxdebug->leave_sub();
1466 $main::lxdebug->enter_sub();
1468 my ($self, $myconfig, $form) = @_;
1470 my $dbh = SL::DB->client->dbh;
1473 qq|SELECT accno, description, link
1475 WHERE link LIKE '%IC%'
1477 my $sth = prepare_execute_query($query, $dbh, $query);
1479 while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
1480 foreach my $key (split(/:/, $ref->{link})) {
1482 push @{ $form->{IC_links}{$key} },
1483 { accno => $ref->{accno},
1484 description => $ref->{description} };
1490 $main::lxdebug->leave_sub();
1493 sub _delete_payments {
1494 $main::lxdebug->enter_sub();
1496 my ($self, $form, $dbh) = @_;
1498 my @delete_acc_trans_ids;
1500 # Delete old payment entries from acc_trans.
1502 qq|SELECT acc_trans_id
1504 WHERE (trans_id = ?) AND fx_transaction
1508 SELECT at.acc_trans_id
1510 LEFT JOIN chart c ON (at.chart_id = c.id)
1511 WHERE (trans_id = ?) AND (c.link LIKE '%AP_paid%')|;
1512 push @delete_acc_trans_ids, selectall_array_query($form, $dbh, $query, conv_i($form->{id}), conv_i($form->{id}));
1515 qq|SELECT at.acc_trans_id
1517 LEFT JOIN chart c ON (at.chart_id = c.id)
1518 WHERE (trans_id = ?)
1519 AND ((c.link = 'AP') OR (c.link LIKE '%:AP') OR (c.link LIKE 'AP:%'))
1520 ORDER BY at.acc_trans_id
1522 push @delete_acc_trans_ids, selectall_array_query($form, $dbh, $query, conv_i($form->{id}));
1524 if (@delete_acc_trans_ids) {
1525 $query = qq|DELETE FROM acc_trans WHERE acc_trans_id IN (| . join(", ", @delete_acc_trans_ids) . qq|)|;
1526 do_query($form, $dbh, $query);
1529 $main::lxdebug->leave_sub();
1533 my ($self, $myconfig, $form, $locale) = @_;
1534 $main::lxdebug->enter_sub();
1536 my $rc = SL::DB->client->with_transaction(\&_post_payment, $self, $myconfig, $form, $locale);
1538 $::lxdebug->leave_sub;
1543 my ($self, $myconfig, $form, $locale) = @_;
1545 my $dbh = SL::DB->client->dbh;
1547 my (%payments, $old_form, $row, $item, $query, %keep_vars);
1549 $old_form = save_form();
1551 # Delete all entries in acc_trans from prior payments.
1552 if (SL::DB::Default->get->payments_changeable != 0) {
1553 $self->_delete_payments($form, $dbh);
1556 # Save the new payments the user made before cleaning up $form.
1557 map { $payments{$_} = $form->{$_} } grep m/^datepaid_\d+$|^gldate_\d+$|^acc_trans_id_\d+$|^memo_\d+$|^source_\d+$|^exchangerate_\d+$|^paid_\d+$|^AP_paid_\d+$|^paidaccounts$/, keys %{ $form };
1559 # Clean up $form so that old content won't tamper the results.
1560 %keep_vars = map { $_, 1 } qw(login password id);
1561 map { delete $form->{$_} unless $keep_vars{$_} } keys %{ $form };
1563 # Retrieve the invoice from the database.
1564 $self->retrieve_invoice($myconfig, $form);
1566 # Set up the content of $form in the way that IR::post_invoice() expects.
1567 $form->{exchangerate} = $form->format_amount($myconfig, $form->{exchangerate});
1569 for $row (1 .. scalar @{ $form->{invoice_details} }) {
1570 $item = $form->{invoice_details}->[$row - 1];
1572 map { $item->{$_} = $form->format_amount($myconfig, $item->{$_}) } qw(qty sellprice);
1574 map { $form->{"${_}_${row}"} = $item->{$_} } keys %{ $item };
1577 $form->{rowcount} = scalar @{ $form->{invoice_details} };
1579 delete @{$form}{qw(invoice_details paidaccounts storno paid)};
1581 # Restore the payment options from the user input.
1582 map { $form->{$_} = $payments{$_} } keys %payments;
1584 # Get the AP accno (which is normally done by Form::create_links()).
1588 LEFT JOIN chart c ON (at.chart_id = c.id)
1589 WHERE (trans_id = ?)
1590 AND ((c.link = 'AP') OR (c.link LIKE '%:AP') OR (c.link LIKE 'AP:%'))
1591 ORDER BY at.acc_trans_id
1594 ($form->{AP}) = selectfirst_array_query($form, $dbh, $query, conv_i($form->{id}));
1596 # Post the new payments.
1597 $self->post_invoice($myconfig, $form, $dbh, 1);
1599 restore_form($old_form);
1605 $::lxdebug->enter_sub;
1607 my ($self, %params) = @_;
1609 if (!$params{vendor_id} || !$params{invdate}) {
1610 $::lxdebug->leave_sub;
1611 return $params{default};
1614 my $dbh = $::form->get_standard_dbh;
1615 my $query = qq|SELECT ?::date + pt.terms_netto
1617 LEFT JOIN payment_terms pt ON (pt.id = v.payment_id)
1620 my ($duedate) = selectfirst_array_query($::form, $dbh, $query, $params{invdate}, $params{vendor_id});
1622 $duedate ||= $params{default};
1624 $::lxdebug->leave_sub;