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
556 globalproject_id = ?,
560 @values = ($form->{invnumber}, $form->{ordnumber}, $form->{quonumber},
561 conv_date($form->{invdate}), conv_date($form->{orddate}), conv_date($form->{quodate}),
562 conv_i($form->{vendor_id}), $amount, $netamount, $form->{paid},
563 $form->{paid} ? conv_date($form->{datepaid}) : undef,
564 conv_date($form->{duedate}), $taxzone_id,
565 $form->{taxincluded} ? 't' : 'f',
566 $form->{notes}, $form->{intnotes}, $form->{currency}, conv_i($form->{department_id}),
567 $form->{storno} ? 't' : 'f',
568 conv_i($form->{globalproject_id}), conv_i($form->{cp_id}),
569 conv_i($form->{employee_id}),
570 conv_i($form->{id}));
571 do_query($form, $dbh, $query, @values);
573 if ($form->{storno}) {
574 $query = qq|UPDATE ap SET paid = paid + amount WHERE id = ?|;
575 do_query($form, $dbh, $query, conv_i($form->{storno_id}));
577 $query = qq|UPDATE ap SET storno = 't' WHERE id = ?|;
578 do_query($form, $dbh, $query, conv_i($form->{storno_id}));
580 $query = qq!UPDATE ap SET intnotes = ? || intnotes WHERE id = ?!;
581 do_query($form, $dbh, $query, 'Rechnung storniert am $form->{invdate} ', conv_i($form->{storno_id}));
583 $query = qq|UPDATE ap SET paid = amount WHERE id = ?|;
584 do_query($form, $dbh, $query, conv_i($form->{id}));
589 $form->{name} = $form->{vendor};
590 $form->{name} =~ s/--$form->{vendor_id}//;
591 $form->add_shipto($dbh, $form->{id}, "AP");
593 # delete zero entries
594 do_query($form, $dbh, qq|DELETE FROM acc_trans WHERE amount = 0|);
596 Common::webdav_folder($form) if ($main::webdav);
600 if (!$provided_dbh) {
601 $rc = $dbh->commit();
605 $main::lxdebug->leave_sub();
610 sub reverse_invoice {
611 $main::lxdebug->enter_sub();
613 my ($dbh, $form) = @_;
615 # reverse inventory items
617 qq|SELECT i.parts_id, p.inventory_accno_id, p.expense_accno_id, i.qty, i.allocated, i.sellprice
618 FROM invoice i, parts p
619 WHERE (i.parts_id = p.id)
620 AND (i.trans_id = ?)|;
621 my $sth = prepare_execute_query($form, $dbh, $query, conv_i($form->{id}));
625 while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
626 $netamount += $form->round_amount($ref->{sellprice} * $ref->{qty} * -1, 2);
628 next unless $ref->{inventory_accno_id};
631 $form->update_balance($dbh, "parts", "onhand", qq|id = $ref->{parts_id}|, $ref->{qty});
633 # if $ref->{allocated} > 0 than we sold that many items
634 next if ($ref->{allocated} <= 0);
636 # get references for sold items
638 qq|SELECT i.id, i.trans_id, i.allocated, a.transdate
640 WHERE (i.parts_id = ?)
641 AND (i.allocated < 0)
642 AND (i.trans_id = a.id)
643 ORDER BY transdate DESC|;
644 my $sth2 = prepare_execute_query($form, $dbh, $query, $ref->{parts_id});
646 while (my $pthref = $sth2->fetchrow_hashref(NAME_lc)) {
647 my $qty = $ref->{allocated};
648 if (($ref->{allocated} + $pthref->{allocated}) > 0) {
649 $qty = $pthref->{allocated} * -1;
652 my $amount = $form->round_amount($ref->{sellprice} * $qty, 2);
655 $form->update_balance($dbh, "invoice", "allocated", qq|id = $pthref->{id}|, $qty);
657 $form->update_balance($dbh, "acc_trans", "amount",
658 qq| (trans_id = $pthref->{trans_id})
659 AND (chart_id = $ref->{expense_accno_id})
660 AND (transdate = '$pthref->{transdate}')|,
663 $form->update_balance($dbh, "acc_trans", "amount",
664 qq| (trans_id = $pthref->{trans_id})
665 AND (chart_id = $ref->{inventory_accno_id})
666 AND (transdate = '$pthref->{transdate}')|,
669 last if (($ref->{allocated} -= $qty) <= 0);
675 my $id = conv_i($form->{id});
678 $query = qq|DELETE FROM acc_trans WHERE trans_id = ?|;
679 do_query($form, $dbh, $query, $id);
681 # delete invoice entries
682 $query = qq|DELETE FROM invoice WHERE trans_id = ?|;
683 do_query($form, $dbh, $query, $id);
685 $query = qq|DELETE FROM shipto WHERE (trans_id = ?) AND (module = 'AP')|;
686 do_query($form, $dbh, $query, $id);
688 $main::lxdebug->leave_sub();
692 $main::lxdebug->enter_sub();
694 my ($self, $myconfig, $form) = @_;
696 # connect to database
697 my $dbh = $form->dbconnect_noauto($myconfig);
699 &reverse_invoice($dbh, $form);
701 # delete zero entries
702 my $query = qq|DELETE FROM acc_trans WHERE amount = 0|;
703 do_query($form, $dbh, $query);
706 my $query = qq|DELETE FROM ap WHERE id = ?|;
707 do_query($form, $dbh, $query, conv_i($form->{id}));
709 my $rc = $dbh->commit;
712 $main::lxdebug->leave_sub();
717 sub retrieve_invoice {
718 $main::lxdebug->enter_sub();
720 my ($self, $myconfig, $form) = @_;
722 # connect to database
723 my $dbh = $form->dbconnect($myconfig);
725 my ($query, $sth, $ref, $q_invdate);
728 $q_invdate = qq|, COALESCE((SELECT transdate FROM ar WHERE id = (SELECT MAX(id) FROM ar)), current_date) AS invdate|;
729 if ($form->{vendor_id}) {
730 my $vendor_id = $dbh->quote($form->{vendor_id} * 1);
732 qq|, COALESCE((SELECT transdate FROM ar WHERE id = (SELECT MAX(id) FROM ar)), current_date) +
733 COALESCE((SELECT pt.terms_netto
735 LEFT JOIN payment_terms pt ON (v.payment_id = pt.id)
736 WHERE v.id = $vendor_id),
741 # get default accounts and last invoice number
745 (SELECT c.accno FROM chart c WHERE d.inventory_accno_id = c.id) AS inventory_accno,
746 (SELECT c.accno FROM chart c WHERE d.income_accno_id = c.id) AS income_accno,
747 (SELECT c.accno FROM chart c WHERE d.expense_accno_id = c.id) AS expense_accno,
748 (SELECT c.accno FROM chart c WHERE d.fxgain_accno_id = c.id) AS fxgain_accno,
749 (SELECT c.accno FROM chart c WHERE d.fxloss_accno_id = c.id) AS fxloss_accno,
753 $ref = selectfirst_hashref_query($form, $dbh, $query);
754 map { $form->{$_} = $ref->{$_} } keys %$ref;
758 $main::lxdebug->leave_sub();
765 qq|SELECT cp_id, invnumber, transdate AS invdate, duedate,
766 orddate, quodate, globalproject_id,
767 ordnumber, quonumber, paid, taxincluded, notes, taxzone_id, storno, gldate,
768 intnotes, curr AS currency
771 $ref = selectfirst_hashref_query($form, $dbh, $query, conv_i($form->{id}));
772 map { $form->{$_} = $ref->{$_} } keys %$ref;
774 $form->{exchangerate} = $form->get_exchangerate($dbh, $form->{currency}, $form->{invdate}, "sell");
777 $query = qq|SELECT * FROM shipto WHERE (trans_id = ?) AND (module = 'AP')|;
778 $ref = selectfirst_hashref_query($form, $dbh, $query, conv_i($form->{id}));
780 map { $form->{$_} = $ref->{$_} } keys %$ref;
782 my $transdate = $form->{invdate} ? $dbh->quote($form->{invdate}) : "current_date";
783 my $taxzone_id = $form->{taxzone_id} * 1;
785 $taxzone_id = 0 if ((3 < $taxzone_id) || (0 > $taxzone_id));
787 # retrieve individual items
790 c1.accno AS inventory_accno,
791 c1.new_chart_id AS inventory_new_chart,
792 date($transdate) - c1.valid_from AS inventory_valid,
794 c2.accno AS income_accno,
795 c2.new_chart_id AS income_new_chart,
796 date($transdate) - c2.valid_from AS income_valid,
798 c3.accno AS expense_accno,
799 c3.new_chart_id AS expense_new_chart,
800 date($transdate) - c3.valid_from AS expense_valid,
802 i.description, i.qty, i.fxsellprice AS sellprice,
803 i.parts_id AS id, i.unit, i.deliverydate, i.project_id, i.serialnumber,
805 p.partnumber, p.inventory_accno_id AS part_inventory_accno_id, p.bin,
810 JOIN parts p ON (i.parts_id = p.id)
811 LEFT JOIN chart c1 ON
812 ((SELECT inventory_accno_id
814 WHERE id = p.buchungsgruppen_id) = c1.id)
815 LEFT JOIN chart c2 ON
816 ((SELECT income_accno_id_${taxzone_id}
818 WHERE id = p.buchungsgruppen_id) = c2.id)
819 LEFT JOIN chart c3 ON
820 ((SELECT expense_accno_id_${taxzone_id}
822 WHERE id = p.buchungsgruppen_id) = c3.id)
823 LEFT JOIN project pr ON (i.project_id = pr.id)
824 LEFT JOIN partsgroup pg ON (pg.id = p.partsgroup_id)
829 $sth = prepare_execute_query($form, $dbh, $query, conv_i($form->{id}));
831 while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
832 if (!$ref->{"part_inventory_accno_id"}) {
833 map({ delete($ref->{$_}); } qw(inventory_accno inventory_new_chart inventory_valid));
835 delete($ref->{"part_inventory_accno_id"});
837 foreach my $type (qw(inventory income expense)) {
838 while ($ref->{"${type}_new_chart"} && ($ref->{"${type}_valid"} >=0)) {
840 qq|SELECT accno, new_chart_id, date($transdate) - valid_from
843 ($ref->{"${type}_accno"},
844 $ref->{"${type}_new_chart"},
845 $ref->{"${type}_valid"})
846 = selectrow_query($form, $dbh, $query, $ref->{"${type}_new_chart"});
850 # get tax rates and description
851 my $accno_id = ($form->{vc} eq "customer") ? $ref->{income_accno} : $ref->{expense_accno};
853 qq|SELECT c.accno, t.taxdescription, t.rate, t.taxnumber
855 LEFT JOIN chart c ON (c.id = t.chart_id)
863 AND (startdate <= $transdate)
864 ORDER BY startdate DESC
867 my $stw = prepare_execute_query($form, $dbh, $query, $accno_id);
868 $ref->{taxaccounts} = "";
871 while ($ptr = $stw->fetchrow_hashref(NAME_lc)) {
872 if (($ptr->{accno} eq "") && ($ptr->{rate} == 0)) {
877 $ref->{taxaccounts} .= "$ptr->{accno} ";
879 if (!($form->{taxaccounts} =~ /$ptr->{accno}/)) {
880 $form->{"$ptr->{accno}_rate"} = $ptr->{rate};
881 $form->{"$ptr->{accno}_description"} = $ptr->{taxdescription};
882 $form->{"$ptr->{accno}_taxnumber"} = $ptr->{taxnumber};
883 $form->{taxaccounts} .= "$ptr->{accno} ";
888 chop $ref->{taxaccounts};
889 push @{ $form->{invoice_details} }, $ref;
894 Common::webdav_folder($form) if ($main::webdav);
898 $main::lxdebug->leave_sub();
902 $main::lxdebug->enter_sub();
904 my ($self, $myconfig, $form) = @_;
906 # connect to database
907 my $dbh = $form->dbconnect($myconfig);
909 my $dateformat = $myconfig->{dateformat};
910 $dateformat .= "yy" if $myconfig->{dateformat} !~ /^y/;
912 my $vid = conv_i($form->{vendor_id});
916 ? "to_date(" . $dbh->quote($form->{invdate}) . ", '$dateformat')"
922 v.name AS vendor, v.creditlimit, v.terms, v.notes AS intnotes,
923 v.email, v.cc, v.bcc, v.language_id, v.payment_id,
924 v.street, v.zipcode, v.city, v.country, v.taxzone_id,
925 $duedate + COALESCE(pt.terms_netto, 0) AS duedate,
926 b.description AS business
928 LEFT JOIN business b ON (b.id = v.business_id)
929 LEFT JOIN payment_terms pt ON (v.payment_id = pt.id)
931 $ref = selectfirst_hashref_query($form, $dbh, $query, $vid);
932 map { $form->{$_} = $ref->{$_} } keys %$ref;
934 $form->{creditremaining} = $form->{creditlimit};
936 $query = qq|SELECT SUM(amount - paid) FROM ap WHERE vendor_id = ?|;
937 my ($unpaid_invoices) = selectfirst_array_query($form, $dbh, $query, $vid);
938 $form->{creditremaining} -= $unpaid_invoices;
940 $query = qq|SELECT o.amount,
943 WHERE (e.curr = o.curr)
944 AND (e.transdate = o.transdate)) AS exch
946 WHERE (o.vendor_id = ?) AND (o.quotation = '0') AND (o.closed = '0')|;
947 my $sth = prepare_execute_query($form, $dbh, $query, $vid);
948 while (my ($amount, $exch) = $sth->fetchrow_array()) {
949 $exch = 1 unless $exch;
950 $form->{creditremaining} -= $amount * $exch;
954 # get shipto if we do not convert an order or invoice
955 if (!$form->{shipto}) {
956 delete @{$form}{qw(shiptoname shiptostreet shiptozipcode shiptocity shiptocountry shiptocontact shiptophone shiptofax shiptoemail)};
958 $query = qq|SELECT * FROM shipto WHERE (trans_id = ?) AND (module= 'CT')|;
959 $ref = selectfirst_hashref_query($form, $dbh, $query, $vid);
960 @{$form}{keys %$ref} = @{$ref}{keys %$ref};
961 map { $form->{$_} = $ref->{$_} } keys %$ref;
964 if (!$form->{id} && $form->{type} !~ /_(order|quotation)/) {
965 # setup last accounts used
967 qq|SELECT c.id, c.accno, c.description, c.link, c.category
969 JOIN acc_trans ac ON (ac.chart_id = c.id)
970 JOIN ap a ON (a.id = ac.trans_id)
971 WHERE (a.vendor_id = ?)
972 AND (NOT ((c.link LIKE '%_tax%') OR (c.link LIKE '%_paid%')))
973 AND (a.id IN (SELECT max(a2.id) FROM ap a2 WHERE a2.vendor_id = ?))|;
974 my $refs = selectall_hashref_query($form, $dbh, $query, $vid, $vid);
978 if ($ref->{category} eq 'E') {
981 if ($form->{initial_transdate}) {
982 my $tax_query = qq|SELECT tk.tax_id, t.rate FROM taxkeys tk
983 LEFT JOIN tax t ON (tk.tax_id = t.id)
984 WHERE (tk.chart_id = ?) AND (startdate <= ?)
985 ORDER BY tk.startdate DESC
987 my ($tax_id, $rate) = selectrow_query($form, $dbh, $tax_query, $ref->{id}, $form->{initial_transdate});
988 $form->{"taxchart_$i"} = "${tax_id}--${rate}";
991 $form->{"AP_amount_$i"} = "$ref->{accno}--$tax_id";
994 if ($ref->{category} eq 'L') {
995 $form->{APselected} = $form->{AP_1} = $ref->{accno};
998 $form->{rowcount} = $i if ($i && !$form->{type});
1003 $main::lxdebug->leave_sub();
1007 $main::lxdebug->enter_sub();
1009 my ($self, $myconfig, $form) = @_;
1011 # connect to database
1012 my $dbh = $form->dbconnect($myconfig);
1014 my $i = $form->{rowcount};
1016 # don't include assemblies or obsolete parts
1017 my $where = "NOT p.assembly = '1' AND NOT p.obsolete = '1'";
1020 foreach my $table_column (qw(p.partnumber p.description pg.partsgroup)) {
1021 my $field = (split m{\.}, $table_column)[1];
1022 next unless $form->{"${field}_${i}"};
1023 $where .= " AND lower(${table_column}) LIKE lower(?)";
1024 push @values, '%' . $form->{"${field}_${i}"} . '%';
1027 if ($form->{"description_$i"}) {
1028 $where .= " ORDER BY p.description";
1030 $where .= " ORDER BY p.partnumber";
1034 if ($form->{type} eq "invoice") {
1035 $transdate = $form->{invdate} ? $dbh->quote($form->{invdate}) : "current_date";
1037 $transdate = $form->{transdate} ? $dbh->quote($form->{transdate}) : "current_date";
1040 my $taxzone_id = $form->{taxzone_id} * 1;
1041 $taxzone_id = 0 if ((3 < $taxzone_id) || (0 > $taxzone_id));
1045 p.id, p.partnumber, p.description, p.lastcost AS sellprice, p.listprice,
1046 p.unit, p.assembly, p.bin, p.onhand, p.formel,
1047 p.notes AS partnotes, p.notes AS longdescription, p.not_discountable,
1048 p.inventory_accno_id,
1050 c1.accno AS inventory_accno,
1051 c1.new_chart_id AS inventory_new_chart,
1052 date($transdate) - c1.valid_from AS inventory_valid,
1054 c2.accno AS income_accno,
1055 c2.new_chart_id AS income_new_chart,
1056 date($transdate) - c2.valid_from AS income_valid,
1058 c3.accno AS expense_accno,
1059 c3.new_chart_id AS expense_new_chart,
1060 date($transdate) - c3.valid_from AS expense_valid,
1065 LEFT JOIN chart c1 ON
1066 ((SELECT inventory_accno_id
1067 FROM buchungsgruppen
1068 WHERE id = p.buchungsgruppen_id) = c1.id)
1069 LEFT JOIN chart c2 ON
1070 ((SELECT income_accno_id_${taxzone_id}
1071 FROM buchungsgruppen
1072 WHERE id = p.buchungsgruppen_id) = c2.id)
1073 LEFT JOIN chart c3 ON
1074 ((SELECT expense_accno_id_${taxzone_id}
1075 FROM buchungsgruppen
1076 WHERE id = p.buchungsgruppen_id) = c3.id)
1077 LEFT JOIN partsgroup pg ON (pg.id = p.partsgroup_id)
1079 my $sth = prepare_execute_query($form, $dbh, $query, @values);
1081 $form->{item_list} = [];
1082 while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
1084 # In der Buchungsgruppe ist immer ein Bestandskonto verknuepft, auch wenn
1085 # es sich um eine Dienstleistung handelt. Bei Dienstleistungen muss das
1086 # Buchungskonto also aus dem Ergebnis rausgenommen werden.
1087 if (!$ref->{inventory_accno_id}) {
1088 map({ delete($ref->{"inventory_${_}"}); } qw(accno new_chart valid));
1090 delete($ref->{inventory_accno_id});
1092 # get tax rates and description
1093 $accno_id = ($form->{vc} eq "customer") ? $ref->{income_accno} : $ref->{expense_accno};
1095 qq|SELECT c.accno, t.taxdescription, t.rate, t.taxnumber
1097 LEFT JOIN chart c on (c.id = t.chart_id)
1105 AND (startdate <= $transdate)
1106 ORDER BY startdate DESC
1109 my $stw = prepare_execute_query($form, $dbh, $query, $accno_id);
1111 $ref->{taxaccounts} = "";
1113 while ($ptr = $stw->fetchrow_hashref(NAME_lc)) {
1115 # if ($customertax{$ref->{accno}}) {
1116 if (($ptr->{accno} eq "") && ($ptr->{rate} == 0)) {
1121 $ref->{taxaccounts} .= "$ptr->{accno} ";
1123 if (!($form->{taxaccounts} =~ /$ptr->{accno}/)) {
1124 $form->{"$ptr->{accno}_rate"} = $ptr->{rate};
1125 $form->{"$ptr->{accno}_description"} = $ptr->{taxdescription};
1126 $form->{"$ptr->{accno}_taxnumber"} = $ptr->{taxnumber};
1127 $form->{taxaccounts} .= "$ptr->{accno} ";
1133 chop $ref->{taxaccounts};
1135 push @{ $form->{item_list} }, $ref;
1142 $main::lxdebug->leave_sub();
1145 sub vendor_details {
1146 $main::lxdebug->enter_sub();
1148 my ($self, $myconfig, $form, @wanted_vars) = @_;
1150 # connect to database
1151 my $dbh = $form->dbconnect($myconfig);
1155 # get contact id, set it if nessessary
1156 $form->{cp_id} = (split /--/, $form->{contact})[1];
1158 if ($form->{cp_id}) {
1159 $contact = "AND cp.cp_id = ?";
1160 push @values, $form->{cp_id};
1163 # get rest for the vendor
1164 # fax and phone and email as vendor*
1166 qq|SELECT ct.*, cp.*, ct.notes as vendornotes, phone as vendorphone, fax as vendorfax, email as vendoremail
1168 LEFT JOIN contacts cp ON (ct.id = cp.cp_cv_id)
1169 WHERE (ct.id = ?) $contact
1172 my $ref = selectfirst_hashref_query($form, $dbh, $query, $form->{vendor_id}, @values);
1174 # remove id and taxincluded before copy back
1175 delete @$ref{qw(id taxincluded)};
1177 @wanted_vars = grep({ $_ } @wanted_vars);
1178 if (scalar(@wanted_vars) > 0) {
1180 map({ $h_wanted_vars{$_} = 1; } @wanted_vars);
1181 map({ delete($ref->{$_}) unless ($h_wanted_vars{$_}); } keys(%{$ref}));
1184 map { $form->{$_} = $ref->{$_} } keys %$ref;
1188 $main::lxdebug->leave_sub();
1192 $main::lxdebug->enter_sub();
1194 my ($self, $myconfig, $form) = @_;
1196 # connect to database
1197 my $dbh = $form->dbconnect($myconfig);
1200 qq|SELECT accno, description, link
1202 WHERE link LIKE '%IC%'
1204 my $sth = prepare_execute_query($query, $dbh, $query);
1206 while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
1207 foreach my $key (split(/:/, $ref->{link})) {
1209 push @{ $form->{IC_links}{$key} },
1210 { accno => $ref->{accno},
1211 description => $ref->{description} };
1219 $main::lxdebug->leave_sub();
1222 sub _delete_payments {
1223 $main::lxdebug->enter_sub();
1225 my ($self, $form, $dbh) = @_;
1229 # Delete old payment entries from acc_trans.
1233 WHERE (trans_id = ?) AND fx_transaction
1239 LEFT JOIN chart c ON (at.chart_id = c.id)
1240 WHERE (trans_id = ?) AND (c.link LIKE '%AP_paid%')|;
1241 push @delete_oids, selectall_array_query($form, $dbh, $query, conv_i($form->{id}), conv_i($form->{id}));
1246 LEFT JOIN chart c ON (at.chart_id = c.id)
1247 WHERE (trans_id = ?)
1248 AND ((c.link = 'AP') OR (c.link LIKE '%:AP') OR (c.link LIKE 'AP:%'))
1251 push @delete_oids, selectall_array_query($form, $dbh, $query, conv_i($form->{id}));
1254 $query = qq|DELETE FROM acc_trans WHERE oid IN (| . join(", ", @delete_oids) . qq|)|;
1255 do_query($form, $dbh, $query);
1258 $main::lxdebug->leave_sub();
1262 $main::lxdebug->enter_sub();
1264 my ($self, $myconfig, $form, $locale) = @_;
1266 # connect to database, turn off autocommit
1267 my $dbh = $form->dbconnect_noauto($myconfig);
1269 my (%payments, $old_form, $row, $item, $query, %keep_vars);
1271 $old_form = save_form();
1273 # Delete all entries in acc_trans from prior payments.
1274 $self->_delete_payments($form, $dbh);
1276 # Save the new payments the user made before cleaning up $form.
1277 map { $payments{$_} = $form->{$_} } grep m/^datepaid_\d+$|^memo_\d+$|^source_\d+$|^exchangerate_\d+$|^paid_\d+$|^AP_paid_\d+$|^paidaccounts$/, keys %{ $form };
1279 # Clean up $form so that old content won't tamper the results.
1280 %keep_vars = map { $_, 1 } qw(login password id);
1281 map { delete $form->{$_} unless $keep_vars{$_} } keys %{ $form };
1283 # Retrieve the invoice from the database.
1284 $self->retrieve_invoice($myconfig, $form);
1286 # Set up the content of $form in the way that IR::post_invoice() expects.
1287 $form->{exchangerate} = $form->format_amount($myconfig, $form->{exchangerate});
1289 for $row (1 .. scalar @{ $form->{invoice_details} }) {
1290 $item = $form->{invoice_details}->[$row - 1];
1292 map { $item->{$_} = $form->format_amount($myconfig, $item->{$_}) } qw(qty sellprice);
1294 map { $form->{"${_}_${row}"} = $item->{$_} } keys %{ $item };
1297 $form->{rowcount} = scalar @{ $form->{invoice_details} };
1299 delete @{$form}{qw(invoice_details paidaccounts storno paid)};
1301 # Restore the payment options from the user input.
1302 map { $form->{$_} = $payments{$_} } keys %payments;
1304 # Get the AP accno (which is normally done by Form::create_links()).
1308 LEFT JOIN chart c ON (at.chart_id = c.id)
1309 WHERE (trans_id = ?)
1310 AND ((c.link = 'AP') OR (c.link LIKE '%:AP') OR (c.link LIKE 'AP:%'))
1314 ($form->{AP}) = selectfirst_array_query($form, $dbh, $query, conv_i($form->{id}));
1316 # Post the new payments.
1317 $self->post_invoice($myconfig, $form, $dbh, 1);
1319 restore_form($old_form);
1321 my $rc = $dbh->commit();
1324 $main::lxdebug->leave_sub();