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);
727 $q_invdate = ", current_date AS invdate" unless $form->{id};
729 # get default accounts and last invoice number
733 (SELECT c.accno FROM chart c WHERE d.inventory_accno_id = c.id) AS inventory_accno,
734 (SELECT c.accno FROM chart c WHERE d.income_accno_id = c.id) AS income_accno,
735 (SELECT c.accno FROM chart c WHERE d.expense_accno_id = c.id) AS expense_accno,
736 (SELECT c.accno FROM chart c WHERE d.fxgain_accno_id = c.id) AS fxgain_accno,
737 (SELECT c.accno FROM chart c WHERE d.fxloss_accno_id = c.id) AS fxloss_accno,
741 $ref = selectfirst_hashref_query($form, $dbh, $query);
742 map { $form->{$_} = $ref->{$_} } keys %$ref;
746 $main::lxdebug->leave_sub();
753 qq|SELECT cp_id, invnumber, transdate AS invdate, duedate,
754 orddate, quodate, globalproject_id,
755 ordnumber, quonumber, paid, taxincluded, notes, taxzone_id, storno, gldate,
756 intnotes, curr AS currency
759 $ref = selectfirst_hashref_query($form, $dbh, $query, conv_i($form->{id}));
760 map { $form->{$_} = $ref->{$_} } keys %$ref;
762 $form->{exchangerate} = $form->get_exchangerate($dbh, $form->{currency}, $form->{invdate}, "sell");
765 $query = qq|SELECT * FROM shipto WHERE (trans_id = ?) AND (module = 'AP')|;
766 $ref = selectfirst_hashref_query($form, $dbh, $query, conv_i($form->{id}));
768 map { $form->{$_} = $ref->{$_} } keys %$ref;
770 my $transdate = $form->{invdate} ? $dbh->quote($form->{invdate}) : "current_date";
771 my $taxzone_id = $form->{taxzone_id} * 1;
773 $taxzone_id = 0 if ((3 < $taxzone_id) || (0 > $taxzone_id));
775 # retrieve individual items
778 c1.accno AS inventory_accno,
779 c1.new_chart_id AS inventory_new_chart,
780 date($transdate) - c1.valid_from AS inventory_valid,
782 c2.accno AS income_accno,
783 c2.new_chart_id AS income_new_chart,
784 date($transdate) - c2.valid_from AS income_valid,
786 c3.accno AS expense_accno,
787 c3.new_chart_id AS expense_new_chart,
788 date($transdate) - c3.valid_from AS expense_valid,
790 i.description, i.qty, i.fxsellprice AS sellprice,
791 i.parts_id AS id, i.unit, i.deliverydate, i.project_id, i.serialnumber,
793 p.partnumber, p.inventory_accno_id AS part_inventory_accno_id, p.bin,
798 JOIN parts p ON (i.parts_id = p.id)
799 LEFT JOIN chart c1 ON
800 ((SELECT inventory_accno_id
802 WHERE id = p.buchungsgruppen_id) = c1.id)
803 LEFT JOIN chart c2 ON
804 ((SELECT income_accno_id_${taxzone_id}
806 WHERE id = p.buchungsgruppen_id) = c2.id)
807 LEFT JOIN chart c3 ON
808 ((SELECT expense_accno_id_${taxzone_id}
810 WHERE id = p.buchungsgruppen_id) = c3.id)
811 LEFT JOIN project pr ON (i.project_id = pr.id)
812 LEFT JOIN partsgroup pg ON (pg.id = p.partsgroup_id)
817 $sth = prepare_execute_query($form, $dbh, $query, conv_i($form->{id}));
819 while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
820 if (!$ref->{"part_inventory_accno_id"}) {
821 map({ delete($ref->{$_}); } qw(inventory_accno inventory_new_chart inventory_valid));
823 delete($ref->{"part_inventory_accno_id"});
825 foreach my $type (qw(inventory income expense)) {
826 while ($ref->{"${type}_new_chart"} && ($ref->{"${type}_valid"} >=0)) {
828 qq|SELECT accno, new_chart_id, date($transdate) - valid_from
831 ($ref->{"${type}_accno"},
832 $ref->{"${type}_new_chart"},
833 $ref->{"${type}_valid"})
834 = selectrow_query($form, $dbh, $query, $ref->{"${type}_new_chart"});
838 # get tax rates and description
839 my $accno_id = ($form->{vc} eq "customer") ? $ref->{income_accno} : $ref->{expense_accno};
841 qq|SELECT c.accno, t.taxdescription, t.rate, t.taxnumber
843 LEFT JOIN chart c ON (c.id = t.chart_id)
851 AND (startdate <= $transdate)
852 ORDER BY startdate DESC
855 my $stw = prepare_execute_query($form, $dbh, $query, $accno_id);
856 $ref->{taxaccounts} = "";
859 while ($ptr = $stw->fetchrow_hashref(NAME_lc)) {
860 if (($ptr->{accno} eq "") && ($ptr->{rate} == 0)) {
865 $ref->{taxaccounts} .= "$ptr->{accno} ";
867 if (!($form->{taxaccounts} =~ /$ptr->{accno}/)) {
868 $form->{"$ptr->{accno}_rate"} = $ptr->{rate};
869 $form->{"$ptr->{accno}_description"} = $ptr->{taxdescription};
870 $form->{"$ptr->{accno}_taxnumber"} = $ptr->{taxnumber};
871 $form->{taxaccounts} .= "$ptr->{accno} ";
876 chop $ref->{taxaccounts};
877 push @{ $form->{invoice_details} }, $ref;
882 Common::webdav_folder($form) if ($main::webdav);
886 $main::lxdebug->leave_sub();
890 $main::lxdebug->enter_sub();
892 my ($self, $myconfig, $form) = @_;
894 # connect to database
895 my $dbh = $form->dbconnect($myconfig);
897 my $dateformat = $myconfig->{dateformat};
898 $dateformat .= "yy" if $myconfig->{dateformat} !~ /^y/;
900 my $vid = conv_i($form->{vendor_id});
904 ? "to_date(" . $dbh->quote($form->{invdate}) . ", '$dateformat')"
910 v.name AS vendor, v.creditlimit, v.terms, v.notes AS intnotes,
911 v.email, v.cc, v.bcc, v.language_id, v.payment_id,
912 v.street, v.zipcode, v.city, v.country, v.taxzone_id,
913 $duedate + COALESCE(pt.terms_netto, 0) AS duedate,
914 b.description AS business
916 LEFT JOIN business b ON (b.id = v.business_id)
917 LEFT JOIN payment_terms pt ON (v.payment_id = pt.id)
919 $ref = selectfirst_hashref_query($form, $dbh, $query, $vid);
920 map { $form->{$_} = $ref->{$_} } keys %$ref;
922 $form->{creditremaining} = $form->{creditlimit};
924 $query = qq|SELECT SUM(amount - paid) FROM ap WHERE vendor_id = ?|;
925 my ($unpaid_invoices) = selectfirst_array_query($form, $dbh, $query, $vid);
926 $form->{creditremaining} -= $unpaid_invoices;
928 $query = qq|SELECT o.amount,
931 WHERE (e.curr = o.curr)
932 AND (e.transdate = o.transdate)) AS exch
934 WHERE (o.vendor_id = ?) AND (o.quotation = '0') AND (o.closed = '0')|;
935 my $sth = prepare_execute_query($form, $dbh, $query, $vid);
936 while (my ($amount, $exch) = $sth->fetchrow_array()) {
937 $exch = 1 unless $exch;
938 $form->{creditremaining} -= $amount * $exch;
942 # get shipto if we do not convert an order or invoice
943 if (!$form->{shipto}) {
944 delete @{$form}{qw(shiptoname shiptostreet shiptozipcode shiptocity shiptocountry shiptocontact shiptophone shiptofax shiptoemail)};
946 $query = qq|SELECT * FROM shipto WHERE (trans_id = ?) AND (module= 'CT')|;
947 $ref = selectfirst_hashref_query($form, $dbh, $query, $vid);
948 @{$form}{keys %$ref} = @{$ref}{keys %$ref};
949 map { $form->{$_} = $ref->{$_} } keys %$ref;
952 if (!$form->{id} && $form->{type} !~ /_(order|quotation)/) {
953 # setup last accounts used
955 qq|SELECT c.id, c.accno, c.description, c.link, c.category
957 JOIN acc_trans ac ON (ac.chart_id = c.id)
958 JOIN ap a ON (a.id = ac.trans_id)
959 WHERE (a.vendor_id = ?)
960 AND (NOT ((c.link LIKE '%_tax%') OR (c.link LIKE '%_paid%')))
961 AND (a.id IN (SELECT max(a2.id) FROM ap a2 WHERE a2.vendor_id = ?))|;
962 my $refs = selectall_hashref_query($form, $dbh, $query, $vid, $vid);
966 if ($ref->{category} eq 'E') {
969 if ($form->{initial_transdate}) {
970 my $tax_query = qq|SELECT tk.tax_id, t.rate FROM taxkeys tk
971 LEFT JOIN tax t ON (tk.tax_id = t.id)
972 WHERE (tk.chart_id = ?) AND (startdate <= ?)
973 ORDER BY tk.startdate DESC
975 my ($tax_id, $rate) = selectrow_query($form, $dbh, $tax_query, $ref->{id}, $form->{initial_transdate});
976 $form->{"taxchart_$i"} = "${tax_id}--${rate}";
979 $form->{"AP_amount_$i"} = "$ref->{accno}--$tax_id";
982 if ($ref->{category} eq 'L') {
983 $form->{APselected} = $form->{AP_1} = $ref->{accno};
986 $form->{rowcount} = $i if ($i && !$form->{type});
991 $main::lxdebug->leave_sub();
995 $main::lxdebug->enter_sub();
997 my ($self, $myconfig, $form) = @_;
999 # connect to database
1000 my $dbh = $form->dbconnect($myconfig);
1002 my $i = $form->{rowcount};
1004 # don't include assemblies or obsolete parts
1005 my $where = "NOT p.assembly = '1' AND NOT p.obsolete = '1'";
1008 foreach my $table_column (qw(p.partnumber p.description pg.partsgroup)) {
1009 my $field = (split m{\.}, $table_column)[1];
1010 next unless $form->{"${field}_${i}"};
1011 $where .= " AND lower(${table_column}) LIKE lower(?)";
1012 push @values, '%' . $form->{"${field}_${i}"} . '%';
1015 if ($form->{"description_$i"}) {
1016 $where .= " ORDER BY p.description";
1018 $where .= " ORDER BY p.partnumber";
1022 if ($form->{type} eq "invoice") {
1023 $transdate = $form->{invdate} ? $dbh->quote($form->{invdate}) : "current_date";
1025 $transdate = $form->{transdate} ? $dbh->quote($form->{transdate}) : "current_date";
1028 my $taxzone_id = $form->{taxzone_id} * 1;
1029 $taxzone_id = 0 if ((3 < $taxzone_id) || (0 > $taxzone_id));
1033 p.id, p.partnumber, p.description, p.lastcost AS sellprice, p.listprice,
1034 p.unit, p.assembly, p.bin, p.onhand, p.formel,
1035 p.notes AS partnotes, p.notes AS longdescription, p.not_discountable,
1036 p.inventory_accno_id,
1038 c1.accno AS inventory_accno,
1039 c1.new_chart_id AS inventory_new_chart,
1040 date($transdate) - c1.valid_from AS inventory_valid,
1042 c2.accno AS income_accno,
1043 c2.new_chart_id AS income_new_chart,
1044 date($transdate) - c2.valid_from AS income_valid,
1046 c3.accno AS expense_accno,
1047 c3.new_chart_id AS expense_new_chart,
1048 date($transdate) - c3.valid_from AS expense_valid,
1053 LEFT JOIN chart c1 ON
1054 ((SELECT inventory_accno_id
1055 FROM buchungsgruppen
1056 WHERE id = p.buchungsgruppen_id) = c1.id)
1057 LEFT JOIN chart c2 ON
1058 ((SELECT income_accno_id_${taxzone_id}
1059 FROM buchungsgruppen
1060 WHERE id = p.buchungsgruppen_id) = c2.id)
1061 LEFT JOIN chart c3 ON
1062 ((SELECT expense_accno_id_${taxzone_id}
1063 FROM buchungsgruppen
1064 WHERE id = p.buchungsgruppen_id) = c3.id)
1065 LEFT JOIN partsgroup pg ON (pg.id = p.partsgroup_id)
1067 my $sth = prepare_execute_query($form, $dbh, $query, @values);
1069 $form->{item_list} = [];
1070 while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
1072 # In der Buchungsgruppe ist immer ein Bestandskonto verknuepft, auch wenn
1073 # es sich um eine Dienstleistung handelt. Bei Dienstleistungen muss das
1074 # Buchungskonto also aus dem Ergebnis rausgenommen werden.
1075 if (!$ref->{inventory_accno_id}) {
1076 map({ delete($ref->{"inventory_${_}"}); } qw(accno new_chart valid));
1078 delete($ref->{inventory_accno_id});
1080 # get tax rates and description
1081 $accno_id = ($form->{vc} eq "customer") ? $ref->{income_accno} : $ref->{expense_accno};
1083 qq|SELECT c.accno, t.taxdescription, t.rate, t.taxnumber
1085 LEFT JOIN chart c on (c.id = t.chart_id)
1093 AND (startdate <= $transdate)
1094 ORDER BY startdate DESC
1097 my $stw = prepare_execute_query($form, $dbh, $query, $accno_id);
1099 $ref->{taxaccounts} = "";
1101 while ($ptr = $stw->fetchrow_hashref(NAME_lc)) {
1103 # if ($customertax{$ref->{accno}}) {
1104 if (($ptr->{accno} eq "") && ($ptr->{rate} == 0)) {
1109 $ref->{taxaccounts} .= "$ptr->{accno} ";
1111 if (!($form->{taxaccounts} =~ /$ptr->{accno}/)) {
1112 $form->{"$ptr->{accno}_rate"} = $ptr->{rate};
1113 $form->{"$ptr->{accno}_description"} = $ptr->{taxdescription};
1114 $form->{"$ptr->{accno}_taxnumber"} = $ptr->{taxnumber};
1115 $form->{taxaccounts} .= "$ptr->{accno} ";
1121 chop $ref->{taxaccounts};
1123 push @{ $form->{item_list} }, $ref;
1130 $main::lxdebug->leave_sub();
1133 sub vendor_details {
1134 $main::lxdebug->enter_sub();
1136 my ($self, $myconfig, $form, @wanted_vars) = @_;
1138 # connect to database
1139 my $dbh = $form->dbconnect($myconfig);
1143 # get contact id, set it if nessessary
1144 $form->{cp_id} = (split /--/, $form->{contact})[1];
1146 if ($form->{cp_id}) {
1147 $contact = "AND cp.cp_id = ?";
1148 push @values, $form->{cp_id};
1151 # get rest for the vendor
1152 # fax and phone and email as vendor*
1154 qq|SELECT ct.*, cp.*, ct.notes as vendornotes, phone as vendorphone, fax as vendorfax, email as vendoremail
1156 LEFT JOIN contacts cp ON (ct.id = cp.cp_cv_id)
1157 WHERE (ct.id = ?) $contact
1160 my $ref = selectfirst_hashref_query($form, $dbh, $query, $form->{vendor_id}, @values);
1162 # remove id and taxincluded before copy back
1163 delete @$ref{qw(id taxincluded)};
1165 @wanted_vars = grep({ $_ } @wanted_vars);
1166 if (scalar(@wanted_vars) > 0) {
1168 map({ $h_wanted_vars{$_} = 1; } @wanted_vars);
1169 map({ delete($ref->{$_}) unless ($h_wanted_vars{$_}); } keys(%{$ref}));
1172 map { $form->{$_} = $ref->{$_} } keys %$ref;
1176 $main::lxdebug->leave_sub();
1180 $main::lxdebug->enter_sub();
1182 my ($self, $myconfig, $form) = @_;
1184 # connect to database
1185 my $dbh = $form->dbconnect($myconfig);
1188 qq|SELECT accno, description, link
1190 WHERE link LIKE '%IC%'
1192 my $sth = prepare_execute_query($query, $dbh, $query);
1194 while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
1195 foreach my $key (split(/:/, $ref->{link})) {
1197 push @{ $form->{IC_links}{$key} },
1198 { accno => $ref->{accno},
1199 description => $ref->{description} };
1207 $main::lxdebug->leave_sub();
1210 sub _delete_payments {
1211 $main::lxdebug->enter_sub();
1213 my ($self, $form, $dbh) = @_;
1217 # Delete old payment entries from acc_trans.
1221 WHERE (trans_id = ?) AND fx_transaction
1227 LEFT JOIN chart c ON (at.chart_id = c.id)
1228 WHERE (trans_id = ?) AND (c.link LIKE '%AP_paid%')|;
1229 push @delete_oids, selectall_array_query($form, $dbh, $query, conv_i($form->{id}), conv_i($form->{id}));
1234 LEFT JOIN chart c ON (at.chart_id = c.id)
1235 WHERE (trans_id = ?)
1236 AND ((c.link = 'AP') OR (c.link LIKE '%:AP') OR (c.link LIKE 'AP:%'))
1239 push @delete_oids, selectall_array_query($form, $dbh, $query, conv_i($form->{id}));
1242 $query = qq|DELETE FROM acc_trans WHERE oid IN (| . join(", ", @delete_oids) . qq|)|;
1243 do_query($form, $dbh, $query);
1246 $main::lxdebug->leave_sub();
1250 $main::lxdebug->enter_sub();
1252 my ($self, $myconfig, $form, $locale) = @_;
1254 # connect to database, turn off autocommit
1255 my $dbh = $form->dbconnect_noauto($myconfig);
1257 my (%payments, $old_form, $row, $item, $query, %keep_vars);
1259 $old_form = save_form();
1261 # Delete all entries in acc_trans from prior payments.
1262 $self->_delete_payments($form, $dbh);
1264 # Save the new payments the user made before cleaning up $form.
1265 map { $payments{$_} = $form->{$_} } grep m/^datepaid_\d+$|^memo_\d+$|^source_\d+$|^exchangerate_\d+$|^paid_\d+$|^AP_paid_\d+$|^paidaccounts$/, keys %{ $form };
1267 # Clean up $form so that old content won't tamper the results.
1268 %keep_vars = map { $_, 1 } qw(login password id);
1269 map { delete $form->{$_} unless $keep_vars{$_} } keys %{ $form };
1271 # Retrieve the invoice from the database.
1272 $self->retrieve_invoice($myconfig, $form);
1274 # Set up the content of $form in the way that IR::post_invoice() expects.
1275 $form->{exchangerate} = $form->format_amount($myconfig, $form->{exchangerate});
1277 for $row (1 .. scalar @{ $form->{invoice_details} }) {
1278 $item = $form->{invoice_details}->[$row - 1];
1280 map { $item->{$_} = $form->format_amount($myconfig, $item->{$_}) } qw(qty sellprice);
1282 map { $form->{"${_}_${row}"} = $item->{$_} } keys %{ $item };
1285 $form->{rowcount} = scalar @{ $form->{invoice_details} };
1287 delete @{$form}{qw(invoice_details paidaccounts storno paid)};
1289 # Restore the payment options from the user input.
1290 map { $form->{$_} = $payments{$_} } keys %payments;
1292 # Get the AP accno (which is normally done by Form::create_links()).
1296 LEFT JOIN chart c ON (at.chart_id = c.id)
1297 WHERE (trans_id = ?)
1298 AND ((c.link = 'AP') OR (c.link LIKE '%:AP') OR (c.link LIKE 'AP:%'))
1302 ($form->{AP}) = selectfirst_array_query($form, $dbh, $query, conv_i($form->{id}));
1304 # Post the new payments.
1305 $self->post_invoice($myconfig, $form, $dbh, 1);
1307 restore_form($old_form);
1309 my $rc = $dbh->commit();
1312 $main::lxdebug->leave_sub();