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 $form->get_lists('price_factors' => 'ALL_PRICE_FACTORS');
86 my %price_factors = map { $_->{id} => $_->{factor} } @{ $form->{ALL_PRICE_FACTORS} };
89 for my $i (1 .. $form->{rowcount}) {
90 next unless $form->{"id_$i"};
92 $form->{"qty_$i"} = $form->parse_amount($myconfig, $form->{"qty_$i"});
93 $form->{"qty_$i"} *= -1 if $form->{storno};
95 $form->{"inventory_accno_$i"} = $form->{"expense_accno_$i"} if $main::eur;
98 if (!$item_units{$form->{"id_$i"}}) {
99 do_statement($form, $h_item_unit, $q_item_unit, $form->{"id_$i"});
100 ($item_units{$form->{"id_$i"}}) = $h_item_unit->fetchrow_array();
103 my $item_unit = $item_units{$form->{"id_$i"}};
105 if (defined($all_units->{$item_unit}->{factor})
106 && ($all_units->{$item_unit}->{factor} ne '')
107 && ($all_units->{$item_unit}->{factor} * 1 != 0)) {
108 $basefactor = $all_units->{$form->{"unit_$i"}}->{factor} / $all_units->{$item_unit}->{factor};
112 $baseqty = $form->{"qty_$i"} * $basefactor;
114 @taxaccounts = split / /, $form->{"taxaccounts_$i"};
119 $form->{"sellprice_$i"} = $form->parse_amount($myconfig, $form->{"sellprice_$i"});
120 (my $fxsellprice = $form->{"sellprice_$i"}) =~ /\.(\d+)/;
122 my $decimalplaces = ($dec > 2) ? $dec : 2;
124 map { $taxrate += $form->{"${_}_rate"} } @taxaccounts;
126 $price_factor = $price_factors{ $form->{"price_factor_id_$i"} } || 1;
128 if ($form->{"inventory_accno_$i"}) {
130 $linetotal = $form->round_amount($form->{"sellprice_$i"} * $form->{"qty_$i"} / $price_factor, 2);
132 if ($form->{taxincluded}) {
133 $taxamount = $linetotal * ($taxrate / (1 + $taxrate));
134 $form->{"sellprice_$i"} = $form->{"sellprice_$i"} * (1 / (1 + $taxrate));
136 $taxamount = $linetotal * $taxrate;
139 $netamount += $linetotal;
141 if ($form->round_amount($taxrate, 7) == 0) {
142 if ($form->{taxincluded}) {
143 foreach $item (@taxaccounts) {
145 $form->round_amount($linetotal * $form->{"${item}_rate"} / (1 + abs($form->{"${item}_rate"})), 2);
146 $taxdiff += $taxamount;
147 $form->{amount}{ $form->{id} }{$item} -= $taxamount;
149 $form->{amount}{ $form->{id} }{ $taxaccounts[0] } += $taxdiff;
152 map { $form->{amount}{ $form->{id} }{$_} -= $linetotal * $form->{"${_}_rate"} } @taxaccounts;
156 map { $form->{amount}{ $form->{id} }{$_} -= $taxamount * $form->{"${_}_rate"} / $taxrate } @taxaccounts;
159 # add purchase to inventory, this one is without the tax!
160 $amount = $form->{"sellprice_$i"} * $form->{"qty_$i"} * $form->{exchangerate} / $price_factor;
161 $linetotal = $form->round_amount($form->{"sellprice_$i"} * $form->{"qty_$i"} / $price_factor, 2) * $form->{exchangerate};
162 $linetotal = $form->round_amount($linetotal, 2);
164 # this is the difference for the inventory
165 $invoicediff += ($amount - $linetotal);
167 $form->{amount}{ $form->{id} }{ $form->{"inventory_accno_$i"} } -= $linetotal;
169 # adjust and round sellprice
170 $form->{"sellprice_$i"} = $form->round_amount($form->{"sellprice_$i"} * $form->{exchangerate}, $decimalplaces);
172 $lastinventoryaccno = $form->{"inventory_accno_$i"};
174 next if $payments_only;
177 $query = qq|UPDATE parts SET lastcost = ? WHERE id = ?|;
178 @values = ($form->{"sellprice_$i"}, conv_i($form->{"id_$i"}));
179 do_query($form, $dbh, $query, @values);
181 # check if we sold the item already and
182 # make an entry for the expense and inventory
184 qq|SELECT i.id, i.qty, i.allocated, i.trans_id,
185 p.inventory_accno_id, p.expense_accno_id, a.transdate
186 FROM invoice i, ar a, parts p
187 WHERE (i.parts_id = p.id)
189 AND ((i.base_qty + i.allocated) > 0)
190 AND (i.trans_id = a.id)
192 $sth = prepare_execute_query($form, $dbh, $query, conv_i($form->{"id_$i"}));
194 my $totalqty = $base_qty;
196 while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
197 my $qty = min $totalqty, ($ref->{base_qty} + $ref->{allocated});
198 $linetotal = $form->round_amount(($form->{"sellprice_$i"} * $qty) / $basefactor, 2);
200 if ($ref->{allocated} < 0) {
202 # we have an entry for it already, adjust amount
203 $form->update_balance($dbh, "acc_trans", "amount",
204 qq| (trans_id = $ref->{trans_id})
205 AND (chart_id = $ref->{inventory_accno_id})
206 AND (transdate = '$ref->{transdate}')|,
209 $form->update_balance($dbh, "acc_trans", "amount",
210 qq| (trans_id = $ref->{trans_id})
211 AND (chart_id = $ref->{expense_accno_id})
212 AND (transdate = '$ref->{transdate}')|,
215 } elsif ($linetotal != 0) {
216 # add entry for inventory, this one is for the sold item
217 $query = qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate, taxkey) VALUES (?, ?, ?, ?, (SELECT taxkey_id FROM chart WHERE id = ?))|;
218 @values = ($ref->{trans_id}, $ref->{inventory_accno_id}, $linetotal, $ref->{transdate}, $ref->{inventory_accno_id});
219 do_query($form, $dbh, $query, @values);
222 $query = qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate, taxkey) VALUES (?, ?, ?, ?, (SELECT taxkey from tax WHERE chart_id = ?))|;
223 @values = ($ref->{trans_id}, $ref->{expense_accno_id}, ($linetotal * -1), $ref->{transdate}, $ref->{expense_accno_id});
224 do_query($form, $dbh, $query, @values);
227 # update allocated for sold item
228 $form->update_balance($dbh, "invoice", "allocated", qq|id = $ref->{id}|, $qty * -1);
232 last if ($totalqty -= $qty) <= 0;
237 } else { # if ($form->{"inventory_accno_id_$i"})
239 $linetotal = $form->round_amount($form->{"sellprice_$i"} * $form->{"qty_$i"} / $price_factor, 2);
241 if ($form->{taxincluded}) {
242 $taxamount = $linetotal * ($taxrate / (1 + $taxrate));
243 $form->{"sellprice_$i"} = $form->{"sellprice_$i"} * (1 / (1 + $taxrate));
246 $taxamount = $linetotal * $taxrate;
249 $netamount += $linetotal;
251 if ($form->round_amount($taxrate, 7) == 0) {
252 if ($form->{taxincluded}) {
253 foreach $item (@taxaccounts) {
254 $taxamount = $linetotal * $form->{"${item}_rate"} / (1 + abs($form->{"${item}_rate"}));
255 $totaltax += $taxamount;
256 $form->{amount}{ $form->{id} }{$item} -= $taxamount;
259 map { $form->{amount}{ $form->{id} }{$_} -= $linetotal * $form->{"${_}_rate"} } @taxaccounts;
262 map { $form->{amount}{ $form->{id} }{$_} -= $taxamount * $form->{"${_}_rate"} / $taxrate } @taxaccounts;
265 $amount = $form->{"sellprice_$i"} * $form->{"qty_$i"} * $form->{exchangerate} / $price_factor;
266 $linetotal = $form->round_amount($form->{"sellprice_$i"} * $form->{"qty_$i"} / $price_factor, 2) * $form->{exchangerate};
267 $linetotal = $form->round_amount($linetotal, 2);
269 # this is the difference for expense
270 $expensediff += ($amount - $linetotal);
272 # add amount to expense
273 $form->{amount}{ $form->{id} }{ $form->{"expense_accno_$i"} } -= $linetotal;
275 $lastexpenseaccno = $form->{"expense_accno_$i"};
277 # adjust and round sellprice
278 $form->{"sellprice_$i"} = $form->round_amount($form->{"sellprice_$i"} * $form->{exchangerate}, $decimalplaces);
280 next if $payments_only;
283 $query = qq|UPDATE parts SET lastcost = ? WHERE id = ?|;
284 do_query($form, $dbh, $query, $form->{"sellprice_$i"}, conv_i($form->{"id_$i"}));
287 next if $payments_only;
289 # save detail record in invoice table
291 qq|INSERT INTO invoice (trans_id, parts_id, description, qty, base_qty,
292 sellprice, fxsellprice, allocated, unit, deliverydate,
293 project_id, serialnumber, price_factor_id, price_factor, marge_price_factor)
294 VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, (SELECT factor FROM price_factors WHERE id = ?), ?)|;
295 @values = (conv_i($form->{id}), conv_i($form->{"id_$i"}),
296 $form->{"description_$i"}, $form->{"qty_$i"} * -1,
297 $baseqty * -1, $form->{"sellprice_$i"}, $fxsellprice, $allocated,
298 $form->{"unit_$i"}, conv_date($form->{deliverydate}),
299 conv_i($form->{"project_id_$i"}), $form->{"serialnumber_$i"},
300 conv_i($form->{"price_factor_id_$i"}), conv_i($form->{"price_factor_id_$i"}), conv_i($form->{"marge_price_factor_$i"}));
301 do_query($form, $dbh, $query, @values);
304 $h_item_unit->finish();
306 $project_id = conv_i($form->{"globalproject_id"});
308 $form->{datepaid} = $form->{invdate};
310 # all amounts are in natural state, netamount includes the taxes
311 # if tax is included, netamount is rounded to 2 decimal places,
315 for my $i (1 .. $form->{paidaccounts}) {
316 $form->{"paid_$i"} = $form->parse_amount($myconfig, $form->{"paid_$i"});
317 $form->{paid} += $form->{"paid_$i"};
318 $form->{datepaid} = $form->{"datepaid_$i"} if $form->{"datepaid_$i"};
321 my ($tax, $paiddiff) = (0, 0);
323 $netamount = $form->round_amount($netamount, 2);
325 # figure out rounding errors for amount paid and total amount
326 if ($form->{taxincluded}) {
328 $amount = $form->round_amount($netamount * $form->{exchangerate}, 2);
329 $paiddiff = $amount - $netamount * $form->{exchangerate};
330 $netamount = $amount;
332 foreach $item (split / /, $form->{taxaccounts}) {
333 $amount = $form->{amount}{ $form->{id} }{$item} * $form->{exchangerate};
334 $form->{amount}{ $form->{id} }{$item} = $form->round_amount($amount, 2);
336 $amount = $form->{amount}{ $form->{id} }{$item} * -1;
338 $netamount -= $amount;
341 $invoicediff += $paiddiff;
342 $expensediff += $paiddiff;
344 ######## this only applies to tax included
346 $form->{amount}{ $form->{id} }{$lastinventoryaccno} -= $invoicediff if $lastinventoryaccno;
347 $form->{amount}{ $form->{id} }{$lastexpenseaccno} -= $expensediff if $lastexpenseaccno;
350 $amount = $form->round_amount($netamount * $form->{exchangerate}, 2);
351 $paiddiff = $amount - $netamount * $form->{exchangerate};
352 $netamount = $amount;
354 foreach my $item (split / /, $form->{taxaccounts}) {
355 $form->{amount}{ $form->{id} }{$item} = $form->round_amount($form->{amount}{ $form->{id} }{$item}, 2);
356 $amount = $form->round_amount( $form->{amount}{ $form->{id} }{$item} * $form->{exchangerate} * -1, 2);
357 $paiddiff += $amount - $form->{amount}{ $form->{id} }{$item} * $form->{exchangerate} * -1;
358 $form->{amount}{ $form->{id} }{$item} = $form->round_amount($amount * -1, 2);
359 $amount = $form->{amount}{ $form->{id} }{$item} * -1;
364 $form->{amount}{ $form->{id} }{ $form->{AP} } = $netamount + $tax;
367 $form->{paid} = $form->round_amount($form->{paid} * $form->{exchangerate} + $paiddiff, 2) if $form->{paid} != 0;
369 # update exchangerate
371 $form->update_exchangerate($dbh, $form->{currency}, $form->{invdate}, 0, $form->{exchangerate})
372 if ($form->{currency} ne $defaultcurrency) && !$exchangerate;
374 # record acc_trans transactions
375 foreach my $trans_id (keys %{ $form->{amount} }) {
376 foreach my $accno (keys %{ $form->{amount}{$trans_id} }) {
377 $form->{amount}{$trans_id}{$accno} = $form->round_amount($form->{amount}{$trans_id}{$accno}, 2);
379 next if $payments_only || !$form->{amount}{$trans_id}{$accno};
381 $query = qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate, taxkey, project_id)
382 VALUES (?, (SELECT id FROM chart WHERE accno = ?), ?, ?,
383 (SELECT taxkey_id FROM chart WHERE accno = ?), ?)|;
384 @values = ($trans_id, $accno, $form->{amount}{$trans_id}{$accno},
385 conv_date($form->{invdate}), $accno, $project_id);
386 do_query($form, $dbh, $query, @values);
390 # deduct payment differences from paiddiff
391 for my $i (1 .. $form->{paidaccounts}) {
392 if ($form->{"paid_$i"} != 0) {
393 $amount = $form->round_amount($form->{"paid_$i"} * $form->{exchangerate}, 2);
394 $paiddiff -= $amount - $form->{"paid_$i"} * $form->{exchangerate};
398 # force AP entry if 0
400 $form->{amount}{ $form->{id} }{ $form->{AP} } = $form->{paid} if $form->{amount}{$form->{id}}{$form->{AP}} == 0;
402 # record payments and offsetting AP
403 for my $i (1 .. $form->{paidaccounts}) {
404 next if $form->{"paid_$i"} == 0;
406 my ($accno) = split /--/, $form->{"AP_paid_$i"};
407 $form->{"datepaid_$i"} = $form->{invdate} unless ($form->{"datepaid_$i"});
408 $form->{datepaid} = $form->{"datepaid_$i"};
410 $amount = $form->round_amount($form->{"paid_$i"} * $form->{exchangerate} + $paiddiff, 2) * -1;
413 if ($form->{amount}{ $form->{id} }{ $form->{AP} } != 0) {
414 $query = qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate, taxkey, project_id)
415 VALUES (?, (SELECT id FROM chart WHERE accno = ?), ?, ?,
416 (SELECT taxkey_id FROM chart WHERE accno = ?), ?)|;
417 @values = (conv_i($form->{id}), $form->{AP}, $amount,
418 $form->{"datepaid_$i"}, $form->{AP}, $project_id);
419 do_query($form, $dbh, $query, @values);
423 $query = qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate, source, memo, taxkey, project_id)
424 VALUES (?, (SELECT id FROM chart WHERE accno = ?), ?, ?, ?, ?,
425 (SELECT taxkey_id FROM chart WHERE accno = ?), ?)|;
426 @values = (conv_i($form->{id}), $accno, $form->{"paid_$i"}, $form->{"datepaid_$i"},
427 $form->{"source_$i"}, $form->{"memo_$i"}, $accno, $project_id);
428 do_query($form, $dbh, $query, @values);
432 if ($form->{currency} eq $defaultcurrency) {
433 $form->{"exchangerate_$i"} = 1;
435 $exchangerate = $form->check_exchangerate($myconfig, $form->{currency}, $form->{"datepaid_$i"}, 'sell');
436 $form->{"exchangerate_$i"} = $exchangerate || $form->parse_amount($myconfig, $form->{"exchangerate_$i"});
439 # exchangerate difference
440 $form->{fx}{$accno}{ $form->{"datepaid_$i"} } += $form->{"paid_$i"} * ($form->{"exchangerate_$i"} - 1) + $paiddiff;
444 ($form->{"paid_$i"} * $form->{exchangerate}) -
445 ($form->{"paid_$i"} * $form->{"exchangerate_$i"});
447 $form->{fx}{ $form->{fxgain_accno} }{ $form->{"datepaid_$i"} } += $amount;
449 $form->{fx}{ $form->{fxloss_accno} }{ $form->{"datepaid_$i"} } += $amount;
454 # update exchange rate
455 $form->update_exchangerate($dbh, $form->{currency}, $form->{"datepaid_$i"}, 0, $form->{"exchangerate_$i"})
456 if ($form->{currency} ne $defaultcurrency) && !$exchangerate;
459 # record exchange rate differences and gains/losses
460 foreach my $accno (keys %{ $form->{fx} }) {
461 foreach my $transdate (keys %{ $form->{fx}{$accno} }) {
462 $form->{fx}{$accno}{$transdate} = $form->round_amount($form->{fx}{$accno}{$transdate}, 2);
463 next if ($form->{fx}{$accno}{$transdate} == 0);
465 $query = qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate, cleared, fx_transaction, taxkey, project_id)
466 VALUES (?, (SELECT id FROM chart WHERE accno = ?), ?, ?, '0', '1', 0, ?)|;
467 @values = (conv_i($form->{id}), $accno, $form->{fx}{$accno}{$transdate}, conv_date($transdate), $project_id);
468 do_query($form, $dbh, $query, @values);
472 if ($payments_only) {
473 $query = qq|UPDATE ap SET paid = ?, datepaid = ? WHERE id = ?|;
474 do_query($form, $dbh, $query, $form->{paid}, $form->{paid} ? conv_date($form->{datepaid}) : undef, conv_i($form->{id}));
476 if (!$provided_dbh) {
481 $main::lxdebug->leave_sub();
485 $amount = $netamount + $tax;
487 # set values which could be empty
488 my $taxzone_id = $form->{taxzone_id} * 1;
489 $form->{department_id} = (split /--/, $form->{department})[1];
490 $form->{invnumber} = $form->{id} unless $form->{invnumber};
492 $taxzone_id = 0 if (3 < $taxzone_id) || (0 > $taxzone_id);
495 $query = qq|UPDATE ap SET
496 invnumber = ?, ordnumber = ?, quonumber = ?, transdate = ?,
497 orddate = ?, quodate = ?, vendor_id = ?, amount = ?,
498 netamount = ?, paid = ?, duedate = ?, datepaid = ?,
499 invoice = ?, taxzone_id = ?, notes = ?, taxincluded = ?,
500 intnotes = ?, curr = ?, storno_id = ?, storno = ?,
501 cp_id = ?, employee_id = ?, department_id = ?,
505 $form->{invnumber}, $form->{ordnumber}, $form->{quonumber}, conv_date($form->{invdate}),
506 conv_date($form->{orddate}), conv_date($form->{quodate}), conv_i($form->{vendor_id}), $amount,
507 $netamount, $form->{paid}, conv_date($form->{duedate}), $form->{paid} ? conv_date($form->{datepaid}) : undef,
508 '1', $taxzone_id, $form->{notes}, $form->{taxincluded} ? 't' : 'f',
509 $form->{intnotes}, $form->{currency}, conv_i($form->{storno_id}), $form->{storno} ? 't' : 'f',
510 conv_i($form->{cp_id}), conv_i($form->{employee_id}), conv_i($form->{department_id}),
511 conv_i($form->{globalproject_id}),
514 do_query($form, $dbh, $query, @values);
516 if ($form->{storno}) {
517 $query = qq|UPDATE ap SET paid = paid + amount WHERE id = ?|;
518 do_query($form, $dbh, $query, conv_i($form->{storno_id}));
520 $query = qq|UPDATE ap SET storno = 't' WHERE id = ?|;
521 do_query($form, $dbh, $query, conv_i($form->{storno_id}));
523 $query = qq!UPDATE ap SET intnotes = ? || intnotes WHERE id = ?!;
524 do_query($form, $dbh, $query, 'Rechnung storniert am $form->{invdate} ', conv_i($form->{storno_id}));
526 $query = qq|UPDATE ap SET paid = amount WHERE id = ?|;
527 do_query($form, $dbh, $query, conv_i($form->{id}));
532 $form->{name} = $form->{vendor};
533 $form->{name} =~ s/--\Q$form->{vendor_id}\E//;
534 $form->add_shipto($dbh, $form->{id}, "AP");
536 # delete zero entries
537 do_query($form, $dbh, qq|DELETE FROM acc_trans WHERE amount = 0|);
539 Common::webdav_folder($form) if ($main::webdav);
543 if (!$provided_dbh) {
544 $rc = $dbh->commit();
548 $main::lxdebug->leave_sub();
553 sub reverse_invoice {
554 $main::lxdebug->enter_sub();
556 my ($dbh, $form) = @_;
558 # reverse inventory items
560 qq|SELECT i.parts_id, p.inventory_accno_id, p.expense_accno_id, i.qty, i.allocated, i.sellprice
561 FROM invoice i, parts p
562 WHERE (i.parts_id = p.id)
563 AND (i.trans_id = ?)|;
564 my $sth = prepare_execute_query($form, $dbh, $query, conv_i($form->{id}));
568 while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
569 $netamount += $form->round_amount($ref->{sellprice} * $ref->{qty} * -1, 2);
571 next unless $ref->{inventory_accno_id};
573 # if $ref->{allocated} > 0 than we sold that many items
574 next if ($ref->{allocated} <= 0);
576 # get references for sold items
578 qq|SELECT i.id, i.trans_id, i.allocated, a.transdate
580 WHERE (i.parts_id = ?)
581 AND (i.allocated < 0)
582 AND (i.trans_id = a.id)
583 ORDER BY transdate DESC|;
584 my $sth2 = prepare_execute_query($form, $dbh, $query, $ref->{parts_id});
586 while (my $pthref = $sth2->fetchrow_hashref(NAME_lc)) {
587 my $qty = $ref->{allocated};
588 if (($ref->{allocated} + $pthref->{allocated}) > 0) {
589 $qty = $pthref->{allocated} * -1;
592 my $amount = $form->round_amount($ref->{sellprice} * $qty, 2);
595 $form->update_balance($dbh, "invoice", "allocated", qq|id = $pthref->{id}|, $qty);
597 $form->update_balance($dbh, "acc_trans", "amount",
598 qq| (trans_id = $pthref->{trans_id})
599 AND (chart_id = $ref->{expense_accno_id})
600 AND (transdate = '$pthref->{transdate}')|,
603 $form->update_balance($dbh, "acc_trans", "amount",
604 qq| (trans_id = $pthref->{trans_id})
605 AND (chart_id = $ref->{inventory_accno_id})
606 AND (transdate = '$pthref->{transdate}')|,
609 last if (($ref->{allocated} -= $qty) <= 0);
615 my $id = conv_i($form->{id});
618 $query = qq|DELETE FROM acc_trans WHERE trans_id = ?|;
619 do_query($form, $dbh, $query, $id);
621 # delete invoice entries
622 $query = qq|DELETE FROM invoice WHERE trans_id = ?|;
623 do_query($form, $dbh, $query, $id);
625 $query = qq|DELETE FROM shipto WHERE (trans_id = ?) AND (module = 'AP')|;
626 do_query($form, $dbh, $query, $id);
628 $main::lxdebug->leave_sub();
632 $main::lxdebug->enter_sub();
634 my ($self, $myconfig, $form) = @_;
636 # connect to database
637 my $dbh = $form->dbconnect_noauto($myconfig);
639 &reverse_invoice($dbh, $form);
641 # delete zero entries
642 $query = qq|DELETE FROM acc_trans WHERE amount = 0|;
643 do_query($form, $dbh, $query);
646 $query = qq|DELETE FROM ap WHERE id = ?|;
647 do_query($form, $dbh, $query, conv_i($form->{id}));
649 my $rc = $dbh->commit;
652 $main::lxdebug->leave_sub();
657 sub retrieve_invoice {
658 $main::lxdebug->enter_sub();
660 my ($self, $myconfig, $form) = @_;
662 # connect to database
663 my $dbh = $form->dbconnect($myconfig);
665 my ($query, $sth, $ref, $q_invdate);
668 $q_invdate = qq|, COALESCE((SELECT transdate FROM ar WHERE id = (SELECT MAX(id) FROM ar)), current_date) AS invdate|;
669 if ($form->{vendor_id}) {
670 my $vendor_id = $dbh->quote($form->{vendor_id} * 1);
672 qq|, COALESCE((SELECT transdate FROM ar WHERE id = (SELECT MAX(id) FROM ar)), current_date) +
673 COALESCE((SELECT pt.terms_netto
675 LEFT JOIN payment_terms pt ON (v.payment_id = pt.id)
676 WHERE v.id = $vendor_id),
681 # get default accounts and last invoice number
684 (SELECT c.accno FROM chart c WHERE d.inventory_accno_id = c.id) AS inventory_accno,
685 (SELECT c.accno FROM chart c WHERE d.income_accno_id = c.id) AS income_accno,
686 (SELECT c.accno FROM chart c WHERE d.expense_accno_id = c.id) AS expense_accno,
687 (SELECT c.accno FROM chart c WHERE d.fxgain_accno_id = c.id) AS fxgain_accno,
688 (SELECT c.accno FROM chart c WHERE d.fxloss_accno_id = c.id) AS fxloss_accno,
692 $ref = selectfirst_hashref_query($form, $dbh, $query);
693 map { $form->{$_} = $ref->{$_} } keys %$ref;
697 $main::lxdebug->leave_sub();
703 $query = 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, c1.new_chart_id AS inventory_new_chart, date($transdate) - c1.valid_from AS inventory_valid,
729 c2.accno AS income_accno, c2.new_chart_id AS income_new_chart, date($transdate) - c2.valid_from AS income_valid,
730 c3.accno AS expense_accno, c3.new_chart_id AS expense_new_chart, date($transdate) - c3.valid_from AS expense_valid,
732 i.description, i.qty, i.fxsellprice AS sellprice, i.parts_id AS id, i.unit, i.deliverydate, i.project_id, i.serialnumber,
733 i.price_factor_id, i.price_factor, i.marge_price_factor,
734 p.partnumber, p.inventory_accno_id AS part_inventory_accno_id, p.bin, pr.projectnumber, pg.partsgroup
737 JOIN parts p ON (i.parts_id = p.id)
738 LEFT JOIN chart c1 ON ((SELECT inventory_accno_id FROM buchungsgruppen WHERE id = p.buchungsgruppen_id) = c1.id)
739 LEFT JOIN chart c2 ON ((SELECT income_accno_id_${taxzone_id} FROM buchungsgruppen WHERE id = p.buchungsgruppen_id) = c2.id)
740 LEFT JOIN chart c3 ON ((SELECT expense_accno_id_${taxzone_id} FROM buchungsgruppen WHERE id = p.buchungsgruppen_id) = c3.id)
741 LEFT JOIN project pr ON (i.project_id = pr.id)
742 LEFT JOIN partsgroup pg ON (pg.id = p.partsgroup_id)
747 $sth = prepare_execute_query($form, $dbh, $query, conv_i($form->{id}));
749 while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
750 map({ delete($ref->{$_}); } qw(inventory_accno inventory_new_chart inventory_valid)) if !$ref->{"part_inventory_accno_id"};
751 delete($ref->{"part_inventory_accno_id"});
753 foreach my $type (qw(inventory income expense)) {
754 while ($ref->{"${type}_new_chart"} && ($ref->{"${type}_valid"} >=0)) {
755 my $query = qq|SELECT accno, new_chart_id, date($transdate) - valid_from FROM chart WHERE id = ?|;
756 @$ref{ map $type.$_, qw(_accno _new_chart _valid) } = selectrow_query($form, $dbh, $query, $ref->{"${type}_new_chart"});
760 # get tax rates and description
761 my $accno_id = ($form->{vc} eq "customer") ? $ref->{income_accno} : $ref->{expense_accno};
763 qq|SELECT c.accno, t.taxdescription, t.rate, t.taxnumber FROM tax t
764 LEFT JOIN chart c ON (c.id = t.chart_id)
766 (SELECT tk.tax_id FROM taxkeys tk
767 WHERE tk.chart_id = (SELECT id FROM chart WHERE accno = ?)
768 AND (startdate <= $transdate)
769 ORDER BY startdate DESC
772 my $stw = prepare_execute_query($form, $dbh, $query, $accno_id);
773 $ref->{taxaccounts} = "";
776 while ($ptr = $stw->fetchrow_hashref(NAME_lc)) {
777 if (($ptr->{accno} eq "") && ($ptr->{rate} == 0)) {
782 $ref->{taxaccounts} .= "$ptr->{accno} ";
784 if (!($form->{taxaccounts} =~ /\Q$ptr->{accno}\E/)) {
785 $form->{"$ptr->{accno}_rate"} = $ptr->{rate};
786 $form->{"$ptr->{accno}_description"} = $ptr->{taxdescription};
787 $form->{"$ptr->{accno}_taxnumber"} = $ptr->{taxnumber};
788 $form->{taxaccounts} .= "$ptr->{accno} ";
793 chop $ref->{taxaccounts};
794 push @{ $form->{invoice_details} }, $ref;
799 Common::webdav_folder($form) if ($main::webdav);
803 $main::lxdebug->leave_sub();
807 $main::lxdebug->enter_sub();
809 my ($self, $myconfig, $form, $params) = @_;
811 $params = $form unless defined $params && ref $params eq "HASH";
813 # connect to database
814 my $dbh = $form->dbconnect($myconfig);
816 my $dateformat = $myconfig->{dateformat};
817 $dateformat .= "yy" if $myconfig->{dateformat} !~ /^y/;
819 my $vid = conv_i($params->{vendor_id});
820 my $vnr = conv_i($params->{vendornumber});
824 ? "to_date(" . $dbh->quote($params->{invdate}) . ", '$dateformat')"
830 $where .= 'AND v.id = ?';
834 $where .= 'AND v.vendornumber = ?';
839 v.name AS vendor, v.creditlimit, v.terms, v.notes AS intnotes,
840 v.email, v.cc, v.bcc, v.language_id, v.payment_id,
841 v.street, v.zipcode, v.city, v.country, v.taxzone_id,
842 $duedate + COALESCE(pt.terms_netto, 0) AS duedate,
843 b.description AS business
845 LEFT JOIN business b ON (b.id = v.business_id)
846 LEFT JOIN payment_terms pt ON (v.payment_id = pt.id)
848 $ref = selectfirst_hashref_query($form, $dbh, $query, @values);
849 map { $params->{$_} = $ref->{$_} } keys %$ref;
851 $params->{creditremaining} = $params->{creditlimit};
853 $query = qq|SELECT SUM(amount - paid) FROM ap WHERE vendor_id = ?|;
854 my ($unpaid_invoices) = selectfirst_array_query($form, $dbh, $query, $vid);
855 $params->{creditremaining} -= $unpaid_invoices;
857 $query = qq|SELECT o.amount,
860 WHERE (e.curr = o.curr)
861 AND (e.transdate = o.transdate)) AS exch
863 WHERE (o.vendor_id = ?) AND (o.quotation = '0') AND (o.closed = '0')|;
864 my $sth = prepare_execute_query($form, $dbh, $query, $vid);
865 while (my ($amount, $exch) = $sth->fetchrow_array()) {
866 $exch = 1 unless $exch;
867 $params->{creditremaining} -= $amount * $exch;
871 # get shipto if we do not convert an order or invoice
872 if (!$params->{shipto}) {
873 delete @{$params}{qw(shiptoname shiptostreet shiptozipcode shiptocity shiptocountry shiptocontact shiptophone shiptofax shiptoemail)};
875 $query = qq|SELECT * FROM shipto WHERE (trans_id = ?) AND (module= 'CT')|;
876 $ref = selectfirst_hashref_query($form, $dbh, $query, $vid);
877 @{$params}{keys %$ref} = @{$ref}{keys %$ref};
878 map { $params->{$_} = $ref->{$_} } keys %$ref;
881 if (!$params->{id} && $params->{type} !~ /_(order|quotation)/) {
882 # setup last accounts used
884 qq|SELECT c.id, c.accno, c.description, c.link, c.category
886 JOIN acc_trans ac ON (ac.chart_id = c.id)
887 JOIN ap a ON (a.id = ac.trans_id)
888 WHERE (a.vendor_id = ?)
889 AND (NOT ((c.link LIKE '%_tax%') OR (c.link LIKE '%_paid%')))
890 AND (a.id IN (SELECT max(a2.id) FROM ap a2 WHERE a2.vendor_id = ?))|;
891 my $refs = selectall_hashref_query($form, $dbh, $query, $vid, $vid);
895 if ($ref->{category} eq 'E') {
898 if ($params->{initial_transdate}) {
899 my $tax_query = qq|SELECT tk.tax_id, t.rate FROM taxkeys tk
900 LEFT JOIN tax t ON (tk.tax_id = t.id)
901 WHERE (tk.chart_id = ?) AND (startdate <= ?)
902 ORDER BY tk.startdate DESC
904 my ($tax_id, $rate) = selectrow_query($form, $dbh, $tax_query, $ref->{id}, $params->{initial_transdate});
905 $params->{"taxchart_$i"} = "${tax_id}--${rate}";
908 $params->{"AP_amount_$i"} = "$ref->{accno}--$tax_id";
911 if ($ref->{category} eq 'L') {
912 $params->{APselected} = $params->{AP_1} = $ref->{accno};
915 $params->{rowcount} = $i if ($i && !$params->{type});
920 $main::lxdebug->leave_sub();
924 $main::lxdebug->enter_sub();
926 my ($self, $myconfig, $form) = @_;
928 # connect to database
929 my $dbh = $form->dbconnect($myconfig);
931 my $i = $form->{rowcount};
933 # don't include assemblies or obsolete parts
934 my $where = "NOT p.assembly = '1' AND NOT p.obsolete = '1'";
937 foreach my $table_column (qw(p.partnumber p.description pg.partsgroup)) {
938 my $field = (split m{\.}, $table_column)[1];
939 next unless $form->{"${field}_${i}"};
940 $where .= " AND lower(${table_column}) LIKE lower(?)";
941 push @values, '%' . $form->{"${field}_${i}"} . '%';
944 if ($form->{"description_$i"}) {
945 $where .= " ORDER BY p.description";
947 $where .= " ORDER BY p.partnumber";
951 if ($form->{type} eq "invoice") {
952 $transdate = $form->{invdate} ? $dbh->quote($form->{invdate}) : "current_date";
954 $transdate = $form->{transdate} ? $dbh->quote($form->{transdate}) : "current_date";
957 my $taxzone_id = $form->{taxzone_id} * 1;
958 $taxzone_id = 0 if ((3 < $taxzone_id) || (0 > $taxzone_id));
962 p.id, p.partnumber, p.description, p.lastcost AS sellprice, p.listprice,
963 p.unit, p.assembly, p.bin, p.onhand, p.formel,
964 p.notes AS partnotes, p.notes AS longdescription, p.not_discountable,
965 p.inventory_accno_id, p.price_factor_id,
967 pfac.factor AS price_factor,
969 c1.accno AS inventory_accno,
970 c1.new_chart_id AS inventory_new_chart,
971 date($transdate) - c1.valid_from AS inventory_valid,
973 c2.accno AS income_accno,
974 c2.new_chart_id AS income_new_chart,
975 date($transdate) - c2.valid_from AS income_valid,
977 c3.accno AS expense_accno,
978 c3.new_chart_id AS expense_new_chart,
979 date($transdate) - c3.valid_from AS expense_valid,
984 LEFT JOIN chart c1 ON
985 ((SELECT inventory_accno_id
987 WHERE id = p.buchungsgruppen_id) = c1.id)
988 LEFT JOIN chart c2 ON
989 ((SELECT income_accno_id_${taxzone_id}
991 WHERE id = p.buchungsgruppen_id) = c2.id)
992 LEFT JOIN chart c3 ON
993 ((SELECT expense_accno_id_${taxzone_id}
995 WHERE id = p.buchungsgruppen_id) = c3.id)
996 LEFT JOIN partsgroup pg ON (pg.id = p.partsgroup_id)
997 LEFT JOIN price_factors pfac ON (pfac.id = p.price_factor_id)
999 my $sth = prepare_execute_query($form, $dbh, $query, @values);
1001 $form->{item_list} = [];
1002 while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
1004 # In der Buchungsgruppe ist immer ein Bestandskonto verknuepft, auch wenn
1005 # es sich um eine Dienstleistung handelt. Bei Dienstleistungen muss das
1006 # Buchungskonto also aus dem Ergebnis rausgenommen werden.
1007 if (!$ref->{inventory_accno_id}) {
1008 map({ delete($ref->{"inventory_${_}"}); } qw(accno new_chart valid));
1010 delete($ref->{inventory_accno_id});
1012 # get tax rates and description
1013 $accno_id = ($form->{vc} eq "customer") ? $ref->{income_accno} : $ref->{expense_accno};
1015 qq|SELECT c.accno, t.taxdescription, t.rate, t.taxnumber
1017 LEFT JOIN chart c on (c.id = t.chart_id)
1025 AND (startdate <= $transdate)
1026 ORDER BY startdate DESC
1029 my $stw = prepare_execute_query($form, $dbh, $query, $accno_id);
1031 $ref->{taxaccounts} = "";
1033 while ($ptr = $stw->fetchrow_hashref(NAME_lc)) {
1035 # if ($customertax{$ref->{accno}}) {
1036 if (($ptr->{accno} eq "") && ($ptr->{rate} == 0)) {
1041 $ref->{taxaccounts} .= "$ptr->{accno} ";
1043 if (!($form->{taxaccounts} =~ /\Q$ptr->{accno}\E/)) {
1044 $form->{"$ptr->{accno}_rate"} = $ptr->{rate};
1045 $form->{"$ptr->{accno}_description"} = $ptr->{taxdescription};
1046 $form->{"$ptr->{accno}_taxnumber"} = $ptr->{taxnumber};
1047 $form->{taxaccounts} .= "$ptr->{accno} ";
1053 chop $ref->{taxaccounts};
1055 $ref->{onhand} *= 1;
1057 push @{ $form->{item_list} }, $ref;
1064 $main::lxdebug->leave_sub();
1067 sub vendor_details {
1068 $main::lxdebug->enter_sub();
1070 my ($self, $myconfig, $form, @wanted_vars) = @_;
1072 # connect to database
1073 my $dbh = $form->dbconnect($myconfig);
1077 # get contact id, set it if nessessary
1078 $form->{cp_id} = (split /--/, $form->{contact})[1];
1080 if ($form->{cp_id}) {
1081 $contact = "AND cp.cp_id = ?";
1082 push @values, $form->{cp_id};
1085 # get rest for the vendor
1086 # fax and phone and email as vendor*
1088 qq|SELECT ct.*, cp.*, ct.notes as vendornotes, phone as vendorphone, fax as vendorfax, email as vendoremail
1090 LEFT JOIN contacts cp ON (ct.id = cp.cp_cv_id)
1091 WHERE (ct.id = ?) $contact
1094 my $ref = selectfirst_hashref_query($form, $dbh, $query, $form->{vendor_id}, @values);
1096 # remove id and taxincluded before copy back
1097 delete @$ref{qw(id taxincluded)};
1099 @wanted_vars = grep({ $_ } @wanted_vars);
1100 if (scalar(@wanted_vars) > 0) {
1102 map({ $h_wanted_vars{$_} = 1; } @wanted_vars);
1103 map({ delete($ref->{$_}) unless ($h_wanted_vars{$_}); } keys(%{$ref}));
1106 map { $form->{$_} = $ref->{$_} } keys %$ref;
1108 my $custom_variables = CVar->get_custom_variables('dbh' => $dbh,
1110 'trans_id' => $form->{vendor_id});
1111 map { $form->{"vc_cvar_$_->{name}"} = $_->{value} } @{ $custom_variables };
1115 $main::lxdebug->leave_sub();
1119 $main::lxdebug->enter_sub();
1121 my ($self, $myconfig, $form) = @_;
1123 # connect to database
1124 my $dbh = $form->dbconnect($myconfig);
1127 qq|SELECT accno, description, link
1129 WHERE link LIKE '%IC%'
1131 my $sth = prepare_execute_query($query, $dbh, $query);
1133 while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
1134 foreach my $key (split(/:/, $ref->{link})) {
1136 push @{ $form->{IC_links}{$key} },
1137 { accno => $ref->{accno},
1138 description => $ref->{description} };
1146 $main::lxdebug->leave_sub();
1149 sub _delete_payments {
1150 $main::lxdebug->enter_sub();
1152 my ($self, $form, $dbh) = @_;
1156 # Delete old payment entries from acc_trans.
1160 WHERE (trans_id = ?) AND fx_transaction
1166 LEFT JOIN chart c ON (at.chart_id = c.id)
1167 WHERE (trans_id = ?) AND (c.link LIKE '%AP_paid%')|;
1168 push @delete_oids, selectall_array_query($form, $dbh, $query, conv_i($form->{id}), conv_i($form->{id}));
1173 LEFT JOIN chart c ON (at.chart_id = c.id)
1174 WHERE (trans_id = ?)
1175 AND ((c.link = 'AP') OR (c.link LIKE '%:AP') OR (c.link LIKE 'AP:%'))
1178 push @delete_oids, selectall_array_query($form, $dbh, $query, conv_i($form->{id}));
1181 $query = qq|DELETE FROM acc_trans WHERE oid IN (| . join(", ", @delete_oids) . qq|)|;
1182 do_query($form, $dbh, $query);
1185 $main::lxdebug->leave_sub();
1189 $main::lxdebug->enter_sub();
1191 my ($self, $myconfig, $form, $locale) = @_;
1193 # connect to database, turn off autocommit
1194 my $dbh = $form->dbconnect_noauto($myconfig);
1196 my (%payments, $old_form, $row, $item, $query, %keep_vars);
1198 $old_form = save_form();
1200 # Delete all entries in acc_trans from prior payments.
1201 $self->_delete_payments($form, $dbh);
1203 # Save the new payments the user made before cleaning up $form.
1204 map { $payments{$_} = $form->{$_} } grep m/^datepaid_\d+$|^memo_\d+$|^source_\d+$|^exchangerate_\d+$|^paid_\d+$|^AP_paid_\d+$|^paidaccounts$/, keys %{ $form };
1206 # Clean up $form so that old content won't tamper the results.
1207 %keep_vars = map { $_, 1 } qw(login password id);
1208 map { delete $form->{$_} unless $keep_vars{$_} } keys %{ $form };
1210 # Retrieve the invoice from the database.
1211 $self->retrieve_invoice($myconfig, $form);
1213 # Set up the content of $form in the way that IR::post_invoice() expects.
1214 $form->{exchangerate} = $form->format_amount($myconfig, $form->{exchangerate});
1216 for $row (1 .. scalar @{ $form->{invoice_details} }) {
1217 $item = $form->{invoice_details}->[$row - 1];
1219 map { $item->{$_} = $form->format_amount($myconfig, $item->{$_}) } qw(qty sellprice);
1221 map { $form->{"${_}_${row}"} = $item->{$_} } keys %{ $item };
1224 $form->{rowcount} = scalar @{ $form->{invoice_details} };
1226 delete @{$form}{qw(invoice_details paidaccounts storno paid)};
1228 # Restore the payment options from the user input.
1229 map { $form->{$_} = $payments{$_} } keys %payments;
1231 # Get the AP accno (which is normally done by Form::create_links()).
1235 LEFT JOIN chart c ON (at.chart_id = c.id)
1236 WHERE (trans_id = ?)
1237 AND ((c.link = 'AP') OR (c.link LIKE '%:AP') OR (c.link LIKE 'AP:%'))
1241 ($form->{AP}) = selectfirst_array_query($form, $dbh, $query, conv_i($form->{id}));
1243 # Post the new payments.
1244 $self->post_invoice($myconfig, $form, $dbh, 1);
1246 restore_form($old_form);
1248 my $rc = $dbh->commit();
1251 $main::lxdebug->leave_sub();