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;
47 use List::Util qw(min);
52 $main::lxdebug->enter_sub();
54 my ($self, $myconfig, $form, $provided_dbh, $payments_only) = @_;
56 # connect to database, turn off autocommit
57 my $dbh = $provided_dbh ? $provided_dbh : $form->dbconnect_noauto($myconfig);
58 $form->{defaultcurrency} = $form->get_default_currency($myconfig);
60 my $ic_cvar_configs = CVar->get_configs(module => 'IC',
63 my ($query, $sth, @values, $project_id);
64 my ($allocated, $taxrate, $taxamount, $taxdiff, $item);
65 my ($amount, $linetotal, $lastinventoryaccno, $lastexpenseaccno);
66 my ($netamount, $invoicediff, $expensediff) = (0, 0, 0);
68 my ($basefactor, $baseqty, @taxaccounts, $totaltax);
70 my $all_units = AM->retrieve_units($myconfig, $form);
72 if (!$payments_only) {
74 &reverse_invoice($dbh, $form);
76 ($form->{id}) = selectrow_query($form, $dbh, qq|SELECT nextval('glid')|);
77 do_query($form, $dbh, qq|INSERT INTO ap (id, invnumber) VALUES (?, '')|, $form->{id});
81 my ($currencies) = selectfirst_array_query($form, $dbh, qq|SELECT curr FROM defaults|);
82 my $defaultcurrency = (split m/:/, $currencies)[0];
84 if ($form->{currency} eq $defaultcurrency) {
85 $form->{exchangerate} = 1;
87 $exchangerate = $form->check_exchangerate($myconfig, $form->{currency}, $form->{invdate}, 'sell');
90 $form->{exchangerate} = $exchangerate || $form->parse_amount($myconfig, $form->{exchangerate});
91 $form->{exchangerate} = 1 unless ($form->{exchangerate} * 1);
94 my $q_item_unit = qq|SELECT unit FROM parts WHERE id = ?|;
95 my $h_item_unit = prepare_query($form, $dbh, $q_item_unit);
97 $form->get_lists('price_factors' => 'ALL_PRICE_FACTORS');
98 my %price_factors = map { $_->{id} => $_->{factor} } @{ $form->{ALL_PRICE_FACTORS} };
101 for my $i (1 .. $form->{rowcount}) {
102 next unless $form->{"id_$i"};
104 $form->{"qty_$i"} = $form->parse_amount($myconfig, $form->{"qty_$i"});
105 $form->{"qty_$i"} *= -1 if $form->{storno};
107 if ( $::instance_conf->get_inventory_system eq 'periodic') {
108 # inventory account number is overwritten with expense account number, so
109 # never book incoming to inventory account but always to expense account
110 $form->{"inventory_accno_$i"} = $form->{"expense_accno_$i"}
114 if (!$item_units{$form->{"id_$i"}}) {
115 do_statement($form, $h_item_unit, $q_item_unit, $form->{"id_$i"});
116 ($item_units{$form->{"id_$i"}}) = $h_item_unit->fetchrow_array();
119 my $item_unit = $item_units{$form->{"id_$i"}};
121 if (defined($all_units->{$item_unit}->{factor})
122 && ($all_units->{$item_unit}->{factor} ne '')
123 && ($all_units->{$item_unit}->{factor} * 1 != 0)) {
124 $basefactor = $all_units->{$form->{"unit_$i"}}->{factor} / $all_units->{$item_unit}->{factor};
128 $baseqty = $form->{"qty_$i"} * $basefactor;
130 @taxaccounts = split / /, $form->{"taxaccounts_$i"};
135 $form->{"sellprice_$i"} = $form->parse_amount($myconfig, $form->{"sellprice_$i"});
136 (my $fxsellprice = $form->{"sellprice_$i"}) =~ /\.(\d+)/;
138 my $decimalplaces = ($dec > 2) ? $dec : 2;
140 map { $taxrate += $form->{"${_}_rate"} } @taxaccounts;
142 $price_factor = $price_factors{ $form->{"price_factor_id_$i"} } || 1;
143 #####################################################################
144 # das ist aus IS.pm kopiert. schlimm. jb 7.10.2009
145 # ich würde mir wünschen, dass diese vier stellen zusammengefasst werden
146 # ... vier stellen = (einkauf + verkauf) * (maske + backend)
147 # ansonsten stolpert man immer wieder viermal statt einmal heftig
148 # und auch das undo discount formatting ist nicht besonders wartungsfreundlich
150 # keine ahnung wofür das in IS.pm gemacht wird:
151 # my ($dec) = ($fxsellprice =~ /\.(\d+)/);
152 # $dec = length $dec;
153 # my $decimalplaces = ($dec > 2) ? $dec : 2;
155 # undo discount formatting
156 $form->{"discount_$i"} = $form->parse_amount($myconfig, $form->{"discount_$i"}) / 100;
158 $form->{"sellprice_$i"} = $fxsellprice * (1 - $form->{"discount_$i"});
160 ######################################################################
161 if ($form->{"inventory_accno_$i"}) {
163 $linetotal = $form->round_amount($form->{"sellprice_$i"} * $form->{"qty_$i"} / $price_factor, 2);
165 if ($form->{taxincluded}) {
167 $taxamount = $linetotal * ($taxrate / (1 + $taxrate));
168 $form->{"sellprice_$i"} = $form->{"sellprice_$i"} * (1 / (1 + $taxrate));
171 $taxamount = $linetotal * $taxrate;
174 $netamount += $linetotal;
176 if ($form->round_amount($taxrate, 7) == 0) {
177 if ($form->{taxincluded}) {
178 foreach $item (@taxaccounts) {
180 $form->round_amount($linetotal * $form->{"${item}_rate"} / (1 + abs($form->{"${item}_rate"})), 2);
181 $taxdiff += $taxamount;
182 $form->{amount}{ $form->{id} }{$item} -= $taxamount;
184 $form->{amount}{ $form->{id} }{ $taxaccounts[0] } += $taxdiff;
187 map { $form->{amount}{ $form->{id} }{$_} -= $linetotal * $form->{"${_}_rate"} } @taxaccounts;
191 map { $form->{amount}{ $form->{id} }{$_} -= $taxamount * $form->{"${_}_rate"} / $taxrate } @taxaccounts;
194 # add purchase to inventory, this one is without the tax!
195 $amount = $form->{"sellprice_$i"} * $form->{"qty_$i"} * $form->{exchangerate} / $price_factor;
196 $linetotal = $form->round_amount($form->{"sellprice_$i"} * $form->{"qty_$i"} / $price_factor, 2) * $form->{exchangerate};
197 $linetotal = $form->round_amount($linetotal, 2);
199 # this is the difference for the inventory
200 $invoicediff += ($amount - $linetotal);
202 $form->{amount}{ $form->{id} }{ $form->{"inventory_accno_$i"} } -= $linetotal;
204 # adjust and round sellprice
205 $form->{"sellprice_$i"} = $form->round_amount($form->{"sellprice_$i"} * $form->{exchangerate}, $decimalplaces);
207 $lastinventoryaccno = $form->{"inventory_accno_$i"};
209 next if $payments_only;
211 # update parts table by setting lastcost to current price, don't allow negative values by using abs
212 $query = qq|UPDATE parts SET lastcost = ? WHERE id = ?|;
213 @values = (abs($form->{"sellprice_$i"} / $basefactor), conv_i($form->{"id_$i"}));
214 do_query($form, $dbh, $query, @values);
216 # check if we sold the item already and
217 # make an entry for the expense and inventory
219 qq|SELECT i.id, i.qty, i.allocated, i.trans_id, i.base_qty,
220 p.inventory_accno_id, p.expense_accno_id, a.transdate
221 FROM invoice i, ar a, parts p
222 WHERE (i.parts_id = p.id)
224 AND ((i.base_qty + i.allocated) > 0)
225 AND (i.trans_id = a.id)
227 # ORDER BY transdate guarantees FIFO
229 # sold two items without having bought them yet, example result of query:
230 # id | qty | allocated | trans_id | inventory_accno_id | expense_accno_id | transdate
231 # ---+-----+-----------+----------+--------------------+------------------+------------
232 # 9 | 2 | 0 | 9 | 15 | 151 | 2011-01-05
234 # base_qty + allocated > 0 if article has already been sold but not bought yet
236 # select qty,allocated,base_qty,sellprice from invoice where trans_id = 9;
237 # qty | allocated | base_qty | sellprice
238 # -----+-----------+----------+------------
239 # 2 | 0 | 2 | 1000.00000
241 $sth = prepare_execute_query($form, $dbh, $query, conv_i($form->{"id_$i"}));
243 my $totalqty = $baseqty;
245 while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
246 my $qty = min $totalqty, ($ref->{base_qty} + $ref->{allocated});
247 $linetotal = $form->round_amount(($form->{"sellprice_$i"} * $qty) / $basefactor, 2);
249 if ( $::instance_conf->get_inventory_system eq 'perpetual' ) {
250 # Warenbestandsbuchungen nur bei Bestandsmethode
252 if ($ref->{allocated} < 0) {
254 # we have an entry for it already, adjust amount
255 $form->update_balance($dbh, "acc_trans", "amount",
256 qq| (trans_id = $ref->{trans_id})
257 AND (chart_id = $ref->{inventory_accno_id})
258 AND (transdate = '$ref->{transdate}')|,
261 $form->update_balance($dbh, "acc_trans", "amount",
262 qq| (trans_id = $ref->{trans_id})
263 AND (chart_id = $ref->{expense_accno_id})
264 AND (transdate = '$ref->{transdate}')|,
267 } elsif ($linetotal != 0) {
270 # add entry for inventory, this one is for the sold item
271 $query = qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate, taxkey) VALUES (?, ?, ?, ?, (SELECT taxkey_id FROM chart WHERE id = ?))|;
272 @values = ($ref->{trans_id}, $ref->{inventory_accno_id}, $linetotal, $ref->{transdate}, $ref->{inventory_accno_id});
273 do_query($form, $dbh, $query, @values);
276 $query = qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate, taxkey) VALUES (?, ?, ?, ?, (SELECT taxkey from tax WHERE chart_id = ?))|;
277 @values = ($ref->{trans_id}, $ref->{expense_accno_id}, ($linetotal * -1), $ref->{transdate}, $ref->{expense_accno_id});
278 do_query($form, $dbh, $query, @values);
282 # update allocated for sold item
283 $form->update_balance($dbh, "invoice", "allocated", qq|id = $ref->{id}|, $qty * -1);
287 last if ($totalqty -= $qty) <= 0;
292 } else { # if ($form->{"inventory_accno_id_$i"})
293 # part doesn't have an inventory_accno_id
294 # lastcost of the part is updated at the end
296 $linetotal = $form->round_amount($form->{"sellprice_$i"} * $form->{"qty_$i"} / $price_factor, 2);
298 if ($form->{taxincluded}) {
299 $taxamount = $linetotal * ($taxrate / (1 + $taxrate));
300 $form->{"sellprice_$i"} = $form->{"sellprice_$i"} * (1 / (1 + $taxrate));
303 $taxamount = $linetotal * $taxrate;
306 $netamount += $linetotal;
308 if ($form->round_amount($taxrate, 7) == 0) {
309 if ($form->{taxincluded}) {
310 foreach $item (@taxaccounts) {
311 $taxamount = $linetotal * $form->{"${item}_rate"} / (1 + abs($form->{"${item}_rate"}));
312 $totaltax += $taxamount;
313 $form->{amount}{ $form->{id} }{$item} -= $taxamount;
316 map { $form->{amount}{ $form->{id} }{$_} -= $linetotal * $form->{"${_}_rate"} } @taxaccounts;
319 map { $form->{amount}{ $form->{id} }{$_} -= $taxamount * $form->{"${_}_rate"} / $taxrate } @taxaccounts;
322 $amount = $form->{"sellprice_$i"} * $form->{"qty_$i"} * $form->{exchangerate} / $price_factor;
323 $linetotal = $form->round_amount($form->{"sellprice_$i"} * $form->{"qty_$i"} / $price_factor, 2) * $form->{exchangerate};
324 $linetotal = $form->round_amount($linetotal, 2);
326 # this is the difference for expense
327 $expensediff += ($amount - $linetotal);
329 # add amount to expense
330 $form->{amount}{ $form->{id} }{ $form->{"expense_accno_$i"} } -= $linetotal;
332 $lastexpenseaccno = $form->{"expense_accno_$i"};
334 # adjust and round sellprice
335 $form->{"sellprice_$i"} = $form->round_amount($form->{"sellprice_$i"} * $form->{exchangerate}, $decimalplaces);
337 next if $payments_only;
340 $query = qq|UPDATE parts SET lastcost = ? WHERE id = ?|;
341 do_query($form, $dbh, $query, $form->{"sellprice_$i"} / $basefactor, conv_i($form->{"id_$i"}));
344 next if $payments_only;
346 # save detail record in invoice table
347 my ($invoice_id) = selectfirst_array_query($form, $dbh, qq|SELECT nextval('invoiceid')|);
350 qq|INSERT INTO invoice (id, trans_id, parts_id, description, longdescription, qty, base_qty,
351 sellprice, fxsellprice, discount, allocated, unit, deliverydate,
352 project_id, serialnumber, price_factor_id, price_factor, marge_price_factor)
353 VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, (SELECT factor FROM price_factors WHERE id = ?), ?)|;
354 @values = ($invoice_id, conv_i($form->{id}), conv_i($form->{"id_$i"}),
355 $form->{"description_$i"}, $form->{"longdescription_$i"}, $form->{"qty_$i"} * -1,
356 $baseqty * -1, $form->{"sellprice_$i"}, $fxsellprice, $form->{"discount_$i"}, $allocated,
357 $form->{"unit_$i"}, conv_date($form->{deliverydate}),
358 conv_i($form->{"project_id_$i"}), $form->{"serialnumber_$i"},
359 conv_i($form->{"price_factor_id_$i"}), conv_i($form->{"price_factor_id_$i"}), conv_i($form->{"marge_price_factor_$i"}));
360 do_query($form, $dbh, $query, @values);
362 CVar->save_custom_variables(module => 'IC',
363 sub_module => 'invoice',
364 trans_id => $invoice_id,
365 configs => $ic_cvar_configs,
367 name_prefix => 'ic_',
368 name_postfix => "_$i",
372 $h_item_unit->finish();
374 $project_id = conv_i($form->{"globalproject_id"});
376 $form->{datepaid} = $form->{invdate};
378 # all amounts are in natural state, netamount includes the taxes
379 # if tax is included, netamount is rounded to 2 decimal places,
383 for my $i (1 .. $form->{paidaccounts}) {
384 $form->{"paid_$i"} = $form->parse_amount($myconfig, $form->{"paid_$i"});
385 $form->{paid} += $form->{"paid_$i"};
386 $form->{datepaid} = $form->{"datepaid_$i"} if $form->{"datepaid_$i"};
389 my ($tax, $paiddiff) = (0, 0);
391 $netamount = $form->round_amount($netamount, 2);
393 # figure out rounding errors for amount paid and total amount
394 if ($form->{taxincluded}) {
396 $amount = $form->round_amount($netamount * $form->{exchangerate}, 2);
397 $paiddiff = $amount - $netamount * $form->{exchangerate};
398 $netamount = $amount;
400 foreach $item (split / /, $form->{taxaccounts}) {
401 $amount = $form->{amount}{ $form->{id} }{$item} * $form->{exchangerate};
402 $form->{amount}{ $form->{id} }{$item} = $form->round_amount($amount, 2);
404 $amount = $form->{amount}{ $form->{id} }{$item} * -1;
406 $netamount -= $amount;
409 $invoicediff += $paiddiff;
410 $expensediff += $paiddiff;
412 ######## this only applies to tax included
414 # in the sales invoice case rounding errors only have to be corrected for
415 # income accounts, it is enough to add the total rounding error to one of
416 # the income accounts, with the one assigned to the last row being used
417 # (lastinventoryaccno)
419 # in the purchase invoice case rounding errors may be split between
420 # inventory accounts and expense accounts. After rounding, an error of 1
421 # cent is introduced if the total rounding error exceeds 0.005. The total
422 # error is made up of $invoicediff and $expensediff, however, so if both
423 # values are below 0.005, but add up to a total >= 0.005, correcting
424 # lastinventoryaccno and lastexpenseaccno separately has no effect after
425 # rounding. This caused bug 1579. Therefore when the combined total exceeds
426 # 0.005, but neither do individually, the account with the larger value
427 # shall receive the total rounding error, and the next time it is rounded
428 # the 1 cent correction will be introduced.
430 $form->{amount}{ $form->{id} }{$lastinventoryaccno} -= $invoicediff if $lastinventoryaccno;
431 $form->{amount}{ $form->{id} }{$lastexpenseaccno} -= $expensediff if $lastexpenseaccno;
433 if ( (abs($expensediff)+abs($invoicediff)) >= 0.005 and abs($expensediff) < 0.005 and abs($invoicediff) < 0.005 ) {
435 # in total the rounding error adds up to 1 cent effectively, correct the
436 # larger of the two numbers
438 if ( abs($form->{amount}{ $form->{id} }{$lastinventoryaccno}) > abs($form->{amount}{ $form->{id} }{$lastexpenseaccno}) ) {
439 # $invoicediff has already been deducted, now also deduct expensediff
440 $form->{amount}{ $form->{id} }{$lastinventoryaccno} -= $expensediff;
442 # expensediff has already been deducted, now also deduct invoicediff
443 $form->{amount}{ $form->{id} }{$lastexpenseaccno} -= $invoicediff;
448 $amount = $form->round_amount($netamount * $form->{exchangerate}, 2);
449 $paiddiff = $amount - $netamount * $form->{exchangerate};
450 $netamount = $amount;
452 foreach my $item (split / /, $form->{taxaccounts}) {
453 $form->{amount}{ $form->{id} }{$item} = $form->round_amount($form->{amount}{ $form->{id} }{$item}, 2);
454 $amount = $form->round_amount( $form->{amount}{ $form->{id} }{$item} * $form->{exchangerate} * -1, 2);
455 $paiddiff += $amount - $form->{amount}{ $form->{id} }{$item} * $form->{exchangerate} * -1;
456 $form->{amount}{ $form->{id} }{$item} = $form->round_amount($amount * -1, 2);
457 $amount = $form->{amount}{ $form->{id} }{$item} * -1;
462 $form->{amount}{ $form->{id} }{ $form->{AP} } = $netamount + $tax;
465 $form->{paid} = $form->round_amount($form->{paid} * $form->{exchangerate} + $paiddiff, 2) if $form->{paid} != 0;
467 # update exchangerate
469 $form->update_exchangerate($dbh, $form->{currency}, $form->{invdate}, 0, $form->{exchangerate})
470 if ($form->{currency} ne $defaultcurrency) && !$exchangerate;
472 # record acc_trans transactions
473 foreach my $trans_id (keys %{ $form->{amount} }) {
474 foreach my $accno (keys %{ $form->{amount}{$trans_id} }) {
475 $form->{amount}{$trans_id}{$accno} = $form->round_amount($form->{amount}{$trans_id}{$accno}, 2);
478 next if $payments_only || !$form->{amount}{$trans_id}{$accno};
480 $query = qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate, taxkey, project_id)
481 VALUES (?, (SELECT id FROM chart WHERE accno = ?), ?, ?,
482 (SELECT taxkey_id FROM chart WHERE accno = ?), ?)|;
483 @values = ($trans_id, $accno, $form->{amount}{$trans_id}{$accno},
484 conv_date($form->{invdate}), $accno, $project_id);
485 do_query($form, $dbh, $query, @values);
489 # deduct payment differences from paiddiff
490 for my $i (1 .. $form->{paidaccounts}) {
491 if ($form->{"paid_$i"} != 0) {
492 $amount = $form->round_amount($form->{"paid_$i"} * $form->{exchangerate}, 2);
493 $paiddiff -= $amount - $form->{"paid_$i"} * $form->{exchangerate};
497 # force AP entry if 0
499 $form->{amount}{ $form->{id} }{ $form->{AP} } = $form->{paid} if $form->{amount}{$form->{id}}{$form->{AP}} == 0;
501 # record payments and offsetting AP
502 for my $i (1 .. $form->{paidaccounts}) {
503 if ($form->{"acc_trans_id_$i"}
505 && ($::lx_office_conf{features}->{payments_changeable} == 0)) {
509 next if $form->{"paid_$i"} == 0;
511 my ($accno) = split /--/, $form->{"AP_paid_$i"};
512 $form->{"datepaid_$i"} = $form->{invdate} unless ($form->{"datepaid_$i"});
513 $form->{datepaid} = $form->{"datepaid_$i"};
515 $amount = $form->round_amount($form->{"paid_$i"} * $form->{exchangerate} + $paiddiff, 2) * -1;
518 if ($form->{amount}{ $form->{id} }{ $form->{AP} } != 0) {
519 $query = qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate, taxkey, project_id)
520 VALUES (?, (SELECT id FROM chart WHERE accno = ?), ?, ?,
521 (SELECT taxkey_id FROM chart WHERE accno = ?), ?)|;
522 @values = (conv_i($form->{id}), $form->{AP}, $amount,
523 $form->{"datepaid_$i"}, $form->{AP}, $project_id);
524 do_query($form, $dbh, $query, @values);
528 my $gldate = (conv_date($form->{"gldate_$i"}))? conv_date($form->{"gldate_$i"}) : conv_date($form->current_date($myconfig));
531 qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate, gldate, source, memo, taxkey, project_id)
532 VALUES (?, (SELECT id FROM chart WHERE accno = ?), ?, ?, ?, ?, ?,
533 (SELECT taxkey_id FROM chart WHERE accno = ?), ?)|;
534 @values = (conv_i($form->{id}), $accno, $form->{"paid_$i"}, $form->{"datepaid_$i"},
535 $gldate, $form->{"source_$i"}, $form->{"memo_$i"}, $accno, $project_id);
536 do_query($form, $dbh, $query, @values);
540 if ($form->{currency} eq $defaultcurrency) {
541 $form->{"exchangerate_$i"} = 1;
543 $exchangerate = $form->check_exchangerate($myconfig, $form->{currency}, $form->{"datepaid_$i"}, 'sell');
544 $form->{"exchangerate_$i"} = $exchangerate || $form->parse_amount($myconfig, $form->{"exchangerate_$i"});
547 # exchangerate difference
548 $form->{fx}{$accno}{ $form->{"datepaid_$i"} } += $form->{"paid_$i"} * ($form->{"exchangerate_$i"} - 1) + $paiddiff;
552 ($form->{"paid_$i"} * $form->{exchangerate}) -
553 ($form->{"paid_$i"} * $form->{"exchangerate_$i"});
555 $form->{fx}{ $form->{fxgain_accno} }{ $form->{"datepaid_$i"} } += $amount;
557 $form->{fx}{ $form->{fxloss_accno} }{ $form->{"datepaid_$i"} } += $amount;
562 # update exchange rate
563 $form->update_exchangerate($dbh, $form->{currency}, $form->{"datepaid_$i"}, 0, $form->{"exchangerate_$i"})
564 if ($form->{currency} ne $defaultcurrency) && !$exchangerate;
567 # record exchange rate differences and gains/losses
568 foreach my $accno (keys %{ $form->{fx} }) {
569 foreach my $transdate (keys %{ $form->{fx}{$accno} }) {
570 $form->{fx}{$accno}{$transdate} = $form->round_amount($form->{fx}{$accno}{$transdate}, 2);
571 next if ($form->{fx}{$accno}{$transdate} == 0);
573 $query = qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate, cleared, fx_transaction, taxkey, project_id)
574 VALUES (?, (SELECT id FROM chart WHERE accno = ?), ?, ?, '0', '1', 0, ?)|;
575 @values = (conv_i($form->{id}), $accno, $form->{fx}{$accno}{$transdate}, conv_date($transdate), $project_id);
576 do_query($form, $dbh, $query, @values);
580 IO->set_datepaid(table => 'ap', id => $form->{id}, dbh => $dbh);
582 if ($payments_only) {
583 $query = qq|UPDATE ap SET paid = ? WHERE id = ?|;
584 do_query($form, $dbh, $query, $form->{paid}, conv_i($form->{id}));
586 if (!$provided_dbh) {
591 $main::lxdebug->leave_sub();
595 $amount = $netamount + $tax;
597 # set values which could be empty
598 my $taxzone_id = $form->{taxzone_id} * 1;
600 # Seit neuestem wird die department_id schon übergeben UND $form->department nicht mehr
601 # korrekt zusammengebaut. Sehr wahrscheinlich beim Umstieg auf T8 kaputt gegangen
602 # Ich lass den Code von 2005 erstmal noch stehen ;-) jb 03-2011
603 # copy & paste von IS.pm
604 if (!$form->{department_id}){
605 $form->{department_id} = (split /--/, $form->{department})[1];
607 $form->{invnumber} = $form->{id} unless $form->{invnumber};
609 $taxzone_id = 0 if (3 < $taxzone_id) || (0 > $taxzone_id);
612 $query = qq|UPDATE ap SET
613 invnumber = ?, ordnumber = ?, quonumber = ?, transdate = ?,
614 orddate = ?, quodate = ?, vendor_id = ?, amount = ?,
615 netamount = ?, paid = ?, duedate = ?,
616 invoice = ?, taxzone_id = ?, notes = ?, taxincluded = ?,
617 intnotes = ?, curr = ?, storno_id = ?, storno = ?,
618 cp_id = ?, employee_id = ?, department_id = ?,
622 $form->{invnumber}, $form->{ordnumber}, $form->{quonumber}, conv_date($form->{invdate}),
623 conv_date($form->{orddate}), conv_date($form->{quodate}), conv_i($form->{vendor_id}), $amount,
624 $netamount, $form->{paid}, conv_date($form->{duedate}),
625 '1', $taxzone_id, $form->{notes}, $form->{taxincluded} ? 't' : 'f',
626 $form->{intnotes}, $form->{currency}, conv_i($form->{storno_id}), $form->{storno} ? 't' : 'f',
627 conv_i($form->{cp_id}), conv_i($form->{employee_id}), conv_i($form->{department_id}),
628 conv_i($form->{globalproject_id}),
631 do_query($form, $dbh, $query, @values);
633 if ($form->{storno}) {
634 $query = qq|UPDATE ap SET paid = paid + amount WHERE id = ?|;
635 do_query($form, $dbh, $query, conv_i($form->{storno_id}));
637 $query = qq|UPDATE ap SET storno = 't' WHERE id = ?|;
638 do_query($form, $dbh, $query, conv_i($form->{storno_id}));
640 $query = qq!UPDATE ap SET intnotes = ? || intnotes WHERE id = ?!;
641 do_query($form, $dbh, $query, "Rechnung storniert am $form->{invdate} ", conv_i($form->{storno_id}));
643 $query = qq|UPDATE ap SET paid = amount WHERE id = ?|;
644 do_query($form, $dbh, $query, conv_i($form->{id}));
649 $form->{name} = $form->{vendor};
650 $form->{name} =~ s/--\Q$form->{vendor_id}\E//;
651 $form->add_shipto($dbh, $form->{id}, "AP");
653 # delete zero entries
654 do_query($form, $dbh, qq|DELETE FROM acc_trans WHERE amount = 0|);
656 Common::webdav_folder($form);
658 # Link this record to the records it was created from.
659 RecordLinks->create_links('dbh' => $dbh,
661 'from_table' => 'oe',
662 'from_ids' => $form->{convert_from_oe_ids},
664 'to_id' => $form->{id},
666 delete $form->{convert_from_oe_ids};
668 my @convert_from_do_ids = map { $_ * 1 } grep { $_ } split m/\s+/, $form->{convert_from_do_ids};
669 if (scalar @convert_from_do_ids) {
670 DO->close_orders('dbh' => $dbh,
671 'ids' => \@convert_from_do_ids);
673 RecordLinks->create_links('dbh' => $dbh,
675 'from_table' => 'delivery_orders',
676 'from_ids' => \@convert_from_do_ids,
678 'to_id' => $form->{id},
681 delete $form->{convert_from_do_ids};
683 ARAP->close_orders_if_billed('dbh' => $dbh,
684 'arap_id' => $form->{id},
687 # safety check datev export
688 if ($::lx_office_conf{datev_check}{check_on_purchase_invoice}) {
689 my $transdate = $::form->{invdate} ? DateTime->from_lxoffice($::form->{invdate}) : undef;
690 $transdate ||= DateTime->today;
692 my $datev = SL::DATEV->new(
693 exporttype => DATEV_ET_BUCHUNGEN,
694 format => DATEV_FORMAT_KNE,
702 if ($datev->errors) {
704 die join "\n", $::locale->text('DATEV check returned errors:'), $datev->errors;
709 if (!$provided_dbh) {
710 $rc = $dbh->commit();
714 $main::lxdebug->leave_sub();
719 sub reverse_invoice {
720 $main::lxdebug->enter_sub();
722 my ($dbh, $form) = @_;
724 # reverse inventory items
726 qq|SELECT i.parts_id, p.inventory_accno_id, p.expense_accno_id, i.qty, i.allocated, i.sellprice
727 FROM invoice i, parts p
728 WHERE (i.parts_id = p.id)
729 AND (i.trans_id = ?)|;
730 my $sth = prepare_execute_query($form, $dbh, $query, conv_i($form->{id}));
734 while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
735 $netamount += $form->round_amount($ref->{sellprice} * $ref->{qty} * -1, 2);
737 next unless $ref->{inventory_accno_id};
739 # if $ref->{allocated} > 0 than we sold that many items
740 next if ($ref->{allocated} <= 0);
742 # get references for sold items
744 qq|SELECT i.id, i.trans_id, i.allocated, a.transdate
746 WHERE (i.parts_id = ?)
747 AND (i.allocated < 0)
748 AND (i.trans_id = a.id)
749 ORDER BY transdate DESC|;
750 my $sth2 = prepare_execute_query($form, $dbh, $query, $ref->{parts_id});
752 while (my $pthref = $sth2->fetchrow_hashref("NAME_lc")) {
753 my $qty = $ref->{allocated};
754 if (($ref->{allocated} + $pthref->{allocated}) > 0) {
755 $qty = $pthref->{allocated} * -1;
758 my $amount = $form->round_amount($ref->{sellprice} * $qty, 2);
761 $form->update_balance($dbh, "invoice", "allocated", qq|id = $pthref->{id}|, $qty);
763 $form->update_balance($dbh, "acc_trans", "amount",
764 qq| (trans_id = $pthref->{trans_id})
765 AND (chart_id = $ref->{expense_accno_id})
766 AND (transdate = '$pthref->{transdate}')|,
769 $form->update_balance($dbh, "acc_trans", "amount",
770 qq| (trans_id = $pthref->{trans_id})
771 AND (chart_id = $ref->{inventory_accno_id})
772 AND (transdate = '$pthref->{transdate}')|,
775 last if (($ref->{allocated} -= $qty) <= 0);
781 my $id = conv_i($form->{id});
784 $query = qq|DELETE FROM acc_trans WHERE trans_id = ?|;
785 do_query($form, $dbh, $query, $id);
787 # delete invoice entries
788 $query = qq|DELETE FROM invoice WHERE trans_id = ?|;
789 do_query($form, $dbh, $query, $id);
791 $query = qq|DELETE FROM shipto WHERE (trans_id = ?) AND (module = 'AP')|;
792 do_query($form, $dbh, $query, $id);
794 $main::lxdebug->leave_sub();
798 $main::lxdebug->enter_sub();
800 my ($self, $myconfig, $form) = @_;
802 # connect to database
803 my $dbh = $form->dbconnect_noauto($myconfig);
805 &reverse_invoice($dbh, $form);
807 # delete zero entries
808 $query = qq|DELETE FROM acc_trans WHERE amount = 0|;
809 do_query($form, $dbh, $query);
812 $query = qq|DELETE FROM ap WHERE id = ?|;
813 do_query($form, $dbh, $query, conv_i($form->{id}));
815 my $rc = $dbh->commit;
818 $main::lxdebug->leave_sub();
823 sub retrieve_invoice {
824 $main::lxdebug->enter_sub();
826 my ($self, $myconfig, $form) = @_;
828 # connect to database
829 my $dbh = $form->dbconnect($myconfig);
831 my ($query, $sth, $ref, $q_invdate);
834 $q_invdate = qq|, COALESCE((SELECT transdate FROM ar WHERE id = (SELECT MAX(id) FROM ar)), current_date) AS invdate|;
835 if ($form->{vendor_id}) {
836 my $vendor_id = $dbh->quote($form->{vendor_id} * 1);
838 qq|, COALESCE((SELECT transdate FROM ar WHERE id = (SELECT MAX(id) FROM ar)), current_date) +
839 COALESCE((SELECT pt.terms_netto
841 LEFT JOIN payment_terms pt ON (v.payment_id = pt.id)
842 WHERE v.id = $vendor_id),
847 # get default accounts and last invoice number
850 (SELECT c.accno FROM chart c WHERE d.inventory_accno_id = c.id) AS inventory_accno,
851 (SELECT c.accno FROM chart c WHERE d.income_accno_id = c.id) AS income_accno,
852 (SELECT c.accno FROM chart c WHERE d.expense_accno_id = c.id) AS expense_accno,
853 (SELECT c.accno FROM chart c WHERE d.fxgain_accno_id = c.id) AS fxgain_accno,
854 (SELECT c.accno FROM chart c WHERE d.fxloss_accno_id = c.id) AS fxloss_accno,
858 $ref = selectfirst_hashref_query($form, $dbh, $query);
859 map { $form->{$_} = $ref->{$_} } keys %$ref;
863 $main::lxdebug->leave_sub();
869 $query = qq|SELECT cp_id, invnumber, transdate AS invdate, duedate,
870 orddate, quodate, globalproject_id,
871 ordnumber, quonumber, paid, taxincluded, notes, taxzone_id, storno, gldate,
872 intnotes, curr AS currency
875 $ref = selectfirst_hashref_query($form, $dbh, $query, conv_i($form->{id}));
876 map { $form->{$_} = $ref->{$_} } keys %$ref;
878 # remove any trailing whitespace
879 $form->{currency} =~ s/\s*$//;
881 $form->{exchangerate} = $form->get_exchangerate($dbh, $form->{currency}, $form->{invdate}, "sell");
884 $query = qq|SELECT * FROM shipto WHERE (trans_id = ?) AND (module = 'AP')|;
885 $ref = selectfirst_hashref_query($form, $dbh, $query, conv_i($form->{id}));
887 map { $form->{$_} = $ref->{$_} } keys %$ref;
889 my $transdate = $form->{invdate} ? $dbh->quote($form->{invdate}) : "current_date";
890 my $taxzone_id = $form->{taxzone_id} * 1;
892 $taxzone_id = 0 if ((3 < $taxzone_id) || (0 > $taxzone_id));
894 # retrieve individual items
897 c1.accno AS inventory_accno, c1.new_chart_id AS inventory_new_chart, date($transdate) - c1.valid_from AS inventory_valid,
898 c2.accno AS income_accno, c2.new_chart_id AS income_new_chart, date($transdate) - c2.valid_from AS income_valid,
899 c3.accno AS expense_accno, c3.new_chart_id AS expense_new_chart, date($transdate) - c3.valid_from AS expense_valid,
902 i.description, i.longdescription, i.qty, i.fxsellprice AS sellprice, i.parts_id AS id, i.unit, i.deliverydate, i.project_id, i.serialnumber,
903 i.price_factor_id, i.price_factor, i.marge_price_factor, i.discount,
904 p.partnumber, p.inventory_accno_id AS part_inventory_accno_id, p.bin, pr.projectnumber, pg.partsgroup
907 JOIN parts p ON (i.parts_id = p.id)
908 LEFT JOIN chart c1 ON ((SELECT inventory_accno_id FROM buchungsgruppen WHERE id = p.buchungsgruppen_id) = c1.id)
909 LEFT JOIN chart c2 ON ((SELECT income_accno_id_${taxzone_id} FROM buchungsgruppen WHERE id = p.buchungsgruppen_id) = c2.id)
910 LEFT JOIN chart c3 ON ((SELECT expense_accno_id_${taxzone_id} FROM buchungsgruppen WHERE id = p.buchungsgruppen_id) = c3.id)
911 LEFT JOIN project pr ON (i.project_id = pr.id)
912 LEFT JOIN partsgroup pg ON (pg.id = p.partsgroup_id)
917 $sth = prepare_execute_query($form, $dbh, $query, conv_i($form->{id}));
919 while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
920 # Retrieve custom variables.
921 my $cvars = CVar->get_custom_variables(dbh => $dbh,
923 sub_module => 'invoice',
924 trans_id => $ref->{invoice_id},
926 map { $ref->{"ic_cvar_$_->{name}"} = $_->{value} } @{ $cvars };
927 delete $ref->{invoice_id};
929 map({ delete($ref->{$_}); } qw(inventory_accno inventory_new_chart inventory_valid)) if !$ref->{"part_inventory_accno_id"};
930 delete($ref->{"part_inventory_accno_id"});
932 foreach my $type (qw(inventory income expense)) {
933 while ($ref->{"${type}_new_chart"} && ($ref->{"${type}_valid"} >=0)) {
934 my $query = qq|SELECT accno, new_chart_id, date($transdate) - valid_from FROM chart WHERE id = ?|;
935 @$ref{ map $type.$_, qw(_accno _new_chart _valid) } = selectrow_query($form, $dbh, $query, $ref->{"${type}_new_chart"});
939 # get tax rates and description
940 my $accno_id = ($form->{vc} eq "customer") ? $ref->{income_accno} : $ref->{expense_accno};
942 qq|SELECT c.accno, t.taxdescription, t.rate, t.taxnumber FROM tax t
943 LEFT JOIN chart c ON (c.id = t.chart_id)
945 (SELECT tk.tax_id FROM taxkeys tk
946 WHERE tk.chart_id = (SELECT id FROM chart WHERE accno = ?)
947 AND (startdate <= $transdate)
948 ORDER BY startdate DESC
951 my $stw = prepare_execute_query($form, $dbh, $query, $accno_id);
952 $ref->{taxaccounts} = "";
955 while (my $ptr = $stw->fetchrow_hashref("NAME_lc")) {
956 if (($ptr->{accno} eq "") && ($ptr->{rate} == 0)) {
961 $ref->{taxaccounts} .= "$ptr->{accno} ";
963 if (!($form->{taxaccounts} =~ /\Q$ptr->{accno}\E/)) {
964 $form->{"$ptr->{accno}_rate"} = $ptr->{rate};
965 $form->{"$ptr->{accno}_description"} = $ptr->{taxdescription};
966 $form->{"$ptr->{accno}_taxnumber"} = $ptr->{taxnumber};
967 $form->{taxaccounts} .= "$ptr->{accno} ";
972 chop $ref->{taxaccounts};
973 push @{ $form->{invoice_details} }, $ref;
978 Common::webdav_folder($form);
982 $main::lxdebug->leave_sub();
986 $main::lxdebug->enter_sub();
988 my ($self, $myconfig, $form, $params) = @_;
990 $params = $form unless defined $params && ref $params eq "HASH";
992 # connect to database
993 my $dbh = $form->dbconnect($myconfig);
995 my $dateformat = $myconfig->{dateformat};
996 $dateformat .= "yy" if $myconfig->{dateformat} !~ /^y/;
998 my $vid = conv_i($params->{vendor_id});
999 my $vnr = conv_i($params->{vendornumber});
1002 ($params->{invdate})
1003 ? "to_date(" . $dbh->quote($params->{invdate}) . ", '$dateformat')"
1010 $where .= 'AND v.id = ?';
1014 $where .= 'AND v.vendornumber = ?';
1019 v.id AS vendor_id, v.name AS vendor, v.discount as vendor_discount,
1020 v.creditlimit, v.terms, v.notes AS intnotes,
1021 v.email, v.cc, v.bcc, v.language_id, v.payment_id,
1022 v.street, v.zipcode, v.city, v.country, v.taxzone_id, v.curr,
1023 $duedate + COALESCE(pt.terms_netto, 0) AS duedate,
1024 b.description AS business
1026 LEFT JOIN business b ON (b.id = v.business_id)
1027 LEFT JOIN payment_terms pt ON (v.payment_id = pt.id)
1029 my $ref = selectfirst_hashref_query($form, $dbh, $query, @values);
1030 map { $params->{$_} = $ref->{$_} } keys %$ref;
1032 # remove any trailing whitespace
1033 $form->{curr} =~ s/\s*$//;
1035 # use vendor currency if not empty
1036 $form->{currency} = $form->{curr} if $form->{curr};
1038 $params->{creditremaining} = $params->{creditlimit};
1040 $query = qq|SELECT SUM(amount - paid) FROM ap WHERE vendor_id = ?|;
1041 my ($unpaid_invoices) = selectfirst_array_query($form, $dbh, $query, $vid);
1042 $params->{creditremaining} -= $unpaid_invoices;
1044 $query = qq|SELECT o.amount,
1047 WHERE (e.curr = o.curr)
1048 AND (e.transdate = o.transdate)) AS exch
1050 WHERE (o.vendor_id = ?) AND (o.quotation = '0') AND (o.closed = '0')|;
1051 my $sth = prepare_execute_query($form, $dbh, $query, $vid);
1052 while (my ($amount, $exch) = $sth->fetchrow_array()) {
1053 $exch = 1 unless $exch;
1054 $params->{creditremaining} -= $amount * $exch;
1058 # get shipto if we do not convert an order or invoice
1059 if (!$params->{shipto}) {
1060 delete @{$params}{qw(shiptoname shiptostreet shiptozipcode shiptocity shiptocountry shiptocontact shiptophone shiptofax shiptoemail)};
1062 $query = qq|SELECT * FROM shipto WHERE (trans_id = ?) AND (module= 'CT')|;
1063 $ref = selectfirst_hashref_query($form, $dbh, $query, $vid);
1064 @{$params}{keys %$ref} = @{$ref}{keys %$ref};
1065 map { $params->{$_} = $ref->{$_} } keys %$ref;
1068 if (!$params->{id} && $params->{type} !~ /_(order|quotation)/) {
1069 # setup last accounts used
1071 qq|SELECT c.id, c.accno, c.description, c.link, c.category
1073 JOIN acc_trans ac ON (ac.chart_id = c.id)
1074 JOIN ap a ON (a.id = ac.trans_id)
1075 WHERE (a.vendor_id = ?)
1076 AND (NOT ((c.link LIKE '%_tax%') OR (c.link LIKE '%_paid%')))
1077 AND (a.id IN (SELECT max(a2.id) FROM ap a2 WHERE a2.vendor_id = ?))|;
1078 my $refs = selectall_hashref_query($form, $dbh, $query, $vid, $vid);
1082 if ($ref->{category} eq 'E') {
1084 my ($tax_id, $rate);
1085 if ($params->{initial_transdate}) {
1086 my $tax_query = qq|SELECT tk.tax_id, t.rate FROM taxkeys tk
1087 LEFT JOIN tax t ON (tk.tax_id = t.id)
1088 WHERE (tk.chart_id = ?) AND (startdate <= ?)
1089 ORDER BY tk.startdate DESC
1091 ($tax_id, $rate) = selectrow_query($form, $dbh, $tax_query, $ref->{id}, $params->{initial_transdate});
1092 $params->{"taxchart_$i"} = "${tax_id}--${rate}";
1095 $params->{"AP_amount_$i"} = "$ref->{accno}--$tax_id";
1098 if ($ref->{category} eq 'L') {
1099 $params->{APselected} = $params->{AP_1} = $ref->{accno};
1102 $params->{rowcount} = $i if ($i && !$params->{type});
1107 $main::lxdebug->leave_sub();
1111 $main::lxdebug->enter_sub();
1113 my ($self, $myconfig, $form) = @_;
1115 # connect to database
1116 my $dbh = $form->dbconnect($myconfig);
1118 my $i = $form->{rowcount};
1120 # don't include assemblies or obsolete parts
1121 my $where = "NOT p.assembly = '1' AND NOT p.obsolete = '1'";
1124 foreach my $table_column (qw(p.partnumber p.description pg.partsgroup)) {
1125 my $field = (split m{\.}, $table_column)[1];
1126 next unless $form->{"${field}_${i}"};
1127 $where .= " AND lower(${table_column}) LIKE lower(?)";
1128 push @values, '%' . $form->{"${field}_${i}"} . '%';
1130 #Es soll auch nach EAN gesucht werden, ohne Einschränkung durch Beschreibung
1131 if ($form->{"partnumber_$i"} && !$form->{"description_$i"}) {
1132 $where .= qq| OR (NOT p.obsolete = '1' AND p.ean = ? )|;
1133 push @values, $form->{"partnumber_$i"};
1136 # Search for part ID overrides all other criteria.
1137 if ($form->{"id_${i}"}) {
1138 $where = qq|p.id = ?|;
1139 @values = ($form->{"id_${i}"});
1142 if ($form->{"description_$i"}) {
1143 $where .= " ORDER BY p.description";
1145 $where .= " ORDER BY p.partnumber";
1149 if ($form->{type} eq "invoice") {
1150 $transdate = $form->{invdate} ? $dbh->quote($form->{invdate}) : "current_date";
1152 $transdate = $form->{transdate} ? $dbh->quote($form->{transdate}) : "current_date";
1155 my $taxzone_id = $form->{taxzone_id} * 1;
1156 $taxzone_id = 0 if ((3 < $taxzone_id) || (0 > $taxzone_id));
1160 p.id, p.partnumber, p.description, p.lastcost AS sellprice, p.listprice,
1161 p.unit, p.assembly, p.bin, p.onhand, p.formel,
1162 p.notes AS partnotes, p.notes AS longdescription, p.not_discountable,
1163 p.inventory_accno_id, p.price_factor_id,
1165 pfac.factor AS price_factor,
1167 c1.accno AS inventory_accno,
1168 c1.new_chart_id AS inventory_new_chart,
1169 date($transdate) - c1.valid_from AS inventory_valid,
1171 c2.accno AS income_accno,
1172 c2.new_chart_id AS income_new_chart,
1173 date($transdate) - c2.valid_from AS income_valid,
1175 c3.accno AS expense_accno,
1176 c3.new_chart_id AS expense_new_chart,
1177 date($transdate) - c3.valid_from AS expense_valid,
1182 LEFT JOIN chart c1 ON
1183 ((SELECT inventory_accno_id
1184 FROM buchungsgruppen
1185 WHERE id = p.buchungsgruppen_id) = c1.id)
1186 LEFT JOIN chart c2 ON
1187 ((SELECT income_accno_id_${taxzone_id}
1188 FROM buchungsgruppen
1189 WHERE id = p.buchungsgruppen_id) = c2.id)
1190 LEFT JOIN chart c3 ON
1191 ((SELECT expense_accno_id_${taxzone_id}
1192 FROM buchungsgruppen
1193 WHERE id = p.buchungsgruppen_id) = c3.id)
1194 LEFT JOIN partsgroup pg ON (pg.id = p.partsgroup_id)
1195 LEFT JOIN price_factors pfac ON (pfac.id = p.price_factor_id)
1197 my $sth = prepare_execute_query($form, $dbh, $query, @values);
1199 my @translation_queries = ( [ qq|SELECT tr.translation, tr.longdescription
1201 WHERE tr.language_id = ? AND tr.parts_id = ?| ],
1202 [ qq|SELECT tr.translation, tr.longdescription
1204 WHERE tr.language_id IN
1207 WHERE article_code = (SELECT article_code FROM language WHERE id = ?))
1210 map { push @{ $_ }, prepare_query($form, $dbh, $_->[0]) } @translation_queries;
1212 $form->{item_list} = [];
1213 while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
1215 # In der Buchungsgruppe ist immer ein Bestandskonto verknuepft, auch wenn
1216 # es sich um eine Dienstleistung handelt. Bei Dienstleistungen muss das
1217 # Buchungskonto also aus dem Ergebnis rausgenommen werden.
1218 if (!$ref->{inventory_accno_id}) {
1219 map({ delete($ref->{"inventory_${_}"}); } qw(accno new_chart valid));
1221 delete($ref->{inventory_accno_id});
1223 # get tax rates and description
1224 my $accno_id = ($form->{vc} eq "customer") ? $ref->{income_accno} : $ref->{expense_accno};
1226 qq|SELECT c.accno, t.taxdescription, t.rate, t.taxnumber
1228 LEFT JOIN chart c on (c.id = t.chart_id)
1236 AND (startdate <= $transdate)
1237 ORDER BY startdate DESC
1240 my $stw = prepare_execute_query($form, $dbh, $query, $accno_id);
1242 $ref->{taxaccounts} = "";
1244 while (my $ptr = $stw->fetchrow_hashref("NAME_lc")) {
1246 # if ($customertax{$ref->{accno}}) {
1247 if (($ptr->{accno} eq "") && ($ptr->{rate} == 0)) {
1252 $ref->{taxaccounts} .= "$ptr->{accno} ";
1254 if (!($form->{taxaccounts} =~ /\Q$ptr->{accno}\E/)) {
1255 $form->{"$ptr->{accno}_rate"} = $ptr->{rate};
1256 $form->{"$ptr->{accno}_description"} = $ptr->{taxdescription};
1257 $form->{"$ptr->{accno}_taxnumber"} = $ptr->{taxnumber};
1258 $form->{taxaccounts} .= "$ptr->{accno} ";
1261 if ($form->{language_id}) {
1262 for my $spec (@translation_queries) {
1263 do_statement($form, $spec->[1], $spec->[0], conv_i($form->{language_id}), conv_i($ref->{id}));
1264 my ($translation, $longdescription) = $spec->[1]->fetchrow_array;
1265 next unless $translation;
1266 $ref->{description} = $translation;
1267 $ref->{longdescription} = $longdescription;
1274 chop $ref->{taxaccounts};
1276 $ref->{onhand} *= 1;
1278 push @{ $form->{item_list} }, $ref;
1283 $_->[1]->finish for @translation_queries;
1285 foreach my $item (@{ $form->{item_list} }) {
1286 my $custom_variables = CVar->get_custom_variables(module => 'IC',
1287 trans_id => $item->{id},
1291 map { $item->{"ic_cvar_" . $_->{name} } = $_->{value} } @{ $custom_variables };
1296 $main::lxdebug->leave_sub();
1299 sub vendor_details {
1300 $main::lxdebug->enter_sub();
1302 my ($self, $myconfig, $form, @wanted_vars) = @_;
1304 # connect to database
1305 my $dbh = $form->dbconnect($myconfig);
1309 # get contact id, set it if nessessary
1310 $form->{cp_id} *= 1;
1312 if ($form->{cp_id}) {
1313 $contact = "AND cp.cp_id = ?";
1314 push @values, $form->{cp_id};
1317 # get rest for the vendor
1318 # fax and phone and email as vendor*
1320 qq|SELECT ct.*, cp.*, ct.notes as vendornotes, phone as vendorphone, fax as vendorfax, email as vendoremail,
1323 LEFT JOIN contacts cp ON (ct.id = cp.cp_cv_id)
1324 WHERE (ct.id = ?) $contact
1327 my $ref = selectfirst_hashref_query($form, $dbh, $query, $form->{vendor_id}, @values);
1329 # remove id and taxincluded before copy back
1330 delete @$ref{qw(id taxincluded)};
1332 @wanted_vars = grep({ $_ } @wanted_vars);
1333 if (scalar(@wanted_vars) > 0) {
1335 map({ $h_wanted_vars{$_} = 1; } @wanted_vars);
1336 map({ delete($ref->{$_}) unless ($h_wanted_vars{$_}); } keys(%{$ref}));
1339 map { $form->{$_} = $ref->{$_} } keys %$ref;
1340 # remove any trailing whitespace
1341 $form->{currency} =~ s/\s*$// if ($form->{currency});
1343 my $custom_variables = CVar->get_custom_variables('dbh' => $dbh,
1345 'trans_id' => $form->{vendor_id});
1346 map { $form->{"vc_cvar_$_->{name}"} = $_->{value} } @{ $custom_variables };
1348 $form->{cp_greeting} = GenericTranslations->get('dbh' => $dbh,
1349 'translation_type' => 'greetings::' . ($form->{cp_gender} eq 'f' ? 'female' : 'male'),
1350 'allow_fallback' => 1);
1354 $main::lxdebug->leave_sub();
1358 $main::lxdebug->enter_sub();
1360 my ($self, $myconfig, $form) = @_;
1362 # connect to database
1363 my $dbh = $form->dbconnect($myconfig);
1366 qq|SELECT accno, description, link
1368 WHERE link LIKE '%IC%'
1370 my $sth = prepare_execute_query($query, $dbh, $query);
1372 while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
1373 foreach my $key (split(/:/, $ref->{link})) {
1375 push @{ $form->{IC_links}{$key} },
1376 { accno => $ref->{accno},
1377 description => $ref->{description} };
1385 $main::lxdebug->leave_sub();
1388 sub _delete_payments {
1389 $main::lxdebug->enter_sub();
1391 my ($self, $form, $dbh) = @_;
1393 my @delete_acc_trans_ids;
1395 # Delete old payment entries from acc_trans.
1397 qq|SELECT acc_trans_id
1399 WHERE (trans_id = ?) AND fx_transaction
1403 SELECT at.acc_trans_id
1405 LEFT JOIN chart c ON (at.chart_id = c.id)
1406 WHERE (trans_id = ?) AND (c.link LIKE '%AP_paid%')|;
1407 push @delete_acc_trans_ids, selectall_array_query($form, $dbh, $query, conv_i($form->{id}), conv_i($form->{id}));
1410 qq|SELECT at.acc_trans_id
1412 LEFT JOIN chart c ON (at.chart_id = c.id)
1413 WHERE (trans_id = ?)
1414 AND ((c.link = 'AP') OR (c.link LIKE '%:AP') OR (c.link LIKE 'AP:%'))
1415 ORDER BY at.acc_trans_id
1417 push @delete_acc_trans_ids, selectall_array_query($form, $dbh, $query, conv_i($form->{id}));
1419 if (@delete_acc_trans_ids) {
1420 $query = qq|DELETE FROM acc_trans WHERE acc_trans_id IN (| . join(", ", @delete_acc_trans_ids) . qq|)|;
1421 do_query($form, $dbh, $query);
1424 $main::lxdebug->leave_sub();
1428 $main::lxdebug->enter_sub();
1430 my ($self, $myconfig, $form, $locale) = @_;
1432 # connect to database, turn off autocommit
1433 my $dbh = $form->dbconnect_noauto($myconfig);
1435 my (%payments, $old_form, $row, $item, $query, %keep_vars);
1437 $old_form = save_form();
1439 # Delete all entries in acc_trans from prior payments.
1440 if ($::lx_office_conf{features}->{payments_changeable} != 0) {
1441 $self->_delete_payments($form, $dbh);
1444 # Save the new payments the user made before cleaning up $form.
1445 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 };
1447 # Clean up $form so that old content won't tamper the results.
1448 %keep_vars = map { $_, 1 } qw(login password id);
1449 map { delete $form->{$_} unless $keep_vars{$_} } keys %{ $form };
1451 # Retrieve the invoice from the database.
1452 $self->retrieve_invoice($myconfig, $form);
1454 # Set up the content of $form in the way that IR::post_invoice() expects.
1455 $form->{exchangerate} = $form->format_amount($myconfig, $form->{exchangerate});
1457 for $row (1 .. scalar @{ $form->{invoice_details} }) {
1458 $item = $form->{invoice_details}->[$row - 1];
1460 map { $item->{$_} = $form->format_amount($myconfig, $item->{$_}) } qw(qty sellprice);
1462 map { $form->{"${_}_${row}"} = $item->{$_} } keys %{ $item };
1465 $form->{rowcount} = scalar @{ $form->{invoice_details} };
1467 delete @{$form}{qw(invoice_details paidaccounts storno paid)};
1469 # Restore the payment options from the user input.
1470 map { $form->{$_} = $payments{$_} } keys %payments;
1472 # Get the AP accno (which is normally done by Form::create_links()).
1476 LEFT JOIN chart c ON (at.chart_id = c.id)
1477 WHERE (trans_id = ?)
1478 AND ((c.link = 'AP') OR (c.link LIKE '%:AP') OR (c.link LIKE 'AP:%'))
1479 ORDER BY at.acc_trans_id
1482 ($form->{AP}) = selectfirst_array_query($form, $dbh, $query, conv_i($form->{id}));
1484 # Post the new payments.
1485 $self->post_invoice($myconfig, $form, $dbh, 1);
1487 restore_form($old_form);
1489 my $rc = $dbh->commit();
1492 $main::lxdebug->leave_sub();
1498 $::lxdebug->enter_sub;
1500 my ($self, %params) = @_;
1502 if (!$params{vendor_id} || !$params{invdate}) {
1503 $::lxdebug->leave_sub;
1504 return $params{default};
1507 my $dbh = $::form->get_standard_dbh;
1508 my $query = qq|SELECT ?::date + pt.terms_netto
1510 LEFT JOIN payment_terms pt ON (pt.id = v.payment_id)
1513 my ($duedate) = selectfirst_array_query($::form, $dbh, $query, $params{invdate}, $params{vendor_id});
1515 $duedate ||= $params{default};
1517 $::lxdebug->leave_sub;