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 List::Util qw(min);
44 $main::lxdebug->enter_sub();
46 my ($self, $myconfig, $form, $provided_dbh, $payments_only) = @_;
48 # connect to database, turn off autocommit
49 my $dbh = $provided_dbh ? $provided_dbh : $form->dbconnect_noauto($myconfig);
50 $form->{defaultcurrency} = $form->get_default_currency($myconfig);
52 my ($query, $sth, @values, $project_id);
53 my ($allocated, $taxrate, $taxamount, $taxdiff, $item);
54 my ($amount, $linetotal, $lastinventoryaccno, $lastexpenseaccno);
55 my ($netamount, $invoicediff, $expensediff) = (0, 0, 0);
58 my $all_units = AM->retrieve_units($myconfig, $form);
60 if (!$payments_only) {
62 &reverse_invoice($dbh, $form);
64 ($form->{id}) = selectrow_query($form, $dbh, qq|SELECT nextval('glid')|);
65 do_query($form, $dbh, qq|INSERT INTO ap (id, invnumber) VALUES (?, '')|, $form->{id});
69 my ($currencies) = selectfirst_array_query($form, $dbh, qq|SELECT curr FROM defaults|);
70 my $defaultcurrency = (split m/:/, $currencies)[0];
72 if ($form->{currency} eq $defaultcurrency) {
73 $form->{exchangerate} = 1;
75 $exchangerate = $form->check_exchangerate($myconfig, $form->{currency}, $form->{transdate}, 'sell');
78 $form->{exchangerate} = $exchangerate || $form->parse_amount($myconfig, $form->{exchangerate});
79 $form->{exchangerate} = 1 unless ($form->{exchangerate} * 1);
82 my $q_item_unit = qq|SELECT unit FROM parts WHERE id = ?|;
83 my $h_item_unit = prepare_query($form, $dbh, $q_item_unit);
85 $form->get_lists('price_factors' => 'ALL_PRICE_FACTORS');
86 my %price_factors = map { $_->{id} => $_->{factor} } @{ $form->{ALL_PRICE_FACTORS} };
89 for my $i (1 .. $form->{rowcount}) {
90 next unless $form->{"id_$i"};
92 $form->{"qty_$i"} = $form->parse_amount($myconfig, $form->{"qty_$i"});
93 $form->{"qty_$i"} *= -1 if $form->{storno};
95 $form->{"inventory_accno_$i"} = $form->{"expense_accno_$i"} if $main::eur;
98 if (!$item_units{$form->{"id_$i"}}) {
99 do_statement($form, $h_item_unit, $q_item_unit, $form->{"id_$i"});
100 ($item_units{$form->{"id_$i"}}) = $h_item_unit->fetchrow_array();
103 my $item_unit = $item_units{$form->{"id_$i"}};
105 if (defined($all_units->{$item_unit}->{factor})
106 && ($all_units->{$item_unit}->{factor} ne '')
107 && ($all_units->{$item_unit}->{factor} * 1 != 0)) {
108 $basefactor = $all_units->{$form->{"unit_$i"}}->{factor} / $all_units->{$item_unit}->{factor};
112 $baseqty = $form->{"qty_$i"} * $basefactor;
114 @taxaccounts = split / /, $form->{"taxaccounts_$i"};
119 $form->{"sellprice_$i"} = $form->parse_amount($myconfig, $form->{"sellprice_$i"});
120 (my $fxsellprice = $form->{"sellprice_$i"}) =~ /\.(\d+)/;
122 my $decimalplaces = ($dec > 2) ? $dec : 2;
124 map { $taxrate += $form->{"${_}_rate"} } @taxaccounts;
126 $price_factor = $price_factors{ $form->{"price_factor_id_$i"} } || 1;
128 if ($form->{"inventory_accno_$i"}) {
130 $linetotal = $form->round_amount($form->{"sellprice_$i"} * $form->{"qty_$i"} / $price_factor, 2);
132 if ($form->{taxincluded}) {
133 $taxamount = $linetotal * ($taxrate / (1 + $taxrate));
134 $form->{"sellprice_$i"} = $form->{"sellprice_$i"} * (1 / (1 + $taxrate));
136 $taxamount = $linetotal * $taxrate;
139 $netamount += $linetotal;
141 if ($form->round_amount($taxrate, 7) == 0) {
142 if ($form->{taxincluded}) {
143 foreach $item (@taxaccounts) {
145 $form->round_amount($linetotal * $form->{"${item}_rate"} / (1 + abs($form->{"${item}_rate"})), 2);
146 $taxdiff += $taxamount;
147 $form->{amount}{ $form->{id} }{$item} -= $taxamount;
149 $form->{amount}{ $form->{id} }{ $taxaccounts[0] } += $taxdiff;
152 map { $form->{amount}{ $form->{id} }{$_} -= $linetotal * $form->{"${_}_rate"} } @taxaccounts;
156 map { $form->{amount}{ $form->{id} }{$_} -= $taxamount * $form->{"${_}_rate"} / $taxrate } @taxaccounts;
159 # add purchase to inventory, this one is without the tax!
160 $amount = $form->{"sellprice_$i"} * $form->{"qty_$i"} * $form->{exchangerate} / $price_factor;
161 $linetotal = $form->round_amount($form->{"sellprice_$i"} * $form->{"qty_$i"} / $price_factor, 2) * $form->{exchangerate};
162 $linetotal = $form->round_amount($linetotal, 2);
164 # this is the difference for the inventory
165 $invoicediff += ($amount - $linetotal);
167 $form->{amount}{ $form->{id} }{ $form->{"inventory_accno_$i"} } -= $linetotal;
169 # adjust and round sellprice
170 $form->{"sellprice_$i"} = $form->round_amount($form->{"sellprice_$i"} * $form->{exchangerate}, $decimalplaces);
172 $lastinventoryaccno = $form->{"inventory_accno_$i"};
174 next if $payments_only;
177 $query = qq|UPDATE parts SET lastcost = ? WHERE id = ?|;
178 @values = ($form->{"sellprice_$i"}, conv_i($form->{"id_$i"}));
179 do_query($form, $dbh, $query, @values);
181 $form->update_balance($dbh, "parts", "onhand", qq|id = ?|, $baseqty, $form->{"id_$i"}) if !$form->{shipped};
183 # check if we sold the item already and
184 # make an entry for the expense and inventory
186 qq|SELECT i.id, i.qty, i.allocated, i.trans_id,
187 p.inventory_accno_id, p.expense_accno_id, a.transdate
188 FROM invoice i, ar a, parts p
189 WHERE (i.parts_id = p.id)
191 AND ((i.base_qty + i.allocated) > 0)
192 AND (i.trans_id = a.id)
194 $sth = prepare_execute_query($form, $dbh, $query, conv_i($form->{"id_$i"}));
196 my $totalqty = $base_qty;
198 while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
199 my $qty = min $totalqty, ($ref->{base_qty} + $ref->{allocated});
200 $linetotal = $form->round_amount(($form->{"sellprice_$i"} * $qty) / $basefactor, 2);
202 if ($ref->{allocated} < 0) {
204 # we have an entry for it already, adjust amount
205 $form->update_balance($dbh, "acc_trans", "amount",
206 qq| (trans_id = $ref->{trans_id})
207 AND (chart_id = $ref->{inventory_accno_id})
208 AND (transdate = '$ref->{transdate}')|,
211 $form->update_balance($dbh, "acc_trans", "amount",
212 qq| (trans_id = $ref->{trans_id})
213 AND (chart_id = $ref->{expense_accno_id})
214 AND (transdate = '$ref->{transdate}')|,
217 } elsif ($linetotal != 0) {
218 # add entry for inventory, this one is for the sold item
219 $query = qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate, taxkey) VALUES (?, ?, ?, ?, (SELECT taxkey_id FROM chart WHERE id = ?))|;
220 @values = ($ref->{trans_id}, $ref->{inventory_accno_id}, $linetotal, $ref->{transdate}, $ref->{inventory_accno_id});
221 do_query($form, $dbh, $query, @values);
224 $query = qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate, taxkey) VALUES (?, ?, ?, ?, (SELECT taxkey from tax WHERE chart_id = ?))|;
225 @values = ($ref->{trans_id}, $ref->{expense_accno_id}, ($linetotal * -1), $ref->{transdate}, $ref->{expense_accno_id});
226 do_query($form, $dbh, $query, @values);
229 # update allocated for sold item
230 $form->update_balance($dbh, "invoice", "allocated", qq|id = $ref->{id}|, $qty * -1);
234 last if ($totalqty -= $qty) <= 0;
239 } else { # if ($form->{"inventory_accno_id_$i"})
241 $linetotal = $form->round_amount($form->{"sellprice_$i"} * $form->{"qty_$i"} / $price_factor, 2);
243 if ($form->{taxincluded}) {
244 $taxamount = $linetotal * ($taxrate / (1 + $taxrate));
245 $form->{"sellprice_$i"} = $form->{"sellprice_$i"} * (1 / (1 + $taxrate));
248 $taxamount = $linetotal * $taxrate;
251 $netamount += $linetotal;
253 if ($form->round_amount($taxrate, 7) == 0) {
254 if ($form->{taxincluded}) {
255 foreach $item (@taxaccounts) {
256 $taxamount = $linetotal * $form->{"${item}_rate"} / (1 + abs($form->{"${item}_rate"}));
257 $totaltax += $taxamount;
258 $form->{amount}{ $form->{id} }{$item} -= $taxamount;
261 map { $form->{amount}{ $form->{id} }{$_} -= $linetotal * $form->{"${_}_rate"} } @taxaccounts;
264 map { $form->{amount}{ $form->{id} }{$_} -= $taxamount * $form->{"${_}_rate"} / $taxrate } @taxaccounts;
267 $amount = $form->{"sellprice_$i"} * $form->{"qty_$i"} * $form->{exchangerate} / $price_factor;
268 $linetotal = $form->round_amount($form->{"sellprice_$i"} * $form->{"qty_$i"} / $price_factor, 2) * $form->{exchangerate};
269 $linetotal = $form->round_amount($linetotal, 2);
271 # this is the difference for expense
272 $expensediff += ($amount - $linetotal);
274 # add amount to expense
275 $form->{amount}{ $form->{id} }{ $form->{"expense_accno_$i"} } -= $linetotal;
277 $lastexpenseaccno = $form->{"expense_accno_$i"};
279 # adjust and round sellprice
280 $form->{"sellprice_$i"} = $form->round_amount($form->{"sellprice_$i"} * $form->{exchangerate}, $decimalplaces);
282 next if $payments_only;
285 $query = qq|UPDATE parts SET lastcost = ? WHERE id = ?|;
286 do_query($form, $dbh, $query, $form->{"sellprice_$i"}, conv_i($form->{"id_$i"}));
289 next if $payments_only;
291 # save detail record in invoice table
293 qq|INSERT INTO invoice (trans_id, parts_id, description, qty, base_qty,
294 sellprice, fxsellprice, allocated, unit, deliverydate,
295 project_id, serialnumber, price_factor_id, price_factor, marge_price_factor)
296 VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, (SELECT factor FROM price_factors WHERE id = ?), ?)|;
297 @values = (conv_i($form->{id}), conv_i($form->{"id_$i"}),
298 $form->{"description_$i"}, $form->{"qty_$i"} * -1,
299 $baseqty * -1, $form->{"sellprice_$i"}, $fxsellprice, $allocated,
300 $form->{"unit_$i"}, conv_date($form->{deliverydate}),
301 conv_i($form->{"project_id_$i"}), $form->{"serialnumber_$i"},
302 conv_i($form->{"price_factor_id_$i"}), conv_i($form->{"price_factor_id_$i"}), conv_i($form->{"marge_price_factor_$i"}));
303 do_query($form, $dbh, $query, @values);
306 $h_item_unit->finish();
308 my $project_id = conv_i($form->{"globalproject_id"});
310 $form->{datepaid} = $form->{invdate};
312 # all amounts are in natural state, netamount includes the taxes
313 # if tax is included, netamount is rounded to 2 decimal places,
317 for my $i (1 .. $form->{paidaccounts}) {
318 $form->{"paid_$i"} = $form->parse_amount($myconfig, $form->{"paid_$i"});
319 $form->{paid} += $form->{"paid_$i"};
320 $form->{datepaid} = $form->{"datepaid_$i"} if $form->{"datepaid_$i"};
323 my ($tax, $paiddiff) = (0, 0);
325 $netamount = $form->round_amount($netamount, 2);
327 # figure out rounding errors for amount paid and total amount
328 if ($form->{taxincluded}) {
330 $amount = $form->round_amount($netamount * $form->{exchangerate}, 2);
331 $paiddiff = $amount - $netamount * $form->{exchangerate};
332 $netamount = $amount;
334 foreach $item (split / /, $form->{taxaccounts}) {
335 $amount = $form->{amount}{ $form->{id} }{$item} * $form->{exchangerate};
336 $form->{amount}{ $form->{id} }{$item} = $form->round_amount($amount, 2);
338 $amount = $form->{amount}{ $form->{id} }{$item} * -1;
340 $netamount -= $amount;
343 $invoicediff += $paiddiff;
344 $expensediff += $paiddiff;
346 ######## this only applies to tax included
348 $form->{amount}{ $form->{id} }{$lastinventoryaccno} -= $invoicediff if $lastinventoryaccno;
349 $form->{amount}{ $form->{id} }{$lastexpenseaccno} -= $expensediff if $lastexpenseaccno;
352 $amount = $form->round_amount($netamount * $form->{exchangerate}, 2);
353 $paiddiff = $amount - $netamount * $form->{exchangerate};
354 $netamount = $amount;
356 foreach my $item (split / /, $form->{taxaccounts}) {
357 $form->{amount}{ $form->{id} }{$item} = $form->round_amount($form->{amount}{ $form->{id} }{$item}, 2);
358 $amount = $form->round_amount( $form->{amount}{ $form->{id} }{$item} * $form->{exchangerate} * -1, 2);
359 $paiddiff += $amount - $form->{amount}{ $form->{id} }{$item} * $form->{exchangerate} * -1;
360 $form->{amount}{ $form->{id} }{$item} = $form->round_amount($amount * -1, 2);
361 $amount = $form->{amount}{ $form->{id} }{$item} * -1;
366 $form->{amount}{ $form->{id} }{ $form->{AP} } = $netamount + $tax;
369 $form->{paid} = $form->round_amount($form->{paid} * $form->{exchangerate} + $paiddiff, 2) if $form->{paid} != 0;
371 # update exchangerate
373 $form->update_exchangerate($dbh, $form->{currency}, $form->{invdate}, 0, $form->{exchangerate})
374 if ($form->{currency} ne $defaultcurrency) && !$exchangerate;
376 # record acc_trans transactions
377 foreach my $trans_id (keys %{ $form->{amount} }) {
378 foreach my $accno (keys %{ $form->{amount}{$trans_id} }) {
379 $form->{amount}{$trans_id}{$accno} = $form->round_amount($form->{amount}{$trans_id}{$accno}, 2);
381 next if $payments_only || !$form->{amount}{$trans_id}{$accno};
383 $query = qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate, taxkey, project_id)
384 VALUES (?, (SELECT id FROM chart WHERE accno = ?), ?, ?,
385 (SELECT taxkey_id FROM chart WHERE accno = ?), ?)|;
386 @values = ($trans_id, $accno, $form->{amount}{$trans_id}{$accno},
387 conv_date($form->{invdate}), $accno, $project_id);
388 do_query($form, $dbh, $query, @values);
392 # deduct payment differences from paiddiff
393 for my $i (1 .. $form->{paidaccounts}) {
394 if ($form->{"paid_$i"} != 0) {
395 $amount = $form->round_amount($form->{"paid_$i"} * $form->{exchangerate}, 2);
396 $paiddiff -= $amount - $form->{"paid_$i"} * $form->{exchangerate};
400 # force AP entry if 0
402 $form->{amount}{ $form->{id} }{ $form->{AP} } = $form->{paid} if $form->{amount}{$form->{id}}{$form->{AP}} == 0;
404 # record payments and offsetting AP
405 for my $i (1 .. $form->{paidaccounts}) {
406 next if $form->{"paid_$i"} == 0;
408 my ($accno) = split /--/, $form->{"AP_paid_$i"};
409 $form->{"datepaid_$i"} = $form->{invdate} unless ($form->{"datepaid_$i"});
410 $form->{datepaid} = $form->{"datepaid_$i"};
412 $amount = $form->round_amount($form->{"paid_$i"} * $form->{exchangerate} + $paiddiff, 2) * -1;
415 if ($form->{amount}{ $form->{id} }{ $form->{AP} } != 0) {
416 $query = qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate, taxkey, project_id)
417 VALUES (?, (SELECT id FROM chart WHERE accno = ?), ?, ?,
418 (SELECT taxkey_id FROM chart WHERE accno = ?), ?)|;
419 @values = (conv_i($form->{id}), $form->{AP}, $amount,
420 $form->{"datepaid_$i"}, $form->{AP}, $project_id);
421 do_query($form, $dbh, $query, @values);
425 $query = qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate, source, memo, taxkey, project_id)
426 VALUES (?, (SELECT id FROM chart WHERE accno = ?), ?, ?, ?, ?,
427 (SELECT taxkey_id FROM chart WHERE accno = ?), ?)|;
428 @values = (conv_i($form->{id}), $accno, $form->{"paid_$i"}, $form->{"datepaid_$i"},
429 $form->{"source_$i"}, $form->{"memo_$i"}, $accno, $project_id);
430 do_query($form, $dbh, $query, @values);
434 if ($form->{currency} eq $defaultcurrency) {
435 $form->{"exchangerate_$i"} = 1;
437 $exchangerate = $form->check_exchangerate($myconfig, $form->{currency}, $form->{"datepaid_$i"}, 'sell');
438 $form->{"exchangerate_$i"} = $exchangerate || $form->parse_amount($myconfig, $form->{"exchangerate_$i"});
441 # exchangerate difference
442 $form->{fx}{$accno}{ $form->{"datepaid_$i"} } += $form->{"paid_$i"} * ($form->{"exchangerate_$i"} - 1) + $paiddiff;
446 ($form->{"paid_$i"} * $form->{exchangerate}) -
447 ($form->{"paid_$i"} * $form->{"exchangerate_$i"});
449 $form->{fx}{ $form->{fxgain_accno} }{ $form->{"datepaid_$i"} } += $amount;
451 $form->{fx}{ $form->{fxloss_accno} }{ $form->{"datepaid_$i"} } += $amount;
456 # update exchange rate
457 $form->update_exchangerate($dbh, $form->{currency}, $form->{"datepaid_$i"}, 0, $form->{"exchangerate_$i"})
458 if ($form->{currency} ne $defaultcurrency) && !$exchangerate;
461 # record exchange rate differences and gains/losses
462 foreach my $accno (keys %{ $form->{fx} }) {
463 foreach my $transdate (keys %{ $form->{fx}{$accno} }) {
464 $form->{fx}{$accno}{$transdate} = $form->round_amount($form->{fx}{$accno}{$transdate}, 2);
465 next if ($form->{fx}{$accno}{$transdate} == 0);
467 $query = qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate, cleared, fx_transaction, taxkey, project_id)
468 VALUES (?, (SELECT id FROM chart WHERE accno = ?), ?, ?, '0', '1', 0, ?)|;
469 @values = (conv_i($form->{id}), $accno, $form->{fx}{$accno}{$transdate}, conv_date($transdate), $project_id);
470 do_query($form, $dbh, $query, @values);
474 if ($payments_only) {
475 $query = qq|UPDATE ap SET paid = ?, datepaid = ? WHERE id = ?|;
476 do_query($form, $dbh, $query, $form->{paid}, $form->{paid} ? conv_date($form->{datepaid}) : undef, conv_i($form->{id}));
478 if (!$provided_dbh) {
483 $main::lxdebug->leave_sub();
487 $amount = $netamount + $tax;
489 # set values which could be empty
490 my $taxzone_id = $form->{taxzone_id} * 1;
491 $form->{department_id} = (split /--/, $form->{department})[1];
492 $form->{invnumber} = $form->{id} unless $form->{invnumber};
494 $taxzone_id = 0 if (3 < $taxzone_id) || (0 > $taxzone_id);
497 $query = qq|UPDATE ap SET
498 invnumber = ?, ordnumber = ?, quonumber = ?, transdate = ?,
499 orddate = ?, quodate = ?, vendor_id = ?, amount = ?,
500 netamount = ?, paid = ?, duedate = ?, datepaid = ?,
501 invoice = ?, taxzone_id = ?, notes = ?, taxincluded = ?,
502 intnotes = ?, curr = ?, storno_id = ?, storno = ?,
503 cp_id = ?, employee_id = ?, department_id = ?,
507 $form->{invnumber}, $form->{ordnumber}, $form->{quonumber}, conv_date($form->{invdate}),
508 conv_date($form->{orddate}), conv_date($form->{quodate}), conv_i($form->{vendor_id}), $amount,
509 $netamount, $form->{paid}, conv_date($form->{duedate}), $form->{paid} ? conv_date($form->{datepaid}) : undef,
510 '1', $taxzone_id, $form->{notes}, $form->{taxincluded} ? 't' : 'f',
511 $form->{intnotes}, $form->{currency}, conv_i($form->{storno_id}), $form->{storno} ? 't' : 'f',
512 conv_i($form->{cp_id}), conv_i($form->{employee_id}), conv_i($form->{department_id}),
513 conv_i($form->{globalproject_id}),
516 do_query($form, $dbh, $query, @values);
518 if ($form->{storno}) {
519 $query = qq|UPDATE ap SET paid = paid + amount WHERE id = ?|;
520 do_query($form, $dbh, $query, conv_i($form->{storno_id}));
522 $query = qq|UPDATE ap SET storno = 't' WHERE id = ?|;
523 do_query($form, $dbh, $query, conv_i($form->{storno_id}));
525 $query = qq!UPDATE ap SET intnotes = ? || intnotes WHERE id = ?!;
526 do_query($form, $dbh, $query, 'Rechnung storniert am $form->{invdate} ', conv_i($form->{storno_id}));
528 $query = qq|UPDATE ap SET paid = amount WHERE id = ?|;
529 do_query($form, $dbh, $query, conv_i($form->{id}));
534 $form->{name} = $form->{vendor};
535 $form->{name} =~ s/--$form->{vendor_id}//;
536 $form->add_shipto($dbh, $form->{id}, "AP");
538 # delete zero entries
539 do_query($form, $dbh, qq|DELETE FROM acc_trans WHERE amount = 0|);
541 Common::webdav_folder($form) if ($main::webdav);
545 if (!$provided_dbh) {
546 $rc = $dbh->commit();
550 $main::lxdebug->leave_sub();
555 sub reverse_invoice {
556 $main::lxdebug->enter_sub();
558 my ($dbh, $form) = @_;
560 # reverse inventory items
562 qq|SELECT i.parts_id, p.inventory_accno_id, p.expense_accno_id, i.qty, i.allocated, i.sellprice
563 FROM invoice i, parts p
564 WHERE (i.parts_id = p.id)
565 AND (i.trans_id = ?)|;
566 my $sth = prepare_execute_query($form, $dbh, $query, conv_i($form->{id}));
570 while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
571 $netamount += $form->round_amount($ref->{sellprice} * $ref->{qty} * -1, 2);
573 next unless $ref->{inventory_accno_id};
576 $form->update_balance($dbh, "parts", "onhand", qq|id = $ref->{parts_id}|, $ref->{qty});
578 # if $ref->{allocated} > 0 than we sold that many items
579 next if ($ref->{allocated} <= 0);
581 # get references for sold items
583 qq|SELECT i.id, i.trans_id, i.allocated, a.transdate
585 WHERE (i.parts_id = ?)
586 AND (i.allocated < 0)
587 AND (i.trans_id = a.id)
588 ORDER BY transdate DESC|;
589 my $sth2 = prepare_execute_query($form, $dbh, $query, $ref->{parts_id});
591 while (my $pthref = $sth2->fetchrow_hashref(NAME_lc)) {
592 my $qty = $ref->{allocated};
593 if (($ref->{allocated} + $pthref->{allocated}) > 0) {
594 $qty = $pthref->{allocated} * -1;
597 my $amount = $form->round_amount($ref->{sellprice} * $qty, 2);
600 $form->update_balance($dbh, "invoice", "allocated", qq|id = $pthref->{id}|, $qty);
602 $form->update_balance($dbh, "acc_trans", "amount",
603 qq| (trans_id = $pthref->{trans_id})
604 AND (chart_id = $ref->{expense_accno_id})
605 AND (transdate = '$pthref->{transdate}')|,
608 $form->update_balance($dbh, "acc_trans", "amount",
609 qq| (trans_id = $pthref->{trans_id})
610 AND (chart_id = $ref->{inventory_accno_id})
611 AND (transdate = '$pthref->{transdate}')|,
614 last if (($ref->{allocated} -= $qty) <= 0);
620 my $id = conv_i($form->{id});
623 $query = qq|DELETE FROM acc_trans WHERE trans_id = ?|;
624 do_query($form, $dbh, $query, $id);
626 # delete invoice entries
627 $query = qq|DELETE FROM invoice WHERE trans_id = ?|;
628 do_query($form, $dbh, $query, $id);
630 $query = qq|DELETE FROM shipto WHERE (trans_id = ?) AND (module = 'AP')|;
631 do_query($form, $dbh, $query, $id);
633 $main::lxdebug->leave_sub();
637 $main::lxdebug->enter_sub();
639 my ($self, $myconfig, $form) = @_;
641 # connect to database
642 my $dbh = $form->dbconnect_noauto($myconfig);
644 &reverse_invoice($dbh, $form);
646 # delete zero entries
647 my $query = qq|DELETE FROM acc_trans WHERE amount = 0|;
648 do_query($form, $dbh, $query);
651 my $query = qq|DELETE FROM ap WHERE id = ?|;
652 do_query($form, $dbh, $query, conv_i($form->{id}));
654 my $rc = $dbh->commit;
657 $main::lxdebug->leave_sub();
662 sub retrieve_invoice {
663 $main::lxdebug->enter_sub();
665 my ($self, $myconfig, $form) = @_;
667 # connect to database
668 my $dbh = $form->dbconnect($myconfig);
670 my ($query, $sth, $ref, $q_invdate);
673 $q_invdate = qq|, COALESCE((SELECT transdate FROM ar WHERE id = (SELECT MAX(id) FROM ar)), current_date) AS invdate|;
674 if ($form->{vendor_id}) {
675 my $vendor_id = $dbh->quote($form->{vendor_id} * 1);
677 qq|, COALESCE((SELECT transdate FROM ar WHERE id = (SELECT MAX(id) FROM ar)), current_date) +
678 COALESCE((SELECT pt.terms_netto
680 LEFT JOIN payment_terms pt ON (v.payment_id = pt.id)
681 WHERE v.id = $vendor_id),
686 # get default accounts and last invoice number
689 (SELECT c.accno FROM chart c WHERE d.inventory_accno_id = c.id) AS inventory_accno,
690 (SELECT c.accno FROM chart c WHERE d.income_accno_id = c.id) AS income_accno,
691 (SELECT c.accno FROM chart c WHERE d.expense_accno_id = c.id) AS expense_accno,
692 (SELECT c.accno FROM chart c WHERE d.fxgain_accno_id = c.id) AS fxgain_accno,
693 (SELECT c.accno FROM chart c WHERE d.fxloss_accno_id = c.id) AS fxloss_accno,
697 $ref = selectfirst_hashref_query($form, $dbh, $query);
698 map { $form->{$_} = $ref->{$_} } keys %$ref;
702 $main::lxdebug->leave_sub();
708 $query = qq|SELECT cp_id, invnumber, transdate AS invdate, duedate,
709 orddate, quodate, globalproject_id,
710 ordnumber, quonumber, paid, taxincluded, notes, taxzone_id, storno, gldate,
711 intnotes, curr AS currency
714 $ref = selectfirst_hashref_query($form, $dbh, $query, conv_i($form->{id}));
715 map { $form->{$_} = $ref->{$_} } keys %$ref;
717 $form->{exchangerate} = $form->get_exchangerate($dbh, $form->{currency}, $form->{invdate}, "sell");
720 $query = qq|SELECT * FROM shipto WHERE (trans_id = ?) AND (module = 'AP')|;
721 $ref = selectfirst_hashref_query($form, $dbh, $query, conv_i($form->{id}));
723 map { $form->{$_} = $ref->{$_} } keys %$ref;
725 my $transdate = $form->{invdate} ? $dbh->quote($form->{invdate}) : "current_date";
726 my $taxzone_id = $form->{taxzone_id} * 1;
728 $taxzone_id = 0 if ((3 < $taxzone_id) || (0 > $taxzone_id));
730 # retrieve individual items
733 c1.accno AS inventory_accno, c1.new_chart_id AS inventory_new_chart, date($transdate) - c1.valid_from AS inventory_valid,
734 c2.accno AS income_accno, c2.new_chart_id AS income_new_chart, date($transdate) - c2.valid_from AS income_valid,
735 c3.accno AS expense_accno, c3.new_chart_id AS expense_new_chart, date($transdate) - c3.valid_from AS expense_valid,
737 i.description, i.qty, i.fxsellprice AS sellprice, i.parts_id AS id, i.unit, i.deliverydate, i.project_id, i.serialnumber,
738 i.price_factor_id, i.price_factor, i.marge_price_factor,
739 p.partnumber, p.inventory_accno_id AS part_inventory_accno_id, p.bin, pr.projectnumber, pg.partsgroup
742 JOIN parts p ON (i.parts_id = p.id)
743 LEFT JOIN chart c1 ON ((SELECT inventory_accno_id FROM buchungsgruppen WHERE id = p.buchungsgruppen_id) = c1.id)
744 LEFT JOIN chart c2 ON ((SELECT income_accno_id_${taxzone_id} FROM buchungsgruppen WHERE id = p.buchungsgruppen_id) = c2.id)
745 LEFT JOIN chart c3 ON ((SELECT expense_accno_id_${taxzone_id} FROM buchungsgruppen WHERE id = p.buchungsgruppen_id) = c3.id)
746 LEFT JOIN project pr ON (i.project_id = pr.id)
747 LEFT JOIN partsgroup pg ON (pg.id = p.partsgroup_id)
752 $sth = prepare_execute_query($form, $dbh, $query, conv_i($form->{id}));
754 while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
755 map({ delete($ref->{$_}); } qw(inventory_accno inventory_new_chart inventory_valid)) if !$ref->{"part_inventory_accno_id"};
756 delete($ref->{"part_inventory_accno_id"});
758 foreach my $type (qw(inventory income expense)) {
759 while ($ref->{"${type}_new_chart"} && ($ref->{"${type}_valid"} >=0)) {
760 my $query = qq|SELECT accno, new_chart_id, date($transdate) - valid_from FROM chart WHERE id = ?|;
761 @$ref{ map $type.$_, qw(_accno _new_chart _valid) } = selectrow_query($form, $dbh, $query, $ref->{"${type}_new_chart"});
765 # get tax rates and description
766 my $accno_id = ($form->{vc} eq "customer") ? $ref->{income_accno} : $ref->{expense_accno};
768 qq|SELECT c.accno, t.taxdescription, t.rate, t.taxnumber FROM tax t
769 LEFT JOIN chart c ON (c.id = t.chart_id)
771 (SELECT tk.tax_id FROM taxkeys tk
772 WHERE tk.chart_id = (SELECT id FROM chart WHERE accno = ?)
773 AND (startdate <= $transdate)
774 ORDER BY startdate DESC
777 my $stw = prepare_execute_query($form, $dbh, $query, $accno_id);
778 $ref->{taxaccounts} = "";
781 while ($ptr = $stw->fetchrow_hashref(NAME_lc)) {
782 if (($ptr->{accno} eq "") && ($ptr->{rate} == 0)) {
787 $ref->{taxaccounts} .= "$ptr->{accno} ";
789 if (!($form->{taxaccounts} =~ /$ptr->{accno}/)) {
790 $form->{"$ptr->{accno}_rate"} = $ptr->{rate};
791 $form->{"$ptr->{accno}_description"} = $ptr->{taxdescription};
792 $form->{"$ptr->{accno}_taxnumber"} = $ptr->{taxnumber};
793 $form->{taxaccounts} .= "$ptr->{accno} ";
798 chop $ref->{taxaccounts};
799 push @{ $form->{invoice_details} }, $ref;
804 Common::webdav_folder($form) if ($main::webdav);
808 $main::lxdebug->leave_sub();
812 $main::lxdebug->enter_sub();
814 my ($self, $myconfig, $form) = @_;
816 # connect to database
817 my $dbh = $form->dbconnect($myconfig);
819 my $dateformat = $myconfig->{dateformat};
820 $dateformat .= "yy" if $myconfig->{dateformat} !~ /^y/;
822 my $vid = conv_i($form->{vendor_id});
826 ? "to_date(" . $dbh->quote($form->{invdate}) . ", '$dateformat')"
832 v.name AS vendor, v.creditlimit, v.terms, v.notes AS intnotes,
833 v.email, v.cc, v.bcc, v.language_id, v.payment_id,
834 v.street, v.zipcode, v.city, v.country, v.taxzone_id,
835 $duedate + COALESCE(pt.terms_netto, 0) AS duedate,
836 b.description AS business
838 LEFT JOIN business b ON (b.id = v.business_id)
839 LEFT JOIN payment_terms pt ON (v.payment_id = pt.id)
841 $ref = selectfirst_hashref_query($form, $dbh, $query, $vid);
842 map { $form->{$_} = $ref->{$_} } keys %$ref;
844 $form->{creditremaining} = $form->{creditlimit};
846 $query = qq|SELECT SUM(amount - paid) FROM ap WHERE vendor_id = ?|;
847 my ($unpaid_invoices) = selectfirst_array_query($form, $dbh, $query, $vid);
848 $form->{creditremaining} -= $unpaid_invoices;
850 $query = qq|SELECT o.amount,
853 WHERE (e.curr = o.curr)
854 AND (e.transdate = o.transdate)) AS exch
856 WHERE (o.vendor_id = ?) AND (o.quotation = '0') AND (o.closed = '0')|;
857 my $sth = prepare_execute_query($form, $dbh, $query, $vid);
858 while (my ($amount, $exch) = $sth->fetchrow_array()) {
859 $exch = 1 unless $exch;
860 $form->{creditremaining} -= $amount * $exch;
864 # get shipto if we do not convert an order or invoice
865 if (!$form->{shipto}) {
866 delete @{$form}{qw(shiptoname shiptostreet shiptozipcode shiptocity shiptocountry shiptocontact shiptophone shiptofax shiptoemail)};
868 $query = qq|SELECT * FROM shipto WHERE (trans_id = ?) AND (module= 'CT')|;
869 $ref = selectfirst_hashref_query($form, $dbh, $query, $vid);
870 @{$form}{keys %$ref} = @{$ref}{keys %$ref};
871 map { $form->{$_} = $ref->{$_} } keys %$ref;
874 if (!$form->{id} && $form->{type} !~ /_(order|quotation)/) {
875 # setup last accounts used
877 qq|SELECT c.id, c.accno, c.description, c.link, c.category
879 JOIN acc_trans ac ON (ac.chart_id = c.id)
880 JOIN ap a ON (a.id = ac.trans_id)
881 WHERE (a.vendor_id = ?)
882 AND (NOT ((c.link LIKE '%_tax%') OR (c.link LIKE '%_paid%')))
883 AND (a.id IN (SELECT max(a2.id) FROM ap a2 WHERE a2.vendor_id = ?))|;
884 my $refs = selectall_hashref_query($form, $dbh, $query, $vid, $vid);
888 if ($ref->{category} eq 'E') {
891 if ($form->{initial_transdate}) {
892 my $tax_query = qq|SELECT tk.tax_id, t.rate FROM taxkeys tk
893 LEFT JOIN tax t ON (tk.tax_id = t.id)
894 WHERE (tk.chart_id = ?) AND (startdate <= ?)
895 ORDER BY tk.startdate DESC
897 my ($tax_id, $rate) = selectrow_query($form, $dbh, $tax_query, $ref->{id}, $form->{initial_transdate});
898 $form->{"taxchart_$i"} = "${tax_id}--${rate}";
901 $form->{"AP_amount_$i"} = "$ref->{accno}--$tax_id";
904 if ($ref->{category} eq 'L') {
905 $form->{APselected} = $form->{AP_1} = $ref->{accno};
908 $form->{rowcount} = $i if ($i && !$form->{type});
913 $main::lxdebug->leave_sub();
917 $main::lxdebug->enter_sub();
919 my ($self, $myconfig, $form) = @_;
921 # connect to database
922 my $dbh = $form->dbconnect($myconfig);
924 my $i = $form->{rowcount};
926 # don't include assemblies or obsolete parts
927 my $where = "NOT p.assembly = '1' AND NOT p.obsolete = '1'";
930 foreach my $table_column (qw(p.partnumber p.description pg.partsgroup)) {
931 my $field = (split m{\.}, $table_column)[1];
932 next unless $form->{"${field}_${i}"};
933 $where .= " AND lower(${table_column}) LIKE lower(?)";
934 push @values, '%' . $form->{"${field}_${i}"} . '%';
937 if ($form->{"description_$i"}) {
938 $where .= " ORDER BY p.description";
940 $where .= " ORDER BY p.partnumber";
944 if ($form->{type} eq "invoice") {
945 $transdate = $form->{invdate} ? $dbh->quote($form->{invdate}) : "current_date";
947 $transdate = $form->{transdate} ? $dbh->quote($form->{transdate}) : "current_date";
950 my $taxzone_id = $form->{taxzone_id} * 1;
951 $taxzone_id = 0 if ((3 < $taxzone_id) || (0 > $taxzone_id));
955 p.id, p.partnumber, p.description, p.lastcost AS sellprice, p.listprice,
956 p.unit, p.assembly, p.bin, p.onhand, p.formel,
957 p.notes AS partnotes, p.notes AS longdescription, p.not_discountable,
958 p.inventory_accno_id, p.price_factor_id,
960 pfac.factor AS price_factor,
962 c1.accno AS inventory_accno,
963 c1.new_chart_id AS inventory_new_chart,
964 date($transdate) - c1.valid_from AS inventory_valid,
966 c2.accno AS income_accno,
967 c2.new_chart_id AS income_new_chart,
968 date($transdate) - c2.valid_from AS income_valid,
970 c3.accno AS expense_accno,
971 c3.new_chart_id AS expense_new_chart,
972 date($transdate) - c3.valid_from AS expense_valid,
977 LEFT JOIN chart c1 ON
978 ((SELECT inventory_accno_id
980 WHERE id = p.buchungsgruppen_id) = c1.id)
981 LEFT JOIN chart c2 ON
982 ((SELECT income_accno_id_${taxzone_id}
984 WHERE id = p.buchungsgruppen_id) = c2.id)
985 LEFT JOIN chart c3 ON
986 ((SELECT expense_accno_id_${taxzone_id}
988 WHERE id = p.buchungsgruppen_id) = c3.id)
989 LEFT JOIN partsgroup pg ON (pg.id = p.partsgroup_id)
990 LEFT JOIN price_factors pfac ON (pfac.id = p.price_factor_id)
992 my $sth = prepare_execute_query($form, $dbh, $query, @values);
994 $form->{item_list} = [];
995 while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
997 # In der Buchungsgruppe ist immer ein Bestandskonto verknuepft, auch wenn
998 # es sich um eine Dienstleistung handelt. Bei Dienstleistungen muss das
999 # Buchungskonto also aus dem Ergebnis rausgenommen werden.
1000 if (!$ref->{inventory_accno_id}) {
1001 map({ delete($ref->{"inventory_${_}"}); } qw(accno new_chart valid));
1003 delete($ref->{inventory_accno_id});
1005 # get tax rates and description
1006 $accno_id = ($form->{vc} eq "customer") ? $ref->{income_accno} : $ref->{expense_accno};
1008 qq|SELECT c.accno, t.taxdescription, t.rate, t.taxnumber
1010 LEFT JOIN chart c on (c.id = t.chart_id)
1018 AND (startdate <= $transdate)
1019 ORDER BY startdate DESC
1022 my $stw = prepare_execute_query($form, $dbh, $query, $accno_id);
1024 $ref->{taxaccounts} = "";
1026 while ($ptr = $stw->fetchrow_hashref(NAME_lc)) {
1028 # if ($customertax{$ref->{accno}}) {
1029 if (($ptr->{accno} eq "") && ($ptr->{rate} == 0)) {
1034 $ref->{taxaccounts} .= "$ptr->{accno} ";
1036 if (!($form->{taxaccounts} =~ /$ptr->{accno}/)) {
1037 $form->{"$ptr->{accno}_rate"} = $ptr->{rate};
1038 $form->{"$ptr->{accno}_description"} = $ptr->{taxdescription};
1039 $form->{"$ptr->{accno}_taxnumber"} = $ptr->{taxnumber};
1040 $form->{taxaccounts} .= "$ptr->{accno} ";
1046 chop $ref->{taxaccounts};
1048 push @{ $form->{item_list} }, $ref;
1055 $main::lxdebug->leave_sub();
1058 sub vendor_details {
1059 $main::lxdebug->enter_sub();
1061 my ($self, $myconfig, $form, @wanted_vars) = @_;
1063 # connect to database
1064 my $dbh = $form->dbconnect($myconfig);
1068 # get contact id, set it if nessessary
1069 $form->{cp_id} = (split /--/, $form->{contact})[1];
1071 if ($form->{cp_id}) {
1072 $contact = "AND cp.cp_id = ?";
1073 push @values, $form->{cp_id};
1076 # get rest for the vendor
1077 # fax and phone and email as vendor*
1079 qq|SELECT ct.*, cp.*, ct.notes as vendornotes, phone as vendorphone, fax as vendorfax, email as vendoremail
1081 LEFT JOIN contacts cp ON (ct.id = cp.cp_cv_id)
1082 WHERE (ct.id = ?) $contact
1085 my $ref = selectfirst_hashref_query($form, $dbh, $query, $form->{vendor_id}, @values);
1087 # remove id and taxincluded before copy back
1088 delete @$ref{qw(id taxincluded)};
1090 @wanted_vars = grep({ $_ } @wanted_vars);
1091 if (scalar(@wanted_vars) > 0) {
1093 map({ $h_wanted_vars{$_} = 1; } @wanted_vars);
1094 map({ delete($ref->{$_}) unless ($h_wanted_vars{$_}); } keys(%{$ref}));
1097 map { $form->{$_} = $ref->{$_} } keys %$ref;
1101 $main::lxdebug->leave_sub();
1105 $main::lxdebug->enter_sub();
1107 my ($self, $myconfig, $form) = @_;
1109 # connect to database
1110 my $dbh = $form->dbconnect($myconfig);
1113 qq|SELECT accno, description, link
1115 WHERE link LIKE '%IC%'
1117 my $sth = prepare_execute_query($query, $dbh, $query);
1119 while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
1120 foreach my $key (split(/:/, $ref->{link})) {
1122 push @{ $form->{IC_links}{$key} },
1123 { accno => $ref->{accno},
1124 description => $ref->{description} };
1132 $main::lxdebug->leave_sub();
1135 sub _delete_payments {
1136 $main::lxdebug->enter_sub();
1138 my ($self, $form, $dbh) = @_;
1142 # Delete old payment entries from acc_trans.
1146 WHERE (trans_id = ?) AND fx_transaction
1152 LEFT JOIN chart c ON (at.chart_id = c.id)
1153 WHERE (trans_id = ?) AND (c.link LIKE '%AP_paid%')|;
1154 push @delete_oids, selectall_array_query($form, $dbh, $query, conv_i($form->{id}), conv_i($form->{id}));
1159 LEFT JOIN chart c ON (at.chart_id = c.id)
1160 WHERE (trans_id = ?)
1161 AND ((c.link = 'AP') OR (c.link LIKE '%:AP') OR (c.link LIKE 'AP:%'))
1164 push @delete_oids, selectall_array_query($form, $dbh, $query, conv_i($form->{id}));
1167 $query = qq|DELETE FROM acc_trans WHERE oid IN (| . join(", ", @delete_oids) . qq|)|;
1168 do_query($form, $dbh, $query);
1171 $main::lxdebug->leave_sub();
1175 $main::lxdebug->enter_sub();
1177 my ($self, $myconfig, $form, $locale) = @_;
1179 # connect to database, turn off autocommit
1180 my $dbh = $form->dbconnect_noauto($myconfig);
1182 my (%payments, $old_form, $row, $item, $query, %keep_vars);
1184 $old_form = save_form();
1186 # Delete all entries in acc_trans from prior payments.
1187 $self->_delete_payments($form, $dbh);
1189 # Save the new payments the user made before cleaning up $form.
1190 map { $payments{$_} = $form->{$_} } grep m/^datepaid_\d+$|^memo_\d+$|^source_\d+$|^exchangerate_\d+$|^paid_\d+$|^AP_paid_\d+$|^paidaccounts$/, keys %{ $form };
1192 # Clean up $form so that old content won't tamper the results.
1193 %keep_vars = map { $_, 1 } qw(login password id);
1194 map { delete $form->{$_} unless $keep_vars{$_} } keys %{ $form };
1196 # Retrieve the invoice from the database.
1197 $self->retrieve_invoice($myconfig, $form);
1199 # Set up the content of $form in the way that IR::post_invoice() expects.
1200 $form->{exchangerate} = $form->format_amount($myconfig, $form->{exchangerate});
1202 for $row (1 .. scalar @{ $form->{invoice_details} }) {
1203 $item = $form->{invoice_details}->[$row - 1];
1205 map { $item->{$_} = $form->format_amount($myconfig, $item->{$_}) } qw(qty sellprice);
1207 map { $form->{"${_}_${row}"} = $item->{$_} } keys %{ $item };
1210 $form->{rowcount} = scalar @{ $form->{invoice_details} };
1212 delete @{$form}{qw(invoice_details paidaccounts storno paid)};
1214 # Restore the payment options from the user input.
1215 map { $form->{$_} = $payments{$_} } keys %payments;
1217 # Get the AP accno (which is normally done by Form::create_links()).
1221 LEFT JOIN chart c ON (at.chart_id = c.id)
1222 WHERE (trans_id = ?)
1223 AND ((c.link = 'AP') OR (c.link LIKE '%:AP') OR (c.link LIKE 'AP:%'))
1227 ($form->{AP}) = selectfirst_array_query($form, $dbh, $query, conv_i($form->{id}));
1229 # Post the new payments.
1230 $self->post_invoice($myconfig, $form, $dbh, 1);
1232 restore_form($old_form);
1234 my $rc = $dbh->commit();
1237 $main::lxdebug->leave_sub();