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);
49 $form->{defaultcurrency} = $form->get_default_currency($myconfig);
51 my ($query, $sth, @values, $project_id);
52 my ($allocated, $taxrate, $taxamount, $taxdiff, $item);
53 my ($amount, $linetotal, $lastinventoryaccno, $lastexpenseaccno);
54 my ($netamount, $invoicediff, $expensediff) = (0, 0, 0);
57 my $all_units = AM->retrieve_units($myconfig, $form);
59 if (!$payments_only) {
61 &reverse_invoice($dbh, $form);
64 ($form->{id}) = selectrow_query($form, $dbh, qq|SELECT nextval('glid')|);
66 do_query($form, $dbh, qq|INSERT INTO ap (id, invnumber) VALUES (?, '')|, $form->{id});
70 my ($currencies) = selectfirst_array_query($form, $dbh, qq|SELECT curr FROM defaults|);
71 my $defaultcurrency = (split m/:/, $currencies)[0];
73 if ($form->{currency} eq $defaultcurrency) {
74 $form->{exchangerate} = 1;
77 $form->check_exchangerate($myconfig, $form->{currency},
78 $form->{transdate}, 'sell');
81 $form->{exchangerate} =
84 : $form->parse_amount($myconfig, $form->{exchangerate});
86 $form->{exchangerate} = 1 unless ($form->{exchangerate} * 1);
89 my $q_item_unit = qq|SELECT unit FROM parts WHERE id = ?|;
90 my $h_item_unit = prepare_query($form, $dbh, $q_item_unit);
92 for my $i (1 .. $form->{rowcount}) {
93 next unless $form->{"id_$i"};
95 $form->{"qty_$i"} = $form->parse_amount($myconfig, $form->{"qty_$i"});
97 if ($form->{storno}) {
98 $form->{"qty_$i"} *= -1;
102 $form->{"inventory_accno_$i"} = $form->{"expense_accno_$i"};
106 if (!$item_units{$form->{"id_$i"}}) {
107 do_statement($form, $h_item_unit, $q_item_unit, $form->{"id_$i"});
108 ($item_units{$form->{"id_$i"}}) = $h_item_unit->fetchrow_array();
111 my $item_unit = $item_units{$form->{"id_$i"}};
113 if (defined($all_units->{$item_unit}->{factor})
114 && ($all_units->{$item_unit}->{factor} ne '')
115 && ($all_units->{$item_unit}->{factor} * 1 != 0)) {
116 $basefactor = $all_units->{$form->{"unit_$i"}}->{factor} / $all_units->{$item_unit}->{factor};
120 $baseqty = $form->{"qty_$i"} * $basefactor;
122 @taxaccounts = split / /, $form->{"taxaccounts_$i"};
127 $form->{"sellprice_$i"} = $form->parse_amount($myconfig, $form->{"sellprice_$i"});
128 my $fxsellprice = $form->{"sellprice_$i"};
130 my ($dec) = ($fxsellprice =~ /\.(\d+)/);
132 my $decimalplaces = ($dec > 2) ? $dec : 2;
134 map { $taxrate += $form->{"${_}_rate"} } @taxaccounts;
136 if ($form->{"inventory_accno_$i"}) {
138 $linetotal = $form->round_amount($form->{"sellprice_$i"} * $form->{"qty_$i"}, 2);
140 if ($form->{taxincluded}) {
141 $taxamount = $linetotal * ($taxrate / (1 + $taxrate));
142 $form->{"sellprice_$i"} = $form->{"sellprice_$i"} * (1 / (1 + $taxrate));
144 $taxamount = $linetotal * $taxrate;
147 $netamount += $linetotal;
149 if ($form->round_amount($taxrate, 7) == 0) {
150 if ($form->{taxincluded}) {
151 foreach $item (@taxaccounts) {
153 $form->round_amount($linetotal * $form->{"${item}_rate"} / (1 + abs($form->{"${item}_rate"})), 2);
154 $taxdiff += $taxamount;
155 $form->{amount}{ $form->{id} }{$item} -= $taxamount;
157 $form->{amount}{ $form->{id} }{ $taxaccounts[0] } += $taxdiff;
160 map { $form->{amount}{ $form->{id} }{$_} -= $linetotal * $form->{"${_}_rate"} } @taxaccounts;
164 map { $form->{amount}{ $form->{id} }{$_} -= $taxamount * $form->{"${_}_rate"} / $taxrate } @taxaccounts;
167 # add purchase to inventory, this one is without the tax!
168 $amount = $form->{"sellprice_$i"} * $form->{"qty_$i"} * $form->{exchangerate};
169 $linetotal = $form->round_amount($form->{"sellprice_$i"} * $form->{"qty_$i"}, 2) * $form->{exchangerate};
170 $linetotal = $form->round_amount($linetotal, 2);
172 # this is the difference for the inventory
173 $invoicediff += ($amount - $linetotal);
175 $form->{amount}{ $form->{id} }{ $form->{"inventory_accno_$i"} } -= $linetotal;
177 # adjust and round sellprice
178 $form->{"sellprice_$i"} =
179 $form->round_amount($form->{"sellprice_$i"} * $form->{exchangerate}, $decimalplaces);
181 $lastinventoryaccno = $form->{"inventory_accno_$i"};
183 next if $payments_only;
186 $query = qq|UPDATE parts SET lastcost = ? WHERE id = ?|;
187 @values = ($form->{"sellprice_$i"}, conv_i($form->{"id_$i"}));
188 do_query($form, $dbh, $query, @values);
190 if (!$form->{shipped}) {
191 $form->update_balance($dbh, "parts", "onhand", qq|id = ?|, $baseqty, $form->{"id_$i"})
194 # check if we sold the item already and
195 # make an entry for the expense and inventory
197 qq|SELECT i.id, i.qty, i.allocated, i.trans_id,
198 p.inventory_accno_id, p.expense_accno_id, a.transdate
199 FROM invoice i, ar a, parts p
200 WHERE (i.parts_id = p.id)
202 AND ((i.base_qty + i.allocated) > 0)
203 AND (i.trans_id = a.id)
205 $sth = prepare_execute_query($form, $dbh, $query, conv_i($form->{"id_$i"}));
207 my $totalqty = $base_qty;
209 while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
211 my $qty = $ref->{base_qty} + $ref->{allocated};
213 if (($qty - $totalqty) > 0) {
217 $linetotal = $form->round_amount(($form->{"sellprice_$i"} * $qty) / $basefactor, 2);
219 if ($ref->{allocated} < 0) {
221 # we have an entry for it already, adjust amount
222 $form->update_balance($dbh, "acc_trans", "amount",
223 qq| (trans_id = $ref->{trans_id})
224 AND (chart_id = $ref->{inventory_accno_id})
225 AND (transdate = '$ref->{transdate}')|,
228 $form->update_balance($dbh, "acc_trans", "amount",
229 qq| (trans_id = $ref->{trans_id})
230 AND (chart_id = $ref->{expense_accno_id})
231 AND (transdate = '$ref->{transdate}')|,
234 } elsif ($linetotal != 0) {
235 # add entry for inventory, this one is for the sold item
236 $query = qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate, taxkey)
237 VALUES (?, ?, ?, ?, (SELECT taxkey_id FROM chart WHERE id = ?))|;
238 @values = ($ref->{trans_id}, $ref->{inventory_accno_id}, $linetotal,
239 $ref->{transdate}, $ref->{inventory_accno_id});
240 do_query($form, $dbh, $query, @values);
243 $query = qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate, taxkey)
244 VALUES (?, ?, ?, ?, (SELECT taxkey from tax WHERE chart_id = ?))|;
245 @values = ($ref->{trans_id}, $ref->{expense_accno_id}, ($linetotal * -1),
246 $ref->{transdate}, $ref->{expense_accno_id});
247 do_query($form, $dbh, $query, @values);
250 # update allocated for sold item
251 $form->update_balance($dbh, "invoice", "allocated", qq|id = $ref->{id}|, $qty * -1);
255 last if (($totalqty -= $qty) <= 0);
262 $linetotal = $form->round_amount($form->{"sellprice_$i"} * $form->{"qty_$i"}, 2);
264 if ($form->{taxincluded}) {
265 $taxamount = $linetotal * ($taxrate / (1 + $taxrate));
266 $form->{"sellprice_$i"} = $form->{"sellprice_$i"} * (1 / (1 + $taxrate));
269 $taxamount = $linetotal * $taxrate;
272 $netamount += $linetotal;
274 if ($form->round_amount($taxrate, 7) == 0) {
275 if ($form->{taxincluded}) {
276 foreach $item (@taxaccounts) {
278 $linetotal * $form->{"${item}_rate"}
279 / (1 + abs($form->{"${item}_rate"}));
280 $totaltax += $taxamount;
281 $form->{amount}{ $form->{id} }{$item} -= $taxamount;
285 map { $form->{amount}{ $form->{id} }{$_} -= $linetotal * $form->{"${_}_rate"} } @taxaccounts;
289 map { $form->{amount}{ $form->{id} }{$_} -= $taxamount * $form->{"${_}_rate"} / $taxrate } @taxaccounts;
292 $amount = $form->{"sellprice_$i"} * $form->{"qty_$i"} * $form->{exchangerate};
293 $linetotal = $form->round_amount($form->{"sellprice_$i"} * $form->{"qty_$i"}, 2) * $form->{exchangerate};
294 $linetotal = $form->round_amount($linetotal, 2);
296 # this is the difference for expense
297 $expensediff += ($amount - $linetotal);
299 # add amount to expense
300 $form->{amount}{ $form->{id} }{ $form->{"expense_accno_$i"} } -= $linetotal;
302 $lastexpenseaccno = $form->{"expense_accno_$i"};
304 # adjust and round sellprice
305 $form->{"sellprice_$i"} = $form->round_amount($form->{"sellprice_$i"} * $form->{exchangerate}, $decimalplaces);
307 next if $payments_only;
310 $query = qq|UPDATE parts SET lastcost = ? WHERE id = ?|;
311 do_query($form, $dbh, $query, $form->{"sellprice_$i"}, conv_i($form->{"id_$i"}));
314 next if $payments_only;
316 # save detail record in invoice table
318 qq|INSERT INTO invoice (trans_id, parts_id, description, qty, base_qty,
319 sellprice, fxsellprice, allocated, unit, deliverydate,
320 project_id, serialnumber)
321 VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)|;
322 @values = (conv_i($form->{id}), conv_i($form->{"id_$i"}),
323 $form->{"description_$i"}, $form->{"qty_$i"} * -1,
324 $baseqty * -1, $form->{"sellprice_$i"}, $fxsellprice, $allocated,
325 $form->{"unit_$i"}, conv_date($form->{deliverydate}),
326 conv_i($form->{"project_id_$i"}), $form->{"serialnumber_$i"});
327 do_query($form, $dbh, $query, @values);
330 $h_item_unit->finish();
332 my $project_id = conv_i($form->{"globalproject_id"});
334 $form->{datepaid} = $form->{invdate};
336 # all amounts are in natural state, netamount includes the taxes
337 # if tax is included, netamount is rounded to 2 decimal places,
341 for my $i (1 .. $form->{paidaccounts}) {
342 $form->{"paid_$i"} = $form->parse_amount($myconfig, $form->{"paid_$i"});
343 $form->{paid} += $form->{"paid_$i"};
344 $form->{datepaid} = $form->{"datepaid_$i"} if ($form->{"datepaid_$i"});
347 my ($tax, $paiddiff) = (0, 0);
349 $netamount = $form->round_amount($netamount, 2);
351 # figure out rounding errors for amount paid and total amount
352 if ($form->{taxincluded}) {
354 $amount = $form->round_amount($netamount * $form->{exchangerate}, 2);
355 $paiddiff = $amount - $netamount * $form->{exchangerate};
356 $netamount = $amount;
358 foreach $item (split / /, $form->{taxaccounts}) {
359 $amount = $form->{amount}{ $form->{id} }{$item} * $form->{exchangerate};
360 $form->{amount}{ $form->{id} }{$item} = $form->round_amount($amount, 2);
362 $amount = $form->{amount}{ $form->{id} }{$item} * -1;
364 $netamount -= $amount;
367 $invoicediff += $paiddiff;
368 $expensediff += $paiddiff;
370 ######## this only applies to tax included
371 if ($lastinventoryaccno) {
372 $form->{amount}{ $form->{id} }{$lastinventoryaccno} -= $invoicediff;
374 if ($lastexpenseaccno) {
375 $form->{amount}{ $form->{id} }{$lastexpenseaccno} -= $expensediff;
379 $amount = $form->round_amount($netamount * $form->{exchangerate}, 2);
380 $paiddiff = $amount - $netamount * $form->{exchangerate};
381 $netamount = $amount;
383 foreach my $item (split / /, $form->{taxaccounts}) {
384 $form->{amount}{ $form->{id} }{$item} = $form->round_amount($form->{amount}{ $form->{id} }{$item}, 2);
385 $amount = $form->round_amount( $form->{amount}{ $form->{id} }{$item} * $form->{exchangerate} * -1, 2);
386 $paiddiff += $amount - $form->{amount}{ $form->{id} }{$item} * $form->{exchangerate} * -1;
387 $form->{amount}{ $form->{id} }{$item} = $form->round_amount($amount * -1, 2);
388 $amount = $form->{amount}{ $form->{id} }{$item} * -1;
393 $form->{amount}{ $form->{id} }{ $form->{AP} } = $netamount + $tax;
395 if ($form->{paid} != 0) {
396 $form->{paid} = $form->round_amount($form->{paid} * $form->{exchangerate} + $paiddiff, 2);
399 # update exchangerate
400 if (($form->{currency} ne $defaultcurrency) && !$exchangerate) {
401 $form->update_exchangerate($dbh, $form->{currency}, $form->{invdate}, 0, $form->{exchangerate});
404 # record acc_trans transactions
405 foreach my $trans_id (keys %{ $form->{amount} }) {
406 foreach my $accno (keys %{ $form->{amount}{$trans_id} }) {
407 $form->{amount}{$trans_id}{$accno} = $form->round_amount($form->{amount}{$trans_id}{$accno}, 2);
409 next if ($payments_only || !$form->{amount}{$trans_id}{$accno});
411 $query = qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate, taxkey, project_id)
412 VALUES (?, (SELECT id FROM chart WHERE accno = ?), ?, ?,
413 (SELECT taxkey_id FROM chart WHERE accno = ?), ?)|;
414 @values = ($trans_id, $accno, $form->{amount}{$trans_id}{$accno},
415 conv_date($form->{invdate}), $accno, $project_id);
416 do_query($form, $dbh, $query, @values);
420 # deduct payment differences from paiddiff
421 for my $i (1 .. $form->{paidaccounts}) {
422 if ($form->{"paid_$i"} != 0) {
423 $amount = $form->round_amount($form->{"paid_$i"} * $form->{exchangerate}, 2);
424 $paiddiff -= $amount - $form->{"paid_$i"} * $form->{exchangerate};
428 # force AP entry if 0
429 if ($form->{amount}{ $form->{id} }{ $form->{AP} } == 0) {
430 $form->{amount}{ $form->{id} }{ $form->{AP} } = $form->{paid};
433 # record payments and offsetting AP
434 for my $i (1 .. $form->{paidaccounts}) {
435 next if ($form->{"paid_$i"} == 0);
437 my ($accno) = split /--/, $form->{"AP_paid_$i"};
438 $form->{"datepaid_$i"} = $form->{invdate} unless ($form->{"datepaid_$i"});
439 $form->{datepaid} = $form->{"datepaid_$i"};
441 $amount = $form->round_amount($form->{"paid_$i"} * $form->{exchangerate} + $paiddiff, 2) * -1;
444 if ($form->{amount}{ $form->{id} }{ $form->{AP} } != 0) {
445 $query = qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate, taxkey, project_id)
446 VALUES (?, (SELECT id FROM chart WHERE accno = ?), ?, ?,
447 (SELECT taxkey_id FROM chart WHERE accno = ?), ?)|;
448 @values = (conv_i($form->{id}), $form->{AP}, $amount,
449 $form->{"datepaid_$i"}, $form->{AP}, $project_id);
450 do_query($form, $dbh, $query, @values);
454 $query = qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate, source, memo, taxkey, project_id)
455 VALUES (?, (SELECT id FROM chart WHERE accno = ?), ?, ?, ?, ?,
456 (SELECT taxkey_id FROM chart WHERE accno = ?), ?)|;
457 @values = (conv_i($form->{id}), $accno, $form->{"paid_$i"}, $form->{"datepaid_$i"},
458 $form->{"source_$i"}, $form->{"memo_$i"}, $accno, $project_id);
459 do_query($form, $dbh, $query, @values);
463 if ($form->{currency} eq $defaultcurrency) {
464 $form->{"exchangerate_$i"} = 1;
466 $exchangerate = $form->check_exchangerate($myconfig, $form->{currency}, $form->{"datepaid_$i"}, 'sell');
468 $form->{"exchangerate_$i"} =
471 : $form->parse_amount($myconfig, $form->{"exchangerate_$i"});
474 # exchangerate difference
475 $form->{fx}{$accno}{ $form->{"datepaid_$i"} } +=
476 $form->{"paid_$i"} * ($form->{"exchangerate_$i"} - 1) + $paiddiff;
480 ($form->{"paid_$i"} * $form->{exchangerate}) -
481 ($form->{"paid_$i"} * $form->{"exchangerate_$i"});
483 $form->{fx}{ $form->{fxgain_accno} }{ $form->{"datepaid_$i"} } += $amount;
486 $form->{fx}{ $form->{fxloss_accno} }{ $form->{"datepaid_$i"} } += $amount;
491 # update exchange rate
492 if (($form->{currency} ne $defaultcurrency) && !$exchangerate) {
493 $form->update_exchangerate($dbh, $form->{currency},
494 $form->{"datepaid_$i"},
495 0, $form->{"exchangerate_$i"});
499 # record exchange rate differences and gains/losses
500 foreach my $accno (keys %{ $form->{fx} }) {
501 foreach my $transdate (keys %{ $form->{fx}{$accno} }) {
502 $form->{fx}{$accno}{$transdate} = $form->round_amount($form->{fx}{$accno}{$transdate}, 2);
503 next if ($form->{fx}{$accno}{$transdate} == 0);
505 $query = qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate, cleared, fx_transaction, taxkey, project_id)
506 VALUES (?, (SELECT id FROM chart WHERE accno = ?), ?, ?, '0', '1', 0, ?)|;
507 @values = (conv_i($form->{id}), $accno, $form->{fx}{$accno}{$transdate}, conv_date($transdate), $project_id);
508 do_query($form, $dbh, $query, @values);
512 if ($payments_only) {
513 $query = qq|UPDATE ap SET paid = ?, datepaid = ? WHERE id = ?|;
514 do_query($form, $dbh, $query, $form->{paid}, $form->{paid} ? conv_date($form->{datepaid}) : undef, conv_i($form->{id}));
516 if (!$provided_dbh) {
521 $main::lxdebug->leave_sub();
525 $amount = $netamount + $tax;
527 # set values which could be empty
528 my $taxzone_id = $form->{taxzone_id} * 1;
529 $form->{department_id} = (split /--/, $form->{department})[1];
530 $form->{invnumber} = $form->{id} unless $form->{invnumber};
532 $taxzone_id = 0 if ((3 < $taxzone_id) || (0 > $taxzone_id));
535 $query = qq|UPDATE ap SET
557 globalproject_id = ?,
561 @values = ($form->{invnumber}, $form->{ordnumber}, $form->{quonumber},
562 conv_date($form->{invdate}), conv_date($form->{orddate}), conv_date($form->{quodate}),
563 conv_i($form->{vendor_id}), $amount, $netamount, $form->{paid},
564 $form->{paid} ? conv_date($form->{datepaid}) : undef,
565 conv_date($form->{duedate}), $taxzone_id,
566 $form->{taxincluded} ? 't' : 'f',
567 $form->{notes}, $form->{intnotes}, $form->{currency}, conv_i($form->{department_id}),
568 $form->{storno} ? 't' : 'f', conv_i($form->{storno_id}),
569 conv_i($form->{globalproject_id}), conv_i($form->{cp_id}),
570 conv_i($form->{employee_id}),
571 conv_i($form->{id}));
572 do_query($form, $dbh, $query, @values);
574 if ($form->{storno}) {
575 $query = qq|UPDATE ap SET paid = paid + amount WHERE id = ?|;
576 do_query($form, $dbh, $query, conv_i($form->{storno_id}));
578 $query = qq|UPDATE ap SET storno = 't' WHERE id = ?|;
579 do_query($form, $dbh, $query, conv_i($form->{storno_id}));
581 $query = qq!UPDATE ap SET intnotes = ? || intnotes WHERE id = ?!;
582 do_query($form, $dbh, $query, 'Rechnung storniert am $form->{invdate} ', conv_i($form->{storno_id}));
584 $query = qq|UPDATE ap SET paid = amount WHERE id = ?|;
585 do_query($form, $dbh, $query, conv_i($form->{id}));
590 $form->{name} = $form->{vendor};
591 $form->{name} =~ s/--$form->{vendor_id}//;
592 $form->add_shipto($dbh, $form->{id}, "AP");
594 # delete zero entries
595 do_query($form, $dbh, qq|DELETE FROM acc_trans WHERE amount = 0|);
597 Common::webdav_folder($form) if ($main::webdav);
601 if (!$provided_dbh) {
602 $rc = $dbh->commit();
606 $main::lxdebug->leave_sub();
611 sub reverse_invoice {
612 $main::lxdebug->enter_sub();
614 my ($dbh, $form) = @_;
616 # reverse inventory items
618 qq|SELECT i.parts_id, p.inventory_accno_id, p.expense_accno_id, i.qty, i.allocated, i.sellprice
619 FROM invoice i, parts p
620 WHERE (i.parts_id = p.id)
621 AND (i.trans_id = ?)|;
622 my $sth = prepare_execute_query($form, $dbh, $query, conv_i($form->{id}));
626 while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
627 $netamount += $form->round_amount($ref->{sellprice} * $ref->{qty} * -1, 2);
629 next unless $ref->{inventory_accno_id};
632 $form->update_balance($dbh, "parts", "onhand", qq|id = $ref->{parts_id}|, $ref->{qty});
634 # if $ref->{allocated} > 0 than we sold that many items
635 next if ($ref->{allocated} <= 0);
637 # get references for sold items
639 qq|SELECT i.id, i.trans_id, i.allocated, a.transdate
641 WHERE (i.parts_id = ?)
642 AND (i.allocated < 0)
643 AND (i.trans_id = a.id)
644 ORDER BY transdate DESC|;
645 my $sth2 = prepare_execute_query($form, $dbh, $query, $ref->{parts_id});
647 while (my $pthref = $sth2->fetchrow_hashref(NAME_lc)) {
648 my $qty = $ref->{allocated};
649 if (($ref->{allocated} + $pthref->{allocated}) > 0) {
650 $qty = $pthref->{allocated} * -1;
653 my $amount = $form->round_amount($ref->{sellprice} * $qty, 2);
656 $form->update_balance($dbh, "invoice", "allocated", qq|id = $pthref->{id}|, $qty);
658 $form->update_balance($dbh, "acc_trans", "amount",
659 qq| (trans_id = $pthref->{trans_id})
660 AND (chart_id = $ref->{expense_accno_id})
661 AND (transdate = '$pthref->{transdate}')|,
664 $form->update_balance($dbh, "acc_trans", "amount",
665 qq| (trans_id = $pthref->{trans_id})
666 AND (chart_id = $ref->{inventory_accno_id})
667 AND (transdate = '$pthref->{transdate}')|,
670 last if (($ref->{allocated} -= $qty) <= 0);
676 my $id = conv_i($form->{id});
679 $query = qq|DELETE FROM acc_trans WHERE trans_id = ?|;
680 do_query($form, $dbh, $query, $id);
682 # delete invoice entries
683 $query = qq|DELETE FROM invoice WHERE trans_id = ?|;
684 do_query($form, $dbh, $query, $id);
686 $query = qq|DELETE FROM shipto WHERE (trans_id = ?) AND (module = 'AP')|;
687 do_query($form, $dbh, $query, $id);
689 $main::lxdebug->leave_sub();
693 $main::lxdebug->enter_sub();
695 my ($self, $myconfig, $form) = @_;
697 # connect to database
698 my $dbh = $form->dbconnect_noauto($myconfig);
700 &reverse_invoice($dbh, $form);
702 # delete zero entries
703 my $query = qq|DELETE FROM acc_trans WHERE amount = 0|;
704 do_query($form, $dbh, $query);
707 my $query = qq|DELETE FROM ap WHERE id = ?|;
708 do_query($form, $dbh, $query, conv_i($form->{id}));
710 my $rc = $dbh->commit;
713 $main::lxdebug->leave_sub();
718 sub retrieve_invoice {
719 $main::lxdebug->enter_sub();
721 my ($self, $myconfig, $form) = @_;
723 # connect to database
724 my $dbh = $form->dbconnect($myconfig);
726 my ($query, $sth, $ref, $q_invdate);
729 $q_invdate = qq|, COALESCE((SELECT transdate FROM ar WHERE id = (SELECT MAX(id) FROM ar)), current_date) AS invdate|;
730 if ($form->{vendor_id}) {
731 my $vendor_id = $dbh->quote($form->{vendor_id} * 1);
733 qq|, COALESCE((SELECT transdate FROM ar WHERE id = (SELECT MAX(id) FROM ar)), current_date) +
734 COALESCE((SELECT pt.terms_netto
736 LEFT JOIN payment_terms pt ON (v.payment_id = pt.id)
737 WHERE v.id = $vendor_id),
742 # get default accounts and last invoice number
746 (SELECT c.accno FROM chart c WHERE d.inventory_accno_id = c.id) AS inventory_accno,
747 (SELECT c.accno FROM chart c WHERE d.income_accno_id = c.id) AS income_accno,
748 (SELECT c.accno FROM chart c WHERE d.expense_accno_id = c.id) AS expense_accno,
749 (SELECT c.accno FROM chart c WHERE d.fxgain_accno_id = c.id) AS fxgain_accno,
750 (SELECT c.accno FROM chart c WHERE d.fxloss_accno_id = c.id) AS fxloss_accno,
754 $ref = selectfirst_hashref_query($form, $dbh, $query);
755 map { $form->{$_} = $ref->{$_} } keys %$ref;
759 $main::lxdebug->leave_sub();
766 qq|SELECT cp_id, invnumber, transdate AS invdate, duedate,
767 orddate, quodate, globalproject_id,
768 ordnumber, quonumber, paid, taxincluded, notes, taxzone_id, storno, gldate,
769 intnotes, curr AS currency
772 $ref = selectfirst_hashref_query($form, $dbh, $query, conv_i($form->{id}));
773 map { $form->{$_} = $ref->{$_} } keys %$ref;
775 $form->{exchangerate} = $form->get_exchangerate($dbh, $form->{currency}, $form->{invdate}, "sell");
778 $query = qq|SELECT * FROM shipto WHERE (trans_id = ?) AND (module = 'AP')|;
779 $ref = selectfirst_hashref_query($form, $dbh, $query, conv_i($form->{id}));
781 map { $form->{$_} = $ref->{$_} } keys %$ref;
783 my $transdate = $form->{invdate} ? $dbh->quote($form->{invdate}) : "current_date";
784 my $taxzone_id = $form->{taxzone_id} * 1;
786 $taxzone_id = 0 if ((3 < $taxzone_id) || (0 > $taxzone_id));
788 # retrieve individual items
791 c1.accno AS inventory_accno,
792 c1.new_chart_id AS inventory_new_chart,
793 date($transdate) - c1.valid_from AS inventory_valid,
795 c2.accno AS income_accno,
796 c2.new_chart_id AS income_new_chart,
797 date($transdate) - c2.valid_from AS income_valid,
799 c3.accno AS expense_accno,
800 c3.new_chart_id AS expense_new_chart,
801 date($transdate) - c3.valid_from AS expense_valid,
803 i.description, i.qty, i.fxsellprice AS sellprice,
804 i.parts_id AS id, i.unit, i.deliverydate, i.project_id, i.serialnumber,
806 p.partnumber, p.inventory_accno_id AS part_inventory_accno_id, p.bin,
811 JOIN parts p ON (i.parts_id = p.id)
812 LEFT JOIN chart c1 ON
813 ((SELECT inventory_accno_id
815 WHERE id = p.buchungsgruppen_id) = c1.id)
816 LEFT JOIN chart c2 ON
817 ((SELECT income_accno_id_${taxzone_id}
819 WHERE id = p.buchungsgruppen_id) = c2.id)
820 LEFT JOIN chart c3 ON
821 ((SELECT expense_accno_id_${taxzone_id}
823 WHERE id = p.buchungsgruppen_id) = c3.id)
824 LEFT JOIN project pr ON (i.project_id = pr.id)
825 LEFT JOIN partsgroup pg ON (pg.id = p.partsgroup_id)
830 $sth = prepare_execute_query($form, $dbh, $query, conv_i($form->{id}));
832 while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
833 if (!$ref->{"part_inventory_accno_id"}) {
834 map({ delete($ref->{$_}); } qw(inventory_accno inventory_new_chart inventory_valid));
836 delete($ref->{"part_inventory_accno_id"});
838 foreach my $type (qw(inventory income expense)) {
839 while ($ref->{"${type}_new_chart"} && ($ref->{"${type}_valid"} >=0)) {
841 qq|SELECT accno, new_chart_id, date($transdate) - valid_from
844 ($ref->{"${type}_accno"},
845 $ref->{"${type}_new_chart"},
846 $ref->{"${type}_valid"})
847 = selectrow_query($form, $dbh, $query, $ref->{"${type}_new_chart"});
851 # get tax rates and description
852 my $accno_id = ($form->{vc} eq "customer") ? $ref->{income_accno} : $ref->{expense_accno};
854 qq|SELECT c.accno, t.taxdescription, t.rate, t.taxnumber
856 LEFT JOIN chart c ON (c.id = t.chart_id)
864 AND (startdate <= $transdate)
865 ORDER BY startdate DESC
868 my $stw = prepare_execute_query($form, $dbh, $query, $accno_id);
869 $ref->{taxaccounts} = "";
872 while ($ptr = $stw->fetchrow_hashref(NAME_lc)) {
873 if (($ptr->{accno} eq "") && ($ptr->{rate} == 0)) {
878 $ref->{taxaccounts} .= "$ptr->{accno} ";
880 if (!($form->{taxaccounts} =~ /$ptr->{accno}/)) {
881 $form->{"$ptr->{accno}_rate"} = $ptr->{rate};
882 $form->{"$ptr->{accno}_description"} = $ptr->{taxdescription};
883 $form->{"$ptr->{accno}_taxnumber"} = $ptr->{taxnumber};
884 $form->{taxaccounts} .= "$ptr->{accno} ";
889 chop $ref->{taxaccounts};
890 push @{ $form->{invoice_details} }, $ref;
895 Common::webdav_folder($form) if ($main::webdav);
899 $main::lxdebug->leave_sub();
903 $main::lxdebug->enter_sub();
905 my ($self, $myconfig, $form) = @_;
907 # connect to database
908 my $dbh = $form->dbconnect($myconfig);
910 my $dateformat = $myconfig->{dateformat};
911 $dateformat .= "yy" if $myconfig->{dateformat} !~ /^y/;
913 my $vid = conv_i($form->{vendor_id});
917 ? "to_date(" . $dbh->quote($form->{invdate}) . ", '$dateformat')"
923 v.name AS vendor, v.creditlimit, v.terms, v.notes AS intnotes,
924 v.email, v.cc, v.bcc, v.language_id, v.payment_id,
925 v.street, v.zipcode, v.city, v.country, v.taxzone_id,
926 $duedate + COALESCE(pt.terms_netto, 0) AS duedate,
927 b.description AS business
929 LEFT JOIN business b ON (b.id = v.business_id)
930 LEFT JOIN payment_terms pt ON (v.payment_id = pt.id)
932 $ref = selectfirst_hashref_query($form, $dbh, $query, $vid);
933 map { $form->{$_} = $ref->{$_} } keys %$ref;
935 $form->{creditremaining} = $form->{creditlimit};
937 $query = qq|SELECT SUM(amount - paid) FROM ap WHERE vendor_id = ?|;
938 my ($unpaid_invoices) = selectfirst_array_query($form, $dbh, $query, $vid);
939 $form->{creditremaining} -= $unpaid_invoices;
941 $query = qq|SELECT o.amount,
944 WHERE (e.curr = o.curr)
945 AND (e.transdate = o.transdate)) AS exch
947 WHERE (o.vendor_id = ?) AND (o.quotation = '0') AND (o.closed = '0')|;
948 my $sth = prepare_execute_query($form, $dbh, $query, $vid);
949 while (my ($amount, $exch) = $sth->fetchrow_array()) {
950 $exch = 1 unless $exch;
951 $form->{creditremaining} -= $amount * $exch;
955 # get shipto if we do not convert an order or invoice
956 if (!$form->{shipto}) {
957 delete @{$form}{qw(shiptoname shiptostreet shiptozipcode shiptocity shiptocountry shiptocontact shiptophone shiptofax shiptoemail)};
959 $query = qq|SELECT * FROM shipto WHERE (trans_id = ?) AND (module= 'CT')|;
960 $ref = selectfirst_hashref_query($form, $dbh, $query, $vid);
961 @{$form}{keys %$ref} = @{$ref}{keys %$ref};
962 map { $form->{$_} = $ref->{$_} } keys %$ref;
965 if (!$form->{id} && $form->{type} !~ /_(order|quotation)/) {
966 # setup last accounts used
968 qq|SELECT c.id, c.accno, c.description, c.link, c.category
970 JOIN acc_trans ac ON (ac.chart_id = c.id)
971 JOIN ap a ON (a.id = ac.trans_id)
972 WHERE (a.vendor_id = ?)
973 AND (NOT ((c.link LIKE '%_tax%') OR (c.link LIKE '%_paid%')))
974 AND (a.id IN (SELECT max(a2.id) FROM ap a2 WHERE a2.vendor_id = ?))|;
975 my $refs = selectall_hashref_query($form, $dbh, $query, $vid, $vid);
979 if ($ref->{category} eq 'E') {
982 if ($form->{initial_transdate}) {
983 my $tax_query = qq|SELECT tk.tax_id, t.rate FROM taxkeys tk
984 LEFT JOIN tax t ON (tk.tax_id = t.id)
985 WHERE (tk.chart_id = ?) AND (startdate <= ?)
986 ORDER BY tk.startdate DESC
988 my ($tax_id, $rate) = selectrow_query($form, $dbh, $tax_query, $ref->{id}, $form->{initial_transdate});
989 $form->{"taxchart_$i"} = "${tax_id}--${rate}";
992 $form->{"AP_amount_$i"} = "$ref->{accno}--$tax_id";
995 if ($ref->{category} eq 'L') {
996 $form->{APselected} = $form->{AP_1} = $ref->{accno};
999 $form->{rowcount} = $i if ($i && !$form->{type});
1004 $main::lxdebug->leave_sub();
1008 $main::lxdebug->enter_sub();
1010 my ($self, $myconfig, $form) = @_;
1012 # connect to database
1013 my $dbh = $form->dbconnect($myconfig);
1015 my $i = $form->{rowcount};
1017 # don't include assemblies or obsolete parts
1018 my $where = "NOT p.assembly = '1' AND NOT p.obsolete = '1'";
1021 foreach my $table_column (qw(p.partnumber p.description pg.partsgroup)) {
1022 my $field = (split m{\.}, $table_column)[1];
1023 next unless $form->{"${field}_${i}"};
1024 $where .= " AND lower(${table_column}) LIKE lower(?)";
1025 push @values, '%' . $form->{"${field}_${i}"} . '%';
1028 if ($form->{"description_$i"}) {
1029 $where .= " ORDER BY p.description";
1031 $where .= " ORDER BY p.partnumber";
1035 if ($form->{type} eq "invoice") {
1036 $transdate = $form->{invdate} ? $dbh->quote($form->{invdate}) : "current_date";
1038 $transdate = $form->{transdate} ? $dbh->quote($form->{transdate}) : "current_date";
1041 my $taxzone_id = $form->{taxzone_id} * 1;
1042 $taxzone_id = 0 if ((3 < $taxzone_id) || (0 > $taxzone_id));
1046 p.id, p.partnumber, p.description, p.lastcost AS sellprice, p.listprice,
1047 p.unit, p.assembly, p.bin, p.onhand, p.formel,
1048 p.notes AS partnotes, p.notes AS longdescription, p.not_discountable,
1049 p.inventory_accno_id,
1051 c1.accno AS inventory_accno,
1052 c1.new_chart_id AS inventory_new_chart,
1053 date($transdate) - c1.valid_from AS inventory_valid,
1055 c2.accno AS income_accno,
1056 c2.new_chart_id AS income_new_chart,
1057 date($transdate) - c2.valid_from AS income_valid,
1059 c3.accno AS expense_accno,
1060 c3.new_chart_id AS expense_new_chart,
1061 date($transdate) - c3.valid_from AS expense_valid,
1066 LEFT JOIN chart c1 ON
1067 ((SELECT inventory_accno_id
1068 FROM buchungsgruppen
1069 WHERE id = p.buchungsgruppen_id) = c1.id)
1070 LEFT JOIN chart c2 ON
1071 ((SELECT income_accno_id_${taxzone_id}
1072 FROM buchungsgruppen
1073 WHERE id = p.buchungsgruppen_id) = c2.id)
1074 LEFT JOIN chart c3 ON
1075 ((SELECT expense_accno_id_${taxzone_id}
1076 FROM buchungsgruppen
1077 WHERE id = p.buchungsgruppen_id) = c3.id)
1078 LEFT JOIN partsgroup pg ON (pg.id = p.partsgroup_id)
1080 my $sth = prepare_execute_query($form, $dbh, $query, @values);
1082 $form->{item_list} = [];
1083 while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
1085 # In der Buchungsgruppe ist immer ein Bestandskonto verknuepft, auch wenn
1086 # es sich um eine Dienstleistung handelt. Bei Dienstleistungen muss das
1087 # Buchungskonto also aus dem Ergebnis rausgenommen werden.
1088 if (!$ref->{inventory_accno_id}) {
1089 map({ delete($ref->{"inventory_${_}"}); } qw(accno new_chart valid));
1091 delete($ref->{inventory_accno_id});
1093 # get tax rates and description
1094 $accno_id = ($form->{vc} eq "customer") ? $ref->{income_accno} : $ref->{expense_accno};
1096 qq|SELECT c.accno, t.taxdescription, t.rate, t.taxnumber
1098 LEFT JOIN chart c on (c.id = t.chart_id)
1106 AND (startdate <= $transdate)
1107 ORDER BY startdate DESC
1110 my $stw = prepare_execute_query($form, $dbh, $query, $accno_id);
1112 $ref->{taxaccounts} = "";
1114 while ($ptr = $stw->fetchrow_hashref(NAME_lc)) {
1116 # if ($customertax{$ref->{accno}}) {
1117 if (($ptr->{accno} eq "") && ($ptr->{rate} == 0)) {
1122 $ref->{taxaccounts} .= "$ptr->{accno} ";
1124 if (!($form->{taxaccounts} =~ /$ptr->{accno}/)) {
1125 $form->{"$ptr->{accno}_rate"} = $ptr->{rate};
1126 $form->{"$ptr->{accno}_description"} = $ptr->{taxdescription};
1127 $form->{"$ptr->{accno}_taxnumber"} = $ptr->{taxnumber};
1128 $form->{taxaccounts} .= "$ptr->{accno} ";
1134 chop $ref->{taxaccounts};
1136 push @{ $form->{item_list} }, $ref;
1143 $main::lxdebug->leave_sub();
1146 sub vendor_details {
1147 $main::lxdebug->enter_sub();
1149 my ($self, $myconfig, $form, @wanted_vars) = @_;
1151 # connect to database
1152 my $dbh = $form->dbconnect($myconfig);
1156 # get contact id, set it if nessessary
1157 $form->{cp_id} = (split /--/, $form->{contact})[1];
1159 if ($form->{cp_id}) {
1160 $contact = "AND cp.cp_id = ?";
1161 push @values, $form->{cp_id};
1164 # get rest for the vendor
1165 # fax and phone and email as vendor*
1167 qq|SELECT ct.*, cp.*, ct.notes as vendornotes, phone as vendorphone, fax as vendorfax, email as vendoremail
1169 LEFT JOIN contacts cp ON (ct.id = cp.cp_cv_id)
1170 WHERE (ct.id = ?) $contact
1173 my $ref = selectfirst_hashref_query($form, $dbh, $query, $form->{vendor_id}, @values);
1175 # remove id and taxincluded before copy back
1176 delete @$ref{qw(id taxincluded)};
1178 @wanted_vars = grep({ $_ } @wanted_vars);
1179 if (scalar(@wanted_vars) > 0) {
1181 map({ $h_wanted_vars{$_} = 1; } @wanted_vars);
1182 map({ delete($ref->{$_}) unless ($h_wanted_vars{$_}); } keys(%{$ref}));
1185 map { $form->{$_} = $ref->{$_} } keys %$ref;
1189 $main::lxdebug->leave_sub();
1193 $main::lxdebug->enter_sub();
1195 my ($self, $myconfig, $form) = @_;
1197 # connect to database
1198 my $dbh = $form->dbconnect($myconfig);
1201 qq|SELECT accno, description, link
1203 WHERE link LIKE '%IC%'
1205 my $sth = prepare_execute_query($query, $dbh, $query);
1207 while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
1208 foreach my $key (split(/:/, $ref->{link})) {
1210 push @{ $form->{IC_links}{$key} },
1211 { accno => $ref->{accno},
1212 description => $ref->{description} };
1220 $main::lxdebug->leave_sub();
1223 sub _delete_payments {
1224 $main::lxdebug->enter_sub();
1226 my ($self, $form, $dbh) = @_;
1230 # Delete old payment entries from acc_trans.
1234 WHERE (trans_id = ?) AND fx_transaction
1240 LEFT JOIN chart c ON (at.chart_id = c.id)
1241 WHERE (trans_id = ?) AND (c.link LIKE '%AP_paid%')|;
1242 push @delete_oids, selectall_array_query($form, $dbh, $query, conv_i($form->{id}), conv_i($form->{id}));
1247 LEFT JOIN chart c ON (at.chart_id = c.id)
1248 WHERE (trans_id = ?)
1249 AND ((c.link = 'AP') OR (c.link LIKE '%:AP') OR (c.link LIKE 'AP:%'))
1252 push @delete_oids, selectall_array_query($form, $dbh, $query, conv_i($form->{id}));
1255 $query = qq|DELETE FROM acc_trans WHERE oid IN (| . join(", ", @delete_oids) . qq|)|;
1256 do_query($form, $dbh, $query);
1259 $main::lxdebug->leave_sub();
1263 $main::lxdebug->enter_sub();
1265 my ($self, $myconfig, $form, $locale) = @_;
1267 # connect to database, turn off autocommit
1268 my $dbh = $form->dbconnect_noauto($myconfig);
1270 my (%payments, $old_form, $row, $item, $query, %keep_vars);
1272 $old_form = save_form();
1274 # Delete all entries in acc_trans from prior payments.
1275 $self->_delete_payments($form, $dbh);
1277 # Save the new payments the user made before cleaning up $form.
1278 map { $payments{$_} = $form->{$_} } grep m/^datepaid_\d+$|^memo_\d+$|^source_\d+$|^exchangerate_\d+$|^paid_\d+$|^AP_paid_\d+$|^paidaccounts$/, keys %{ $form };
1280 # Clean up $form so that old content won't tamper the results.
1281 %keep_vars = map { $_, 1 } qw(login password id);
1282 map { delete $form->{$_} unless $keep_vars{$_} } keys %{ $form };
1284 # Retrieve the invoice from the database.
1285 $self->retrieve_invoice($myconfig, $form);
1287 # Set up the content of $form in the way that IR::post_invoice() expects.
1288 $form->{exchangerate} = $form->format_amount($myconfig, $form->{exchangerate});
1290 for $row (1 .. scalar @{ $form->{invoice_details} }) {
1291 $item = $form->{invoice_details}->[$row - 1];
1293 map { $item->{$_} = $form->format_amount($myconfig, $item->{$_}) } qw(qty sellprice);
1295 map { $form->{"${_}_${row}"} = $item->{$_} } keys %{ $item };
1298 $form->{rowcount} = scalar @{ $form->{invoice_details} };
1300 delete @{$form}{qw(invoice_details paidaccounts storno paid)};
1302 # Restore the payment options from the user input.
1303 map { $form->{$_} = $payments{$_} } keys %payments;
1305 # Get the AP accno (which is normally done by Form::create_links()).
1309 LEFT JOIN chart c ON (at.chart_id = c.id)
1310 WHERE (trans_id = ?)
1311 AND ((c.link = 'AP') OR (c.link LIKE '%:AP') OR (c.link LIKE 'AP:%'))
1315 ($form->{AP}) = selectfirst_array_query($form, $dbh, $query, conv_i($form->{id}));
1317 # Post the new payments.
1318 $self->post_invoice($myconfig, $form, $dbh, 1);
1320 restore_form($old_form);
1322 my $rc = $dbh->commit();
1325 $main::lxdebug->leave_sub();