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 #======================================================================
43 $main::lxdebug->enter_sub();
45 my ($self, $myconfig, $form, $provided_dbh, $payments_only) = @_;
47 # connect to database, turn off autocommit
48 my $dbh = $provided_dbh ? $provided_dbh : $form->dbconnect_noauto($myconfig);
50 my ($query, $sth, @values, $project_id);
51 my ($allocated, $taxrate, $taxamount, $taxdiff, $item);
52 my ($amount, $linetotal, $lastinventoryaccno, $lastexpenseaccno);
53 my ($netamount, $invoicediff, $expensediff) = (0, 0, 0);
56 my $all_units = AM->retrieve_units($myconfig, $form);
58 if (!$payments_only) {
60 &reverse_invoice($dbh, $form);
63 ($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;
76 $form->check_exchangerate($myconfig, $form->{currency},
77 $form->{transdate}, 'sell');
80 $form->{exchangerate} =
83 : $form->parse_amount($myconfig, $form->{exchangerate});
85 $form->{exchangerate} = 1 unless ($form->{exchangerate} * 1);
88 my $q_item_unit = qq|SELECT unit FROM parts WHERE id = ?|;
89 my $h_item_unit = prepare_query($form, $dbh, $q_item_unit);
91 for my $i (1 .. $form->{rowcount}) {
92 next unless $form->{"id_$i"};
94 $form->{"qty_$i"} = $form->parse_amount($myconfig, $form->{"qty_$i"});
96 if ($form->{storno}) {
97 $form->{"qty_$i"} *= -1;
101 $form->{"inventory_accno_$i"} = $form->{"expense_accno_$i"};
105 if (!$item_units{$form->{"id_$i"}}) {
106 do_statement($form, $h_item_unit, $q_item_unit, $form->{"id_$i"});
107 ($item_units{$form->{"id_$i"}}) = $h_item_unit->fetchrow_array();
110 my $item_unit = $item_units{$form->{"id_$i"}};
112 if (defined($all_units->{$item_unit}->{factor})
113 && ($all_units->{$item_unit}->{factor} ne '')
114 && ($all_units->{$item_unit}->{factor} * 1 != 0)) {
115 $basefactor = $all_units->{$form->{"unit_$i"}}->{factor} / $all_units->{$item_unit}->{factor};
119 $baseqty = $form->{"qty_$i"} * $basefactor;
121 @taxaccounts = split / /, $form->{"taxaccounts_$i"};
126 $form->{"sellprice_$i"} = $form->parse_amount($myconfig, $form->{"sellprice_$i"});
127 my $fxsellprice = $form->{"sellprice_$i"};
129 my ($dec) = ($fxsellprice =~ /\.(\d+)/);
131 my $decimalplaces = ($dec > 2) ? $dec : 2;
133 map { $taxrate += $form->{"${_}_rate"} } @taxaccounts;
135 if ($form->{"inventory_accno_$i"}) {
137 $linetotal = $form->round_amount($form->{"sellprice_$i"} * $form->{"qty_$i"}, 2);
139 if ($form->{taxincluded}) {
140 $taxamount = $linetotal * ($taxrate / (1 + $taxrate));
141 $form->{"sellprice_$i"} = $form->{"sellprice_$i"} * (1 / (1 + $taxrate));
143 $taxamount = $linetotal * $taxrate;
146 $netamount += $linetotal;
148 if ($form->round_amount($taxrate, 7) == 0) {
149 if ($form->{taxincluded}) {
150 foreach $item (@taxaccounts) {
152 $form->round_amount($linetotal * $form->{"${item}_rate"} / (1 + abs($form->{"${item}_rate"})), 2);
153 $taxdiff += $taxamount;
154 $form->{amount}{ $form->{id} }{$item} -= $taxamount;
156 $form->{amount}{ $form->{id} }{ $taxaccounts[0] } += $taxdiff;
159 map { $form->{amount}{ $form->{id} }{$_} -= $linetotal * $form->{"${_}_rate"} } @taxaccounts;
163 map { $form->{amount}{ $form->{id} }{$_} -= $taxamount * $form->{"${_}_rate"} / $taxrate } @taxaccounts;
166 # add purchase to inventory, this one is without the tax!
167 $amount = $form->{"sellprice_$i"} * $form->{"qty_$i"} * $form->{exchangerate};
168 $linetotal = $form->round_amount($form->{"sellprice_$i"} * $form->{"qty_$i"}, 2) * $form->{exchangerate};
169 $linetotal = $form->round_amount($linetotal, 2);
171 # this is the difference for the inventory
172 $invoicediff += ($amount - $linetotal);
174 $form->{amount}{ $form->{id} }{ $form->{"inventory_accno_$i"} } -= $linetotal;
176 # adjust and round sellprice
177 $form->{"sellprice_$i"} =
178 $form->round_amount($form->{"sellprice_$i"} * $form->{exchangerate}, $decimalplaces);
180 $lastinventoryaccno = $form->{"inventory_accno_$i"};
182 next if $payments_only;
185 $query = qq|UPDATE parts SET lastcost = ? WHERE id = ?|;
186 @values = ($form->{"sellprice_$i"}, conv_i($form->{"id_$i"}));
187 do_query($form, $dbh, $query, @values);
189 if (!$form->{shipped}) {
190 $form->update_balance($dbh, "parts", "onhand", qq|id = ?|, $baseqty, $form->{"id_$i"})
193 # check if we sold the item already and
194 # make an entry for the expense and inventory
196 qq|SELECT i.id, i.qty, i.allocated, i.trans_id,
197 p.inventory_accno_id, p.expense_accno_id, a.transdate
198 FROM invoice i, ar a, parts p
199 WHERE (i.parts_id = p.id)
201 AND ((i.base_qty + i.allocated) > 0)
202 AND (i.trans_id = a.id)
204 $sth = prepare_execute_query($form, $dbh, $query, conv_i($form->{"id_$i"}));
206 my $totalqty = $base_qty;
208 while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
210 my $qty = $ref->{base_qty} + $ref->{allocated};
212 if (($qty - $totalqty) > 0) {
216 $linetotal = $form->round_amount(($form->{"sellprice_$i"} * $qty) / $basefactor, 2);
218 if ($ref->{allocated} < 0) {
220 # we have an entry for it already, adjust amount
221 $form->update_balance($dbh, "acc_trans", "amount",
222 qq| (trans_id = $ref->{trans_id})
223 AND (chart_id = $ref->{inventory_accno_id})
224 AND (transdate = '$ref->{transdate}')|,
227 $form->update_balance($dbh, "acc_trans", "amount",
228 qq| (trans_id = $ref->{trans_id})
229 AND (chart_id = $ref->{expense_accno_id})
230 AND (transdate = '$ref->{transdate}')|,
233 } elsif ($linetotal != 0) {
234 # add entry for inventory, this one is for the sold item
235 $query = qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate, taxkey)
236 VALUES (?, ?, ?, ?, (SELECT taxkey_id FROM chart WHERE id = ?))|;
237 @values = ($ref->{trans_id}, $ref->{inventory_accno_id}, $linetotal,
238 $ref->{transdate}, $ref->{inventory_accno_id});
239 do_query($form, $dbh, $query, @values);
242 $query = qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate, taxkey)
243 VALUES (?, ?, ?, ?, (SELECT taxkey from tax WHERE chart_id = ?))|;
244 @values = ($ref->{trans_id}, $ref->{expense_accno_id}, ($linetotal * -1),
245 $ref->{transdate}, $ref->{expense_accno_id});
246 do_query($form, $dbh, $query, @values);
249 # update allocated for sold item
250 $form->update_balance($dbh, "invoice", "allocated", qq|id = $ref->{id}|, $qty * -1);
254 last if (($totalqty -= $qty) <= 0);
261 $linetotal = $form->round_amount($form->{"sellprice_$i"} * $form->{"qty_$i"}, 2);
263 if ($form->{taxincluded}) {
264 $taxamount = $linetotal * ($taxrate / (1 + $taxrate));
265 $form->{"sellprice_$i"} = $form->{"sellprice_$i"} * (1 / (1 + $taxrate));
268 $taxamount = $linetotal * $taxrate;
271 $netamount += $linetotal;
273 if ($form->round_amount($taxrate, 7) == 0) {
274 if ($form->{taxincluded}) {
275 foreach $item (@taxaccounts) {
277 $linetotal * $form->{"${item}_rate"}
278 / (1 + abs($form->{"${item}_rate"}));
279 $totaltax += $taxamount;
280 $form->{amount}{ $form->{id} }{$item} -= $taxamount;
284 map { $form->{amount}{ $form->{id} }{$_} -= $linetotal * $form->{"${_}_rate"} } @taxaccounts;
288 map { $form->{amount}{ $form->{id} }{$_} -= $taxamount * $form->{"${_}_rate"} / $taxrate } @taxaccounts;
291 $amount = $form->{"sellprice_$i"} * $form->{"qty_$i"} * $form->{exchangerate};
292 $linetotal = $form->round_amount($form->{"sellprice_$i"} * $form->{"qty_$i"}, 2) * $form->{exchangerate};
293 $linetotal = $form->round_amount($linetotal, 2);
295 # this is the difference for expense
296 $expensediff += ($amount - $linetotal);
298 # add amount to expense
299 $form->{amount}{ $form->{id} }{ $form->{"expense_accno_$i"} } -= $linetotal;
301 $lastexpenseaccno = $form->{"expense_accno_$i"};
303 # adjust and round sellprice
304 $form->{"sellprice_$i"} = $form->round_amount($form->{"sellprice_$i"} * $form->{exchangerate}, $decimalplaces);
306 next if $payments_only;
309 $query = qq|UPDATE parts SET lastcost = ? WHERE id = ?|;
310 do_query($form, $dbh, $query, $form->{"sellprice_$i"}, conv_i($form->{"id_$i"}));
313 next if $payments_only;
315 # save detail record in invoice table
317 qq|INSERT INTO invoice (trans_id, parts_id, description, qty, base_qty,
318 sellprice, fxsellprice, allocated, unit, deliverydate,
319 project_id, serialnumber)
320 VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)|;
321 @values = (conv_i($form->{id}), conv_i($form->{"id_$i"}),
322 $form->{"description_$i"}, $form->{"qty_$i"} * -1,
323 $baseqty * -1, $form->{"sellprice_$i"}, $fxsellprice, $allocated,
324 $form->{"unit_$i"}, conv_date($form->{deliverydate}),
325 conv_i($form->{"project_id_$i"}), $form->{"serialnumber_$i"});
326 do_query($form, $dbh, $query, @values);
329 $h_item_unit->finish();
331 my $project_id = conv_i($form->{"globalproject_id"});
333 $form->{datepaid} = $form->{invdate};
335 # all amounts are in natural state, netamount includes the taxes
336 # if tax is included, netamount is rounded to 2 decimal places,
340 for my $i (1 .. $form->{paidaccounts}) {
341 $form->{"paid_$i"} = $form->parse_amount($myconfig, $form->{"paid_$i"});
342 $form->{paid} += $form->{"paid_$i"};
343 $form->{datepaid} = $form->{"datepaid_$i"} if ($form->{"datepaid_$i"});
346 my ($tax, $paiddiff) = (0, 0);
348 $netamount = $form->round_amount($netamount, 2);
350 # figure out rounding errors for amount paid and total amount
351 if ($form->{taxincluded}) {
353 $amount = $form->round_amount($netamount * $form->{exchangerate}, 2);
354 $paiddiff = $amount - $netamount * $form->{exchangerate};
355 $netamount = $amount;
357 foreach $item (split / /, $form->{taxaccounts}) {
358 $amount = $form->{amount}{ $form->{id} }{$item} * $form->{exchangerate};
359 $form->{amount}{ $form->{id} }{$item} = $form->round_amount($amount, 2);
361 $amount = $form->{amount}{ $form->{id} }{$item} * -1;
363 $netamount -= $amount;
366 $invoicediff += $paiddiff;
367 $expensediff += $paiddiff;
369 ######## this only applies to tax included
370 if ($lastinventoryaccno) {
371 $form->{amount}{ $form->{id} }{$lastinventoryaccno} -= $invoicediff;
373 if ($lastexpenseaccno) {
374 $form->{amount}{ $form->{id} }{$lastexpenseaccno} -= $expensediff;
378 $amount = $form->round_amount($netamount * $form->{exchangerate}, 2);
379 $paiddiff = $amount - $netamount * $form->{exchangerate};
380 $netamount = $amount;
382 foreach my $item (split / /, $form->{taxaccounts}) {
383 $form->{amount}{ $form->{id} }{$item} = $form->round_amount($form->{amount}{ $form->{id} }{$item}, 2);
384 $amount = $form->round_amount( $form->{amount}{ $form->{id} }{$item} * $form->{exchangerate} * -1, 2);
385 $paiddiff += $amount - $form->{amount}{ $form->{id} }{$item} * $form->{exchangerate} * -1;
386 $form->{amount}{ $form->{id} }{$item} = $form->round_amount($amount * -1, 2);
387 $amount = $form->{amount}{ $form->{id} }{$item} * -1;
392 $form->{amount}{ $form->{id} }{ $form->{AP} } = $netamount + $tax;
394 if ($form->{paid} != 0) {
395 $form->{paid} = $form->round_amount($form->{paid} * $form->{exchangerate} + $paiddiff, 2);
398 # update exchangerate
399 if (($form->{currency} ne $defaultcurrency) && !$exchangerate) {
400 $form->update_exchangerate($dbh, $form->{currency}, $form->{invdate}, 0, $form->{exchangerate});
403 # record acc_trans transactions
404 foreach my $trans_id (keys %{ $form->{amount} }) {
405 foreach my $accno (keys %{ $form->{amount}{$trans_id} }) {
406 $form->{amount}{$trans_id}{$accno} = $form->round_amount($form->{amount}{$trans_id}{$accno}, 2);
408 next if ($payments_only || !$form->{amount}{$trans_id}{$accno});
410 $query = qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate, taxkey, project_id)
411 VALUES (?, (SELECT id FROM chart WHERE accno = ?), ?, ?,
412 (SELECT taxkey_id FROM chart WHERE accno = ?), ?)|;
413 @values = ($trans_id, $accno, $form->{amount}{$trans_id}{$accno},
414 conv_date($form->{invdate}), $accno, $project_id);
415 do_query($form, $dbh, $query, @values);
419 # deduct payment differences from paiddiff
420 for my $i (1 .. $form->{paidaccounts}) {
421 if ($form->{"paid_$i"} != 0) {
422 $amount = $form->round_amount($form->{"paid_$i"} * $form->{exchangerate}, 2);
423 $paiddiff -= $amount - $form->{"paid_$i"} * $form->{exchangerate};
427 # force AP entry if 0
428 if ($form->{amount}{ $form->{id} }{ $form->{AP} } == 0) {
429 $form->{amount}{ $form->{id} }{ $form->{AP} } = $form->{paid};
432 # record payments and offsetting AP
433 for my $i (1 .. $form->{paidaccounts}) {
434 next if ($form->{"paid_$i"} == 0);
436 my ($accno) = split /--/, $form->{"AP_paid_$i"};
437 $form->{"datepaid_$i"} = $form->{invdate} unless ($form->{"datepaid_$i"});
438 $form->{datepaid} = $form->{"datepaid_$i"};
440 $amount = $form->round_amount($form->{"paid_$i"} * $form->{exchangerate} + $paiddiff, 2) * -1;
443 if ($form->{amount}{ $form->{id} }{ $form->{AP} } != 0) {
444 $query = qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate, taxkey, project_id)
445 VALUES (?, (SELECT id FROM chart WHERE accno = ?), ?, ?,
446 (SELECT taxkey_id FROM chart WHERE accno = ?), ?)|;
447 @values = (conv_i($form->{id}), $form->{AP}, $amount,
448 $form->{"datepaid_$i"}, $form->{AP}, $project_id);
449 do_query($form, $dbh, $query, @values);
453 $query = qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate, source, memo, taxkey, project_id)
454 VALUES (?, (SELECT id FROM chart WHERE accno = ?), ?, ?, ?, ?,
455 (SELECT taxkey_id FROM chart WHERE accno = ?), ?)|;
456 @values = (conv_i($form->{id}), $accno, $form->{"paid_$i"}, $form->{"datepaid_$i"},
457 $form->{"source_$i"}, $form->{"memo_$i"}, $accno, $project_id);
458 do_query($form, $dbh, $query, @values);
462 if ($form->{currency} eq $defaultcurrency) {
463 $form->{"exchangerate_$i"} = 1;
465 $exchangerate = $form->check_exchangerate($myconfig, $form->{currency}, $form->{"datepaid_$i"}, 'sell');
467 $form->{"exchangerate_$i"} =
470 : $form->parse_amount($myconfig, $form->{"exchangerate_$i"});
473 # exchangerate difference
474 $form->{fx}{$accno}{ $form->{"datepaid_$i"} } +=
475 $form->{"paid_$i"} * ($form->{"exchangerate_$i"} - 1) + $paiddiff;
479 ($form->{"paid_$i"} * $form->{exchangerate}) -
480 ($form->{"paid_$i"} * $form->{"exchangerate_$i"});
482 $form->{fx}{ $form->{fxgain_accno} }{ $form->{"datepaid_$i"} } += $amount;
485 $form->{fx}{ $form->{fxloss_accno} }{ $form->{"datepaid_$i"} } += $amount;
490 # update exchange rate
491 if (($form->{currency} ne $defaultcurrency) && !$exchangerate) {
492 $form->update_exchangerate($dbh, $form->{currency},
493 $form->{"datepaid_$i"},
494 0, $form->{"exchangerate_$i"});
498 # record exchange rate differences and gains/losses
499 foreach my $accno (keys %{ $form->{fx} }) {
500 foreach my $transdate (keys %{ $form->{fx}{$accno} }) {
501 $form->{fx}{$accno}{$transdate} = $form->round_amount($form->{fx}{$accno}{$transdate}, 2);
502 next if ($form->{fx}{$accno}{$transdate} == 0);
504 $query = qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate, cleared, fx_transaction, taxkey, project_id)
505 VALUES (?, (SELECT id FROM chart WHERE accno = ?), ?, ?, '0', '1', 0, ?)|;
506 @values = (conv_i($form->{id}), $accno, $form->{fx}{$accno}{$transdate}, conv_date($transdate), $project_id);
507 do_query($form, $dbh, $query, @values);
511 if ($payments_only) {
512 $query = qq|UPDATE ap SET paid = ?, datepaid = ? WHERE id = ?|;
513 do_query($form, $dbh, $query, $form->{paid}, $form->{paid} ? conv_date($form->{datepaid}) : undef, conv_i($form->{id}));
515 if (!$provided_dbh) {
520 $main::lxdebug->leave_sub();
524 $amount = $netamount + $tax;
526 # set values which could be empty
527 my $taxzone_id = $form->{taxzone_id} * 1;
528 $form->{department_id} = (split /--/, $form->{department})[1];
529 $form->{invnumber} = $form->{id} unless $form->{invnumber};
531 $taxzone_id = 0 if ((3 < $taxzone_id) || (0 > $taxzone_id));
534 $query = qq|UPDATE ap SET
555 globalproject_id = ?,
559 @values = ($form->{invnumber}, $form->{ordnumber}, $form->{quonumber},
560 conv_date($form->{invdate}), conv_date($form->{orddate}), conv_date($form->{quodate}),
561 conv_i($form->{vendor_id}), $amount, $netamount, $form->{paid},
562 $form->{paid} ? conv_date($form->{datepaid}) : undef,
563 conv_date($form->{duedate}), $taxzone_id,
564 $form->{taxincluded} ? 't' : 'f',
565 $form->{notes}, $form->{intnotes}, $form->{currency}, conv_i($form->{department_id}),
566 $form->{storno} ? 't' : 'f',
567 conv_i($form->{globalproject_id}), conv_i($form->{cp_id}),
568 conv_i($form->{employee_id}),
569 conv_i($form->{id}));
570 do_query($form, $dbh, $query, @values);
572 if ($form->{storno}) {
573 $query = qq|UPDATE ap SET paid = paid + amount WHERE id = ?|;
574 do_query($form, $dbh, $query, conv_i($form->{storno_id}));
576 $query = qq|UPDATE ap SET storno = 't' WHERE id = ?|;
577 do_query($form, $dbh, $query, conv_i($form->{storno_id}));
579 $query = qq!UPDATE ap SET intnotes = ? || intnotes WHERE id = ?!;
580 do_query($form, $dbh, $query, 'Rechnung storniert am $form->{invdate} ', conv_i($form->{storno_id}));
582 $query = qq|UPDATE ap SET paid = amount WHERE id = ?|;
583 do_query($form, $dbh, $query, conv_i($form->{id}));
588 $form->{name} = $form->{vendor};
589 $form->{name} =~ s/--$form->{vendor_id}//;
590 $form->add_shipto($dbh, $form->{id}, "AP");
592 # delete zero entries
593 do_query($form, $dbh, qq|DELETE FROM acc_trans WHERE amount = 0|);
595 Common::webdav_folder($form) if ($main::webdav);
599 if (!$provided_dbh) {
600 $rc = $dbh->commit();
604 $main::lxdebug->leave_sub();
609 sub reverse_invoice {
610 $main::lxdebug->enter_sub();
612 my ($dbh, $form) = @_;
614 # reverse inventory items
616 qq|SELECT i.parts_id, p.inventory_accno_id, p.expense_accno_id, i.qty, i.allocated, i.sellprice
617 FROM invoice i, parts p
618 WHERE (i.parts_id = p.id)
619 AND (i.trans_id = ?)|;
620 my $sth = prepare_execute_query($form, $dbh, $query, conv_i($form->{id}));
624 while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
625 $netamount += $form->round_amount($ref->{sellprice} * $ref->{qty} * -1, 2);
627 next unless $ref->{inventory_accno_id};
630 $form->update_balance($dbh, "parts", "onhand", qq|id = $ref->{parts_id}|, $ref->{qty});
632 # if $ref->{allocated} > 0 than we sold that many items
633 next if ($ref->{allocated} <= 0);
635 # get references for sold items
637 qq|SELECT i.id, i.trans_id, i.allocated, a.transdate
639 WHERE (i.parts_id = ?)
640 AND (i.allocated < 0)
641 AND (i.trans_id = a.id)
642 ORDER BY transdate DESC|;
643 my $sth2 = prepare_execute_query($form, $dbh, $query, $ref->{parts_id});
645 while (my $pthref = $sth2->fetchrow_hashref(NAME_lc)) {
646 my $qty = $ref->{allocated};
647 if (($ref->{allocated} + $pthref->{allocated}) > 0) {
648 $qty = $pthref->{allocated} * -1;
651 my $amount = $form->round_amount($ref->{sellprice} * $qty, 2);
654 $form->update_balance($dbh, "invoice", "allocated", qq|id = $pthref->{id}|, $qty);
656 $form->update_balance($dbh, "acc_trans", "amount",
657 qq| (trans_id = $pthref->{trans_id})
658 AND (chart_id = $ref->{expense_accno_id})
659 AND (transdate = '$pthref->{transdate}')|,
662 $form->update_balance($dbh, "acc_trans", "amount",
663 qq| (trans_id = $pthref->{trans_id})
664 AND (chart_id = $ref->{inventory_accno_id})
665 AND (transdate = '$pthref->{transdate}')|,
668 last if (($ref->{allocated} -= $qty) <= 0);
674 my $id = conv_i($form->{id});
677 $query = qq|DELETE FROM acc_trans WHERE trans_id = ?|;
678 do_query($form, $dbh, $query, $id);
680 # delete invoice entries
681 $query = qq|DELETE FROM invoice WHERE trans_id = ?|;
682 do_query($form, $dbh, $query, $id);
684 $query = qq|DELETE FROM shipto WHERE (trans_id = ?) AND (module = 'AP')|;
685 do_query($form, $dbh, $query, $id);
687 $main::lxdebug->leave_sub();
691 $main::lxdebug->enter_sub();
693 my ($self, $myconfig, $form) = @_;
695 # connect to database
696 my $dbh = $form->dbconnect_noauto($myconfig);
698 &reverse_invoice($dbh, $form);
700 # delete zero entries
701 my $query = qq|DELETE FROM acc_trans WHERE amount = 0|;
702 do_query($form, $dbh, $query);
705 my $query = qq|DELETE FROM ap WHERE id = ?|;
706 do_query($form, $dbh, $query, conv_i($form->{id}));
708 my $rc = $dbh->commit;
711 $main::lxdebug->leave_sub();
716 sub retrieve_invoice {
717 $main::lxdebug->enter_sub();
719 my ($self, $myconfig, $form) = @_;
721 # connect to database
722 my $dbh = $form->dbconnect($myconfig);
724 my ($query, $sth, $ref, $q_invdate);
726 $q_invdate = ", current_date AS invdate" unless $form->{id};
728 # get default accounts and last invoice number
732 (SELECT c.accno FROM chart c WHERE d.inventory_accno_id = c.id) AS inventory_accno,
733 (SELECT c.accno FROM chart c WHERE d.income_accno_id = c.id) AS income_accno,
734 (SELECT c.accno FROM chart c WHERE d.expense_accno_id = c.id) AS expense_accno,
735 (SELECT c.accno FROM chart c WHERE d.fxgain_accno_id = c.id) AS fxgain_accno,
736 (SELECT c.accno FROM chart c WHERE d.fxloss_accno_id = c.id) AS fxloss_accno,
740 $ref = selectfirst_hashref_query($form, $dbh, $query);
741 map { $form->{$_} = $ref->{$_} } keys %$ref;
745 $main::lxdebug->leave_sub();
752 qq|SELECT cp_id, invnumber, transdate AS invdate, duedate,
753 orddate, quodate, globalproject_id,
754 ordnumber, quonumber, paid, taxincluded, notes, taxzone_id, storno, gldate,
755 intnotes, curr AS currency
758 $ref = selectfirst_hashref_query($form, $dbh, $query, conv_i($form->{id}));
759 map { $form->{$_} = $ref->{$_} } keys %$ref;
761 $form->{exchangerate} = $form->get_exchangerate($dbh, $form->{currency}, $form->{invdate}, "sell");
764 $query = qq|SELECT * FROM shipto WHERE (trans_id = ?) AND (module = 'AP')|;
765 $ref = selectfirst_hashref_query($form, $dbh, $query, conv_i($form->{id}));
767 map { $form->{$_} = $ref->{$_} } keys %$ref;
769 my $transdate = $form->{invdate} ? $dbh->quote($form->{invdate}) : "current_date";
770 my $taxzone_id = $form->{taxzone_id} * 1;
772 $taxzone_id = 0 if ((3 < $taxzone_id) || (0 > $taxzone_id));
774 # retrieve individual items
777 c1.accno AS inventory_accno,
778 c1.new_chart_id AS inventory_new_chart,
779 date($transdate) - c1.valid_from AS inventory_valid,
781 c2.accno AS income_accno,
782 c2.new_chart_id AS income_new_chart,
783 date($transdate) - c2.valid_from AS income_valid,
785 c3.accno AS expense_accno,
786 c3.new_chart_id AS expense_new_chart,
787 date($transdate) - c3.valid_from AS expense_valid,
789 i.description, i.qty, i.fxsellprice AS sellprice,
790 i.parts_id AS id, i.unit, i.deliverydate, i.project_id, i.serialnumber,
792 p.partnumber, p.inventory_accno_id AS part_inventory_accno_id, p.bin,
797 JOIN parts p ON (i.parts_id = p.id)
798 LEFT JOIN chart c1 ON
799 ((SELECT inventory_accno_id
801 WHERE id = p.buchungsgruppen_id) = c1.id)
802 LEFT JOIN chart c2 ON
803 ((SELECT income_accno_id_${taxzone_id}
805 WHERE id = p.buchungsgruppen_id) = c2.id)
806 LEFT JOIN chart c3 ON
807 ((SELECT expense_accno_id_${taxzone_id}
809 WHERE id = p.buchungsgruppen_id) = c3.id)
810 LEFT JOIN project pr ON (i.project_id = pr.id)
811 LEFT JOIN partsgroup pg ON (pg.id = p.partsgroup_id)
816 $sth = prepare_execute_query($form, $dbh, $query, conv_i($form->{id}));
818 while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
819 if (!$ref->{"part_inventory_accno_id"}) {
820 map({ delete($ref->{$_}); } qw(inventory_accno inventory_new_chart inventory_valid));
822 delete($ref->{"part_inventory_accno_id"});
824 foreach my $type (qw(inventory income expense)) {
825 while ($ref->{"${type}_new_chart"} && ($ref->{"${type}_valid"} >=0)) {
827 qq|SELECT accno, new_chart_id, date($transdate) - valid_from
830 ($ref->{"${type}_accno"},
831 $ref->{"${type}_new_chart"},
832 $ref->{"${type}_valid"})
833 = selectrow_query($form, $dbh, $query, $ref->{"${type}_new_chart"});
837 # get tax rates and description
838 my $accno_id = ($form->{vc} eq "customer") ? $ref->{income_accno} : $ref->{expense_accno};
840 qq|SELECT c.accno, t.taxdescription, t.rate, t.taxnumber
842 LEFT JOIN chart c ON (c.id = t.chart_id)
850 AND (startdate <= $transdate)
851 ORDER BY startdate DESC
854 my $stw = prepare_execute_query($form, $dbh, $query, $accno_id);
855 $ref->{taxaccounts} = "";
858 while ($ptr = $stw->fetchrow_hashref(NAME_lc)) {
859 if (($ptr->{accno} eq "") && ($ptr->{rate} == 0)) {
864 $ref->{taxaccounts} .= "$ptr->{accno} ";
866 if (!($form->{taxaccounts} =~ /$ptr->{accno}/)) {
867 $form->{"$ptr->{accno}_rate"} = $ptr->{rate};
868 $form->{"$ptr->{accno}_description"} = $ptr->{taxdescription};
869 $form->{"$ptr->{accno}_taxnumber"} = $ptr->{taxnumber};
870 $form->{taxaccounts} .= "$ptr->{accno} ";
875 chop $ref->{taxaccounts};
876 push @{ $form->{invoice_details} }, $ref;
881 Common::webdav_folder($form) if ($main::webdav);
885 $main::lxdebug->leave_sub();
889 $main::lxdebug->enter_sub();
891 my ($self, $myconfig, $form) = @_;
893 # connect to database
894 my $dbh = $form->dbconnect($myconfig);
896 my $dateformat = $myconfig->{dateformat};
897 $dateformat .= "yy" if $myconfig->{dateformat} !~ /^y/;
899 my $vid = conv_i($form->{vendor_id});
903 ? "to_date(" . $dbh->quote($form->{invdate}) . ", '$dateformat')"
909 v.name AS vendor, v.creditlimit, v.terms, v.notes AS intnotes,
910 v.email, v.cc, v.bcc, v.language_id, v.payment_id,
911 v.street, v.zipcode, v.city, v.country, v.taxzone_id,
912 $duedate + COALESCE(pt.terms_netto, 0) AS duedate,
913 b.description AS business
915 LEFT JOIN business b ON (b.id = v.business_id)
916 LEFT JOIN payment_terms pt ON (v.payment_id = pt.id)
918 $ref = selectfirst_hashref_query($form, $dbh, $query, $vid);
919 map { $form->{$_} = $ref->{$_} } keys %$ref;
921 $form->{creditremaining} = $form->{creditlimit};
923 $query = qq|SELECT SUM(amount - paid) FROM ap WHERE vendor_id = ?|;
924 my ($unpaid_invoices) = selectfirst_array_query($form, $dbh, $query, $vid);
925 $form->{creditremaining} -= $unpaid_invoices;
927 $query = qq|SELECT o.amount,
930 WHERE (e.curr = o.curr)
931 AND (e.transdate = o.transdate)) AS exch
933 WHERE (o.vendor_id = ?) AND (o.quotation = '0') AND (o.closed = '0')|;
934 my $sth = prepare_execute_query($form, $dbh, $query, $vid);
935 while (my ($amount, $exch) = $sth->fetchrow_array()) {
936 $exch = 1 unless $exch;
937 $form->{creditremaining} -= $amount * $exch;
941 # get shipto if we do not convert an order or invoice
942 if (!$form->{shipto}) {
943 delete @{$form}{qw(shiptoname shiptostreet shiptozipcode shiptocity shiptocountry shiptocontact shiptophone shiptofax shiptoemail)};
945 $query = qq|SELECT * FROM shipto WHERE (trans_id = ?) AND (module= 'CT')|;
946 $ref = selectfirst_hashref_query($form, $dbh, $query, $vid);
947 @{$form}{keys %$ref} = @{$ref}{keys %$ref};
948 map { $form->{$_} = $ref->{$_} } keys %$ref;
951 if (!$form->{id} && $form->{type} !~ /_(order|quotation)/) {
952 # setup last accounts used
954 qq|SELECT c.id, c.accno, c.description, c.link, c.category
956 JOIN acc_trans ac ON (ac.chart_id = c.id)
957 JOIN ap a ON (a.id = ac.trans_id)
958 WHERE (a.vendor_id = ?)
959 AND (NOT ((c.link LIKE '%_tax%') OR (c.link LIKE '%_paid%')))
960 AND (a.id IN (SELECT max(a2.id) FROM ap a2 WHERE a2.vendor_id = ?))|;
961 my $refs = selectall_hashref_query($form, $dbh, $query, $vid, $vid);
965 if ($ref->{category} eq 'E') {
968 if ($form->{initial_transdate}) {
969 my $tax_query = qq|SELECT tk.tax_id, t.rate FROM taxkeys tk
970 LEFT JOIN tax t ON (tk.tax_id = t.id)
971 WHERE (tk.chart_id = ?) AND (startdate <= ?)
972 ORDER BY tk.startdate DESC
974 my ($tax_id, $rate) = selectrow_query($form, $dbh, $tax_query, $ref->{id}, $form->{initial_transdate});
975 $form->{"taxchart_$i"} = "${tax_id}--${rate}";
978 $form->{"AP_amount_$i"} = "$ref->{accno}--$tax_id";
981 if ($ref->{category} eq 'L') {
982 $form->{APselected} = $form->{AP_1} = $ref->{accno};
985 $form->{rowcount} = $i if ($i && !$form->{type});
990 $main::lxdebug->leave_sub();
994 $main::lxdebug->enter_sub();
996 my ($self, $myconfig, $form) = @_;
998 # connect to database
999 my $dbh = $form->dbconnect($myconfig);
1001 my $i = $form->{rowcount};
1003 # don't include assemblies or obsolete parts
1004 my $where = "NOT p.assembly = '1' AND NOT p.obsolete = '1'";
1007 foreach my $table_column (qw(p.partnumber p.description pg.partsgroup)) {
1008 my $field = (split m{\.}, $table_column)[1];
1009 next unless $form->{"${field}_${i}"};
1010 $where .= " AND lower(${table_column}) LIKE lower(?)";
1011 push @values, '%' . $form->{"${field}_${i}"} . '%';
1014 if ($form->{"description_$i"}) {
1015 $where .= " ORDER BY p.description";
1017 $where .= " ORDER BY p.partnumber";
1021 if ($form->{type} eq "invoice") {
1022 $transdate = $form->{invdate} ? $dbh->quote($form->{invdate}) : "current_date";
1024 $transdate = $form->{transdate} ? $dbh->quote($form->{transdate}) : "current_date";
1027 my $taxzone_id = $form->{taxzone_id} * 1;
1028 $taxzone_id = 0 if ((3 < $taxzone_id) || (0 > $taxzone_id));
1032 p.id, p.partnumber, p.description, p.lastcost AS sellprice, p.listprice,
1033 p.unit, p.assembly, p.bin, p.onhand, p.formel,
1034 p.notes AS partnotes, p.notes AS longdescription, p.not_discountable,
1035 p.inventory_accno_id,
1037 c1.accno AS inventory_accno,
1038 c1.new_chart_id AS inventory_new_chart,
1039 date($transdate) - c1.valid_from AS inventory_valid,
1041 c2.accno AS income_accno,
1042 c2.new_chart_id AS income_new_chart,
1043 date($transdate) - c2.valid_from AS income_valid,
1045 c3.accno AS expense_accno,
1046 c3.new_chart_id AS expense_new_chart,
1047 date($transdate) - c3.valid_from AS expense_valid,
1052 LEFT JOIN chart c1 ON
1053 ((SELECT inventory_accno_id
1054 FROM buchungsgruppen
1055 WHERE id = p.buchungsgruppen_id) = c1.id)
1056 LEFT JOIN chart c2 ON
1057 ((SELECT income_accno_id_${taxzone_id}
1058 FROM buchungsgruppen
1059 WHERE id = p.buchungsgruppen_id) = c2.id)
1060 LEFT JOIN chart c3 ON
1061 ((SELECT expense_accno_id_${taxzone_id}
1062 FROM buchungsgruppen
1063 WHERE id = p.buchungsgruppen_id) = c3.id)
1064 LEFT JOIN partsgroup pg ON (pg.id = p.partsgroup_id)
1066 my $sth = prepare_execute_query($form, $dbh, $query, @values);
1068 $form->{item_list} = [];
1069 while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
1071 # In der Buchungsgruppe ist immer ein Bestandskonto verknuepft, auch wenn
1072 # es sich um eine Dienstleistung handelt. Bei Dienstleistungen muss das
1073 # Buchungskonto also aus dem Ergebnis rausgenommen werden.
1074 if (!$ref->{inventory_accno_id}) {
1075 map({ delete($ref->{"inventory_${_}"}); } qw(accno new_chart valid));
1077 delete($ref->{inventory_accno_id});
1079 # get tax rates and description
1080 $accno_id = ($form->{vc} eq "customer") ? $ref->{income_accno} : $ref->{expense_accno};
1082 qq|SELECT c.accno, t.taxdescription, t.rate, t.taxnumber
1084 LEFT JOIN chart c on (c.id = t.chart_id)
1092 AND (startdate <= $transdate)
1093 ORDER BY startdate DESC
1096 my $stw = prepare_execute_query($form, $dbh, $query, $accno_id);
1098 $ref->{taxaccounts} = "";
1100 while ($ptr = $stw->fetchrow_hashref(NAME_lc)) {
1102 # if ($customertax{$ref->{accno}}) {
1103 if (($ptr->{accno} eq "") && ($ptr->{rate} == 0)) {
1108 $ref->{taxaccounts} .= "$ptr->{accno} ";
1110 if (!($form->{taxaccounts} =~ /$ptr->{accno}/)) {
1111 $form->{"$ptr->{accno}_rate"} = $ptr->{rate};
1112 $form->{"$ptr->{accno}_description"} = $ptr->{taxdescription};
1113 $form->{"$ptr->{accno}_taxnumber"} = $ptr->{taxnumber};
1114 $form->{taxaccounts} .= "$ptr->{accno} ";
1120 chop $ref->{taxaccounts};
1122 push @{ $form->{item_list} }, $ref;
1129 $main::lxdebug->leave_sub();
1132 sub vendor_details {
1133 $main::lxdebug->enter_sub();
1135 my ($self, $myconfig, $form, @wanted_vars) = @_;
1137 # connect to database
1138 my $dbh = $form->dbconnect($myconfig);
1142 # get contact id, set it if nessessary
1143 $form->{cp_id} = (split /--/, $form->{contact})[1];
1145 if ($form->{cp_id}) {
1146 $contact = "AND cp.cp_id = ?";
1147 push @values, $form->{cp_id};
1150 # get rest for the vendor
1151 # fax and phone and email as vendor*
1153 qq|SELECT ct.*, cp.*, ct.notes as vendornotes, phone as vendorphone, fax as vendorfax, email as vendoremail
1155 LEFT JOIN contacts cp ON (ct.id = cp.cp_cv_id)
1156 WHERE (ct.id = ?) $contact
1159 my $ref = selectfirst_hashref_query($form, $dbh, $query, $form->{vendor_id}, @values);
1161 # remove id and taxincluded before copy back
1162 delete @$ref{qw(id taxincluded)};
1164 @wanted_vars = grep({ $_ } @wanted_vars);
1165 if (scalar(@wanted_vars) > 0) {
1167 map({ $h_wanted_vars{$_} = 1; } @wanted_vars);
1168 map({ delete($ref->{$_}) unless ($h_wanted_vars{$_}); } keys(%{$ref}));
1171 map { $form->{$_} = $ref->{$_} } keys %$ref;
1175 $main::lxdebug->leave_sub();
1179 $main::lxdebug->enter_sub();
1181 my ($self, $myconfig, $form) = @_;
1183 # connect to database
1184 my $dbh = $form->dbconnect($myconfig);
1187 qq|SELECT accno, description, link
1189 WHERE link LIKE '%IC%'
1191 my $sth = prepare_execute_query($query, $dbh, $query);
1193 while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
1194 foreach my $key (split(/:/, $ref->{link})) {
1196 push @{ $form->{IC_links}{$key} },
1197 { accno => $ref->{accno},
1198 description => $ref->{description} };
1206 $main::lxdebug->leave_sub();
1209 sub _delete_payments {
1210 $main::lxdebug->enter_sub();
1212 my ($self, $form, $dbh) = @_;
1216 # Delete old payment entries from acc_trans.
1220 WHERE (trans_id = ?) AND fx_transaction
1226 LEFT JOIN chart c ON (at.chart_id = c.id)
1227 WHERE (trans_id = ?) AND (c.link LIKE '%AP_paid%')|;
1228 push @delete_oids, selectall_array_query($form, $dbh, $query, conv_i($form->{id}), conv_i($form->{id}));
1233 LEFT JOIN chart c ON (at.chart_id = c.id)
1234 WHERE (trans_id = ?)
1235 AND ((c.link = 'AP') OR (c.link LIKE '%:AP') OR (c.link LIKE 'AP:%'))
1238 push @delete_oids, selectall_array_query($form, $dbh, $query, conv_i($form->{id}));
1241 $query = qq|DELETE FROM acc_trans WHERE oid IN (| . join(", ", @delete_oids) . qq|)|;
1242 do_query($form, $dbh, $query);
1245 $main::lxdebug->leave_sub();
1249 $main::lxdebug->enter_sub();
1251 my ($self, $myconfig, $form, $locale) = @_;
1253 # connect to database, turn off autocommit
1254 my $dbh = $form->dbconnect_noauto($myconfig);
1256 my (%payments, $old_form, $row, $item, $query, %keep_vars);
1258 $old_form = save_form();
1260 # Delete all entries in acc_trans from prior payments.
1261 $self->_delete_payments($form, $dbh);
1263 # Save the new payments the user made before cleaning up $form.
1264 map { $payments{$_} = $form->{$_} } grep m/^datepaid_\d+$|^memo_\d+$|^source_\d+$|^exchangerate_\d+$|^paid_\d+$|^AP_paid_\d+$|^paidaccounts$/, keys %{ $form };
1266 # Clean up $form so that old content won't tamper the results.
1267 %keep_vars = map { $_, 1 } qw(login password id);
1268 map { delete $form->{$_} unless $keep_vars{$_} } keys %{ $form };
1270 # Retrieve the invoice from the database.
1271 $self->retrieve_invoice($myconfig, $form);
1273 # Set up the content of $form in the way that IR::post_invoice() expects.
1274 $form->{exchangerate} = $form->format_amount($myconfig, $form->{exchangerate});
1276 for $row (1 .. scalar @{ $form->{invoice_details} }) {
1277 $item = $form->{invoice_details}->[$row - 1];
1279 map { $item->{$_} = $form->format_amount($myconfig, $item->{$_}) } qw(qty sellprice);
1281 map { $form->{"${_}_${row}"} = $item->{$_} } keys %{ $item };
1284 $form->{rowcount} = scalar @{ $form->{invoice_details} };
1286 delete @{$form}{qw(invoice_details paidaccounts storno paid)};
1288 # Restore the payment options from the user input.
1289 map { $form->{$_} = $payments{$_} } keys %payments;
1291 # Get the AP accno (which is normally done by Form::create_links()).
1295 LEFT JOIN chart c ON (at.chart_id = c.id)
1296 WHERE (trans_id = ?)
1297 AND ((c.link = 'AP') OR (c.link LIKE '%:AP') OR (c.link LIKE 'AP:%'))
1301 ($form->{AP}) = selectfirst_array_query($form, $dbh, $query, conv_i($form->{id}));
1303 # Post the new payments.
1304 $self->post_invoice($myconfig, $form, $dbh, 1);
1306 restore_form($old_form);
1308 my $rc = $dbh->commit();
1311 $main::lxdebug->leave_sub();