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);
43 use SL::Util qw(trim);
47 use SL::GenericTranslations;
48 use SL::HTML::Restrict;
50 use SL::Locale::String qw(t8);
54 use SL::DB::MakeModel;
55 use SL::DB::ValidityToken;
57 use SL::Presenter::Part qw(type_abbreviation classification_abbreviation);
58 use List::Util qw(min);
61 use constant PCLASS_OK => 0;
62 use constant PCLASS_NOTFORSALE => 1;
63 use constant PCLASS_NOTFORPURCHASE => 2;
66 my ($self, $myconfig, $form, $provided_dbh, %params) = @_;
67 $main::lxdebug->enter_sub();
69 my $rc = SL::DB->client->with_transaction(\&_post_invoice, $self, $myconfig, $form, $provided_dbh, %params);
71 $::lxdebug->leave_sub;
76 my ($self, $myconfig, $form, $provided_dbh, %params) = @_;
80 $validity_token = SL::DB::Manager::ValidityToken->fetch_valid_token(
81 scope => SL::DB::ValidityToken::SCOPE_PURCHASE_INVOICE_POST(),
82 token => $form->{form_validity_token},
85 die $::locale->text('The form is not valid anymore.') if !$validity_token;
88 my $payments_only = $params{payments_only};
89 my $dbh = $provided_dbh || SL::DB->client->dbh;
90 my $restricter = SL::HTML::Restrict->create;
92 $form->{defaultcurrency} = $form->get_default_currency($myconfig);
93 my $defaultcurrency = $form->{defaultcurrency};
95 my $ic_cvar_configs = CVar->get_configs(module => 'IC',
98 my ($query, $sth, @values, $project_id);
99 my ($allocated, $taxrate, $taxamount, $taxdiff, $item);
100 my ($amount, $linetotal, $last_inventory_accno_tax_id_key, $last_expense_accno_tax_id_key);
101 my ($netamount, $invoicediff, $expensediff) = (0, 0, 0);
102 my $exchangerate = 0;
103 my ($basefactor, $baseqty, @taxaccounts, $totaltax);
105 my $all_units = AM->retrieve_units($myconfig, $form);
108 if (!$payments_only) {
110 &reverse_invoice($dbh, $form);
112 ($form->{id}) = selectrow_query($form, $dbh, qq|SELECT nextval('glid')|);
113 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});
116 if ($form->{currency} eq $defaultcurrency) {
117 $form->{exchangerate} = 1;
119 $exchangerate = $form->check_exchangerate($myconfig, $form->{currency}, $form->{invdate}, 'sell');
120 $form->{exchangerate} = $form->parse_amount($myconfig, $form->{exchangerate}, 5);
122 # if default exchangerate is not defined, define one
123 unless ($exchangerate) {
124 $form->update_exchangerate($dbh, $form->{currency}, $form->{invdate}, 0, $form->{exchangerate});
125 # delete records exchangerate -> if user sets new invdate for record
126 $query = qq|UPDATE ap set exchangerate = NULL where id = ?|;
127 do_query($form, $dbh, $query, $form->{"id"});
129 # update record exchangerate, if the default is set and differs from current
130 if ($exchangerate && ($form->{exchangerate} != $exchangerate)) {
131 $form->update_exchangerate($dbh, $form->{currency}, $form->{invdate},
132 0, $form->{exchangerate}, $form->{id}, 'ap');
136 my $q_item_unit = qq|SELECT unit FROM parts WHERE id = ?|;
137 my $h_item_unit = prepare_query($form, $dbh, $q_item_unit);
139 $form->get_lists('price_factors' => 'ALL_PRICE_FACTORS');
140 my %price_factors = map { $_->{id} => $_->{factor} } @{ $form->{ALL_PRICE_FACTORS} };
143 my @processed_invoice_ids;
144 for my $i (1 .. $form->{rowcount}) {
145 next unless $form->{"id_$i"};
149 $form->{"qty_$i"} = $form->parse_amount($myconfig, $form->{"qty_$i"});
150 $form->{"qty_$i"} *= -1 if $form->{storno};
152 if ( ($form->{"tax_chart_type_$i"} eq 'expense')
153 || ($form->{"tax_chart_type_$i"} eq ''
154 && $::instance_conf->get_inventory_system eq 'periodic')
156 # inventory account number is overwritten with expense account number, so
157 # never book incoming to inventory account but always to expense account
158 $form->{"inventory_accno_$i"} = $form->{"expense_accno_$i"}
162 if (!$item_units{$form->{"id_$i"}}) {
163 do_statement($form, $h_item_unit, $q_item_unit, $form->{"id_$i"});
164 ($item_units{$form->{"id_$i"}}) = $h_item_unit->fetchrow_array();
167 my $item_unit = $item_units{$form->{"id_$i"}};
169 if (defined($all_units->{$item_unit}->{factor})
170 && ($all_units->{$item_unit}->{factor} ne '')
171 && ($all_units->{$item_unit}->{factor} * 1 != 0)) {
172 $basefactor = $all_units->{$form->{"unit_$i"}}->{factor} / $all_units->{$item_unit}->{factor};
176 $baseqty = $form->{"qty_$i"} * $basefactor;
178 @taxaccounts = split / /, $form->{"taxaccounts_$i"};
183 # preset tax_id and accno for all taxaccounts
184 foreach $item (@taxaccounts) {
186 my $tax_id = $form->{"${item}_tax_id"};
187 $form->{amount}{$item . "_" . $tax_id}{tax_id} = $tax_id;
188 $form->{amount}{$item . "_" . $tax_id}{accno} = $item;
191 $form->{"sellprice_$i"} = $form->parse_amount($myconfig, $form->{"sellprice_$i"});
192 (my $fxsellprice = $form->{"sellprice_$i"}) =~ /\.(\d+)/;
194 my $decimalplaces = ($dec > 2) ? $dec : 2;
196 map { $taxrate += $form->{"${_}_rate"} } @taxaccounts;
198 $price_factor = $price_factors{ $form->{"price_factor_id_$i"} } || 1;
199 # copied from IS.pm, with some changes (no decimalplaces corrections here etc)
200 # TODO maybe use PriceTaxCalculation or something like this for backends (IR.pm / IS.pm)
202 # undo discount formatting
203 $form->{"discount_$i"} = $form->parse_amount($myconfig, $form->{"discount_$i"}) / 100;
205 $form->{"sellprice_$i"} = $fxsellprice * (1 - $form->{"discount_$i"});
207 ######################################################################
208 if ($form->{"inventory_accno_$i"}) {
210 $linetotal = $form->round_amount($form->{"sellprice_$i"} * $form->{"qty_$i"} / $price_factor, 2);
212 if ($form->{taxincluded}) {
214 $taxamount = $linetotal * ($taxrate / (1 + $taxrate));
215 $form->{"sellprice_$i"} = $form->{"sellprice_$i"} * (1 / (1 + $taxrate));
218 $taxamount = $linetotal * $taxrate;
221 $netamount += $linetotal;
223 if ($form->round_amount($taxrate, 7) == 0) {
224 if ($form->{taxincluded}) {
225 foreach $item (@taxaccounts) {
227 $form->round_amount($linetotal * $form->{"${item}_rate"} / (1 + abs($form->{"${item}_rate"})), 2);
228 $taxdiff += $taxamount;
229 $form->{amount}{$item . "_" . $form->{"${item}_tax_id"}}{amount} -= $taxamount;
231 my $first_taxaccno = $taxaccounts[0];
232 $form->{amount}{ $first_taxaccno . "_" . $form->{"${first_taxaccno}_tax_id"} }{amount} += $taxdiff;
235 map { $form->{amount}{$_ . "_" . $form->{"${_}_tax_id"}}{amount} -= $linetotal * $form->{"${_}_rate"} } @taxaccounts;
239 map { $form->{amount}{$_ . "_" . $form->{"${_}_tax_id"}}{amount} -= $taxamount * $form->{"${_}_rate"} / $taxrate } @taxaccounts;
242 # add purchase to inventory, this one is without the tax!
243 $amount = $form->{"sellprice_$i"} * $form->{"qty_$i"} * $form->{exchangerate} / $price_factor;
244 $linetotal = $form->round_amount($form->{"sellprice_$i"} * $form->{"qty_$i"} / $price_factor, 2) * $form->{exchangerate};
245 $linetotal = $form->round_amount($linetotal, 2);
247 # this is the difference for the inventory
248 $invoicediff += ($amount - $linetotal);
250 my $inventory_key = $form->{"inventory_accno_$i"} . "_" . $form->{"expense_accno_tax_id_$i"};
251 $form->{amount}{$inventory_key}{amount} -= $linetotal;
252 $form->{amount}{$inventory_key}{accno} = $form->{"inventory_accno_$i"};
253 $form->{amount}{$inventory_key}{tax_id} = $form->{"expense_accno_tax_id_$i"};
255 # adjust and round sellprice
256 $form->{"sellprice_$i"} = $form->round_amount($form->{"sellprice_$i"} * $form->{exchangerate}, $decimalplaces);
258 $last_inventory_accno_tax_id_key = $inventory_key;
260 next if $payments_only;
262 # change lastcost for part and all assemblies and assortments recursively
263 my $a = SL::DB::Part->load_cached(conv_i($form->{"id_$i"}));
264 my $part_price_factor = $a->price_factor_id ? $a->price_factor->factor : 1;
265 my $new_lastcost = abs($fxsellprice * $form->{exchangerate} / $basefactor / $price_factor * $part_price_factor);
266 if ( abs($a->lastcost - $new_lastcost) >= 0.009 ) {
267 $a->update_attributes(lastcost => $new_lastcost);
268 $a->set_lastcost_assemblies_and_assortiments;
271 # check if we sold the item already and
272 # make an entry for the expense and inventory
273 my $taxzone = $form->{taxzone_id} * 1;
275 qq|SELECT i.id, i.qty, i.allocated, i.trans_id, i.base_qty,
276 bg.inventory_accno_id, tc.expense_accno_id AS expense_accno_id, a.transdate
277 FROM invoice i, ar a, parts p, buchungsgruppen bg, taxzone_charts tc
278 WHERE (i.parts_id = p.id)
280 AND ((i.base_qty + i.allocated) > 0)
281 AND (i.trans_id = a.id)
282 AND (p.buchungsgruppen_id = bg.id)
283 AND (tc.buchungsgruppen_id = p.buchungsgruppen_id)
284 AND (tc.taxzone_id = ${taxzone})
286 # ORDER BY transdate guarantees FIFO
288 # sold two items without having bought them yet, example result of query:
289 # id | qty | allocated | trans_id | inventory_accno_id | expense_accno_id | transdate
290 # ---+-----+-----------+----------+--------------------+------------------+------------
291 # 9 | 2 | 0 | 9 | 15 | 151 | 2011-01-05
293 # base_qty + allocated > 0 if article has already been sold but not bought yet
295 # select qty,allocated,base_qty,sellprice from invoice where trans_id = 9;
296 # qty | allocated | base_qty | sellprice
297 # -----+-----------+----------+------------
298 # 2 | 0 | 2 | 1000.00000
300 $sth = prepare_execute_query($form, $dbh, $query, conv_i($form->{"id_$i"}));
302 my $totalqty = $baseqty;
304 while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
305 my $qty = min $totalqty, ($ref->{base_qty} + $ref->{allocated});
306 $linetotal = $form->round_amount(($form->{"sellprice_$i"} * $qty) / $basefactor, 2);
308 if ( $::instance_conf->get_inventory_system eq 'perpetual' ) {
309 # Warenbestandsbuchungen nur bei Bestandsmethode
311 if ($ref->{allocated} < 0) {
313 # we have an entry for it already, adjust amount
314 $form->update_balance($dbh, "acc_trans", "amount",
315 qq| (trans_id = $ref->{trans_id})
316 AND (chart_id = $ref->{inventory_accno_id})
317 AND (transdate = '$ref->{transdate}')|,
320 $form->update_balance($dbh, "acc_trans", "amount",
321 qq| (trans_id = $ref->{trans_id})
322 AND (chart_id = $ref->{expense_accno_id})
323 AND (transdate = '$ref->{transdate}')|,
326 } elsif ($linetotal != 0) {
329 # add entry for inventory, this one is for the sold item
330 $query = qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate, taxkey, tax_id, chart_link) VALUES (?, ?, ?, ?,
335 ORDER BY startdate DESC LIMIT 1),
340 ORDER BY startdate DESC LIMIT 1),
341 (SELECT link FROM chart WHERE id = ?))|;
342 @values = ($ref->{trans_id}, $ref->{inventory_accno_id}, $linetotal, $ref->{transdate}, $ref->{inventory_accno_id}, $ref->{transdate}, $ref->{inventory_accno_id}, $ref->{transdate},
343 $ref->{inventory_accno_id});
344 do_query($form, $dbh, $query, @values);
347 $query = qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate, taxkey, tax_id, chart_link) VALUES (?, ?, ?, ?,
352 ORDER BY startdate DESC LIMIT 1),
357 ORDER BY startdate DESC LIMIT 1),
358 (SELECT link FROM chart WHERE id = ?))|;
359 @values = ($ref->{trans_id}, $ref->{expense_accno_id}, ($linetotal * -1), $ref->{transdate}, $ref->{expense_accno_id}, $ref->{transdate}, $ref->{expense_accno_id}, $ref->{transdate},
360 $ref->{expense_accno_id});
361 do_query($form, $dbh, $query, @values);
365 # update allocated for sold item
366 $form->update_balance($dbh, "invoice", "allocated", qq|id = $ref->{id}|, $qty * -1);
370 last if ($totalqty -= $qty) <= 0;
375 } else { # if ($form->{"inventory_accno_id_$i"})
376 # part doesn't have an inventory_accno_id
377 # lastcost of the part is updated at the end
379 $linetotal = $form->round_amount($form->{"sellprice_$i"} * $form->{"qty_$i"} / $price_factor, 2);
381 if ($form->{taxincluded}) {
382 $taxamount = $linetotal * ($taxrate / (1 + $taxrate));
383 $form->{"sellprice_$i"} = $form->{"sellprice_$i"} * (1 / (1 + $taxrate));
386 $taxamount = $linetotal * $taxrate;
389 $netamount += $linetotal;
391 if ($form->round_amount($taxrate, 7) == 0) {
392 if ($form->{taxincluded}) {
393 foreach $item (@taxaccounts) {
394 $taxamount = $linetotal * $form->{"${item}_rate"} / (1 + abs($form->{"${item}_rate"}));
395 $totaltax += $taxamount;
396 $form->{amount}{$item . "_" . $form->{"${item}_tax_id"}}{amount} -= $taxamount;
399 map { $form->{amount}{$_ . "_" . $form->{"${_}_tax_id"}}{amount} -= $linetotal * $form->{"${_}_rate"} } @taxaccounts;
402 map { $form->{amount}{$_ . "_" . $form->{"${_}_tax_id"}}{amount} -= $taxamount * $form->{"${_}_rate"} / $taxrate } @taxaccounts;
405 $amount = $form->{"sellprice_$i"} * $form->{"qty_$i"} * $form->{exchangerate} / $price_factor;
406 $linetotal = $form->round_amount($form->{"sellprice_$i"} * $form->{"qty_$i"} / $price_factor, 2) * $form->{exchangerate};
407 $linetotal = $form->round_amount($linetotal, 2);
409 # this is the difference for expense
410 $expensediff += ($amount - $linetotal);
412 # add amount to expense
413 my $expense_key = $form->{"expense_accno_$i"} . "_" . $form->{"expense_accno_tax_id_$i"};
414 $form->{amount}{$expense_key}{amount} -= $linetotal;
415 $form->{amount}{$expense_key}{accno} = $form->{"expense_accno_$i"};
416 $form->{amount}{$expense_key}{tax_id} = $form->{"expense_accno_tax_id_$i"};
418 $last_expense_accno_tax_id_key = $expense_key;
420 # adjust and round sellprice
421 $form->{"sellprice_$i"} = $form->round_amount($form->{"sellprice_$i"} * $form->{exchangerate}, $decimalplaces);
423 next if $payments_only;
425 # change lastcost for part and all assemblies and assortments recursively
426 my $a = SL::DB::Part->load_cached(conv_i($form->{"id_$i"}));
427 my $part_price_factor = $a->price_factor_id ? $a->price_factor->factor : 1;
428 my $new_lastcost = abs($fxsellprice * $form->{exchangerate} / $basefactor / $price_factor * $part_price_factor);
429 if ( abs($a->lastcost - $new_lastcost) >= 0.009 ) {
430 $a->update_attributes(lastcost => $new_lastcost);
431 $a->set_lastcost_assemblies_and_assortiments;
435 next if $payments_only;
437 CVar->get_non_editable_ic_cvars(form => $form,
440 sub_module => 'invoice',
441 may_converted_from => ['delivery_order_items', 'orderitems', 'invoice']);
443 if (!$form->{"invoice_id_$i"}) {
444 # there is no persistent id, therefore create one with all necessary constraints
445 my $q_invoice_id = qq|SELECT nextval('invoiceid')|;
446 my $h_invoice_id = prepare_query($form, $dbh, $q_invoice_id);
447 do_statement($form, $h_invoice_id, $q_invoice_id);
448 $form->{"invoice_id_$i"} = $h_invoice_id->fetchrow_array();
449 my $q_create_invoice_id = qq|INSERT INTO invoice (id, trans_id, position, parts_id) values (?, ?, ?, ?)|;
450 do_query($form, $dbh, $q_create_invoice_id, conv_i($form->{"invoice_id_$i"}),
451 conv_i($form->{id}), conv_i($position), conv_i($form->{"id_$i"}));
452 $h_invoice_id->finish();
455 # save detail record in invoice table
457 UPDATE invoice SET trans_id = ?, position = ?, parts_id = ?, description = ?, longdescription = ?, qty = ?, base_qty = ?,
458 sellprice = ?, fxsellprice = ?, discount = ?, allocated = ?, unit = ?, deliverydate = ?,
459 project_id = ?, serialnumber = ?, price_factor_id = ?,
460 price_factor = (SELECT factor FROM price_factors WHERE id = ?), marge_price_factor = ?,
461 active_price_source = ?, active_discount_source = ?
462 ,expense_chart_id = ?, inventory_chart_id = ?, tax_id = ?, tax_chart_type = ?
466 @values = (conv_i($form->{id}), conv_i($position), conv_i($form->{"id_$i"}),
467 $form->{"description_$i"}, $restricter->process($form->{"longdescription_$i"}), $form->{"qty_$i"} * -1,
468 $baseqty * -1, $form->{"sellprice_$i"}, $fxsellprice, $form->{"discount_$i"}, $allocated,
469 $form->{"unit_$i"}, conv_date($form->{deliverydate}),
470 conv_i($form->{"project_id_$i"}), trim($form->{"serialnumber_$i"}),
471 conv_i($form->{"price_factor_id_$i"}), conv_i($form->{"price_factor_id_$i"}), conv_i($form->{"marge_price_factor_$i"}),
472 $form->{"active_price_source_$i"}, $form->{"active_discount_source_$i"},
473 $form->{"expense_chart_id_$i"}, $form->{"inventory_chart_id_$i"}, $form->{"tax_id_$i"}, $form->{"tax_chart_type_$i"},
474 conv_i($form->{"invoice_id_$i"}));
475 do_query($form, $dbh, $query, @values);
476 push @processed_invoice_ids, $form->{"invoice_id_$i"};
478 CVar->save_custom_variables(module => 'IC',
479 sub_module => 'invoice',
480 trans_id => $form->{"invoice_id_$i"},
481 configs => $ic_cvar_configs,
483 name_prefix => 'ic_',
484 name_postfix => "_$i",
487 # link previous items with invoice items See IS.pm (no credit note -> no invoice item)
488 foreach (qw(delivery_order_items orderitems invoice)) {
489 if (!$form->{useasnew} && $form->{"converted_from_${_}_id_$i"}) {
490 RecordLinks->create_links('dbh' => $dbh,
493 'from_ids' => $form->{"converted_from_${_}_id_$i"},
494 'to_table' => 'invoice',
495 'to_id' => $form->{"invoice_id_$i"},
498 delete $form->{"converted_from_${_}_id_$i"};
502 $h_item_unit->finish();
504 $project_id = conv_i($form->{"globalproject_id"});
506 $form->{datepaid} = $form->{invdate};
508 # all amounts are in natural state, netamount includes the taxes
509 # if tax is included, netamount is rounded to 2 decimal places,
513 for my $i (1 .. $form->{paidaccounts}) {
514 $form->{"paid_$i"} = $form->parse_amount($myconfig, $form->{"paid_$i"});
515 $form->{paid} += $form->{"paid_$i"};
516 $form->{datepaid} = $form->{"datepaid_$i"} if $form->{"datepaid_$i"};
519 my ($tax, $paiddiff) = (0, 0);
521 $netamount = $form->round_amount($netamount, 2);
523 # figure out rounding errors for amount paid and total amount
524 if ($form->{taxincluded}) {
526 $amount = $form->round_amount($netamount * $form->{exchangerate}, 2);
527 $paiddiff = $amount - $netamount * $form->{exchangerate};
528 $netamount = $amount;
530 foreach $item (split / /, $form->{taxaccounts}) {
531 my $key = $item . "_" . $form->{"${item}_tax_id"};
532 $amount = $form->{amount}{$key}{amount} * $form->{exchangerate};
533 $form->{amount}{$key}{amount} = $form->round_amount($amount, 2);
535 $amount = $form->{amount}{$key}{amount} * -1;
537 $netamount -= $amount;
540 $invoicediff += $paiddiff;
541 $expensediff += $paiddiff;
543 ######## this only applies to tax included
545 # in the sales invoice case rounding errors only have to be corrected for
546 # income accounts, it is enough to add the total rounding error to one of
547 # the income accounts, with the one assigned to the last row being used
548 # (last_inventory_accno_tax_id_key)
550 # in the purchase invoice case rounding errors may be split between
551 # inventory accounts and expense accounts. After rounding, an error of 1
552 # cent is introduced if the total rounding error exceeds 0.005. The total
553 # error is made up of $invoicediff and $expensediff, however, so if both
554 # values are below 0.005, but add up to a total >= 0.005, correcting
555 # last_inventory_accno_tax_id_key and last_expense_accno_tax_id_key separately has no effect after
556 # rounding. This caused bug 1579. Therefore when the combined total exceeds
557 # 0.005, but neither do individually, the account with the larger value
558 # shall receive the total rounding error, and the next time it is rounded
559 # the 1 cent correction will be introduced.
561 $form->{amount}{$last_inventory_accno_tax_id_key}{amount} -= $invoicediff if $last_inventory_accno_tax_id_key;
562 $form->{amount}{$last_expense_accno_tax_id_key}{amount} -= $expensediff if $last_expense_accno_tax_id_key;
564 if ( (abs($expensediff)+abs($invoicediff)) >= 0.005 and abs($expensediff) < 0.005 and abs($invoicediff) < 0.005 ) {
566 # in total the rounding error adds up to 1 cent effectively, correct the
567 # larger of the two numbers
569 if ( abs($form->{amount}{$last_inventory_accno_tax_id_key}{amount}) > abs($form->{amount}{$last_expense_accno_tax_id_key}{amount}) ) {
570 # $invoicediff has already been deducted, now also deduct expensediff
571 $form->{amount}{$last_inventory_accno_tax_id_key}{amount} -= $expensediff;
573 # expensediff has already been deducted, now also deduct invoicediff
574 $form->{amount}{$last_expense_accno_tax_id_key}{amount} -= $invoicediff;
579 $amount = $form->round_amount($netamount * $form->{exchangerate}, 2);
580 $paiddiff = $amount - $netamount * $form->{exchangerate};
581 $netamount = $amount;
583 foreach my $item (split / /, $form->{taxaccounts}) {
584 my $key = $item . "_" . $form->{"${item}_tax_id"};
585 $form->{amount}{$key}{amount} = $form->round_amount($form->{amount}{$key}{amount}, 2);
586 $amount = $form->round_amount( $form->{amount}{$key}{amount} * $form->{exchangerate} * -1, 2);
587 $paiddiff += $amount - $form->{amount}{$key}{amount} * $form->{exchangerate} * -1;
588 $form->{amount}{$key}{amount} = $form->round_amount($amount * -1, 2);
589 $amount = $form->{amount}{$key}{amount} * -1;
594 # record acc_trans transactions
595 my $taxdate = $form->{tax_point} || $form->{deliverydate} || $form->{invdate};
596 foreach my $accno_tax_id_key (keys %{ $form->{amount} }) {
597 $form->{amount}{$accno_tax_id_key}{amount} = $form->round_amount($form->{amount}{$accno_tax_id_key}{amount}, 2);
600 next if $payments_only || !$form->{amount}{$accno_tax_id_key}{amount};
601 my $amount = $form->{amount}{$accno_tax_id_key}{amount};
602 my $accno = $form->{amount}{$accno_tax_id_key}{accno};
603 my $tax_id = $form->{amount}{$accno_tax_id_key}{tax_id};
605 $query = qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate, taxkey, project_id, tax_id, chart_link)
606 VALUES (?, (SELECT id FROM chart WHERE accno = ?), ?, ?,
612 (SELECT link FROM chart WHERE accno = ?))|;
613 @values = (conv_i($form->{id}), $accno, $amount,
614 conv_date($form->{invdate}), $tax_id, $project_id, $tax_id, $accno);
615 do_query($form, $dbh, $query, @values);
618 my $ap_amount = $netamount + $tax;
619 my $ap_accno = $form->{AP};
620 $query = qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate, taxkey, project_id, tax_id, chart_link)
621 VALUES (?, (SELECT id FROM chart WHERE accno = ?), ?, ?,
624 WHERE chart_id= (SELECT id
628 ORDER BY startdate DESC LIMIT 1),
632 WHERE chart_id= (SELECT id
636 ORDER BY startdate DESC LIMIT 1),
637 (SELECT link FROM chart WHERE accno = ?))|;
638 @values = (conv_i($form->{id}), $ap_accno, $ap_amount,
639 conv_date($form->{invdate}), $ap_accno, conv_date($taxdate), $project_id, $ap_accno, conv_date($taxdate), $ap_accno);
640 do_query($form, $dbh, $query, @values) unless $payments_only;
643 $form->{paid} = $form->round_amount($form->{paid} * $form->{exchangerate} + $paiddiff, 2) if $form->{paid} != 0;
645 # deduct payment differences from paiddiff
646 for my $i (1 .. $form->{paidaccounts}) {
647 if ($form->{"paid_$i"} != 0) {
648 $amount = $form->round_amount($form->{"paid_$i"} * $form->{exchangerate}, 2);
649 $paiddiff -= $amount - $form->{"paid_$i"} * $form->{exchangerate};
653 # force AP entry if 0
655 $ap_amount = $form->{paid} if $ap_amount == 0;
657 my %already_cleared = %{ $params{already_cleared} // {} };
659 # record payments and offsetting AP
660 for my $i (1 .. $form->{paidaccounts}) {
661 if ($form->{"acc_trans_id_$i"}
663 && (SL::DB::Default->get->payments_changeable == 0)) {
667 next if $form->{"paid_$i"} == 0;
669 my ($accno) = split /--/, $form->{"AP_paid_$i"};
670 $form->{"datepaid_$i"} = $form->{invdate} unless ($form->{"datepaid_$i"});
671 $form->{datepaid} = $form->{"datepaid_$i"};
673 $amount = $form->round_amount($form->{"paid_$i"} * $form->{exchangerate} + $paiddiff, 2) * -1;
675 my $new_cleared = !$form->{"acc_trans_id_$i"} ? 'f'
676 : !$already_cleared{$form->{"acc_trans_id_$i"}} ? 'f'
677 : $already_cleared{$form->{"acc_trans_id_$i"}}->{amount} != $form->{"paid_$i"} ? 'f'
678 : $already_cleared{$form->{"acc_trans_id_$i"}}->{accno} != $accno ? 'f'
679 : $already_cleared{$form->{"acc_trans_id_$i"}}->{cleared} ? 't'
683 if ($ap_amount != 0) {
684 $query = qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate, taxkey, project_id, cleared, tax_id, chart_link)
685 VALUES (?, (SELECT id FROM chart WHERE accno = ?), ?, ?,
688 WHERE chart_id= (SELECT id
692 ORDER BY startdate DESC LIMIT 1),
696 WHERE chart_id= (SELECT id
700 ORDER BY startdate DESC LIMIT 1),
701 (SELECT link FROM chart WHERE accno = ?))|;
702 @values = (conv_i($form->{id}), $form->{AP}, $amount,
703 $form->{"datepaid_$i"}, $form->{AP}, conv_date($form->{"datepaid_$i"}), $project_id, $new_cleared, $form->{AP}, conv_date($form->{"datepaid_$i"}), $form->{AP});
704 do_query($form, $dbh, $query, @values);
708 my $gldate = (conv_date($form->{"gldate_$i"}))? conv_date($form->{"gldate_$i"}) : conv_date($form->current_date($myconfig));
711 qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate, gldate, source, memo, taxkey, project_id, cleared, tax_id, chart_link)
712 VALUES (?, (SELECT id FROM chart WHERE accno = ?), ?, ?, ?, ?, ?,
715 WHERE chart_id= (SELECT id
716 FROM chart WHERE accno = ?)
718 ORDER BY startdate DESC LIMIT 1),
722 WHERE chart_id= (SELECT id
723 FROM chart WHERE accno = ?)
725 ORDER BY startdate DESC LIMIT 1),
726 (SELECT link FROM chart WHERE accno = ?))|;
727 @values = (conv_i($form->{id}), $accno, $form->{"paid_$i"}, $form->{"datepaid_$i"},
728 $gldate, $form->{"source_$i"}, $form->{"memo_$i"}, $accno, conv_date($form->{"datepaid_$i"}), $project_id, $new_cleared, $accno, conv_date($form->{"datepaid_$i"}), $accno);
729 do_query($form, $dbh, $query, @values);
733 if ($form->{currency} eq $defaultcurrency) {
734 $form->{"exchangerate_$i"} = 1;
736 $exchangerate = $form->check_exchangerate($myconfig, $form->{currency}, $form->{"datepaid_$i"}, 'sell');
737 $form->{"exchangerate_$i"} = $exchangerate || $form->parse_amount($myconfig, $form->{"exchangerate_$i"});
740 # exchangerate difference
741 $form->{fx}{$accno}{ $form->{"datepaid_$i"} } += $form->{"paid_$i"} * ($form->{"exchangerate_$i"} - 1) + $paiddiff;
745 ($form->{"paid_$i"} * $form->{exchangerate}) -
746 ($form->{"paid_$i"} * $form->{"exchangerate_$i"});
748 $form->{fx}{ $form->{fxgain_accno} }{ $form->{"datepaid_$i"} } += $amount;
750 $form->{fx}{ $form->{fxloss_accno} }{ $form->{"datepaid_$i"} } += $amount;
755 # update exchange rate for PAYMENTS
756 $form->{script} = 'ir.pl';
757 $form->update_exchangerate($dbh, $form->{currency}, $form->{"datepaid_$i"}, 0, $form->{"exchangerate_$i"})
758 if ($form->{currency} ne $defaultcurrency) && !$exchangerate;
761 # record exchange rate differences and gains/losses
762 foreach my $accno (keys %{ $form->{fx} }) {
763 foreach my $transdate (keys %{ $form->{fx}{$accno} }) {
764 $form->{fx}{$accno}{$transdate} = $form->round_amount($form->{fx}{$accno}{$transdate}, 2);
765 next if ($form->{fx}{$accno}{$transdate} == 0);
767 $query = qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate, cleared, fx_transaction, taxkey, project_id, tax_id, chart_link)
768 VALUES (?, (SELECT id FROM chart WHERE accno = ?), ?, ?, '0', '1', 0, ?,
769 (SELECT id FROM tax WHERE taxkey=0 LIMIT 1),
770 (SELECT link FROM chart WHERE accno = ?))|;
771 @values = (conv_i($form->{id}), $accno, $form->{fx}{$accno}{$transdate}, conv_date($transdate), $project_id, $accno);
772 do_query($form, $dbh, $query, @values);
776 IO->set_datepaid(table => 'ap', id => $form->{id}, dbh => $dbh);
778 if ($payments_only) {
779 $query = qq|UPDATE ap SET paid = ? WHERE id = ?|;
780 do_query($form, $dbh, $query, $form->{paid}, conv_i($form->{id}));
781 $form->new_lastmtime('ap');
786 $amount = $netamount + $tax;
788 # set values which could be empty
789 my $taxzone_id = $form->{taxzone_id} * 1;
790 $taxzone_id = SL::DB::Manager::TaxZone->get_default->id unless SL::DB::Manager::TaxZone->find_by(id => $taxzone_id);
792 $form->{invnumber} = $form->{id} unless $form->{invnumber};
795 $query = qq|UPDATE ap SET
796 invnumber = ?, ordnumber = ?, quonumber = ?, transdate = ?,
797 orddate = ?, quodate = ?, vendor_id = ?, amount = ?,
798 netamount = ?, paid = ?, duedate = ?, deliverydate = ?,
799 invoice = ?, taxzone_id = ?, notes = ?, taxincluded = ?,
800 intnotes = ?, storno_id = ?, storno = ?, tax_point = ?,
801 cp_id = ?, employee_id = ?, department_id = ?, delivery_term_id = ?,
802 payment_id = ?, transaction_description = ?,
803 currency_id = (SELECT id FROM currencies WHERE name = ?),
804 globalproject_id = ?, direct_debit = ?
807 $form->{invnumber}, $form->{ordnumber}, $form->{quonumber}, conv_date($form->{invdate}),
808 conv_date($form->{orddate}), conv_date($form->{quodate}), conv_i($form->{vendor_id}), $amount,
809 $netamount, $form->{paid}, conv_date($form->{duedate}), conv_date($form->{deliverydate}),
810 '1', $taxzone_id, $restricter->process($form->{notes}), $form->{taxincluded} ? 't' : 'f',
811 $form->{intnotes}, conv_i($form->{storno_id}), $form->{storno} ? 't' : 'f', conv_date($form->{tax_point}),
812 conv_i($form->{cp_id}), conv_i($form->{employee_id}), conv_i($form->{department_id}), conv_i($form->{delivery_term_id}),
813 conv_i($form->{payment_id}), $form->{transaction_description},
815 conv_i($form->{globalproject_id}),
816 $form->{direct_debit} ? 't' : 'f',
819 do_query($form, $dbh, $query, @values);
821 if ($form->{storno}) {
822 $query = qq|UPDATE ap SET paid = paid + amount WHERE id = ?|;
823 do_query($form, $dbh, $query, conv_i($form->{storno_id}));
825 $query = qq|UPDATE ap SET storno = 't' WHERE id = ?|;
826 do_query($form, $dbh, $query, conv_i($form->{storno_id}));
828 $query = qq!UPDATE ap SET intnotes = ? || intnotes WHERE id = ?!;
829 do_query($form, $dbh, $query, "Rechnung storniert am $form->{invdate} ", conv_i($form->{storno_id}));
831 $query = qq|UPDATE ap SET paid = amount WHERE id = ?|;
832 do_query($form, $dbh, $query, conv_i($form->{id}));
835 $form->new_lastmtime('ap');
837 $form->{name} = $form->{vendor};
838 $form->{name} =~ s/--\Q$form->{vendor_id}\E//;
841 $form->add_shipto($dbh, $form->{id}, "AP");
843 # delete zero entries
844 do_query($form, $dbh, qq|DELETE FROM acc_trans WHERE amount = 0 AND trans_id = ?|, $form->{id});
847 Common::webdav_folder($form);
849 # Link this record to the records it was created from order or invoice (storno)
850 foreach (qw(oe ap)) {
851 if ($form->{"convert_from_${_}_ids"}) {
852 RecordLinks->create_links('dbh' => $dbh,
855 'from_ids' => $form->{"convert_from_${_}_ids"},
857 'to_id' => $form->{id},
859 delete $form->{"convert_from_${_}_ids"};
863 my @convert_from_do_ids = map { $_ * 1 } grep { $_ } split m/\s+/, $form->{convert_from_do_ids};
864 if (scalar @convert_from_do_ids) {
865 DO->close_orders('dbh' => $dbh,
866 'ids' => \@convert_from_do_ids);
868 RecordLinks->create_links('dbh' => $dbh,
870 'from_table' => 'delivery_orders',
871 'from_ids' => \@convert_from_do_ids,
873 'to_id' => $form->{id},
876 delete $form->{convert_from_do_ids};
878 ARAP->close_orders_if_billed('dbh' => $dbh,
879 'arap_id' => $form->{id},
882 # search for orphaned invoice items
883 $query = sprintf 'SELECT id FROM invoice WHERE trans_id = ? AND NOT id IN (%s)', join ', ', ("?") x scalar @processed_invoice_ids;
884 @values = (conv_i($form->{id}), map { conv_i($_) } @processed_invoice_ids);
885 my @orphaned_ids = map { $_->{id} } selectall_hashref_query($form, $dbh, $query, @values);
886 if (scalar @orphaned_ids) {
887 # clean up invoice items
888 $query = sprintf 'DELETE FROM invoice WHERE id IN (%s)', join ', ', ("?") x scalar @orphaned_ids;
889 do_query($form, $dbh, $query, @orphaned_ids);
892 if ($form->{draft_id}) {
893 SL::DB::Manager::Draft->delete_all(where => [ id => delete($form->{draft_id}) ]);
896 # safety check datev export
897 if ($::instance_conf->get_datev_check_on_purchase_invoice) {
899 my $datev = SL::DATEV->new(
901 trans_id => $form->{id},
904 $datev->generate_datev_data;
906 if ($datev->errors) {
907 die join "\n", $::locale->text('DATEV check returned errors:'), $datev->errors;
911 $validity_token->delete if $validity_token;
912 delete $form->{form_validity_token};
917 sub reverse_invoice {
918 $main::lxdebug->enter_sub();
920 my ($dbh, $form) = @_;
922 # reverse inventory items
924 qq|SELECT i.parts_id, p.part_type, i.qty, i.allocated, i.sellprice
925 FROM invoice i, parts p
926 WHERE (i.parts_id = p.id)
927 AND (i.trans_id = ?)|;
928 my $sth = prepare_execute_query($form, $dbh, $query, conv_i($form->{id}));
932 while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
933 $netamount += $form->round_amount($ref->{sellprice} * $ref->{qty} * -1, 2);
935 next unless $ref->{part_type} eq 'part';
937 # if $ref->{allocated} > 0 than we sold that many items
938 next if ($ref->{allocated} <= 0);
940 # get references for sold items
942 qq|SELECT i.id, i.trans_id, i.allocated, a.transdate
944 WHERE (i.parts_id = ?)
945 AND (i.allocated < 0)
946 AND (i.trans_id = a.id)
947 ORDER BY transdate DESC|;
948 my $sth2 = prepare_execute_query($form, $dbh, $query, $ref->{parts_id});
950 while (my $pthref = $sth2->fetchrow_hashref("NAME_lc")) {
951 my $qty = $ref->{allocated};
952 if (($ref->{allocated} + $pthref->{allocated}) > 0) {
953 $qty = $pthref->{allocated} * -1;
956 my $amount = $form->round_amount($ref->{sellprice} * $qty, 2);
959 $form->update_balance($dbh, "invoice", "allocated", qq|id = $pthref->{id}|, $qty);
961 if ( $::instance_conf->get_inventory_system eq 'perpetual' ) {
963 $form->update_balance($dbh, "acc_trans", "amount",
964 qq| (trans_id = $pthref->{trans_id})
965 AND (chart_id = $ref->{expense_accno_id})
966 AND (transdate = '$pthref->{transdate}')|,
969 $form->update_balance($dbh, "acc_trans", "amount",
970 qq| (trans_id = $pthref->{trans_id})
971 AND (chart_id = $ref->{inventory_accno_id})
972 AND (transdate = '$pthref->{transdate}')|,
976 last if (($ref->{allocated} -= $qty) <= 0);
982 my $id = conv_i($form->{id});
985 $query = qq|DELETE FROM acc_trans WHERE trans_id = ?|;
986 do_query($form, $dbh, $query, $id);
988 $query = qq|DELETE FROM shipto WHERE (trans_id = ?) AND (module = 'AP')|;
989 do_query($form, $dbh, $query, $id);
991 $main::lxdebug->leave_sub();
995 $main::lxdebug->enter_sub();
997 my ($self, $myconfig, $form) = @_;
999 # connect to database
1000 my $dbh = SL::DB->client->dbh;
1002 SL::DB->client->with_transaction(sub{
1004 &reverse_invoice($dbh, $form);
1006 my @values = (conv_i($form->{id}));
1009 qq|DELETE FROM invoice WHERE trans_id = ?|,
1010 qq|DELETE FROM ap WHERE id = ?|,
1013 map { do_query($form, $dbh, $_, @values) } @queries;
1015 }) or do { die SL::DB->client->error };
1020 sub retrieve_invoice {
1021 $main::lxdebug->enter_sub();
1023 my ($self, $myconfig, $form) = @_;
1025 # connect to database
1026 my $dbh = SL::DB->client->dbh;
1028 my ($query, $sth, $ref, $q_invdate);
1031 $q_invdate = qq|, COALESCE((SELECT transdate FROM ar WHERE id = (SELECT MAX(id) FROM ar)), current_date) AS invdate|;
1032 if ($form->{vendor_id}) {
1033 my $vendor_id = $dbh->quote($form->{vendor_id} * 1);
1035 qq|, COALESCE((SELECT transdate FROM ar WHERE id = (SELECT MAX(id) FROM ar)), current_date) +
1036 COALESCE((SELECT pt.terms_netto
1038 LEFT JOIN payment_terms pt ON (v.payment_id = pt.id)
1039 WHERE v.id = $vendor_id),
1044 # get default accounts and last invoice number
1047 (SELECT c.accno FROM chart c WHERE d.inventory_accno_id = c.id) AS inventory_accno,
1048 (SELECT c.accno FROM chart c WHERE d.income_accno_id = c.id) AS income_accno,
1049 (SELECT c.accno FROM chart c WHERE d.expense_accno_id = c.id) AS expense_accno,
1050 (SELECT c.accno FROM chart c WHERE d.fxgain_accno_id = c.id) AS fxgain_accno,
1051 (SELECT c.accno FROM chart c WHERE d.fxloss_accno_id = c.id) AS fxloss_accno
1054 $ref = selectfirst_hashref_query($form, $dbh, $query);
1055 map { $form->{$_} = $ref->{$_} } keys %$ref;
1058 $main::lxdebug->leave_sub();
1064 $query = qq|SELECT cp_id, invnumber, transdate AS invdate, duedate,
1065 orddate, quodate, deliverydate, tax_point, globalproject_id,
1066 ordnumber, quonumber, paid, taxincluded, notes, taxzone_id, storno, gldate,
1068 intnotes, (SELECT cu.name FROM currencies cu WHERE cu.id=ap.currency_id) AS currency, direct_debit,
1069 payment_id, delivery_term_id, transaction_description
1072 $ref = selectfirst_hashref_query($form, $dbh, $query, conv_i($form->{id}));
1073 map { $form->{$_} = $ref->{$_} } keys %$ref;
1074 $form->{mtime} = $form->{itime} if !$form->{mtime};
1075 $form->{lastmtime} = $form->{mtime};
1077 ($form->{exchangerate}, $form->{record_forex}) = $form->check_exchangerate($myconfig, $form->{currency}, $form->{invdate}, "sell", conv_i($form->{id}), 'ap');
1080 $query = qq|SELECT * FROM shipto WHERE (trans_id = ?) AND (module = 'AP')|;
1081 $ref = selectfirst_hashref_query($form, $dbh, $query, conv_i($form->{id}));
1083 map { $form->{$_} = $ref->{$_} } keys %$ref;
1085 my $transdate = $form->{tax_point} ? $dbh->quote($form->{tax_point}) :$form->{invdate} ? $dbh->quote($form->{invdate}) : "current_date";
1087 my $taxzone_id = $form->{taxzone_id} * 1;
1088 $taxzone_id = SL::DB::Manager::TaxZone->get_default->id unless SL::DB::Manager::TaxZone->find_by(id => $taxzone_id);
1090 # retrieve individual items
1093 c1.accno AS inventory_accno, c1.new_chart_id AS inventory_new_chart, date($transdate) - c1.valid_from AS inventory_valid,
1094 c2.accno AS income_accno, c2.new_chart_id AS income_new_chart, date($transdate) - c2.valid_from AS income_valid,
1095 c3.accno AS expense_accno, c3.new_chart_id AS expense_new_chart, date($transdate) - c3.valid_from AS expense_valid,
1098 i.description, i.longdescription, i.qty, i.fxsellprice AS sellprice, i.parts_id AS id, i.unit, i.deliverydate, i.project_id, i.serialnumber,
1099 i.price_factor_id, i.price_factor, i.marge_price_factor, i.discount, i.active_price_source, i.active_discount_source,
1100 p.partnumber, p.part_type, pr.projectnumber, pg.partsgroup
1101 ,p.classification_id
1102 ,i.expense_chart_id, i.inventory_chart_id, i.tax_id, i.tax_chart_type
1105 JOIN parts p ON (i.parts_id = p.id)
1106 LEFT JOIN chart c1 ON ((SELECT inventory_accno_id FROM buchungsgruppen WHERE id = p.buchungsgruppen_id) = c1.id)
1107 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)
1108 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)
1109 LEFT JOIN project pr ON (i.project_id = pr.id)
1110 LEFT JOIN partsgroup pg ON (pg.id = p.partsgroup_id)
1112 WHERE i.trans_id = ?
1114 ORDER BY i.position|;
1115 $sth = prepare_execute_query($form, $dbh, $query, conv_i($form->{id}));
1117 while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
1118 # Retrieve custom variables.
1119 my $cvars = CVar->get_custom_variables(dbh => $dbh,
1121 sub_module => 'invoice',
1122 trans_id => $ref->{invoice_id},
1124 map { $ref->{"ic_cvar_$_->{name}"} = $_->{value} } @{ $cvars };
1126 map({ delete($ref->{$_}); } qw(inventory_accno inventory_new_chart inventory_valid)) if !$ref->{"part_type"} eq 'part';
1128 foreach my $type (qw(inventory income expense)) {
1129 while ($ref->{"${type}_new_chart"} && ($ref->{"${type}_valid"} >=0)) {
1130 my $query = qq|SELECT accno, new_chart_id, date($transdate) - valid_from FROM chart WHERE id = ?|;
1131 @$ref{ map $type.$_, qw(_accno _new_chart _valid) } = selectrow_query($form, $dbh, $query, $ref->{"${type}_new_chart"});
1135 # get tax rates and description
1136 my $get_default_tax = $ref->{tax_id} eq '' ? 1 : 0;
1138 if ($get_default_tax) {
1139 my $accno_id = ($form->{vc} eq "customer") ? $ref->{income_accno} : $ref->{expense_accno};
1141 qq|SELECT c.accno, t.taxdescription, t.rate, t.id as tax_id,
1142 c.accno as taxnumber -- taxnumber is same as accno, but still accessed as taxnumber in code
1144 LEFT JOIN chart c ON (c.id = t.chart_id)
1146 (SELECT tk.tax_id FROM taxkeys tk
1147 WHERE tk.chart_id = (SELECT id FROM chart WHERE accno = ?)
1148 AND (startdate <= $transdate)
1149 ORDER BY startdate DESC
1152 $stw = prepare_execute_query($form, $dbh, $query, $accno_id);
1154 } else { # use saved tax_id
1156 qq|SELECT c.accno, t.taxdescription, t.rate, t.id as tax_id,
1157 c.accno as taxnumber -- taxnumber is same as accno, but still accessed as taxnumber in code
1159 LEFT JOIN chart c ON (c.id = t.chart_id)
1163 $stw = prepare_execute_query($form, $dbh, $query, $ref->{tax_id});
1166 $ref->{taxaccounts} = "";
1167 while (my $ptr = $stw->fetchrow_hashref("NAME_lc")) {
1168 if (($ptr->{accno} eq "") && ($ptr->{rate} == 0)) {
1169 $ptr->{accno} = "NO_ACCNO_" . $ptr->{tax_id};
1172 $ref->{taxaccounts} .= "$ptr->{accno} ";
1174 if (!($form->{taxaccounts} =~ /\Q$ptr->{accno}\E/)) {
1175 $form->{"$ptr->{accno}_rate"} = $ptr->{rate};
1176 $form->{"$ptr->{accno}_description"} = $ptr->{taxdescription};
1177 $form->{"$ptr->{accno}_taxnumber"} = $ptr->{taxnumber};
1178 $form->{"$ptr->{accno}_tax_id"} = $ptr->{tax_id};
1179 $form->{taxaccounts} .= "$ptr->{accno} ";
1184 chop $ref->{taxaccounts};
1185 push @{ $form->{invoice_details} }, $ref;
1190 Common::webdav_folder($form);
1192 $main::lxdebug->leave_sub();
1196 $main::lxdebug->enter_sub();
1198 my ($self, $myconfig, $form, $params) = @_;
1200 $params = $form unless defined $params && ref $params eq "HASH";
1202 # connect to database
1203 my $dbh = SL::DB->client->dbh;
1205 my $dateformat = $myconfig->{dateformat};
1206 $dateformat .= "yy" if $myconfig->{dateformat} !~ /^y/;
1208 my $vid = conv_i($params->{vendor_id});
1209 my $vnr = $params->{vendornumber};
1212 ($params->{invdate})
1213 ? "to_date(" . $dbh->quote($params->{invdate}) . ", '$dateformat')"
1220 $where .= 'AND v.id = ?';
1223 $where .= 'AND v.vendornumber = ?';
1228 v.id AS vendor_id, v.name AS vendor, v.discount as vendor_discount,
1229 v.creditlimit, v.notes AS intnotes,
1230 v.email, v.cc, v.bcc, v.language_id, v.payment_id, v.delivery_term_id,
1231 v.street, v.zipcode, v.city, v.country, v.taxzone_id, cu.name AS curr, v.direct_debit,
1232 $duedate + COALESCE(pt.terms_netto, 0) AS duedate,
1233 b.discount AS tradediscount, b.description AS business
1235 LEFT JOIN business b ON (b.id = v.business_id)
1236 LEFT JOIN payment_terms pt ON (v.payment_id = pt.id)
1237 LEFT JOIN currencies cu ON (v.currency_id = cu.id)
1239 my $ref = selectfirst_hashref_query($form, $dbh, $query, @values);
1240 die t8("Cannot find a single vendor. Maybe there is no vendor yet?") unless $ref;
1242 map { $params->{$_} = $ref->{$_} } keys %$ref;
1244 # use vendor currency
1245 $form->{currency} = $form->{curr};
1247 $params->{creditremaining} = $params->{creditlimit};
1249 $query = qq|SELECT SUM(amount - paid) FROM ap WHERE vendor_id = ?|;
1250 my ($unpaid_invoices) = selectfirst_array_query($form, $dbh, $query, $vid);
1251 $params->{creditremaining} -= $unpaid_invoices;
1253 $query = qq|SELECT o.amount,
1256 WHERE (e.currency_id = o.currency_id)
1257 AND (e.transdate = o.transdate)) AS exch
1259 WHERE (o.vendor_id = ?) AND (o.record_type = 'purchase_order') AND (o.closed = '0')|;
1260 my $sth = prepare_execute_query($form, $dbh, $query, $vid);
1261 while (my ($amount, $exch) = $sth->fetchrow_array()) {
1262 $exch = 1 unless $exch;
1263 $params->{creditremaining} -= $amount * $exch;
1267 $main::lxdebug->leave_sub();
1271 $main::lxdebug->enter_sub();
1273 my ($self, $myconfig, $form) = @_;
1275 my $dbh = SL::DB->client->dbh;
1277 my $i = $form->{rowcount};
1279 # don't include assemblies or obsolete parts
1280 my $where = "NOT p.part_type = 'assembly' AND NOT p.obsolete = '1'";
1283 foreach my $table_column (qw(p.partnumber p.description pg.partsgroup)) {
1284 my $field = (split m{\.}, $table_column)[1];
1285 next unless $form->{"${field}_${i}"};
1286 $where .= " AND lower(${table_column}) LIKE lower(?)";
1287 push @values, like($form->{"${field}_${i}"});
1291 if ($form->{"partnumber_$i"} && !$form->{"description_$i"}) {
1292 $where .= qq| OR (NOT p.obsolete = '1' AND p.ean = ? )|;
1293 push @values, $form->{"partnumber_$i"};
1295 # also search hits in makemodels, but only cache the results by id and merge later
1297 SELECT parts_id, model FROM makemodel
1298 LEFT JOIN parts ON parts.id = parts_id
1299 WHERE NOT parts.obsolete AND model ILIKE ? AND (make IS NULL OR make = ?);
1301 my $mm_results = selectall_hashref_query($::form, $dbh, $mm_query, like($form->{"partnumber_$i"}), $::form->{vendor_id});
1302 my @mm_ids = map { $_->{parts_id} } @$mm_results;
1303 push @{$mm_by_id{ $_->{parts_id} } ||= []}, $_ for @$mm_results;
1306 $where .= qq| OR p.id IN (| . join(',', ('?') x @mm_ids) . qq|)|;
1307 push @values, @mm_ids;
1311 # Search for part ID overrides all other criteria.
1312 if ($form->{"id_${i}"}) {
1313 $where = qq|p.id = ?|;
1314 @values = ($form->{"id_${i}"});
1317 if ($form->{"description_$i"}) {
1318 $where .= " ORDER BY p.description";
1320 $where .= " ORDER BY p.partnumber";
1324 if ($form->{type} eq "invoice") {
1325 $transdate = $form->{deliverydate} ? $dbh->quote($form->{deliverydate})
1326 : $form->{invdate} ? $dbh->quote($form->{invdate})
1329 $transdate = $form->{transdate} ? $dbh->quote($form->{transdate}) : "current_date";
1332 my $taxzone_id = $form->{taxzone_id} * 1;
1333 $taxzone_id = SL::DB::Manager::TaxZone->get_default->id unless SL::DB::Manager::TaxZone->find_by(id => $taxzone_id);
1337 p.id, p.partnumber, p.description, p.lastcost AS sellprice, p.listprice,
1338 p.unit, p.part_type, p.onhand, p.formel,
1339 p.notes AS partnotes, p.notes AS longdescription, p.not_discountable,
1342 p.classification_id,
1344 pfac.factor AS price_factor,
1346 c1.accno AS inventory_accno,
1347 c1.new_chart_id AS inventory_new_chart,
1348 date($transdate) - c1.valid_from AS inventory_valid,
1350 c2.accno AS income_accno,
1351 c2.new_chart_id AS income_new_chart,
1352 date($transdate) - c2.valid_from AS income_valid,
1354 c3.accno AS expense_accno,
1355 c3.new_chart_id AS expense_new_chart,
1356 date($transdate) - c3.valid_from AS expense_valid,
1358 pt.used_for_purchase AS used_for_purchase,
1362 LEFT JOIN chart c1 ON
1363 ((SELECT inventory_accno_id
1364 FROM buchungsgruppen
1365 WHERE id = p.buchungsgruppen_id) = c1.id)
1366 LEFT JOIN chart c2 ON
1367 ((SELECT tc.income_accno_id
1368 FROM taxzone_charts tc
1369 WHERE tc.taxzone_id = '$taxzone_id' and tc.buchungsgruppen_id = p.buchungsgruppen_id) = c2.id)
1370 LEFT JOIN chart c3 ON
1371 ((SELECT tc.expense_accno_id
1372 FROM taxzone_charts tc
1373 WHERE tc.taxzone_id = '$taxzone_id' and tc.buchungsgruppen_id = p.buchungsgruppen_id) = c3.id)
1374 LEFT JOIN partsgroup pg ON (pg.id = p.partsgroup_id)
1375 LEFT JOIN part_classifications pt ON (pt.id = p.classification_id)
1376 LEFT JOIN price_factors pfac ON (pfac.id = p.price_factor_id)
1378 my $sth = prepare_execute_query($form, $dbh, $query, @values);
1380 my @translation_queries = ( [ qq|SELECT tr.translation, tr.longdescription
1382 WHERE tr.language_id = ? AND tr.parts_id = ?| ],
1383 [ qq|SELECT tr.translation, tr.longdescription
1385 WHERE tr.language_id IN
1388 WHERE article_code = (SELECT article_code FROM language WHERE id = ?))
1391 map { push @{ $_ }, prepare_query($form, $dbh, $_->[0]) } @translation_queries;
1393 $form->{item_list} = [];
1394 my $has_wrong_pclass = PCLASS_OK;
1395 while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
1397 if ($mm_by_id{$ref->{id}}) {
1398 $ref->{makemodels} = $mm_by_id{$ref->{id}};
1399 push @{ $ref->{matches} ||= [] }, $::locale->text('Model') . ': ' . join ', ', map { $_->{model} } @{ $mm_by_id{$ref->{id}} };
1402 if (($::form->{"partnumber_$i"} ne '') && ($ref->{ean} eq $::form->{"partnumber_$i"})) {
1403 push @{ $ref->{matches} ||= [] }, $::locale->text('EAN') . ': ' . $ref->{ean};
1405 $ref->{type_and_classific} = type_abbreviation($ref->{part_type}) .
1406 classification_abbreviation($ref->{classification_id});
1408 if (! $ref->{used_for_purchase} ) {
1409 $has_wrong_pclass = PCLASS_NOTFORPURCHASE;
1412 # In der Buchungsgruppe ist immer ein Bestandskonto verknuepft, auch wenn
1413 # es sich um eine Dienstleistung handelt. Bei Dienstleistungen muss das
1414 # Buchungskonto also aus dem Ergebnis rausgenommen werden.
1415 if (!$ref->{inventory_accno_id}) {
1416 map({ delete($ref->{"inventory_${_}"}); } qw(accno new_chart valid));
1418 delete($ref->{inventory_accno_id});
1420 # get tax rates and description
1421 my $accno_id = ($form->{vc} eq "customer") ? $ref->{income_accno} : $ref->{expense_accno};
1423 qq|SELECT c.accno, t.taxdescription, t.rate, c.accno as taxnumber, t.id as tax_id
1425 LEFT JOIN chart c on (c.id = t.chart_id)
1433 AND (startdate <= $transdate)
1434 ORDER BY startdate DESC
1437 my $stw = prepare_execute_query($form, $dbh, $query, $accno_id);
1439 $ref->{taxaccounts} = "";
1441 while (my $ptr = $stw->fetchrow_hashref("NAME_lc")) {
1443 if (($ptr->{accno} eq "") && ($ptr->{rate} == 0)) {
1448 $ref->{taxaccounts} .= "$ptr->{accno} ";
1450 if (!($form->{taxaccounts} =~ /\Q$ptr->{accno}\E/)) {
1451 $form->{"$ptr->{accno}_rate"} = $ptr->{rate};
1452 $form->{"$ptr->{accno}_description"} = $ptr->{taxdescription};
1453 $form->{"$ptr->{accno}_taxnumber"} = $ptr->{taxnumber};
1454 $form->{"$ptr->{accno}_tax_id"} = $ptr->{tax_id};
1455 $form->{taxaccounts} .= "$ptr->{accno} ";
1458 if ($form->{language_id}) {
1459 for my $spec (@translation_queries) {
1460 do_statement($form, $spec->[1], $spec->[0], conv_i($form->{language_id}), conv_i($ref->{id}));
1461 my ($translation, $longdescription) = $spec->[1]->fetchrow_array;
1462 next unless $translation;
1463 $ref->{description} = $translation;
1464 $ref->{longdescription} = $longdescription;
1471 chop $ref->{taxaccounts};
1473 $ref->{onhand} *= 1;
1474 push @{ $form->{item_list} }, $ref;
1479 $_->[1]->finish for @translation_queries;
1481 $form->{is_wrong_pclass} = $has_wrong_pclass;
1482 $form->{NOTFORSALE} = PCLASS_NOTFORSALE;
1483 $form->{NOTFORPURCHASE} = PCLASS_NOTFORPURCHASE;
1484 foreach my $item (@{ $form->{item_list} }) {
1485 my $custom_variables = CVar->get_custom_variables(module => 'IC',
1486 trans_id => $item->{id},
1489 $form->{is_wrong_pclass} = PCLASS_OK; # one correct type
1490 map { $item->{"ic_cvar_" . $_->{name} } = $_->{value} } @{ $custom_variables };
1493 $main::lxdebug->leave_sub();
1496 sub vendor_details {
1497 $main::lxdebug->enter_sub();
1499 my ($self, $myconfig, $form, @wanted_vars) = @_;
1501 my $dbh = SL::DB->client->dbh;
1505 # get contact id, set it if nessessary
1506 $form->{cp_id} *= 1;
1508 if ($form->{cp_id}) {
1509 $contact = "AND cp.cp_id = ?";
1510 push @values, $form->{cp_id};
1513 # get rest for the vendor
1514 # fax and phone and email as vendor*
1516 qq|SELECT ct.*, cp.*, ct.notes as vendornotes, phone as vendorphone, fax as vendorfax, email as vendoremail,
1519 LEFT JOIN contacts cp ON (ct.id = cp.cp_cv_id)
1520 LEFT JOIN currencies cu ON (ct.currency_id = cu.id)
1521 WHERE (ct.id = ?) $contact
1524 my $ref = selectfirst_hashref_query($form, $dbh, $query, $form->{vendor_id}, @values);
1526 # remove id,notes (double of vendornotes) and taxincluded before copy back
1527 delete @$ref{qw(id taxincluded notes)};
1529 @wanted_vars = grep({ $_ } @wanted_vars);
1530 if (scalar(@wanted_vars) > 0) {
1532 map({ $h_wanted_vars{$_} = 1; } @wanted_vars);
1533 map({ delete($ref->{$_}) unless ($h_wanted_vars{$_}); } keys(%{$ref}));
1536 map { $form->{$_} = $ref->{$_} } keys %$ref;
1538 my $custom_variables = CVar->get_custom_variables('dbh' => $dbh,
1540 'trans_id' => $form->{vendor_id});
1541 map { $form->{"vc_cvar_$_->{name}"} = $_->{value} } @{ $custom_variables };
1543 if ($form->{cp_id}) {
1544 $custom_variables = CVar->get_custom_variables(dbh => $dbh,
1545 module => 'Contacts',
1546 trans_id => $form->{cp_id});
1547 $form->{"cp_cvar_$_->{name}"} = $_->{value} for @{ $custom_variables };
1550 $form->{cp_greeting} = GenericTranslations->get('dbh' => $dbh,
1551 'translation_type' => 'greetings::' . ($form->{cp_gender} eq 'f' ? 'female' : 'male'),
1552 'allow_fallback' => 1);
1554 $main::lxdebug->leave_sub();
1558 $main::lxdebug->enter_sub();
1560 my ($self, $myconfig, $form) = @_;
1562 my $dbh = SL::DB->client->dbh;
1565 qq|SELECT accno, description, link
1567 WHERE link LIKE '%IC%'
1569 my $sth = prepare_execute_query($query, $dbh, $query);
1571 while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
1572 foreach my $key (split(/:/, $ref->{link})) {
1574 push @{ $form->{IC_links}{$key} },
1575 { accno => $ref->{accno},
1576 description => $ref->{description} };
1582 $main::lxdebug->leave_sub();
1585 sub _delete_payments {
1586 $main::lxdebug->enter_sub();
1588 my ($self, $form, $dbh) = @_;
1590 my @delete_acc_trans_ids;
1592 # Delete old payment entries from acc_trans.
1594 qq|SELECT acc_trans_id
1596 WHERE (trans_id = ?) AND fx_transaction
1600 SELECT at.acc_trans_id
1602 LEFT JOIN chart c ON (at.chart_id = c.id)
1603 WHERE (trans_id = ?) AND (c.link LIKE '%AP_paid%')|;
1604 push @delete_acc_trans_ids, selectall_array_query($form, $dbh, $query, conv_i($form->{id}), conv_i($form->{id}));
1607 qq|SELECT at.acc_trans_id
1609 LEFT JOIN chart c ON (at.chart_id = c.id)
1610 WHERE (trans_id = ?)
1611 AND ((c.link = 'AP') OR (c.link LIKE '%:AP') OR (c.link LIKE 'AP:%'))
1612 ORDER BY at.acc_trans_id
1614 push @delete_acc_trans_ids, selectall_array_query($form, $dbh, $query, conv_i($form->{id}));
1616 if (@delete_acc_trans_ids) {
1617 $query = qq|DELETE FROM acc_trans WHERE acc_trans_id IN (| . join(", ", @delete_acc_trans_ids) . qq|)|;
1618 do_query($form, $dbh, $query);
1621 $main::lxdebug->leave_sub();
1625 my ($self, $myconfig, $form, $locale) = @_;
1626 $main::lxdebug->enter_sub();
1628 my $rc = SL::DB->client->with_transaction(\&_post_payment, $self, $myconfig, $form, $locale);
1630 $::lxdebug->leave_sub;
1635 my ($self, $myconfig, $form, $locale) = @_;
1637 my $dbh = SL::DB->client->dbh;
1639 my (%payments, $old_form, $row, $item, $query, %keep_vars);
1641 $old_form = save_form();
1644 SELECT at.acc_trans_id, at.amount, at.cleared, c.accno
1646 LEFT JOIN chart c ON (at.chart_id = c.id)
1647 WHERE (at.trans_id = ?)
1650 my %already_cleared = selectall_as_map($form, $dbh, $query, 'acc_trans_id', [ qw(amount cleared accno) ], $form->{id});
1652 # Delete all entries in acc_trans from prior payments.
1653 if (SL::DB::Default->get->payments_changeable != 0) {
1654 $self->_delete_payments($form, $dbh);
1657 # Save the new payments the user made before cleaning up $form.
1658 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 };
1660 # Clean up $form so that old content won't tamper the results.
1661 %keep_vars = map { $_, 1 } qw(login password id);
1662 map { delete $form->{$_} unless $keep_vars{$_} } keys %{ $form };
1664 # Retrieve the invoice from the database.
1665 $self->retrieve_invoice($myconfig, $form);
1667 # Set up the content of $form in the way that IR::post_invoice() expects.
1668 $form->{exchangerate} = $form->format_amount($myconfig, $form->{exchangerate});
1670 for $row (1 .. scalar @{ $form->{invoice_details} }) {
1671 $item = $form->{invoice_details}->[$row - 1];
1673 map { $item->{$_} = $form->format_amount($myconfig, $item->{$_}) } qw(qty sellprice);
1675 map { $form->{"${_}_${row}"} = $item->{$_} } keys %{ $item };
1678 $form->{rowcount} = scalar @{ $form->{invoice_details} };
1680 delete @{$form}{qw(invoice_details paidaccounts storno paid)};
1682 # Restore the payment options from the user input.
1683 map { $form->{$_} = $payments{$_} } keys %payments;
1685 # Get the AP accno (which is normally done by Form::create_links()).
1689 LEFT JOIN chart c ON (at.chart_id = c.id)
1690 WHERE (trans_id = ?)
1691 AND ((c.link = 'AP') OR (c.link LIKE '%:AP') OR (c.link LIKE 'AP:%'))
1692 ORDER BY at.acc_trans_id
1695 ($form->{AP}) = selectfirst_array_query($form, $dbh, $query, conv_i($form->{id}));
1697 # Post the new payments.
1698 $self->post_invoice($myconfig, $form, $dbh, payments_only => 1, already_cleared => \%already_cleared);
1700 restore_form($old_form);
1706 $::lxdebug->enter_sub;
1708 my ($self, %params) = @_;
1710 if (!$params{vendor_id} || !$params{invdate}) {
1711 $::lxdebug->leave_sub;
1712 return $params{default};
1715 my $dbh = $::form->get_standard_dbh;
1716 my $query = qq|SELECT ?::date + pt.terms_netto
1718 LEFT JOIN payment_terms pt ON (pt.id = v.payment_id)
1721 my ($duedate) = selectfirst_array_query($::form, $dbh, $query, $params{invdate}, $params{vendor_id});
1723 $duedate ||= $params{default};
1725 $::lxdebug->leave_sub;