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., 675 Mass Ave, Cambridge, MA 02139, USA.
29 #======================================================================
31 # Inventory received module
33 #======================================================================
41 use SL::DATEV qw(:CONSTANTS);
44 use SL::GenericTranslations;
45 use SL::HTML::Restrict;
50 use List::Util qw(min);
55 $main::lxdebug->enter_sub();
57 my ($self, $myconfig, $form, $provided_dbh, $payments_only) = @_;
59 # connect to database, turn off autocommit
60 my $dbh = $provided_dbh ? $provided_dbh : $form->dbconnect_noauto($myconfig);
61 my $restricter = SL::HTML::Restrict->create;
63 $form->{defaultcurrency} = $form->get_default_currency($myconfig);
64 my $defaultcurrency = $form->{defaultcurrency};
66 my $ic_cvar_configs = CVar->get_configs(module => 'IC',
69 my ($query, $sth, @values, $project_id);
70 my ($allocated, $taxrate, $taxamount, $taxdiff, $item);
71 my ($amount, $linetotal, $lastinventoryaccno, $lastexpenseaccno);
72 my ($netamount, $invoicediff, $expensediff) = (0, 0, 0);
74 my ($basefactor, $baseqty, @taxaccounts, $totaltax);
76 my $all_units = AM->retrieve_units($myconfig, $form);
79 if (!$payments_only) {
81 &reverse_invoice($dbh, $form);
83 ($form->{id}) = selectrow_query($form, $dbh, qq|SELECT nextval('glid')|);
84 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});
88 if ($form->{currency} eq $defaultcurrency) {
89 $form->{exchangerate} = 1;
91 $exchangerate = $form->check_exchangerate($myconfig, $form->{currency}, $form->{invdate}, 'sell');
94 $form->{exchangerate} = $exchangerate || $form->parse_amount($myconfig, $form->{exchangerate});
95 $form->{exchangerate} = 1 unless ($form->{exchangerate} * 1);
98 my $q_item_unit = qq|SELECT unit FROM parts WHERE id = ?|;
99 my $h_item_unit = prepare_query($form, $dbh, $q_item_unit);
101 $form->get_lists('price_factors' => 'ALL_PRICE_FACTORS');
102 my %price_factors = map { $_->{id} => $_->{factor} } @{ $form->{ALL_PRICE_FACTORS} };
105 my @processed_invoice_ids;
106 for my $i (1 .. $form->{rowcount}) {
107 next unless $form->{"id_$i"};
111 $form->{"qty_$i"} = $form->parse_amount($myconfig, $form->{"qty_$i"});
112 $form->{"qty_$i"} *= -1 if $form->{storno};
114 if ( $::instance_conf->get_inventory_system eq 'periodic') {
115 # inventory account number is overwritten with expense account number, so
116 # never book incoming to inventory account but always to expense account
117 $form->{"inventory_accno_$i"} = $form->{"expense_accno_$i"}
121 if (!$item_units{$form->{"id_$i"}}) {
122 do_statement($form, $h_item_unit, $q_item_unit, $form->{"id_$i"});
123 ($item_units{$form->{"id_$i"}}) = $h_item_unit->fetchrow_array();
126 my $item_unit = $item_units{$form->{"id_$i"}};
128 if (defined($all_units->{$item_unit}->{factor})
129 && ($all_units->{$item_unit}->{factor} ne '')
130 && ($all_units->{$item_unit}->{factor} * 1 != 0)) {
131 $basefactor = $all_units->{$form->{"unit_$i"}}->{factor} / $all_units->{$item_unit}->{factor};
135 $baseqty = $form->{"qty_$i"} * $basefactor;
137 @taxaccounts = split / /, $form->{"taxaccounts_$i"};
142 $form->{"sellprice_$i"} = $form->parse_amount($myconfig, $form->{"sellprice_$i"});
143 (my $fxsellprice = $form->{"sellprice_$i"}) =~ /\.(\d+)/;
145 my $decimalplaces = ($dec > 2) ? $dec : 2;
147 map { $taxrate += $form->{"${_}_rate"} } @taxaccounts;
149 $price_factor = $price_factors{ $form->{"price_factor_id_$i"} } || 1;
150 # copied from IS.pm, with some changes (no decimalplaces corrections here etc)
151 # TODO maybe use PriceTaxCalculation or something like this for backends (IR.pm / IS.pm)
153 # undo discount formatting
154 $form->{"discount_$i"} = $form->parse_amount($myconfig, $form->{"discount_$i"}) / 100;
156 $form->{"sellprice_$i"} = $fxsellprice * (1 - $form->{"discount_$i"});
158 ######################################################################
159 if ($form->{"inventory_accno_$i"}) {
161 $linetotal = $form->round_amount($form->{"sellprice_$i"} * $form->{"qty_$i"} / $price_factor, 2);
163 if ($form->{taxincluded}) {
165 $taxamount = $linetotal * ($taxrate / (1 + $taxrate));
166 $form->{"sellprice_$i"} = $form->{"sellprice_$i"} * (1 / (1 + $taxrate));
169 $taxamount = $linetotal * $taxrate;
172 $netamount += $linetotal;
174 if ($form->round_amount($taxrate, 7) == 0) {
175 if ($form->{taxincluded}) {
176 foreach $item (@taxaccounts) {
178 $form->round_amount($linetotal * $form->{"${item}_rate"} / (1 + abs($form->{"${item}_rate"})), 2);
179 $taxdiff += $taxamount;
180 $form->{amount}{ $form->{id} }{$item} -= $taxamount;
182 $form->{amount}{ $form->{id} }{ $taxaccounts[0] } += $taxdiff;
185 map { $form->{amount}{ $form->{id} }{$_} -= $linetotal * $form->{"${_}_rate"} } @taxaccounts;
189 map { $form->{amount}{ $form->{id} }{$_} -= $taxamount * $form->{"${_}_rate"} / $taxrate } @taxaccounts;
192 # add purchase to inventory, this one is without the tax!
193 $amount = $form->{"sellprice_$i"} * $form->{"qty_$i"} * $form->{exchangerate} / $price_factor;
194 $linetotal = $form->round_amount($form->{"sellprice_$i"} * $form->{"qty_$i"} / $price_factor, 2) * $form->{exchangerate};
195 $linetotal = $form->round_amount($linetotal, 2);
197 # this is the difference for the inventory
198 $invoicediff += ($amount - $linetotal);
200 $form->{amount}{ $form->{id} }{ $form->{"inventory_accno_$i"} } -= $linetotal;
202 # adjust and round sellprice
203 $form->{"sellprice_$i"} = $form->round_amount($form->{"sellprice_$i"} * $form->{exchangerate}, $decimalplaces);
205 $lastinventoryaccno = $form->{"inventory_accno_$i"};
207 next if $payments_only;
209 # update parts table by setting lastcost to current price, don't allow negative values by using abs
210 $query = qq|UPDATE parts SET lastcost = ? WHERE id = ?|;
211 @values = (abs($fxsellprice * $form->{exchangerate} / $basefactor), conv_i($form->{"id_$i"}));
212 do_query($form, $dbh, $query, @values);
214 # check if we sold the item already and
215 # make an entry for the expense and inventory
216 my $taxzone = $form->{taxzone_id} * 1;
218 qq|SELECT i.id, i.qty, i.allocated, i.trans_id, i.base_qty,
219 bg.inventory_accno_id, tc.expense_accno_id AS expense_accno_id, a.transdate
220 FROM invoice i, ar a, parts p, buchungsgruppen bg, taxzone_charts tc
221 WHERE (i.parts_id = p.id)
223 AND ((i.base_qty + i.allocated) > 0)
224 AND (i.trans_id = a.id)
225 AND (p.buchungsgruppen_id = bg.id)
226 AND (tc.buchungsgruppen_id = p.buchungsgruppen_id)
227 AND (tc.taxzone_id = ${taxzone})
229 # ORDER BY transdate guarantees FIFO
231 # sold two items without having bought them yet, example result of query:
232 # id | qty | allocated | trans_id | inventory_accno_id | expense_accno_id | transdate
233 # ---+-----+-----------+----------+--------------------+------------------+------------
234 # 9 | 2 | 0 | 9 | 15 | 151 | 2011-01-05
236 # base_qty + allocated > 0 if article has already been sold but not bought yet
238 # select qty,allocated,base_qty,sellprice from invoice where trans_id = 9;
239 # qty | allocated | base_qty | sellprice
240 # -----+-----------+----------+------------
241 # 2 | 0 | 2 | 1000.00000
243 $sth = prepare_execute_query($form, $dbh, $query, conv_i($form->{"id_$i"}));
245 my $totalqty = $baseqty;
247 while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
248 my $qty = min $totalqty, ($ref->{base_qty} + $ref->{allocated});
249 $linetotal = $form->round_amount(($form->{"sellprice_$i"} * $qty) / $basefactor, 2);
251 if ( $::instance_conf->get_inventory_system eq 'perpetual' ) {
252 # Warenbestandsbuchungen nur bei Bestandsmethode
254 if ($ref->{allocated} < 0) {
256 # we have an entry for it already, adjust amount
257 $form->update_balance($dbh, "acc_trans", "amount",
258 qq| (trans_id = $ref->{trans_id})
259 AND (chart_id = $ref->{inventory_accno_id})
260 AND (transdate = '$ref->{transdate}')|,
263 $form->update_balance($dbh, "acc_trans", "amount",
264 qq| (trans_id = $ref->{trans_id})
265 AND (chart_id = $ref->{expense_accno_id})
266 AND (transdate = '$ref->{transdate}')|,
269 } elsif ($linetotal != 0) {
272 # add entry for inventory, this one is for the sold item
273 $query = qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate, taxkey, tax_id, chart_link) VALUES (?, ?, ?, ?,
278 ORDER BY startdate DESC LIMIT 1),
283 ORDER BY startdate DESC LIMIT 1),
284 (SELECT link FROM chart WHERE id = ?))|;
285 @values = ($ref->{trans_id}, $ref->{inventory_accno_id}, $linetotal, $ref->{transdate}, $ref->{inventory_accno_id}, $ref->{transdate}, $ref->{inventory_accno_id}, $ref->{transdate},
286 $ref->{inventory_accno_id});
287 do_query($form, $dbh, $query, @values);
290 $query = qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate, taxkey, tax_id, chart_link) VALUES (?, ?, ?, ?,
295 ORDER BY startdate DESC LIMIT 1),
300 ORDER BY startdate DESC LIMIT 1),
301 (SELECT link FROM chart WHERE id = ?))|;
302 @values = ($ref->{trans_id}, $ref->{expense_accno_id}, ($linetotal * -1), $ref->{transdate}, $ref->{expense_accno_id}, $ref->{transdate}, $ref->{expense_accno_id}, $ref->{transdate},
303 $ref->{expense_accno_id});
304 do_query($form, $dbh, $query, @values);
308 # update allocated for sold item
309 $form->update_balance($dbh, "invoice", "allocated", qq|id = $ref->{id}|, $qty * -1);
313 last if ($totalqty -= $qty) <= 0;
318 } else { # if ($form->{"inventory_accno_id_$i"})
319 # part doesn't have an inventory_accno_id
320 # lastcost of the part is updated at the end
322 $linetotal = $form->round_amount($form->{"sellprice_$i"} * $form->{"qty_$i"} / $price_factor, 2);
324 if ($form->{taxincluded}) {
325 $taxamount = $linetotal * ($taxrate / (1 + $taxrate));
326 $form->{"sellprice_$i"} = $form->{"sellprice_$i"} * (1 / (1 + $taxrate));
329 $taxamount = $linetotal * $taxrate;
332 $netamount += $linetotal;
334 if ($form->round_amount($taxrate, 7) == 0) {
335 if ($form->{taxincluded}) {
336 foreach $item (@taxaccounts) {
337 $taxamount = $linetotal * $form->{"${item}_rate"} / (1 + abs($form->{"${item}_rate"}));
338 $totaltax += $taxamount;
339 $form->{amount}{ $form->{id} }{$item} -= $taxamount;
342 map { $form->{amount}{ $form->{id} }{$_} -= $linetotal * $form->{"${_}_rate"} } @taxaccounts;
345 map { $form->{amount}{ $form->{id} }{$_} -= $taxamount * $form->{"${_}_rate"} / $taxrate } @taxaccounts;
348 $amount = $form->{"sellprice_$i"} * $form->{"qty_$i"} * $form->{exchangerate} / $price_factor;
349 $linetotal = $form->round_amount($form->{"sellprice_$i"} * $form->{"qty_$i"} / $price_factor, 2) * $form->{exchangerate};
350 $linetotal = $form->round_amount($linetotal, 2);
352 # this is the difference for expense
353 $expensediff += ($amount - $linetotal);
355 # add amount to expense
356 $form->{amount}{ $form->{id} }{ $form->{"expense_accno_$i"} } -= $linetotal;
358 $lastexpenseaccno = $form->{"expense_accno_$i"};
360 # adjust and round sellprice
361 $form->{"sellprice_$i"} = $form->round_amount($form->{"sellprice_$i"} * $form->{exchangerate}, $decimalplaces);
363 next if $payments_only;
366 $query = qq|UPDATE parts SET lastcost = ? WHERE id = ?|;
367 do_query($form, $dbh, $query, $form->{"sellprice_$i"} / $basefactor, conv_i($form->{"id_$i"}));
370 next if $payments_only;
373 if (!$form->{"invoice_id_$i"}) {
374 # there is no persistent id, therefore create one with all necessary constraints
375 my $q_invoice_id = qq|SELECT nextval('invoiceid')|;
376 my $h_invoice_id = prepare_query($form, $dbh, $q_invoice_id);
377 do_statement($form, $h_invoice_id, $q_invoice_id);
378 $form->{"invoice_id_$i"} = $h_invoice_id->fetchrow_array();
379 my $q_create_invoice_id = qq|INSERT INTO invoice (id, trans_id, position, parts_id) values (?, ?, ?, ?)|;
380 do_query($form, $dbh, $q_create_invoice_id, conv_i($form->{"invoice_id_$i"}),
381 conv_i($form->{id}), conv_i($position), conv_i($form->{"id_$i"}));
382 $h_invoice_id->finish();
384 # get values for CVars from master data for new items
385 $cvars = CVar->get_custom_variables(dbh => $dbh,
387 trans_id => $form->{"id_$i"},
390 # get values for CVars from custom_variables for existing items
391 $cvars = CVar->get_custom_variables(dbh => $dbh,
393 sub_module => 'invoice',
394 trans_id => $form->{"invoice_id_$i"},
397 # map only non-editable CVars to form (editable ones are already there)
398 map { $form->{"ic_cvar_$_->{name}_$i"} = $_->{value} unless $_->{flag_editable} } @{ $cvars };
400 # save detail record in invoice table
402 UPDATE invoice SET trans_id = ?, position = ?, parts_id = ?, description = ?, longdescription = ?, qty = ?, base_qty = ?,
403 sellprice = ?, fxsellprice = ?, discount = ?, allocated = ?, unit = ?, deliverydate = ?,
404 project_id = ?, serialnumber = ?, price_factor_id = ?,
405 price_factor = (SELECT factor FROM price_factors WHERE id = ?), marge_price_factor = ?,
406 active_price_source = ?, active_discount_source = ?
410 @values = (conv_i($form->{id}), conv_i($position), conv_i($form->{"id_$i"}),
411 $form->{"description_$i"}, $restricter->process($form->{"longdescription_$i"}), $form->{"qty_$i"} * -1,
412 $baseqty * -1, $form->{"sellprice_$i"}, $fxsellprice, $form->{"discount_$i"}, $allocated,
413 $form->{"unit_$i"}, conv_date($form->{deliverydate}),
414 conv_i($form->{"project_id_$i"}), $form->{"serialnumber_$i"},
415 conv_i($form->{"price_factor_id_$i"}), conv_i($form->{"price_factor_id_$i"}), conv_i($form->{"marge_price_factor_$i"}),
416 $form->{"active_price_source_$i"}, $form->{"active_discount_source_$i"},
417 conv_i($form->{"invoice_id_$i"}));
418 do_query($form, $dbh, $query, @values);
419 push @processed_invoice_ids, $form->{"invoice_id_$i"};
421 CVar->save_custom_variables(module => 'IC',
422 sub_module => 'invoice',
423 trans_id => $form->{"invoice_id_$i"},
424 configs => $ic_cvar_configs,
426 name_prefix => 'ic_',
427 name_postfix => "_$i",
429 # link previous items with invoice items See IS.pm (no credit note -> no invoice item)
430 foreach (qw(delivery_order_items orderitems)) {
431 if ($form->{"converted_from_${_}_id_$i"}) {
432 RecordLinks->create_links('dbh' => $dbh,
435 'from_ids' => $form->{"converted_from_${_}_id_$i"},
436 'to_table' => 'invoice',
437 'to_id' => $form->{"invoice_id_$i"},
439 delete $form->{"converted_from_${_}_id_$i"};
444 $h_item_unit->finish();
446 $project_id = conv_i($form->{"globalproject_id"});
448 $form->{datepaid} = $form->{invdate};
450 # all amounts are in natural state, netamount includes the taxes
451 # if tax is included, netamount is rounded to 2 decimal places,
455 for my $i (1 .. $form->{paidaccounts}) {
456 $form->{"paid_$i"} = $form->parse_amount($myconfig, $form->{"paid_$i"});
457 $form->{paid} += $form->{"paid_$i"};
458 $form->{datepaid} = $form->{"datepaid_$i"} if $form->{"datepaid_$i"};
461 my ($tax, $paiddiff) = (0, 0);
463 $netamount = $form->round_amount($netamount, 2);
465 # figure out rounding errors for amount paid and total amount
466 if ($form->{taxincluded}) {
468 $amount = $form->round_amount($netamount * $form->{exchangerate}, 2);
469 $paiddiff = $amount - $netamount * $form->{exchangerate};
470 $netamount = $amount;
472 foreach $item (split / /, $form->{taxaccounts}) {
473 $amount = $form->{amount}{ $form->{id} }{$item} * $form->{exchangerate};
474 $form->{amount}{ $form->{id} }{$item} = $form->round_amount($amount, 2);
476 $amount = $form->{amount}{ $form->{id} }{$item} * -1;
478 $netamount -= $amount;
481 $invoicediff += $paiddiff;
482 $expensediff += $paiddiff;
484 ######## this only applies to tax included
486 # in the sales invoice case rounding errors only have to be corrected for
487 # income accounts, it is enough to add the total rounding error to one of
488 # the income accounts, with the one assigned to the last row being used
489 # (lastinventoryaccno)
491 # in the purchase invoice case rounding errors may be split between
492 # inventory accounts and expense accounts. After rounding, an error of 1
493 # cent is introduced if the total rounding error exceeds 0.005. The total
494 # error is made up of $invoicediff and $expensediff, however, so if both
495 # values are below 0.005, but add up to a total >= 0.005, correcting
496 # lastinventoryaccno and lastexpenseaccno separately has no effect after
497 # rounding. This caused bug 1579. Therefore when the combined total exceeds
498 # 0.005, but neither do individually, the account with the larger value
499 # shall receive the total rounding error, and the next time it is rounded
500 # the 1 cent correction will be introduced.
502 $form->{amount}{ $form->{id} }{$lastinventoryaccno} -= $invoicediff if $lastinventoryaccno;
503 $form->{amount}{ $form->{id} }{$lastexpenseaccno} -= $expensediff if $lastexpenseaccno;
505 if ( (abs($expensediff)+abs($invoicediff)) >= 0.005 and abs($expensediff) < 0.005 and abs($invoicediff) < 0.005 ) {
507 # in total the rounding error adds up to 1 cent effectively, correct the
508 # larger of the two numbers
510 if ( abs($form->{amount}{ $form->{id} }{$lastinventoryaccno}) > abs($form->{amount}{ $form->{id} }{$lastexpenseaccno}) ) {
511 # $invoicediff has already been deducted, now also deduct expensediff
512 $form->{amount}{ $form->{id} }{$lastinventoryaccno} -= $expensediff;
514 # expensediff has already been deducted, now also deduct invoicediff
515 $form->{amount}{ $form->{id} }{$lastexpenseaccno} -= $invoicediff;
520 $amount = $form->round_amount($netamount * $form->{exchangerate}, 2);
521 $paiddiff = $amount - $netamount * $form->{exchangerate};
522 $netamount = $amount;
524 foreach my $item (split / /, $form->{taxaccounts}) {
525 $form->{amount}{ $form->{id} }{$item} = $form->round_amount($form->{amount}{ $form->{id} }{$item}, 2);
526 $amount = $form->round_amount( $form->{amount}{ $form->{id} }{$item} * $form->{exchangerate} * -1, 2);
527 $paiddiff += $amount - $form->{amount}{ $form->{id} }{$item} * $form->{exchangerate} * -1;
528 $form->{amount}{ $form->{id} }{$item} = $form->round_amount($amount * -1, 2);
529 $amount = $form->{amount}{ $form->{id} }{$item} * -1;
534 $form->{amount}{ $form->{id} }{ $form->{AP} } = $netamount + $tax;
537 $form->{paid} = $form->round_amount($form->{paid} * $form->{exchangerate} + $paiddiff, 2) if $form->{paid} != 0;
539 # update exchangerate
541 $form->update_exchangerate($dbh, $form->{currency}, $form->{invdate}, 0, $form->{exchangerate})
542 if ($form->{currency} ne $defaultcurrency) && !$exchangerate;
544 # record acc_trans transactions
545 foreach my $trans_id (keys %{ $form->{amount} }) {
546 foreach my $accno (keys %{ $form->{amount}{$trans_id} }) {
547 $form->{amount}{$trans_id}{$accno} = $form->round_amount($form->{amount}{$trans_id}{$accno}, 2);
550 next if $payments_only || !$form->{amount}{$trans_id}{$accno};
552 $query = qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate, taxkey, project_id, tax_id, chart_link)
553 VALUES (?, (SELECT id FROM chart WHERE accno = ?), ?, ?,
556 WHERE chart_id= (SELECT id
560 ORDER BY startdate DESC LIMIT 1),
564 WHERE chart_id= (SELECT id
568 ORDER BY startdate DESC LIMIT 1),
569 (SELECT link FROM chart WHERE accno = ?))|;
570 @values = ($trans_id, $accno, $form->{amount}{$trans_id}{$accno},
571 conv_date($form->{invdate}), $accno, conv_date($form->{invdate}), $project_id, $accno, conv_date($form->{invdate}), $accno);
572 do_query($form, $dbh, $query, @values);
576 # deduct payment differences from paiddiff
577 for my $i (1 .. $form->{paidaccounts}) {
578 if ($form->{"paid_$i"} != 0) {
579 $amount = $form->round_amount($form->{"paid_$i"} * $form->{exchangerate}, 2);
580 $paiddiff -= $amount - $form->{"paid_$i"} * $form->{exchangerate};
584 # force AP entry if 0
586 $form->{amount}{ $form->{id} }{ $form->{AP} } = $form->{paid} if $form->{amount}{$form->{id}}{$form->{AP}} == 0;
588 # record payments and offsetting AP
589 for my $i (1 .. $form->{paidaccounts}) {
590 if ($form->{"acc_trans_id_$i"}
592 && (SL::DB::Default->get->payments_changeable == 0)) {
596 next if $form->{"paid_$i"} == 0;
598 my ($accno) = split /--/, $form->{"AP_paid_$i"};
599 $form->{"datepaid_$i"} = $form->{invdate} unless ($form->{"datepaid_$i"});
600 $form->{datepaid} = $form->{"datepaid_$i"};
602 $amount = $form->round_amount($form->{"paid_$i"} * $form->{exchangerate} + $paiddiff, 2) * -1;
605 if ($form->{amount}{ $form->{id} }{ $form->{AP} } != 0) {
606 $query = qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate, taxkey, project_id, tax_id, chart_link)
607 VALUES (?, (SELECT id FROM chart WHERE accno = ?), ?, ?,
610 WHERE chart_id= (SELECT id
614 ORDER BY startdate DESC LIMIT 1),
618 WHERE chart_id= (SELECT id
622 ORDER BY startdate DESC LIMIT 1),
623 (SELECT link FROM chart WHERE accno = ?))|;
624 @values = (conv_i($form->{id}), $form->{AP}, $amount,
625 $form->{"datepaid_$i"}, $form->{AP}, conv_date($form->{"datepaid_$i"}), $project_id, $form->{AP}, conv_date($form->{"datepaid_$i"}), $form->{AP});
626 do_query($form, $dbh, $query, @values);
630 my $gldate = (conv_date($form->{"gldate_$i"}))? conv_date($form->{"gldate_$i"}) : conv_date($form->current_date($myconfig));
633 qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate, gldate, source, memo, taxkey, project_id, tax_id, chart_link)
634 VALUES (?, (SELECT id FROM chart WHERE accno = ?), ?, ?, ?, ?, ?,
637 WHERE chart_id= (SELECT id
638 FROM chart WHERE accno = ?)
640 ORDER BY startdate DESC LIMIT 1),
644 WHERE chart_id= (SELECT id
645 FROM chart WHERE accno = ?)
647 ORDER BY startdate DESC LIMIT 1),
648 (SELECT link FROM chart WHERE accno = ?))|;
649 @values = (conv_i($form->{id}), $accno, $form->{"paid_$i"}, $form->{"datepaid_$i"},
650 $gldate, $form->{"source_$i"}, $form->{"memo_$i"}, $accno, conv_date($form->{"datepaid_$i"}), $project_id, $accno, conv_date($form->{"datepaid_$i"}), $accno);
651 do_query($form, $dbh, $query, @values);
655 if ($form->{currency} eq $defaultcurrency) {
656 $form->{"exchangerate_$i"} = 1;
658 $exchangerate = $form->check_exchangerate($myconfig, $form->{currency}, $form->{"datepaid_$i"}, 'sell');
659 $form->{"exchangerate_$i"} = $exchangerate || $form->parse_amount($myconfig, $form->{"exchangerate_$i"});
662 # exchangerate difference
663 $form->{fx}{$accno}{ $form->{"datepaid_$i"} } += $form->{"paid_$i"} * ($form->{"exchangerate_$i"} - 1) + $paiddiff;
667 ($form->{"paid_$i"} * $form->{exchangerate}) -
668 ($form->{"paid_$i"} * $form->{"exchangerate_$i"});
670 $form->{fx}{ $form->{fxgain_accno} }{ $form->{"datepaid_$i"} } += $amount;
672 $form->{fx}{ $form->{fxloss_accno} }{ $form->{"datepaid_$i"} } += $amount;
677 # update exchange rate
678 $form->update_exchangerate($dbh, $form->{currency}, $form->{"datepaid_$i"}, 0, $form->{"exchangerate_$i"})
679 if ($form->{currency} ne $defaultcurrency) && !$exchangerate;
682 # record exchange rate differences and gains/losses
683 foreach my $accno (keys %{ $form->{fx} }) {
684 foreach my $transdate (keys %{ $form->{fx}{$accno} }) {
685 $form->{fx}{$accno}{$transdate} = $form->round_amount($form->{fx}{$accno}{$transdate}, 2);
686 next if ($form->{fx}{$accno}{$transdate} == 0);
688 $query = qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate, cleared, fx_transaction, taxkey, project_id, tax_id, chart_link)
689 VALUES (?, (SELECT id FROM chart WHERE accno = ?), ?, ?, '0', '1', 0, ?,
690 (SELECT id FROM tax WHERE taxkey=0 LIMIT 1),
691 (SELECT link FROM chart WHERE accno = ?))|;
692 @values = (conv_i($form->{id}), $accno, $form->{fx}{$accno}{$transdate}, conv_date($transdate), $project_id, $accno);
693 do_query($form, $dbh, $query, @values);
697 IO->set_datepaid(table => 'ap', id => $form->{id}, dbh => $dbh);
699 if ($payments_only) {
700 $query = qq|UPDATE ap SET paid = ? WHERE id = ?|;
701 do_query($form, $dbh, $query, $form->{paid}, conv_i($form->{id}));
703 if (!$provided_dbh) {
708 $main::lxdebug->leave_sub();
712 $amount = $netamount + $tax;
714 # set values which could be empty
715 my $taxzone_id = $form->{taxzone_id} * 1;
716 $taxzone_id = SL::DB::Manager::TaxZone->get_default->id unless SL::DB::Manager::TaxZone->find_by(id => $taxzone_id);
718 $form->{invnumber} = $form->{id} unless $form->{invnumber};
721 $query = qq|UPDATE ap SET
722 invnumber = ?, ordnumber = ?, quonumber = ?, transdate = ?,
723 orddate = ?, quodate = ?, vendor_id = ?, amount = ?,
724 netamount = ?, paid = ?, duedate = ?,
725 invoice = ?, taxzone_id = ?, notes = ?, taxincluded = ?,
726 intnotes = ?, storno_id = ?, storno = ?,
727 cp_id = ?, employee_id = ?, department_id = ?, delivery_term_id = ?,
728 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, $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}),
737 conv_i($form->{globalproject_id}),
738 $form->{direct_debit} ? 't' : 'f',
741 do_query($form, $dbh, $query, @values);
743 if ($form->{storno}) {
744 $query = qq|UPDATE ap SET paid = paid + amount WHERE id = ?|;
745 do_query($form, $dbh, $query, conv_i($form->{storno_id}));
747 $query = qq|UPDATE ap SET storno = 't' WHERE id = ?|;
748 do_query($form, $dbh, $query, conv_i($form->{storno_id}));
750 $query = qq!UPDATE ap SET intnotes = ? || intnotes WHERE id = ?!;
751 do_query($form, $dbh, $query, "Rechnung storniert am $form->{invdate} ", conv_i($form->{storno_id}));
753 $query = qq|UPDATE ap SET paid = amount WHERE id = ?|;
754 do_query($form, $dbh, $query, conv_i($form->{id}));
758 $form->{name} = $form->{vendor};
759 $form->{name} =~ s/--\Q$form->{vendor_id}\E//;
762 $form->add_shipto($dbh, $form->{id}, "AP");
764 # delete zero entries
765 do_query($form, $dbh, qq|DELETE FROM acc_trans WHERE amount = 0|);
767 Common::webdav_folder($form);
769 # Link this record to the records it was created from.
770 if ($form->{convert_from_oe_ids}) {
771 RecordLinks->create_links('dbh' => $dbh,
773 'from_table' => 'oe',
774 'from_ids' => $form->{convert_from_oe_ids},
776 'to_id' => $form->{id},
778 delete $form->{convert_from_oe_ids};
781 my @convert_from_do_ids = map { $_ * 1 } grep { $_ } split m/\s+/, $form->{convert_from_do_ids};
782 if (scalar @convert_from_do_ids) {
783 DO->close_orders('dbh' => $dbh,
784 'ids' => \@convert_from_do_ids);
786 RecordLinks->create_links('dbh' => $dbh,
788 'from_table' => 'delivery_orders',
789 'from_ids' => \@convert_from_do_ids,
791 'to_id' => $form->{id},
794 delete $form->{convert_from_do_ids};
796 ARAP->close_orders_if_billed('dbh' => $dbh,
797 'arap_id' => $form->{id},
800 # search for orphaned invoice items
801 $query = sprintf 'SELECT id FROM invoice WHERE trans_id = ? AND NOT id IN (%s)', join ', ', ("?") x scalar @processed_invoice_ids;
802 @values = (conv_i($form->{id}), map { conv_i($_) } @processed_invoice_ids);
803 my @orphaned_ids = map { $_->{id} } selectall_hashref_query($form, $dbh, $query, @values);
804 if (scalar @orphaned_ids) {
805 # clean up invoice items
806 $query = sprintf 'DELETE FROM invoice WHERE id IN (%s)', join ', ', ("?") x scalar @orphaned_ids;
807 do_query($form, $dbh, $query, @orphaned_ids);
810 # safety check datev export
811 if ($::instance_conf->get_datev_check_on_purchase_invoice) {
812 my $transdate = $::form->{invdate} ? DateTime->from_lxoffice($::form->{invdate}) : undef;
813 $transdate ||= DateTime->today;
815 my $datev = SL::DATEV->new(
816 exporttype => DATEV_ET_BUCHUNGEN,
817 format => DATEV_FORMAT_KNE,
821 trans_id => $form->{id},
826 if ($datev->errors) {
828 die join "\n", $::locale->text('DATEV check returned errors:'), $datev->errors;
833 if (!$provided_dbh) {
834 $rc = $dbh->commit();
838 $main::lxdebug->leave_sub();
843 sub reverse_invoice {
844 $main::lxdebug->enter_sub();
846 my ($dbh, $form) = @_;
848 # reverse inventory items
850 qq|SELECT i.parts_id, p.inventory_accno_id, p.expense_accno_id, i.qty, i.allocated, i.sellprice
851 FROM invoice i, parts p
852 WHERE (i.parts_id = p.id)
853 AND (i.trans_id = ?)|;
854 my $sth = prepare_execute_query($form, $dbh, $query, conv_i($form->{id}));
858 while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
859 $netamount += $form->round_amount($ref->{sellprice} * $ref->{qty} * -1, 2);
861 next unless $ref->{inventory_accno_id};
863 # if $ref->{allocated} > 0 than we sold that many items
864 next if ($ref->{allocated} <= 0);
866 # get references for sold items
868 qq|SELECT i.id, i.trans_id, i.allocated, a.transdate
870 WHERE (i.parts_id = ?)
871 AND (i.allocated < 0)
872 AND (i.trans_id = a.id)
873 ORDER BY transdate DESC|;
874 my $sth2 = prepare_execute_query($form, $dbh, $query, $ref->{parts_id});
876 while (my $pthref = $sth2->fetchrow_hashref("NAME_lc")) {
877 my $qty = $ref->{allocated};
878 if (($ref->{allocated} + $pthref->{allocated}) > 0) {
879 $qty = $pthref->{allocated} * -1;
882 my $amount = $form->round_amount($ref->{sellprice} * $qty, 2);
885 $form->update_balance($dbh, "invoice", "allocated", qq|id = $pthref->{id}|, $qty);
887 $form->update_balance($dbh, "acc_trans", "amount",
888 qq| (trans_id = $pthref->{trans_id})
889 AND (chart_id = $ref->{expense_accno_id})
890 AND (transdate = '$pthref->{transdate}')|,
893 $form->update_balance($dbh, "acc_trans", "amount",
894 qq| (trans_id = $pthref->{trans_id})
895 AND (chart_id = $ref->{inventory_accno_id})
896 AND (transdate = '$pthref->{transdate}')|,
899 last if (($ref->{allocated} -= $qty) <= 0);
905 my $id = conv_i($form->{id});
908 $query = qq|DELETE FROM acc_trans WHERE trans_id = ?|;
909 do_query($form, $dbh, $query, $id);
911 $query = qq|DELETE FROM shipto WHERE (trans_id = ?) AND (module = 'AP')|;
912 do_query($form, $dbh, $query, $id);
914 $main::lxdebug->leave_sub();
918 $main::lxdebug->enter_sub();
920 my ($self, $myconfig, $form) = @_;
922 # connect to database
923 my $dbh = $form->dbconnect_noauto($myconfig);
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 my $rc = $dbh->commit;
945 $main::lxdebug->leave_sub();
950 sub retrieve_invoice {
951 $main::lxdebug->enter_sub();
953 my ($self, $myconfig, $form) = @_;
955 # connect to database
956 my $dbh = $form->dbconnect($myconfig);
958 my ($query, $sth, $ref, $q_invdate);
961 $q_invdate = qq|, COALESCE((SELECT transdate FROM ar WHERE id = (SELECT MAX(id) FROM ar)), current_date) AS invdate|;
962 if ($form->{vendor_id}) {
963 my $vendor_id = $dbh->quote($form->{vendor_id} * 1);
965 qq|, COALESCE((SELECT transdate FROM ar WHERE id = (SELECT MAX(id) FROM ar)), current_date) +
966 COALESCE((SELECT pt.terms_netto
968 LEFT JOIN payment_terms pt ON (v.payment_id = pt.id)
969 WHERE v.id = $vendor_id),
974 # get default accounts and last invoice number
977 (SELECT c.accno FROM chart c WHERE d.inventory_accno_id = c.id) AS inventory_accno,
978 (SELECT c.accno FROM chart c WHERE d.income_accno_id = c.id) AS income_accno,
979 (SELECT c.accno FROM chart c WHERE d.expense_accno_id = c.id) AS expense_accno,
980 (SELECT c.accno FROM chart c WHERE d.fxgain_accno_id = c.id) AS fxgain_accno,
981 (SELECT c.accno FROM chart c WHERE d.fxloss_accno_id = c.id) AS fxloss_accno
984 $ref = selectfirst_hashref_query($form, $dbh, $query);
985 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,
998 intnotes, (SELECT cu.name FROM currencies cu WHERE cu.id=ap.currency_id) AS currency, direct_debit,
1002 $ref = selectfirst_hashref_query($form, $dbh, $query, conv_i($form->{id}));
1003 map { $form->{$_} = $ref->{$_} } keys %$ref;
1005 $form->{exchangerate} = $form->get_exchangerate($dbh, $form->{currency}, $form->{invdate}, "sell");
1008 $query = qq|SELECT * FROM shipto WHERE (trans_id = ?) AND (module = 'AP')|;
1009 $ref = selectfirst_hashref_query($form, $dbh, $query, conv_i($form->{id}));
1011 map { $form->{$_} = $ref->{$_} } keys %$ref;
1013 my $transdate = $form->{invdate} ? $dbh->quote($form->{invdate}) : "current_date";
1015 my $taxzone_id = $form->{taxzone_id} * 1;
1016 $taxzone_id = SL::DB::Manager::TaxZone->get_default->id unless SL::DB::Manager::TaxZone->find_by(id => $taxzone_id);
1018 # retrieve individual items
1021 c1.accno AS inventory_accno, c1.new_chart_id AS inventory_new_chart, date($transdate) - c1.valid_from AS inventory_valid,
1022 c2.accno AS income_accno, c2.new_chart_id AS income_new_chart, date($transdate) - c2.valid_from AS income_valid,
1023 c3.accno AS expense_accno, c3.new_chart_id AS expense_new_chart, date($transdate) - c3.valid_from AS expense_valid,
1026 i.description, i.longdescription, i.qty, i.fxsellprice AS sellprice, i.parts_id AS id, i.unit, i.deliverydate, i.project_id, i.serialnumber,
1027 i.price_factor_id, i.price_factor, i.marge_price_factor, i.discount, i.active_price_source, i.active_discount_source,
1028 p.partnumber, p.inventory_accno_id AS part_inventory_accno_id, pr.projectnumber, pg.partsgroup
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_inventory_accno_id"};
1053 delete($ref->{"part_inventory_accno_id"});
1055 foreach my $type (qw(inventory income expense)) {
1056 while ($ref->{"${type}_new_chart"} && ($ref->{"${type}_valid"} >=0)) {
1057 my $query = qq|SELECT accno, new_chart_id, date($transdate) - valid_from FROM chart WHERE id = ?|;
1058 @$ref{ map $type.$_, qw(_accno _new_chart _valid) } = selectrow_query($form, $dbh, $query, $ref->{"${type}_new_chart"});
1062 # get tax rates and description
1063 my $accno_id = ($form->{vc} eq "customer") ? $ref->{income_accno} : $ref->{expense_accno};
1065 qq|SELECT c.accno, t.taxdescription, t.rate, t.taxnumber FROM tax t
1066 LEFT JOIN chart c ON (c.id = t.chart_id)
1068 (SELECT tk.tax_id FROM taxkeys tk
1069 WHERE tk.chart_id = (SELECT id FROM chart WHERE accno = ?)
1070 AND (startdate <= $transdate)
1071 ORDER BY startdate DESC
1074 my $stw = prepare_execute_query($form, $dbh, $query, $accno_id);
1075 $ref->{taxaccounts} = "";
1078 while (my $ptr = $stw->fetchrow_hashref("NAME_lc")) {
1079 if (($ptr->{accno} eq "") && ($ptr->{rate} == 0)) {
1084 $ref->{taxaccounts} .= "$ptr->{accno} ";
1086 if (!($form->{taxaccounts} =~ /\Q$ptr->{accno}\E/)) {
1087 $form->{"$ptr->{accno}_rate"} = $ptr->{rate};
1088 $form->{"$ptr->{accno}_description"} = $ptr->{taxdescription};
1089 $form->{"$ptr->{accno}_taxnumber"} = $ptr->{taxnumber};
1090 $form->{taxaccounts} .= "$ptr->{accno} ";
1095 chop $ref->{taxaccounts};
1096 push @{ $form->{invoice_details} }, $ref;
1101 Common::webdav_folder($form);
1105 $main::lxdebug->leave_sub();
1109 $main::lxdebug->enter_sub();
1111 my ($self, $myconfig, $form, $params) = @_;
1113 $params = $form unless defined $params && ref $params eq "HASH";
1115 # connect to database
1116 my $dbh = $form->dbconnect($myconfig);
1118 my $dateformat = $myconfig->{dateformat};
1119 $dateformat .= "yy" if $myconfig->{dateformat} !~ /^y/;
1121 my $vid = conv_i($params->{vendor_id});
1122 my $vnr = conv_i($params->{vendornumber});
1125 ($params->{invdate})
1126 ? "to_date(" . $dbh->quote($params->{invdate}) . ", '$dateformat')"
1133 $where .= 'AND v.id = ?';
1137 $where .= 'AND v.vendornumber = ?';
1142 v.id AS vendor_id, v.name AS vendor, v.discount as vendor_discount,
1143 v.creditlimit, v.terms, v.notes AS intnotes,
1144 v.email, v.cc, v.bcc, v.language_id, v.payment_id, v.delivery_term_id,
1145 v.street, v.zipcode, v.city, v.country, v.taxzone_id, cu.name AS curr, v.direct_debit,
1146 $duedate + COALESCE(pt.terms_netto, 0) AS duedate,
1147 b.description AS business
1149 LEFT JOIN business b ON (b.id = v.business_id)
1150 LEFT JOIN payment_terms pt ON (v.payment_id = pt.id)
1151 LEFT JOIN currencies cu ON (v.currency_id = cu.id)
1153 my $ref = selectfirst_hashref_query($form, $dbh, $query, @values);
1154 map { $params->{$_} = $ref->{$_} } keys %$ref;
1156 # use vendor currency
1157 $form->{currency} = $form->{curr};
1159 $params->{creditremaining} = $params->{creditlimit};
1161 $query = qq|SELECT SUM(amount - paid) FROM ap WHERE vendor_id = ?|;
1162 my ($unpaid_invoices) = selectfirst_array_query($form, $dbh, $query, $vid);
1163 $params->{creditremaining} -= $unpaid_invoices;
1165 $query = qq|SELECT o.amount,
1168 WHERE (e.currency_id = o.currency_id)
1169 AND (e.transdate = o.transdate)) AS exch
1171 WHERE (o.vendor_id = ?) AND (o.quotation = '0') AND (o.closed = '0')|;
1172 my $sth = prepare_execute_query($form, $dbh, $query, $vid);
1173 while (my ($amount, $exch) = $sth->fetchrow_array()) {
1174 $exch = 1 unless $exch;
1175 $params->{creditremaining} -= $amount * $exch;
1179 if (!$params->{id} && $params->{type} !~ /_(order|quotation)/) {
1180 # setup last accounts used
1182 qq|SELECT c.id, c.accno, c.description, c.link, c.category
1184 JOIN acc_trans ac ON (ac.chart_id = c.id)
1185 JOIN ap a ON (a.id = ac.trans_id)
1186 WHERE (a.vendor_id = ?)
1187 AND (NOT ((c.link LIKE '%_tax%') OR (c.link LIKE '%_paid%')))
1188 AND (a.id IN (SELECT max(a2.id) FROM ap a2 WHERE a2.vendor_id = ?))|;
1189 my $refs = selectall_hashref_query($form, $dbh, $query, $vid, $vid);
1193 if ($ref->{category} eq 'E') {
1195 my ($tax_id, $rate);
1196 if ($params->{initial_transdate}) {
1197 my $tax_query = qq|SELECT tk.tax_id, t.rate FROM taxkeys tk
1198 LEFT JOIN tax t ON (tk.tax_id = t.id)
1199 WHERE (tk.chart_id = ?) AND (startdate <= ?)
1200 ORDER BY tk.startdate DESC
1202 ($tax_id, $rate) = selectrow_query($form, $dbh, $tax_query, $ref->{id}, $params->{initial_transdate});
1203 $params->{"taxchart_$i"} = "${tax_id}--${rate}";
1206 $params->{"AP_amount_$i"} = "$ref->{accno}--$tax_id";
1209 if ($ref->{category} eq 'L') {
1210 $params->{APselected} = $params->{AP_1} = $ref->{accno};
1213 $params->{rowcount} = $i if ($i && !$params->{type});
1218 $main::lxdebug->leave_sub();
1222 $main::lxdebug->enter_sub();
1224 my ($self, $myconfig, $form) = @_;
1226 # connect to database
1227 my $dbh = $form->dbconnect($myconfig);
1229 my $i = $form->{rowcount};
1231 # don't include assemblies or obsolete parts
1232 my $where = "NOT p.assembly = '1' AND NOT p.obsolete = '1'";
1235 foreach my $table_column (qw(p.partnumber p.description pg.partsgroup)) {
1236 my $field = (split m{\.}, $table_column)[1];
1237 next unless $form->{"${field}_${i}"};
1238 $where .= " AND lower(${table_column}) LIKE lower(?)";
1239 push @values, '%' . $form->{"${field}_${i}"} . '%';
1243 if ($form->{"partnumber_$i"} && !$form->{"description_$i"}) {
1244 $where .= qq| OR (NOT p.obsolete = '1' AND p.ean = ? )|;
1245 push @values, $form->{"partnumber_$i"};
1247 # also search hits in makemodels, but only cache the results by id and merge later
1249 SELECT parts_id, model FROM makemodel
1250 LEFT JOIN parts ON parts.id = parts_id
1251 WHERE NOT parts.obsolete AND model ILIKE ? AND (make IS NULL OR make = ?);
1253 my $mm_results = selectall_hashref_query($::form, $dbh, $mm_query, '%' . $form->{"partnumber_$i"} . '%', $::form->{vendor_id});
1254 my @mm_ids = map { $_->{parts_id} } @$mm_results;
1255 push @{$mm_by_id{ $_->{parts_id} } ||= []}, $_ for @$mm_results;
1258 $where .= qq| OR p.id IN (| . join(',', ('?') x @mm_ids) . qq|)|;
1259 push @values, @mm_ids;
1263 # Search for part ID overrides all other criteria.
1264 if ($form->{"id_${i}"}) {
1265 $where = qq|p.id = ?|;
1266 @values = ($form->{"id_${i}"});
1269 if ($form->{"description_$i"}) {
1270 $where .= " ORDER BY p.description";
1272 $where .= " ORDER BY p.partnumber";
1276 if ($form->{type} eq "invoice") {
1277 $transdate = $form->{deliverydate} ? $dbh->quote($form->{deliverydate})
1278 : $form->{invdate} ? $dbh->quote($form->{invdate})
1281 $transdate = $form->{transdate} ? $dbh->quote($form->{transdate}) : "current_date";
1284 my $taxzone_id = $form->{taxzone_id} * 1;
1285 $taxzone_id = SL::DB::Manager::TaxZone->get_default->id unless SL::DB::Manager::TaxZone->find_by(id => $taxzone_id);
1289 p.id, p.partnumber, p.description, p.lastcost AS sellprice, p.listprice,
1290 p.unit, p.assembly, p.onhand, p.formel,
1291 p.notes AS partnotes, p.notes AS longdescription, p.not_discountable,
1292 p.inventory_accno_id, p.price_factor_id,
1295 pfac.factor AS price_factor,
1297 c1.accno AS inventory_accno,
1298 c1.new_chart_id AS inventory_new_chart,
1299 date($transdate) - c1.valid_from AS inventory_valid,
1301 c2.accno AS income_accno,
1302 c2.new_chart_id AS income_new_chart,
1303 date($transdate) - c2.valid_from AS income_valid,
1305 c3.accno AS expense_accno,
1306 c3.new_chart_id AS expense_new_chart,
1307 date($transdate) - c3.valid_from AS expense_valid,
1312 LEFT JOIN chart c1 ON
1313 ((SELECT inventory_accno_id
1314 FROM buchungsgruppen
1315 WHERE id = p.buchungsgruppen_id) = c1.id)
1316 LEFT JOIN chart c2 ON
1317 ((SELECT tc.income_accno_id
1318 FROM taxzone_charts tc
1319 WHERE tc.taxzone_id = '$taxzone_id' and tc.buchungsgruppen_id = p.buchungsgruppen_id) = c2.id)
1320 LEFT JOIN chart c3 ON
1321 ((SELECT tc.expense_accno_id
1322 FROM taxzone_charts tc
1323 WHERE tc.taxzone_id = '$taxzone_id' and tc.buchungsgruppen_id = p.buchungsgruppen_id) = c3.id)
1324 LEFT JOIN partsgroup pg ON (pg.id = p.partsgroup_id)
1325 LEFT JOIN price_factors pfac ON (pfac.id = p.price_factor_id)
1327 my $sth = prepare_execute_query($form, $dbh, $query, @values);
1329 my @translation_queries = ( [ qq|SELECT tr.translation, tr.longdescription
1331 WHERE tr.language_id = ? AND tr.parts_id = ?| ],
1332 [ qq|SELECT tr.translation, tr.longdescription
1334 WHERE tr.language_id IN
1337 WHERE article_code = (SELECT article_code FROM language WHERE id = ?))
1340 map { push @{ $_ }, prepare_query($form, $dbh, $_->[0]) } @translation_queries;
1342 $form->{item_list} = [];
1343 while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
1345 if ($mm_by_id{$ref->{id}}) {
1346 $ref->{makemodels} = $mm_by_id{$ref->{id}};
1347 push @{ $ref->{matches} ||= [] }, $::locale->text('Model') . ': ' . join ', ', map { $_->{model} } @{ $mm_by_id{$ref->{id}} };
1350 if ($ref->{ean} eq $::form->{"partnumber_$i"}) {
1351 push @{ $ref->{matches} ||= [] }, $::locale->text('EAN') . ': ' . $ref->{ean};
1354 # In der Buchungsgruppe ist immer ein Bestandskonto verknuepft, auch wenn
1355 # es sich um eine Dienstleistung handelt. Bei Dienstleistungen muss das
1356 # Buchungskonto also aus dem Ergebnis rausgenommen werden.
1357 if (!$ref->{inventory_accno_id}) {
1358 map({ delete($ref->{"inventory_${_}"}); } qw(accno new_chart valid));
1360 delete($ref->{inventory_accno_id});
1362 # get tax rates and description
1363 my $accno_id = ($form->{vc} eq "customer") ? $ref->{income_accno} : $ref->{expense_accno};
1365 qq|SELECT c.accno, t.taxdescription, t.rate, t.taxnumber
1367 LEFT JOIN chart c on (c.id = t.chart_id)
1375 AND (startdate <= $transdate)
1376 ORDER BY startdate DESC
1379 my $stw = prepare_execute_query($form, $dbh, $query, $accno_id);
1381 $ref->{taxaccounts} = "";
1383 while (my $ptr = $stw->fetchrow_hashref("NAME_lc")) {
1385 if (($ptr->{accno} eq "") && ($ptr->{rate} == 0)) {
1390 $ref->{taxaccounts} .= "$ptr->{accno} ";
1392 if (!($form->{taxaccounts} =~ /\Q$ptr->{accno}\E/)) {
1393 $form->{"$ptr->{accno}_rate"} = $ptr->{rate};
1394 $form->{"$ptr->{accno}_description"} = $ptr->{taxdescription};
1395 $form->{"$ptr->{accno}_taxnumber"} = $ptr->{taxnumber};
1396 $form->{taxaccounts} .= "$ptr->{accno} ";
1399 if ($form->{language_id}) {
1400 for my $spec (@translation_queries) {
1401 do_statement($form, $spec->[1], $spec->[0], conv_i($form->{language_id}), conv_i($ref->{id}));
1402 my ($translation, $longdescription) = $spec->[1]->fetchrow_array;
1403 next unless $translation;
1404 $ref->{description} = $translation;
1405 $ref->{longdescription} = $longdescription;
1412 chop $ref->{taxaccounts};
1414 $ref->{onhand} *= 1;
1416 push @{ $form->{item_list} }, $ref;
1421 $_->[1]->finish for @translation_queries;
1423 foreach my $item (@{ $form->{item_list} }) {
1424 my $custom_variables = CVar->get_custom_variables(module => 'IC',
1425 trans_id => $item->{id},
1429 map { $item->{"ic_cvar_" . $_->{name} } = $_->{value} } @{ $custom_variables };
1434 $main::lxdebug->leave_sub();
1437 sub vendor_details {
1438 $main::lxdebug->enter_sub();
1440 my ($self, $myconfig, $form, @wanted_vars) = @_;
1442 # connect to database
1443 my $dbh = $form->dbconnect($myconfig);
1447 # get contact id, set it if nessessary
1448 $form->{cp_id} *= 1;
1450 if ($form->{cp_id}) {
1451 $contact = "AND cp.cp_id = ?";
1452 push @values, $form->{cp_id};
1455 # get rest for the vendor
1456 # fax and phone and email as vendor*
1458 qq|SELECT ct.*, cp.*, ct.notes as vendornotes, phone as vendorphone, fax as vendorfax, email as vendoremail,
1461 LEFT JOIN contacts cp ON (ct.id = cp.cp_cv_id)
1462 LEFT JOIN currencies cu ON (ct.currency_id = cu.id)
1463 WHERE (ct.id = ?) $contact
1466 my $ref = selectfirst_hashref_query($form, $dbh, $query, $form->{vendor_id}, @values);
1468 # remove id and taxincluded before copy back
1469 delete @$ref{qw(id taxincluded)};
1471 @wanted_vars = grep({ $_ } @wanted_vars);
1472 if (scalar(@wanted_vars) > 0) {
1474 map({ $h_wanted_vars{$_} = 1; } @wanted_vars);
1475 map({ delete($ref->{$_}) unless ($h_wanted_vars{$_}); } keys(%{$ref}));
1478 map { $form->{$_} = $ref->{$_} } keys %$ref;
1480 my $custom_variables = CVar->get_custom_variables('dbh' => $dbh,
1482 'trans_id' => $form->{vendor_id});
1483 map { $form->{"vc_cvar_$_->{name}"} = $_->{value} } @{ $custom_variables };
1485 $form->{cp_greeting} = GenericTranslations->get('dbh' => $dbh,
1486 'translation_type' => 'greetings::' . ($form->{cp_gender} eq 'f' ? 'female' : 'male'),
1487 'allow_fallback' => 1);
1491 $main::lxdebug->leave_sub();
1495 $main::lxdebug->enter_sub();
1497 my ($self, $myconfig, $form) = @_;
1499 # connect to database
1500 my $dbh = $form->dbconnect($myconfig);
1503 qq|SELECT accno, description, link
1505 WHERE link LIKE '%IC%'
1507 my $sth = prepare_execute_query($query, $dbh, $query);
1509 while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
1510 foreach my $key (split(/:/, $ref->{link})) {
1512 push @{ $form->{IC_links}{$key} },
1513 { accno => $ref->{accno},
1514 description => $ref->{description} };
1522 $main::lxdebug->leave_sub();
1525 sub _delete_payments {
1526 $main::lxdebug->enter_sub();
1528 my ($self, $form, $dbh) = @_;
1530 my @delete_acc_trans_ids;
1532 # Delete old payment entries from acc_trans.
1534 qq|SELECT acc_trans_id
1536 WHERE (trans_id = ?) AND fx_transaction
1540 SELECT at.acc_trans_id
1542 LEFT JOIN chart c ON (at.chart_id = c.id)
1543 WHERE (trans_id = ?) AND (c.link LIKE '%AP_paid%')|;
1544 push @delete_acc_trans_ids, selectall_array_query($form, $dbh, $query, conv_i($form->{id}), conv_i($form->{id}));
1547 qq|SELECT at.acc_trans_id
1549 LEFT JOIN chart c ON (at.chart_id = c.id)
1550 WHERE (trans_id = ?)
1551 AND ((c.link = 'AP') OR (c.link LIKE '%:AP') OR (c.link LIKE 'AP:%'))
1552 ORDER BY at.acc_trans_id
1554 push @delete_acc_trans_ids, selectall_array_query($form, $dbh, $query, conv_i($form->{id}));
1556 if (@delete_acc_trans_ids) {
1557 $query = qq|DELETE FROM acc_trans WHERE acc_trans_id IN (| . join(", ", @delete_acc_trans_ids) . qq|)|;
1558 do_query($form, $dbh, $query);
1561 $main::lxdebug->leave_sub();
1565 $main::lxdebug->enter_sub();
1567 my ($self, $myconfig, $form, $locale) = @_;
1569 # connect to database, turn off autocommit
1570 my $dbh = $form->dbconnect_noauto($myconfig);
1572 my (%payments, $old_form, $row, $item, $query, %keep_vars);
1574 $old_form = save_form();
1576 # Delete all entries in acc_trans from prior payments.
1577 if (SL::DB::Default->get->payments_changeable != 0) {
1578 $self->_delete_payments($form, $dbh);
1581 # Save the new payments the user made before cleaning up $form.
1582 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 };
1584 # Clean up $form so that old content won't tamper the results.
1585 %keep_vars = map { $_, 1 } qw(login password id);
1586 map { delete $form->{$_} unless $keep_vars{$_} } keys %{ $form };
1588 # Retrieve the invoice from the database.
1589 $self->retrieve_invoice($myconfig, $form);
1591 # Set up the content of $form in the way that IR::post_invoice() expects.
1592 $form->{exchangerate} = $form->format_amount($myconfig, $form->{exchangerate});
1594 for $row (1 .. scalar @{ $form->{invoice_details} }) {
1595 $item = $form->{invoice_details}->[$row - 1];
1597 map { $item->{$_} = $form->format_amount($myconfig, $item->{$_}) } qw(qty sellprice);
1599 map { $form->{"${_}_${row}"} = $item->{$_} } keys %{ $item };
1602 $form->{rowcount} = scalar @{ $form->{invoice_details} };
1604 delete @{$form}{qw(invoice_details paidaccounts storno paid)};
1606 # Restore the payment options from the user input.
1607 map { $form->{$_} = $payments{$_} } keys %payments;
1609 # Get the AP accno (which is normally done by Form::create_links()).
1613 LEFT JOIN chart c ON (at.chart_id = c.id)
1614 WHERE (trans_id = ?)
1615 AND ((c.link = 'AP') OR (c.link LIKE '%:AP') OR (c.link LIKE 'AP:%'))
1616 ORDER BY at.acc_trans_id
1619 ($form->{AP}) = selectfirst_array_query($form, $dbh, $query, conv_i($form->{id}));
1621 # Post the new payments.
1622 $self->post_invoice($myconfig, $form, $dbh, 1);
1624 restore_form($old_form);
1626 my $rc = $dbh->commit();
1629 $main::lxdebug->leave_sub();
1635 $::lxdebug->enter_sub;
1637 my ($self, %params) = @_;
1639 if (!$params{vendor_id} || !$params{invdate}) {
1640 $::lxdebug->leave_sub;
1641 return $params{default};
1644 my $dbh = $::form->get_standard_dbh;
1645 my $query = qq|SELECT ?::date + pt.terms_netto
1647 LEFT JOIN payment_terms pt ON (pt.id = v.payment_id)
1650 my ($duedate) = selectfirst_array_query($::form, $dbh, $query, $params{invdate}, $params{vendor_id});
1652 $duedate ||= $params{default};
1654 $::lxdebug->leave_sub;