1 #=====================================================================
4 # Based on SQL-Ledger Version 2.1.9
5 # Web http://www.lx-office.org
7 #=====================================================================
8 # SQL-Ledger Accounting
11 # Author: Dieter Simader
12 # Email: dsimader@sql-ledger.org
13 # Web: http://www.sql-ledger.org
17 # This program is free software; you can redistribute it and/or modify
18 # it under the terms of the GNU General Public License as published by
19 # the Free Software Foundation; either version 2 of the License, or
20 # (at your option) any later version.
22 # This program is distributed in the hope that it will be useful,
23 # but WITHOUT ANY WARRANTY; without even the implied warranty of
24 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
25 # GNU General Public License for more details.
26 # You should have received a copy of the GNU General Public License
27 # along with this program; if not, write to the Free Software
28 # Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
29 #======================================================================
31 # Inventory received module
33 #======================================================================
41 use List::Util qw(min);
44 $main::lxdebug->enter_sub();
46 my ($self, $myconfig, $form, $provided_dbh, $payments_only) = @_;
48 # connect to database, turn off autocommit
49 my $dbh = $provided_dbh ? $provided_dbh : $form->dbconnect_noauto($myconfig);
50 $form->{defaultcurrency} = $form->get_default_currency($myconfig);
52 my ($query, $sth, @values, $project_id);
53 my ($allocated, $taxrate, $taxamount, $taxdiff, $item);
54 my ($amount, $linetotal, $lastinventoryaccno, $lastexpenseaccno);
55 my ($netamount, $invoicediff, $expensediff) = (0, 0, 0);
58 my $all_units = AM->retrieve_units($myconfig, $form);
60 if (!$payments_only) {
62 &reverse_invoice($dbh, $form);
64 ($form->{id}) = selectrow_query($form, $dbh, qq|SELECT nextval('glid')|);
65 do_query($form, $dbh, qq|INSERT INTO ap (id, invnumber) VALUES (?, '')|, $form->{id});
69 my ($currencies) = selectfirst_array_query($form, $dbh, qq|SELECT curr FROM defaults|);
70 my $defaultcurrency = (split m/:/, $currencies)[0];
72 if ($form->{currency} eq $defaultcurrency) {
73 $form->{exchangerate} = 1;
75 $exchangerate = $form->check_exchangerate($myconfig, $form->{currency}, $form->{transdate}, 'sell');
78 $form->{exchangerate} = $exchangerate || $form->parse_amount($myconfig, $form->{exchangerate});
79 $form->{exchangerate} = 1 unless ($form->{exchangerate} * 1);
82 my $q_item_unit = qq|SELECT unit FROM parts WHERE id = ?|;
83 my $h_item_unit = prepare_query($form, $dbh, $q_item_unit);
85 for my $i (1 .. $form->{rowcount}) {
86 next unless $form->{"id_$i"};
88 $form->{"qty_$i"} = $form->parse_amount($myconfig, $form->{"qty_$i"});
89 $form->{"qty_$i"} *= -1 if $form->{storno};
91 $form->{"inventory_accno_$i"} = $form->{"expense_accno_$i"} if $main::eur;
94 if (!$item_units{$form->{"id_$i"}}) {
95 do_statement($form, $h_item_unit, $q_item_unit, $form->{"id_$i"});
96 ($item_units{$form->{"id_$i"}}) = $h_item_unit->fetchrow_array();
99 my $item_unit = $item_units{$form->{"id_$i"}};
101 if (defined($all_units->{$item_unit}->{factor})
102 && ($all_units->{$item_unit}->{factor} ne '')
103 && ($all_units->{$item_unit}->{factor} * 1 != 0)) {
104 $basefactor = $all_units->{$form->{"unit_$i"}}->{factor} / $all_units->{$item_unit}->{factor};
108 $baseqty = $form->{"qty_$i"} * $basefactor;
110 @taxaccounts = split / /, $form->{"taxaccounts_$i"};
115 $form->{"sellprice_$i"} = $form->parse_amount($myconfig, $form->{"sellprice_$i"});
116 (my $fxsellprice = $form->{"sellprice_$i"}) =~ /\.(\d+)/;
118 my $decimalplaces = ($dec > 2) ? $dec : 2;
120 map { $taxrate += $form->{"${_}_rate"} } @taxaccounts;
122 if ($form->{"inventory_accno_$i"}) {
124 $linetotal = $form->round_amount($form->{"sellprice_$i"} * $form->{"qty_$i"}, 2);
126 if ($form->{taxincluded}) {
127 $taxamount = $linetotal * ($taxrate / (1 + $taxrate));
128 $form->{"sellprice_$i"} = $form->{"sellprice_$i"} * (1 / (1 + $taxrate));
130 $taxamount = $linetotal * $taxrate;
133 $netamount += $linetotal;
135 if ($form->round_amount($taxrate, 7) == 0) {
136 if ($form->{taxincluded}) {
137 foreach $item (@taxaccounts) {
139 $form->round_amount($linetotal * $form->{"${item}_rate"} / (1 + abs($form->{"${item}_rate"})), 2);
140 $taxdiff += $taxamount;
141 $form->{amount}{ $form->{id} }{$item} -= $taxamount;
143 $form->{amount}{ $form->{id} }{ $taxaccounts[0] } += $taxdiff;
146 map { $form->{amount}{ $form->{id} }{$_} -= $linetotal * $form->{"${_}_rate"} } @taxaccounts;
150 map { $form->{amount}{ $form->{id} }{$_} -= $taxamount * $form->{"${_}_rate"} / $taxrate } @taxaccounts;
153 # add purchase to inventory, this one is without the tax!
154 $amount = $form->{"sellprice_$i"} * $form->{"qty_$i"} * $form->{exchangerate};
155 $linetotal = $form->round_amount($form->{"sellprice_$i"} * $form->{"qty_$i"}, 2) * $form->{exchangerate};
156 $linetotal = $form->round_amount($linetotal, 2);
158 # this is the difference for the inventory
159 $invoicediff += ($amount - $linetotal);
161 $form->{amount}{ $form->{id} }{ $form->{"inventory_accno_$i"} } -= $linetotal;
163 # adjust and round sellprice
164 $form->{"sellprice_$i"} = $form->round_amount($form->{"sellprice_$i"} * $form->{exchangerate}, $decimalplaces);
166 $lastinventoryaccno = $form->{"inventory_accno_$i"};
168 next if $payments_only;
171 $query = qq|UPDATE parts SET lastcost = ? WHERE id = ?|;
172 @values = ($form->{"sellprice_$i"}, conv_i($form->{"id_$i"}));
173 do_query($form, $dbh, $query, @values);
175 $form->update_balance($dbh, "parts", "onhand", qq|id = ?|, $baseqty, $form->{"id_$i"}) if !$form->{shipped};
177 # check if we sold the item already and
178 # make an entry for the expense and inventory
180 qq|SELECT i.id, i.qty, i.allocated, i.trans_id,
181 p.inventory_accno_id, p.expense_accno_id, a.transdate
182 FROM invoice i, ar a, parts p
183 WHERE (i.parts_id = p.id)
185 AND ((i.base_qty + i.allocated) > 0)
186 AND (i.trans_id = a.id)
188 $sth = prepare_execute_query($form, $dbh, $query, conv_i($form->{"id_$i"}));
190 my $totalqty = $base_qty;
192 while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
193 my $qty = min $totalqty, ($ref->{base_qty} + $ref->{allocated});
194 $linetotal = $form->round_amount(($form->{"sellprice_$i"} * $qty) / $basefactor, 2);
196 if ($ref->{allocated} < 0) {
198 # we have an entry for it already, adjust amount
199 $form->update_balance($dbh, "acc_trans", "amount",
200 qq| (trans_id = $ref->{trans_id})
201 AND (chart_id = $ref->{inventory_accno_id})
202 AND (transdate = '$ref->{transdate}')|,
205 $form->update_balance($dbh, "acc_trans", "amount",
206 qq| (trans_id = $ref->{trans_id})
207 AND (chart_id = $ref->{expense_accno_id})
208 AND (transdate = '$ref->{transdate}')|,
211 } elsif ($linetotal != 0) {
212 # add entry for inventory, this one is for the sold item
213 $query = qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate, taxkey) VALUES (?, ?, ?, ?, (SELECT taxkey_id FROM chart WHERE id = ?))|;
214 @values = ($ref->{trans_id}, $ref->{inventory_accno_id}, $linetotal, $ref->{transdate}, $ref->{inventory_accno_id});
215 do_query($form, $dbh, $query, @values);
218 $query = qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate, taxkey) VALUES (?, ?, ?, ?, (SELECT taxkey from tax WHERE chart_id = ?))|;
219 @values = ($ref->{trans_id}, $ref->{expense_accno_id}, ($linetotal * -1), $ref->{transdate}, $ref->{expense_accno_id});
220 do_query($form, $dbh, $query, @values);
223 # update allocated for sold item
224 $form->update_balance($dbh, "invoice", "allocated", qq|id = $ref->{id}|, $qty * -1);
228 last if ($totalqty -= $qty) <= 0;
235 $linetotal = $form->round_amount($form->{"sellprice_$i"} * $form->{"qty_$i"}, 2);
237 if ($form->{taxincluded}) {
238 $taxamount = $linetotal * ($taxrate / (1 + $taxrate));
239 $form->{"sellprice_$i"} = $form->{"sellprice_$i"} * (1 / (1 + $taxrate));
242 $taxamount = $linetotal * $taxrate;
245 $netamount += $linetotal;
247 if ($form->round_amount($taxrate, 7) == 0) {
248 if ($form->{taxincluded}) {
249 foreach $item (@taxaccounts) {
250 $taxamount = $linetotal * $form->{"${item}_rate"} / (1 + abs($form->{"${item}_rate"}));
251 $totaltax += $taxamount;
252 $form->{amount}{ $form->{id} }{$item} -= $taxamount;
255 map { $form->{amount}{ $form->{id} }{$_} -= $linetotal * $form->{"${_}_rate"} } @taxaccounts;
258 map { $form->{amount}{ $form->{id} }{$_} -= $taxamount * $form->{"${_}_rate"} / $taxrate } @taxaccounts;
261 $amount = $form->{"sellprice_$i"} * $form->{"qty_$i"} * $form->{exchangerate};
262 $linetotal = $form->round_amount($form->{"sellprice_$i"} * $form->{"qty_$i"}, 2) * $form->{exchangerate};
263 $linetotal = $form->round_amount($linetotal, 2);
265 # this is the difference for expense
266 $expensediff += ($amount - $linetotal);
268 # add amount to expense
269 $form->{amount}{ $form->{id} }{ $form->{"expense_accno_$i"} } -= $linetotal;
271 $lastexpenseaccno = $form->{"expense_accno_$i"};
273 # adjust and round sellprice
274 $form->{"sellprice_$i"} = $form->round_amount($form->{"sellprice_$i"} * $form->{exchangerate}, $decimalplaces);
276 next if $payments_only;
279 $query = qq|UPDATE parts SET lastcost = ? WHERE id = ?|;
280 do_query($form, $dbh, $query, $form->{"sellprice_$i"}, conv_i($form->{"id_$i"}));
283 next if $payments_only;
285 # save detail record in invoice table
287 qq|INSERT INTO invoice (trans_id, parts_id, description, qty, base_qty,
288 sellprice, fxsellprice, allocated, unit, deliverydate,
289 project_id, serialnumber)
290 VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)|;
291 @values = (conv_i($form->{id}), conv_i($form->{"id_$i"}),
292 $form->{"description_$i"}, $form->{"qty_$i"} * -1,
293 $baseqty * -1, $form->{"sellprice_$i"}, $fxsellprice, $allocated,
294 $form->{"unit_$i"}, conv_date($form->{deliverydate}),
295 conv_i($form->{"project_id_$i"}), $form->{"serialnumber_$i"});
296 do_query($form, $dbh, $query, @values);
299 $h_item_unit->finish();
301 my $project_id = conv_i($form->{"globalproject_id"});
303 $form->{datepaid} = $form->{invdate};
305 # all amounts are in natural state, netamount includes the taxes
306 # if tax is included, netamount is rounded to 2 decimal places,
310 for my $i (1 .. $form->{paidaccounts}) {
311 $form->{"paid_$i"} = $form->parse_amount($myconfig, $form->{"paid_$i"});
312 $form->{paid} += $form->{"paid_$i"};
313 $form->{datepaid} = $form->{"datepaid_$i"} if $form->{"datepaid_$i"};
316 my ($tax, $paiddiff) = (0, 0);
318 $netamount = $form->round_amount($netamount, 2);
320 # figure out rounding errors for amount paid and total amount
321 if ($form->{taxincluded}) {
323 $amount = $form->round_amount($netamount * $form->{exchangerate}, 2);
324 $paiddiff = $amount - $netamount * $form->{exchangerate};
325 $netamount = $amount;
327 foreach $item (split / /, $form->{taxaccounts}) {
328 $amount = $form->{amount}{ $form->{id} }{$item} * $form->{exchangerate};
329 $form->{amount}{ $form->{id} }{$item} = $form->round_amount($amount, 2);
331 $amount = $form->{amount}{ $form->{id} }{$item} * -1;
333 $netamount -= $amount;
336 $invoicediff += $paiddiff;
337 $expensediff += $paiddiff;
339 ######## this only applies to tax included
341 $form->{amount}{ $form->{id} }{$lastinventoryaccno} -= $invoicediff if $lastinventoryaccno;
342 $form->{amount}{ $form->{id} }{$lastexpenseaccno} -= $expensediff if $lastexpenseaccno;
345 $amount = $form->round_amount($netamount * $form->{exchangerate}, 2);
346 $paiddiff = $amount - $netamount * $form->{exchangerate};
347 $netamount = $amount;
349 foreach my $item (split / /, $form->{taxaccounts}) {
350 $form->{amount}{ $form->{id} }{$item} = $form->round_amount($form->{amount}{ $form->{id} }{$item}, 2);
351 $amount = $form->round_amount( $form->{amount}{ $form->{id} }{$item} * $form->{exchangerate} * -1, 2);
352 $paiddiff += $amount - $form->{amount}{ $form->{id} }{$item} * $form->{exchangerate} * -1;
353 $form->{amount}{ $form->{id} }{$item} = $form->round_amount($amount * -1, 2);
354 $amount = $form->{amount}{ $form->{id} }{$item} * -1;
359 $form->{amount}{ $form->{id} }{ $form->{AP} } = $netamount + $tax;
362 $form->{paid} = $form->round_amount($form->{paid} * $form->{exchangerate} + $paiddiff, 2) if $form->{paid} != 0;
364 # update exchangerate
366 $form->update_exchangerate($dbh, $form->{currency}, $form->{invdate}, 0, $form->{exchangerate})
367 if ($form->{currency} ne $defaultcurrency) && !$exchangerate;
369 # record acc_trans transactions
370 foreach my $trans_id (keys %{ $form->{amount} }) {
371 foreach my $accno (keys %{ $form->{amount}{$trans_id} }) {
372 $form->{amount}{$trans_id}{$accno} = $form->round_amount($form->{amount}{$trans_id}{$accno}, 2);
374 next if $payments_only || !$form->{amount}{$trans_id}{$accno};
376 $query = qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate, taxkey, project_id)
377 VALUES (?, (SELECT id FROM chart WHERE accno = ?), ?, ?,
378 (SELECT taxkey_id FROM chart WHERE accno = ?), ?)|;
379 @values = ($trans_id, $accno, $form->{amount}{$trans_id}{$accno},
380 conv_date($form->{invdate}), $accno, $project_id);
381 do_query($form, $dbh, $query, @values);
385 # deduct payment differences from paiddiff
386 for my $i (1 .. $form->{paidaccounts}) {
387 if ($form->{"paid_$i"} != 0) {
388 $amount = $form->round_amount($form->{"paid_$i"} * $form->{exchangerate}, 2);
389 $paiddiff -= $amount - $form->{"paid_$i"} * $form->{exchangerate};
393 # force AP entry if 0
395 $form->{amount}{ $form->{id} }{ $form->{AP} } = $form->{paid} if $form->{amount}{$form->{id}}{$form->{AP}} == 0;
397 # record payments and offsetting AP
398 for my $i (1 .. $form->{paidaccounts}) {
399 next if $form->{"paid_$i"} == 0;
401 my ($accno) = split /--/, $form->{"AP_paid_$i"};
402 $form->{"datepaid_$i"} = $form->{invdate} unless ($form->{"datepaid_$i"});
403 $form->{datepaid} = $form->{"datepaid_$i"};
405 $amount = $form->round_amount($form->{"paid_$i"} * $form->{exchangerate} + $paiddiff, 2) * -1;
408 if ($form->{amount}{ $form->{id} }{ $form->{AP} } != 0) {
409 $query = qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate, taxkey, project_id)
410 VALUES (?, (SELECT id FROM chart WHERE accno = ?), ?, ?,
411 (SELECT taxkey_id FROM chart WHERE accno = ?), ?)|;
412 @values = (conv_i($form->{id}), $form->{AP}, $amount,
413 $form->{"datepaid_$i"}, $form->{AP}, $project_id);
414 do_query($form, $dbh, $query, @values);
418 $query = qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate, source, memo, taxkey, project_id)
419 VALUES (?, (SELECT id FROM chart WHERE accno = ?), ?, ?, ?, ?,
420 (SELECT taxkey_id FROM chart WHERE accno = ?), ?)|;
421 @values = (conv_i($form->{id}), $accno, $form->{"paid_$i"}, $form->{"datepaid_$i"},
422 $form->{"source_$i"}, $form->{"memo_$i"}, $accno, $project_id);
423 do_query($form, $dbh, $query, @values);
427 if ($form->{currency} eq $defaultcurrency) {
428 $form->{"exchangerate_$i"} = 1;
430 $exchangerate = $form->check_exchangerate($myconfig, $form->{currency}, $form->{"datepaid_$i"}, 'sell');
431 $form->{"exchangerate_$i"} = $exchangerate || $form->parse_amount($myconfig, $form->{"exchangerate_$i"});
434 # exchangerate difference
435 $form->{fx}{$accno}{ $form->{"datepaid_$i"} } += $form->{"paid_$i"} * ($form->{"exchangerate_$i"} - 1) + $paiddiff;
439 ($form->{"paid_$i"} * $form->{exchangerate}) -
440 ($form->{"paid_$i"} * $form->{"exchangerate_$i"});
442 $form->{fx}{ $form->{fxgain_accno} }{ $form->{"datepaid_$i"} } += $amount;
444 $form->{fx}{ $form->{fxloss_accno} }{ $form->{"datepaid_$i"} } += $amount;
449 # update exchange rate
450 $form->update_exchangerate($dbh, $form->{currency}, $form->{"datepaid_$i"}, 0, $form->{"exchangerate_$i"})
451 if ($form->{currency} ne $defaultcurrency) && !$exchangerate;
454 # record exchange rate differences and gains/losses
455 foreach my $accno (keys %{ $form->{fx} }) {
456 foreach my $transdate (keys %{ $form->{fx}{$accno} }) {
457 $form->{fx}{$accno}{$transdate} = $form->round_amount($form->{fx}{$accno}{$transdate}, 2);
458 next if ($form->{fx}{$accno}{$transdate} == 0);
460 $query = qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate, cleared, fx_transaction, taxkey, project_id)
461 VALUES (?, (SELECT id FROM chart WHERE accno = ?), ?, ?, '0', '1', 0, ?)|;
462 @values = (conv_i($form->{id}), $accno, $form->{fx}{$accno}{$transdate}, conv_date($transdate), $project_id);
463 do_query($form, $dbh, $query, @values);
467 if ($payments_only) {
468 $query = qq|UPDATE ap SET paid = ?, datepaid = ? WHERE id = ?|;
469 do_query($form, $dbh, $query, $form->{paid}, $form->{paid} ? conv_date($form->{datepaid}) : undef, conv_i($form->{id}));
471 if (!$provided_dbh) {
476 $main::lxdebug->leave_sub();
480 $amount = $netamount + $tax;
482 # set values which could be empty
483 my $taxzone_id = $form->{taxzone_id} * 1;
484 $form->{department_id} = (split /--/, $form->{department})[1];
485 $form->{invnumber} = $form->{id} unless $form->{invnumber};
487 $taxzone_id = 0 if (3 < $taxzone_id) || (0 > $taxzone_id);
490 $query = qq|UPDATE ap SET
491 invnumber = ?, ordnumber = ?, quonumber = ?, transdate = ?,
492 orddate = ?, quodate = ?, vendor_id = ?, amount = ?,
493 netamount = ?, paid = ?, duedate = ?, datepaid = ?,
494 invoice = ?, taxzone_id = ?, notes = ?, taxincluded = ?,
495 intnotes = ?, curr = ?, storno_id = ?, storno = ?,
496 cp_id = ?, employee_id = ?, department_id = ?,
500 $form->{invnumber}, $form->{ordnumber}, $form->{quonumber}, conv_date($form->{invdate}),
501 conv_date($form->{orddate}), conv_date($form->{quodate}), conv_i($form->{vendor_id}), $amount,
502 $netamount, $form->{paid}, conv_date($form->{duedate}), $form->{paid} ? conv_date($form->{datepaid}) : undef,
503 '1', $taxzone_id, $form->{notes}, $form->{taxincluded} ? 't' : 'f',
504 $form->{intnotes}, $form->{currency}, conv_i($form->{storno_id}), $form->{storno} ? 't' : 'f',
505 conv_i($form->{cp_id}), conv_i($form->{employee_id}), conv_i($form->{department_id}),
506 conv_i($form->{globalproject_id}),
509 do_query($form, $dbh, $query, @values);
511 if ($form->{storno}) {
512 $query = qq|UPDATE ap SET paid = paid + amount WHERE id = ?|;
513 do_query($form, $dbh, $query, conv_i($form->{storno_id}));
515 $query = qq|UPDATE ap SET storno = 't' WHERE id = ?|;
516 do_query($form, $dbh, $query, conv_i($form->{storno_id}));
518 $query = qq!UPDATE ap SET intnotes = ? || intnotes WHERE id = ?!;
519 do_query($form, $dbh, $query, 'Rechnung storniert am $form->{invdate} ', conv_i($form->{storno_id}));
521 $query = qq|UPDATE ap SET paid = amount WHERE id = ?|;
522 do_query($form, $dbh, $query, conv_i($form->{id}));
527 $form->{name} = $form->{vendor};
528 $form->{name} =~ s/--$form->{vendor_id}//;
529 $form->add_shipto($dbh, $form->{id}, "AP");
531 # delete zero entries
532 do_query($form, $dbh, qq|DELETE FROM acc_trans WHERE amount = 0|);
534 Common::webdav_folder($form) if ($main::webdav);
538 if (!$provided_dbh) {
539 $rc = $dbh->commit();
543 $main::lxdebug->leave_sub();
548 sub reverse_invoice {
549 $main::lxdebug->enter_sub();
551 my ($dbh, $form) = @_;
553 # reverse inventory items
555 qq|SELECT i.parts_id, p.inventory_accno_id, p.expense_accno_id, i.qty, i.allocated, i.sellprice
556 FROM invoice i, parts p
557 WHERE (i.parts_id = p.id)
558 AND (i.trans_id = ?)|;
559 my $sth = prepare_execute_query($form, $dbh, $query, conv_i($form->{id}));
563 while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
564 $netamount += $form->round_amount($ref->{sellprice} * $ref->{qty} * -1, 2);
566 next unless $ref->{inventory_accno_id};
569 $form->update_balance($dbh, "parts", "onhand", qq|id = $ref->{parts_id}|, $ref->{qty});
571 # if $ref->{allocated} > 0 than we sold that many items
572 next if ($ref->{allocated} <= 0);
574 # get references for sold items
576 qq|SELECT i.id, i.trans_id, i.allocated, a.transdate
578 WHERE (i.parts_id = ?)
579 AND (i.allocated < 0)
580 AND (i.trans_id = a.id)
581 ORDER BY transdate DESC|;
582 my $sth2 = prepare_execute_query($form, $dbh, $query, $ref->{parts_id});
584 while (my $pthref = $sth2->fetchrow_hashref(NAME_lc)) {
585 my $qty = $ref->{allocated};
586 if (($ref->{allocated} + $pthref->{allocated}) > 0) {
587 $qty = $pthref->{allocated} * -1;
590 my $amount = $form->round_amount($ref->{sellprice} * $qty, 2);
593 $form->update_balance($dbh, "invoice", "allocated", qq|id = $pthref->{id}|, $qty);
595 $form->update_balance($dbh, "acc_trans", "amount",
596 qq| (trans_id = $pthref->{trans_id})
597 AND (chart_id = $ref->{expense_accno_id})
598 AND (transdate = '$pthref->{transdate}')|,
601 $form->update_balance($dbh, "acc_trans", "amount",
602 qq| (trans_id = $pthref->{trans_id})
603 AND (chart_id = $ref->{inventory_accno_id})
604 AND (transdate = '$pthref->{transdate}')|,
607 last if (($ref->{allocated} -= $qty) <= 0);
613 my $id = conv_i($form->{id});
616 $query = qq|DELETE FROM acc_trans WHERE trans_id = ?|;
617 do_query($form, $dbh, $query, $id);
619 # delete invoice entries
620 $query = qq|DELETE FROM invoice WHERE trans_id = ?|;
621 do_query($form, $dbh, $query, $id);
623 $query = qq|DELETE FROM shipto WHERE (trans_id = ?) AND (module = 'AP')|;
624 do_query($form, $dbh, $query, $id);
626 $main::lxdebug->leave_sub();
630 $main::lxdebug->enter_sub();
632 my ($self, $myconfig, $form) = @_;
634 # connect to database
635 my $dbh = $form->dbconnect_noauto($myconfig);
637 &reverse_invoice($dbh, $form);
639 # delete zero entries
640 my $query = qq|DELETE FROM acc_trans WHERE amount = 0|;
641 do_query($form, $dbh, $query);
644 my $query = qq|DELETE FROM ap WHERE id = ?|;
645 do_query($form, $dbh, $query, conv_i($form->{id}));
647 my $rc = $dbh->commit;
650 $main::lxdebug->leave_sub();
655 sub retrieve_invoice {
656 $main::lxdebug->enter_sub();
658 my ($self, $myconfig, $form) = @_;
660 # connect to database
661 my $dbh = $form->dbconnect($myconfig);
663 my ($query, $sth, $ref, $q_invdate);
666 $q_invdate = qq|, COALESCE((SELECT transdate FROM ar WHERE id = (SELECT MAX(id) FROM ar)), current_date) AS invdate|;
667 if ($form->{vendor_id}) {
668 my $vendor_id = $dbh->quote($form->{vendor_id} * 1);
670 qq|, COALESCE((SELECT transdate FROM ar WHERE id = (SELECT MAX(id) FROM ar)), current_date) +
671 COALESCE((SELECT pt.terms_netto
673 LEFT JOIN payment_terms pt ON (v.payment_id = pt.id)
674 WHERE v.id = $vendor_id),
679 # get default accounts and last invoice number
683 (SELECT c.accno FROM chart c WHERE d.inventory_accno_id = c.id) AS inventory_accno,
684 (SELECT c.accno FROM chart c WHERE d.income_accno_id = c.id) AS income_accno,
685 (SELECT c.accno FROM chart c WHERE d.expense_accno_id = c.id) AS expense_accno,
686 (SELECT c.accno FROM chart c WHERE d.fxgain_accno_id = c.id) AS fxgain_accno,
687 (SELECT c.accno FROM chart c WHERE d.fxloss_accno_id = c.id) AS fxloss_accno,
691 $ref = selectfirst_hashref_query($form, $dbh, $query);
692 map { $form->{$_} = $ref->{$_} } keys %$ref;
696 $main::lxdebug->leave_sub();
703 qq|SELECT cp_id, invnumber, transdate AS invdate, duedate,
704 orddate, quodate, globalproject_id,
705 ordnumber, quonumber, paid, taxincluded, notes, taxzone_id, storno, gldate,
706 intnotes, curr AS currency
709 $ref = selectfirst_hashref_query($form, $dbh, $query, conv_i($form->{id}));
710 map { $form->{$_} = $ref->{$_} } keys %$ref;
712 $form->{exchangerate} = $form->get_exchangerate($dbh, $form->{currency}, $form->{invdate}, "sell");
715 $query = qq|SELECT * FROM shipto WHERE (trans_id = ?) AND (module = 'AP')|;
716 $ref = selectfirst_hashref_query($form, $dbh, $query, conv_i($form->{id}));
718 map { $form->{$_} = $ref->{$_} } keys %$ref;
720 my $transdate = $form->{invdate} ? $dbh->quote($form->{invdate}) : "current_date";
721 my $taxzone_id = $form->{taxzone_id} * 1;
723 $taxzone_id = 0 if ((3 < $taxzone_id) || (0 > $taxzone_id));
725 # retrieve individual items
728 c1.accno AS inventory_accno,
729 c1.new_chart_id AS inventory_new_chart,
730 date($transdate) - c1.valid_from AS inventory_valid,
732 c2.accno AS income_accno,
733 c2.new_chart_id AS income_new_chart,
734 date($transdate) - c2.valid_from AS income_valid,
736 c3.accno AS expense_accno,
737 c3.new_chart_id AS expense_new_chart,
738 date($transdate) - c3.valid_from AS expense_valid,
740 i.description, i.qty, i.fxsellprice AS sellprice,
741 i.parts_id AS id, i.unit, i.deliverydate, i.project_id, i.serialnumber,
743 p.partnumber, p.inventory_accno_id AS part_inventory_accno_id, p.bin,
748 JOIN parts p ON (i.parts_id = p.id)
749 LEFT JOIN chart c1 ON
750 ((SELECT inventory_accno_id
752 WHERE id = p.buchungsgruppen_id) = c1.id)
753 LEFT JOIN chart c2 ON
754 ((SELECT income_accno_id_${taxzone_id}
756 WHERE id = p.buchungsgruppen_id) = c2.id)
757 LEFT JOIN chart c3 ON
758 ((SELECT expense_accno_id_${taxzone_id}
760 WHERE id = p.buchungsgruppen_id) = c3.id)
761 LEFT JOIN project pr ON (i.project_id = pr.id)
762 LEFT JOIN partsgroup pg ON (pg.id = p.partsgroup_id)
767 $sth = prepare_execute_query($form, $dbh, $query, conv_i($form->{id}));
769 while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
770 if (!$ref->{"part_inventory_accno_id"}) {
771 map({ delete($ref->{$_}); } qw(inventory_accno inventory_new_chart inventory_valid));
773 delete($ref->{"part_inventory_accno_id"});
775 foreach my $type (qw(inventory income expense)) {
776 while ($ref->{"${type}_new_chart"} && ($ref->{"${type}_valid"} >=0)) {
778 qq|SELECT accno, new_chart_id, date($transdate) - valid_from
781 ($ref->{"${type}_accno"},
782 $ref->{"${type}_new_chart"},
783 $ref->{"${type}_valid"})
784 = selectrow_query($form, $dbh, $query, $ref->{"${type}_new_chart"});
788 # get tax rates and description
789 my $accno_id = ($form->{vc} eq "customer") ? $ref->{income_accno} : $ref->{expense_accno};
791 qq|SELECT c.accno, t.taxdescription, t.rate, t.taxnumber
793 LEFT JOIN chart c ON (c.id = t.chart_id)
801 AND (startdate <= $transdate)
802 ORDER BY startdate DESC
805 my $stw = prepare_execute_query($form, $dbh, $query, $accno_id);
806 $ref->{taxaccounts} = "";
809 while ($ptr = $stw->fetchrow_hashref(NAME_lc)) {
810 if (($ptr->{accno} eq "") && ($ptr->{rate} == 0)) {
815 $ref->{taxaccounts} .= "$ptr->{accno} ";
817 if (!($form->{taxaccounts} =~ /$ptr->{accno}/)) {
818 $form->{"$ptr->{accno}_rate"} = $ptr->{rate};
819 $form->{"$ptr->{accno}_description"} = $ptr->{taxdescription};
820 $form->{"$ptr->{accno}_taxnumber"} = $ptr->{taxnumber};
821 $form->{taxaccounts} .= "$ptr->{accno} ";
826 chop $ref->{taxaccounts};
827 push @{ $form->{invoice_details} }, $ref;
832 Common::webdav_folder($form) if ($main::webdav);
836 $main::lxdebug->leave_sub();
840 $main::lxdebug->enter_sub();
842 my ($self, $myconfig, $form) = @_;
844 # connect to database
845 my $dbh = $form->dbconnect($myconfig);
847 my $dateformat = $myconfig->{dateformat};
848 $dateformat .= "yy" if $myconfig->{dateformat} !~ /^y/;
850 my $vid = conv_i($form->{vendor_id});
854 ? "to_date(" . $dbh->quote($form->{invdate}) . ", '$dateformat')"
860 v.name AS vendor, v.creditlimit, v.terms, v.notes AS intnotes,
861 v.email, v.cc, v.bcc, v.language_id, v.payment_id,
862 v.street, v.zipcode, v.city, v.country, v.taxzone_id,
863 $duedate + COALESCE(pt.terms_netto, 0) AS duedate,
864 b.description AS business
866 LEFT JOIN business b ON (b.id = v.business_id)
867 LEFT JOIN payment_terms pt ON (v.payment_id = pt.id)
869 $ref = selectfirst_hashref_query($form, $dbh, $query, $vid);
870 map { $form->{$_} = $ref->{$_} } keys %$ref;
872 $form->{creditremaining} = $form->{creditlimit};
874 $query = qq|SELECT SUM(amount - paid) FROM ap WHERE vendor_id = ?|;
875 my ($unpaid_invoices) = selectfirst_array_query($form, $dbh, $query, $vid);
876 $form->{creditremaining} -= $unpaid_invoices;
878 $query = qq|SELECT o.amount,
881 WHERE (e.curr = o.curr)
882 AND (e.transdate = o.transdate)) AS exch
884 WHERE (o.vendor_id = ?) AND (o.quotation = '0') AND (o.closed = '0')|;
885 my $sth = prepare_execute_query($form, $dbh, $query, $vid);
886 while (my ($amount, $exch) = $sth->fetchrow_array()) {
887 $exch = 1 unless $exch;
888 $form->{creditremaining} -= $amount * $exch;
892 # get shipto if we do not convert an order or invoice
893 if (!$form->{shipto}) {
894 delete @{$form}{qw(shiptoname shiptostreet shiptozipcode shiptocity shiptocountry shiptocontact shiptophone shiptofax shiptoemail)};
896 $query = qq|SELECT * FROM shipto WHERE (trans_id = ?) AND (module= 'CT')|;
897 $ref = selectfirst_hashref_query($form, $dbh, $query, $vid);
898 @{$form}{keys %$ref} = @{$ref}{keys %$ref};
899 map { $form->{$_} = $ref->{$_} } keys %$ref;
902 if (!$form->{id} && $form->{type} !~ /_(order|quotation)/) {
903 # setup last accounts used
905 qq|SELECT c.id, c.accno, c.description, c.link, c.category
907 JOIN acc_trans ac ON (ac.chart_id = c.id)
908 JOIN ap a ON (a.id = ac.trans_id)
909 WHERE (a.vendor_id = ?)
910 AND (NOT ((c.link LIKE '%_tax%') OR (c.link LIKE '%_paid%')))
911 AND (a.id IN (SELECT max(a2.id) FROM ap a2 WHERE a2.vendor_id = ?))|;
912 my $refs = selectall_hashref_query($form, $dbh, $query, $vid, $vid);
916 if ($ref->{category} eq 'E') {
919 if ($form->{initial_transdate}) {
920 my $tax_query = qq|SELECT tk.tax_id, t.rate FROM taxkeys tk
921 LEFT JOIN tax t ON (tk.tax_id = t.id)
922 WHERE (tk.chart_id = ?) AND (startdate <= ?)
923 ORDER BY tk.startdate DESC
925 my ($tax_id, $rate) = selectrow_query($form, $dbh, $tax_query, $ref->{id}, $form->{initial_transdate});
926 $form->{"taxchart_$i"} = "${tax_id}--${rate}";
929 $form->{"AP_amount_$i"} = "$ref->{accno}--$tax_id";
932 if ($ref->{category} eq 'L') {
933 $form->{APselected} = $form->{AP_1} = $ref->{accno};
936 $form->{rowcount} = $i if ($i && !$form->{type});
941 $main::lxdebug->leave_sub();
945 $main::lxdebug->enter_sub();
947 my ($self, $myconfig, $form) = @_;
949 # connect to database
950 my $dbh = $form->dbconnect($myconfig);
952 my $i = $form->{rowcount};
954 # don't include assemblies or obsolete parts
955 my $where = "NOT p.assembly = '1' AND NOT p.obsolete = '1'";
958 foreach my $table_column (qw(p.partnumber p.description pg.partsgroup)) {
959 my $field = (split m{\.}, $table_column)[1];
960 next unless $form->{"${field}_${i}"};
961 $where .= " AND lower(${table_column}) LIKE lower(?)";
962 push @values, '%' . $form->{"${field}_${i}"} . '%';
965 if ($form->{"description_$i"}) {
966 $where .= " ORDER BY p.description";
968 $where .= " ORDER BY p.partnumber";
972 if ($form->{type} eq "invoice") {
973 $transdate = $form->{invdate} ? $dbh->quote($form->{invdate}) : "current_date";
975 $transdate = $form->{transdate} ? $dbh->quote($form->{transdate}) : "current_date";
978 my $taxzone_id = $form->{taxzone_id} * 1;
979 $taxzone_id = 0 if ((3 < $taxzone_id) || (0 > $taxzone_id));
983 p.id, p.partnumber, p.description, p.lastcost AS sellprice, p.listprice,
984 p.unit, p.assembly, p.bin, p.onhand, p.formel,
985 p.notes AS partnotes, p.notes AS longdescription, p.not_discountable,
986 p.inventory_accno_id,
988 c1.accno AS inventory_accno,
989 c1.new_chart_id AS inventory_new_chart,
990 date($transdate) - c1.valid_from AS inventory_valid,
992 c2.accno AS income_accno,
993 c2.new_chart_id AS income_new_chart,
994 date($transdate) - c2.valid_from AS income_valid,
996 c3.accno AS expense_accno,
997 c3.new_chart_id AS expense_new_chart,
998 date($transdate) - c3.valid_from AS expense_valid,
1003 LEFT JOIN chart c1 ON
1004 ((SELECT inventory_accno_id
1005 FROM buchungsgruppen
1006 WHERE id = p.buchungsgruppen_id) = c1.id)
1007 LEFT JOIN chart c2 ON
1008 ((SELECT income_accno_id_${taxzone_id}
1009 FROM buchungsgruppen
1010 WHERE id = p.buchungsgruppen_id) = c2.id)
1011 LEFT JOIN chart c3 ON
1012 ((SELECT expense_accno_id_${taxzone_id}
1013 FROM buchungsgruppen
1014 WHERE id = p.buchungsgruppen_id) = c3.id)
1015 LEFT JOIN partsgroup pg ON (pg.id = p.partsgroup_id)
1017 my $sth = prepare_execute_query($form, $dbh, $query, @values);
1019 $form->{item_list} = [];
1020 while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
1022 # In der Buchungsgruppe ist immer ein Bestandskonto verknuepft, auch wenn
1023 # es sich um eine Dienstleistung handelt. Bei Dienstleistungen muss das
1024 # Buchungskonto also aus dem Ergebnis rausgenommen werden.
1025 if (!$ref->{inventory_accno_id}) {
1026 map({ delete($ref->{"inventory_${_}"}); } qw(accno new_chart valid));
1028 delete($ref->{inventory_accno_id});
1030 # get tax rates and description
1031 $accno_id = ($form->{vc} eq "customer") ? $ref->{income_accno} : $ref->{expense_accno};
1033 qq|SELECT c.accno, t.taxdescription, t.rate, t.taxnumber
1035 LEFT JOIN chart c on (c.id = t.chart_id)
1043 AND (startdate <= $transdate)
1044 ORDER BY startdate DESC
1047 my $stw = prepare_execute_query($form, $dbh, $query, $accno_id);
1049 $ref->{taxaccounts} = "";
1051 while ($ptr = $stw->fetchrow_hashref(NAME_lc)) {
1053 # if ($customertax{$ref->{accno}}) {
1054 if (($ptr->{accno} eq "") && ($ptr->{rate} == 0)) {
1059 $ref->{taxaccounts} .= "$ptr->{accno} ";
1061 if (!($form->{taxaccounts} =~ /$ptr->{accno}/)) {
1062 $form->{"$ptr->{accno}_rate"} = $ptr->{rate};
1063 $form->{"$ptr->{accno}_description"} = $ptr->{taxdescription};
1064 $form->{"$ptr->{accno}_taxnumber"} = $ptr->{taxnumber};
1065 $form->{taxaccounts} .= "$ptr->{accno} ";
1071 chop $ref->{taxaccounts};
1073 push @{ $form->{item_list} }, $ref;
1080 $main::lxdebug->leave_sub();
1083 sub vendor_details {
1084 $main::lxdebug->enter_sub();
1086 my ($self, $myconfig, $form, @wanted_vars) = @_;
1088 # connect to database
1089 my $dbh = $form->dbconnect($myconfig);
1093 # get contact id, set it if nessessary
1094 $form->{cp_id} = (split /--/, $form->{contact})[1];
1096 if ($form->{cp_id}) {
1097 $contact = "AND cp.cp_id = ?";
1098 push @values, $form->{cp_id};
1101 # get rest for the vendor
1102 # fax and phone and email as vendor*
1104 qq|SELECT ct.*, cp.*, ct.notes as vendornotes, phone as vendorphone, fax as vendorfax, email as vendoremail
1106 LEFT JOIN contacts cp ON (ct.id = cp.cp_cv_id)
1107 WHERE (ct.id = ?) $contact
1110 my $ref = selectfirst_hashref_query($form, $dbh, $query, $form->{vendor_id}, @values);
1112 # remove id and taxincluded before copy back
1113 delete @$ref{qw(id taxincluded)};
1115 @wanted_vars = grep({ $_ } @wanted_vars);
1116 if (scalar(@wanted_vars) > 0) {
1118 map({ $h_wanted_vars{$_} = 1; } @wanted_vars);
1119 map({ delete($ref->{$_}) unless ($h_wanted_vars{$_}); } keys(%{$ref}));
1122 map { $form->{$_} = $ref->{$_} } keys %$ref;
1126 $main::lxdebug->leave_sub();
1130 $main::lxdebug->enter_sub();
1132 my ($self, $myconfig, $form) = @_;
1134 # connect to database
1135 my $dbh = $form->dbconnect($myconfig);
1138 qq|SELECT accno, description, link
1140 WHERE link LIKE '%IC%'
1142 my $sth = prepare_execute_query($query, $dbh, $query);
1144 while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
1145 foreach my $key (split(/:/, $ref->{link})) {
1147 push @{ $form->{IC_links}{$key} },
1148 { accno => $ref->{accno},
1149 description => $ref->{description} };
1157 $main::lxdebug->leave_sub();
1160 sub _delete_payments {
1161 $main::lxdebug->enter_sub();
1163 my ($self, $form, $dbh) = @_;
1167 # Delete old payment entries from acc_trans.
1171 WHERE (trans_id = ?) AND fx_transaction
1177 LEFT JOIN chart c ON (at.chart_id = c.id)
1178 WHERE (trans_id = ?) AND (c.link LIKE '%AP_paid%')|;
1179 push @delete_oids, selectall_array_query($form, $dbh, $query, conv_i($form->{id}), conv_i($form->{id}));
1184 LEFT JOIN chart c ON (at.chart_id = c.id)
1185 WHERE (trans_id = ?)
1186 AND ((c.link = 'AP') OR (c.link LIKE '%:AP') OR (c.link LIKE 'AP:%'))
1189 push @delete_oids, selectall_array_query($form, $dbh, $query, conv_i($form->{id}));
1192 $query = qq|DELETE FROM acc_trans WHERE oid IN (| . join(", ", @delete_oids) . qq|)|;
1193 do_query($form, $dbh, $query);
1196 $main::lxdebug->leave_sub();
1200 $main::lxdebug->enter_sub();
1202 my ($self, $myconfig, $form, $locale) = @_;
1204 # connect to database, turn off autocommit
1205 my $dbh = $form->dbconnect_noauto($myconfig);
1207 my (%payments, $old_form, $row, $item, $query, %keep_vars);
1209 $old_form = save_form();
1211 # Delete all entries in acc_trans from prior payments.
1212 $self->_delete_payments($form, $dbh);
1214 # Save the new payments the user made before cleaning up $form.
1215 map { $payments{$_} = $form->{$_} } grep m/^datepaid_\d+$|^memo_\d+$|^source_\d+$|^exchangerate_\d+$|^paid_\d+$|^AP_paid_\d+$|^paidaccounts$/, keys %{ $form };
1217 # Clean up $form so that old content won't tamper the results.
1218 %keep_vars = map { $_, 1 } qw(login password id);
1219 map { delete $form->{$_} unless $keep_vars{$_} } keys %{ $form };
1221 # Retrieve the invoice from the database.
1222 $self->retrieve_invoice($myconfig, $form);
1224 # Set up the content of $form in the way that IR::post_invoice() expects.
1225 $form->{exchangerate} = $form->format_amount($myconfig, $form->{exchangerate});
1227 for $row (1 .. scalar @{ $form->{invoice_details} }) {
1228 $item = $form->{invoice_details}->[$row - 1];
1230 map { $item->{$_} = $form->format_amount($myconfig, $item->{$_}) } qw(qty sellprice);
1232 map { $form->{"${_}_${row}"} = $item->{$_} } keys %{ $item };
1235 $form->{rowcount} = scalar @{ $form->{invoice_details} };
1237 delete @{$form}{qw(invoice_details paidaccounts storno paid)};
1239 # Restore the payment options from the user input.
1240 map { $form->{$_} = $payments{$_} } keys %payments;
1242 # Get the AP accno (which is normally done by Form::create_links()).
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:%'))
1252 ($form->{AP}) = selectfirst_array_query($form, $dbh, $query, conv_i($form->{id}));
1254 # Post the new payments.
1255 $self->post_invoice($myconfig, $form, $dbh, 1);
1257 restore_form($old_form);
1259 my $rc = $dbh->commit();
1262 $main::lxdebug->leave_sub();