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 #======================================================================
42 use List::Util qw(min);
45 $main::lxdebug->enter_sub();
47 my ($self, $myconfig, $form, $provided_dbh, $payments_only) = @_;
49 # connect to database, turn off autocommit
50 my $dbh = $provided_dbh ? $provided_dbh : $form->dbconnect_noauto($myconfig);
51 $form->{defaultcurrency} = $form->get_default_currency($myconfig);
53 my ($query, $sth, @values, $project_id);
54 my ($allocated, $taxrate, $taxamount, $taxdiff, $item);
55 my ($amount, $linetotal, $lastinventoryaccno, $lastexpenseaccno);
56 my ($netamount, $invoicediff, $expensediff) = (0, 0, 0);
59 my $all_units = AM->retrieve_units($myconfig, $form);
61 if (!$payments_only) {
63 &reverse_invoice($dbh, $form);
65 ($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;
76 $exchangerate = $form->check_exchangerate($myconfig, $form->{currency}, $form->{transdate}, 'sell');
79 $form->{exchangerate} = $exchangerate || $form->parse_amount($myconfig, $form->{exchangerate});
80 $form->{exchangerate} = 1 unless ($form->{exchangerate} * 1);
83 my $q_item_unit = qq|SELECT unit FROM parts WHERE id = ?|;
84 my $h_item_unit = prepare_query($form, $dbh, $q_item_unit);
86 $form->get_lists('price_factors' => 'ALL_PRICE_FACTORS');
87 my %price_factors = map { $_->{id} => $_->{factor} } @{ $form->{ALL_PRICE_FACTORS} };
90 for my $i (1 .. $form->{rowcount}) {
91 next unless $form->{"id_$i"};
93 $form->{"qty_$i"} = $form->parse_amount($myconfig, $form->{"qty_$i"});
94 $form->{"qty_$i"} *= -1 if $form->{storno};
96 $form->{"inventory_accno_$i"} = $form->{"expense_accno_$i"} if $main::eur;
99 if (!$item_units{$form->{"id_$i"}}) {
100 do_statement($form, $h_item_unit, $q_item_unit, $form->{"id_$i"});
101 ($item_units{$form->{"id_$i"}}) = $h_item_unit->fetchrow_array();
104 my $item_unit = $item_units{$form->{"id_$i"}};
106 if (defined($all_units->{$item_unit}->{factor})
107 && ($all_units->{$item_unit}->{factor} ne '')
108 && ($all_units->{$item_unit}->{factor} * 1 != 0)) {
109 $basefactor = $all_units->{$form->{"unit_$i"}}->{factor} / $all_units->{$item_unit}->{factor};
113 $baseqty = $form->{"qty_$i"} * $basefactor;
115 @taxaccounts = split / /, $form->{"taxaccounts_$i"};
120 $form->{"sellprice_$i"} = $form->parse_amount($myconfig, $form->{"sellprice_$i"});
121 (my $fxsellprice = $form->{"sellprice_$i"}) =~ /\.(\d+)/;
123 my $decimalplaces = ($dec > 2) ? $dec : 2;
125 map { $taxrate += $form->{"${_}_rate"} } @taxaccounts;
127 $price_factor = $price_factors{ $form->{"price_factor_id_$i"} } || 1;
129 if ($form->{"inventory_accno_$i"}) {
131 $linetotal = $form->round_amount($form->{"sellprice_$i"} * $form->{"qty_$i"} / $price_factor, 2);
133 if ($form->{taxincluded}) {
134 $taxamount = $linetotal * ($taxrate / (1 + $taxrate));
135 $form->{"sellprice_$i"} = $form->{"sellprice_$i"} * (1 / (1 + $taxrate));
137 $taxamount = $linetotal * $taxrate;
140 $netamount += $linetotal;
142 if ($form->round_amount($taxrate, 7) == 0) {
143 if ($form->{taxincluded}) {
144 foreach $item (@taxaccounts) {
146 $form->round_amount($linetotal * $form->{"${item}_rate"} / (1 + abs($form->{"${item}_rate"})), 2);
147 $taxdiff += $taxamount;
148 $form->{amount}{ $form->{id} }{$item} -= $taxamount;
150 $form->{amount}{ $form->{id} }{ $taxaccounts[0] } += $taxdiff;
153 map { $form->{amount}{ $form->{id} }{$_} -= $linetotal * $form->{"${_}_rate"} } @taxaccounts;
157 map { $form->{amount}{ $form->{id} }{$_} -= $taxamount * $form->{"${_}_rate"} / $taxrate } @taxaccounts;
160 # add purchase to inventory, this one is without the tax!
161 $amount = $form->{"sellprice_$i"} * $form->{"qty_$i"} * $form->{exchangerate} / $price_factor;
162 $linetotal = $form->round_amount($form->{"sellprice_$i"} * $form->{"qty_$i"} / $price_factor, 2) * $form->{exchangerate};
163 $linetotal = $form->round_amount($linetotal, 2);
165 # this is the difference for the inventory
166 $invoicediff += ($amount - $linetotal);
168 $form->{amount}{ $form->{id} }{ $form->{"inventory_accno_$i"} } -= $linetotal;
170 # adjust and round sellprice
171 $form->{"sellprice_$i"} = $form->round_amount($form->{"sellprice_$i"} * $form->{exchangerate}, $decimalplaces);
173 $lastinventoryaccno = $form->{"inventory_accno_$i"};
175 next if $payments_only;
178 $query = qq|UPDATE parts SET lastcost = ? WHERE id = ?|;
179 @values = ($form->{"sellprice_$i"}, conv_i($form->{"id_$i"}));
180 do_query($form, $dbh, $query, @values);
182 # check if we sold the item already and
183 # make an entry for the expense and inventory
185 qq|SELECT i.id, i.qty, i.allocated, i.trans_id,
186 p.inventory_accno_id, p.expense_accno_id, a.transdate
187 FROM invoice i, ar a, parts p
188 WHERE (i.parts_id = p.id)
190 AND ((i.base_qty + i.allocated) > 0)
191 AND (i.trans_id = a.id)
193 $sth = prepare_execute_query($form, $dbh, $query, conv_i($form->{"id_$i"}));
195 my $totalqty = $base_qty;
197 while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
198 my $qty = min $totalqty, ($ref->{base_qty} + $ref->{allocated});
199 $linetotal = $form->round_amount(($form->{"sellprice_$i"} * $qty) / $basefactor, 2);
201 if ($ref->{allocated} < 0) {
203 # we have an entry for it already, adjust amount
204 $form->update_balance($dbh, "acc_trans", "amount",
205 qq| (trans_id = $ref->{trans_id})
206 AND (chart_id = $ref->{inventory_accno_id})
207 AND (transdate = '$ref->{transdate}')|,
210 $form->update_balance($dbh, "acc_trans", "amount",
211 qq| (trans_id = $ref->{trans_id})
212 AND (chart_id = $ref->{expense_accno_id})
213 AND (transdate = '$ref->{transdate}')|,
216 } elsif ($linetotal != 0) {
217 # add entry for inventory, this one is for the sold item
218 $query = qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate, taxkey) VALUES (?, ?, ?, ?, (SELECT taxkey_id FROM chart WHERE id = ?))|;
219 @values = ($ref->{trans_id}, $ref->{inventory_accno_id}, $linetotal, $ref->{transdate}, $ref->{inventory_accno_id});
220 do_query($form, $dbh, $query, @values);
223 $query = qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate, taxkey) VALUES (?, ?, ?, ?, (SELECT taxkey from tax WHERE chart_id = ?))|;
224 @values = ($ref->{trans_id}, $ref->{expense_accno_id}, ($linetotal * -1), $ref->{transdate}, $ref->{expense_accno_id});
225 do_query($form, $dbh, $query, @values);
228 # update allocated for sold item
229 $form->update_balance($dbh, "invoice", "allocated", qq|id = $ref->{id}|, $qty * -1);
233 last if ($totalqty -= $qty) <= 0;
238 } else { # if ($form->{"inventory_accno_id_$i"})
240 $linetotal = $form->round_amount($form->{"sellprice_$i"} * $form->{"qty_$i"} / $price_factor, 2);
242 if ($form->{taxincluded}) {
243 $taxamount = $linetotal * ($taxrate / (1 + $taxrate));
244 $form->{"sellprice_$i"} = $form->{"sellprice_$i"} * (1 / (1 + $taxrate));
247 $taxamount = $linetotal * $taxrate;
250 $netamount += $linetotal;
252 if ($form->round_amount($taxrate, 7) == 0) {
253 if ($form->{taxincluded}) {
254 foreach $item (@taxaccounts) {
255 $taxamount = $linetotal * $form->{"${item}_rate"} / (1 + abs($form->{"${item}_rate"}));
256 $totaltax += $taxamount;
257 $form->{amount}{ $form->{id} }{$item} -= $taxamount;
260 map { $form->{amount}{ $form->{id} }{$_} -= $linetotal * $form->{"${_}_rate"} } @taxaccounts;
263 map { $form->{amount}{ $form->{id} }{$_} -= $taxamount * $form->{"${_}_rate"} / $taxrate } @taxaccounts;
266 $amount = $form->{"sellprice_$i"} * $form->{"qty_$i"} * $form->{exchangerate} / $price_factor;
267 $linetotal = $form->round_amount($form->{"sellprice_$i"} * $form->{"qty_$i"} / $price_factor, 2) * $form->{exchangerate};
268 $linetotal = $form->round_amount($linetotal, 2);
270 # this is the difference for expense
271 $expensediff += ($amount - $linetotal);
273 # add amount to expense
274 $form->{amount}{ $form->{id} }{ $form->{"expense_accno_$i"} } -= $linetotal;
276 $lastexpenseaccno = $form->{"expense_accno_$i"};
278 # adjust and round sellprice
279 $form->{"sellprice_$i"} = $form->round_amount($form->{"sellprice_$i"} * $form->{exchangerate}, $decimalplaces);
281 next if $payments_only;
284 $query = qq|UPDATE parts SET lastcost = ? WHERE id = ?|;
285 do_query($form, $dbh, $query, $form->{"sellprice_$i"}, conv_i($form->{"id_$i"}));
288 next if $payments_only;
290 # save detail record in invoice table
292 qq|INSERT INTO invoice (trans_id, parts_id, description, qty, base_qty,
293 sellprice, fxsellprice, allocated, unit, deliverydate,
294 project_id, serialnumber, price_factor_id, price_factor, marge_price_factor)
295 VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, (SELECT factor FROM price_factors WHERE id = ?), ?)|;
296 @values = (conv_i($form->{id}), conv_i($form->{"id_$i"}),
297 $form->{"description_$i"}, $form->{"qty_$i"} * -1,
298 $baseqty * -1, $form->{"sellprice_$i"}, $fxsellprice, $allocated,
299 $form->{"unit_$i"}, conv_date($form->{deliverydate}),
300 conv_i($form->{"project_id_$i"}), $form->{"serialnumber_$i"},
301 conv_i($form->{"price_factor_id_$i"}), conv_i($form->{"price_factor_id_$i"}), conv_i($form->{"marge_price_factor_$i"}));
302 do_query($form, $dbh, $query, @values);
305 $h_item_unit->finish();
307 $project_id = conv_i($form->{"globalproject_id"});
309 $form->{datepaid} = $form->{invdate};
311 # all amounts are in natural state, netamount includes the taxes
312 # if tax is included, netamount is rounded to 2 decimal places,
316 for my $i (1 .. $form->{paidaccounts}) {
317 $form->{"paid_$i"} = $form->parse_amount($myconfig, $form->{"paid_$i"});
318 $form->{paid} += $form->{"paid_$i"};
319 $form->{datepaid} = $form->{"datepaid_$i"} if $form->{"datepaid_$i"};
322 my ($tax, $paiddiff) = (0, 0);
324 $netamount = $form->round_amount($netamount, 2);
326 # figure out rounding errors for amount paid and total amount
327 if ($form->{taxincluded}) {
329 $amount = $form->round_amount($netamount * $form->{exchangerate}, 2);
330 $paiddiff = $amount - $netamount * $form->{exchangerate};
331 $netamount = $amount;
333 foreach $item (split / /, $form->{taxaccounts}) {
334 $amount = $form->{amount}{ $form->{id} }{$item} * $form->{exchangerate};
335 $form->{amount}{ $form->{id} }{$item} = $form->round_amount($amount, 2);
337 $amount = $form->{amount}{ $form->{id} }{$item} * -1;
339 $netamount -= $amount;
342 $invoicediff += $paiddiff;
343 $expensediff += $paiddiff;
345 ######## this only applies to tax included
347 $form->{amount}{ $form->{id} }{$lastinventoryaccno} -= $invoicediff if $lastinventoryaccno;
348 $form->{amount}{ $form->{id} }{$lastexpenseaccno} -= $expensediff if $lastexpenseaccno;
351 $amount = $form->round_amount($netamount * $form->{exchangerate}, 2);
352 $paiddiff = $amount - $netamount * $form->{exchangerate};
353 $netamount = $amount;
355 foreach my $item (split / /, $form->{taxaccounts}) {
356 $form->{amount}{ $form->{id} }{$item} = $form->round_amount($form->{amount}{ $form->{id} }{$item}, 2);
357 $amount = $form->round_amount( $form->{amount}{ $form->{id} }{$item} * $form->{exchangerate} * -1, 2);
358 $paiddiff += $amount - $form->{amount}{ $form->{id} }{$item} * $form->{exchangerate} * -1;
359 $form->{amount}{ $form->{id} }{$item} = $form->round_amount($amount * -1, 2);
360 $amount = $form->{amount}{ $form->{id} }{$item} * -1;
365 $form->{amount}{ $form->{id} }{ $form->{AP} } = $netamount + $tax;
368 $form->{paid} = $form->round_amount($form->{paid} * $form->{exchangerate} + $paiddiff, 2) if $form->{paid} != 0;
370 # update exchangerate
372 $form->update_exchangerate($dbh, $form->{currency}, $form->{invdate}, 0, $form->{exchangerate})
373 if ($form->{currency} ne $defaultcurrency) && !$exchangerate;
375 # record acc_trans transactions
376 foreach my $trans_id (keys %{ $form->{amount} }) {
377 foreach my $accno (keys %{ $form->{amount}{$trans_id} }) {
378 $form->{amount}{$trans_id}{$accno} = $form->round_amount($form->{amount}{$trans_id}{$accno}, 2);
380 next if $payments_only || !$form->{amount}{$trans_id}{$accno};
382 $query = qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate, taxkey, project_id)
383 VALUES (?, (SELECT id FROM chart WHERE accno = ?), ?, ?,
384 (SELECT taxkey_id FROM chart WHERE accno = ?), ?)|;
385 @values = ($trans_id, $accno, $form->{amount}{$trans_id}{$accno},
386 conv_date($form->{invdate}), $accno, $project_id);
387 do_query($form, $dbh, $query, @values);
391 # deduct payment differences from paiddiff
392 for my $i (1 .. $form->{paidaccounts}) {
393 if ($form->{"paid_$i"} != 0) {
394 $amount = $form->round_amount($form->{"paid_$i"} * $form->{exchangerate}, 2);
395 $paiddiff -= $amount - $form->{"paid_$i"} * $form->{exchangerate};
399 # force AP entry if 0
401 $form->{amount}{ $form->{id} }{ $form->{AP} } = $form->{paid} if $form->{amount}{$form->{id}}{$form->{AP}} == 0;
403 # record payments and offsetting AP
404 for my $i (1 .. $form->{paidaccounts}) {
405 next if $form->{"paid_$i"} == 0;
407 my ($accno) = split /--/, $form->{"AP_paid_$i"};
408 $form->{"datepaid_$i"} = $form->{invdate} unless ($form->{"datepaid_$i"});
409 $form->{datepaid} = $form->{"datepaid_$i"};
411 $amount = $form->round_amount($form->{"paid_$i"} * $form->{exchangerate} + $paiddiff, 2) * -1;
414 if ($form->{amount}{ $form->{id} }{ $form->{AP} } != 0) {
415 $query = qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate, taxkey, project_id)
416 VALUES (?, (SELECT id FROM chart WHERE accno = ?), ?, ?,
417 (SELECT taxkey_id FROM chart WHERE accno = ?), ?)|;
418 @values = (conv_i($form->{id}), $form->{AP}, $amount,
419 $form->{"datepaid_$i"}, $form->{AP}, $project_id);
420 do_query($form, $dbh, $query, @values);
424 $query = qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate, source, memo, taxkey, project_id)
425 VALUES (?, (SELECT id FROM chart WHERE accno = ?), ?, ?, ?, ?,
426 (SELECT taxkey_id FROM chart WHERE accno = ?), ?)|;
427 @values = (conv_i($form->{id}), $accno, $form->{"paid_$i"}, $form->{"datepaid_$i"},
428 $form->{"source_$i"}, $form->{"memo_$i"}, $accno, $project_id);
429 do_query($form, $dbh, $query, @values);
433 if ($form->{currency} eq $defaultcurrency) {
434 $form->{"exchangerate_$i"} = 1;
436 $exchangerate = $form->check_exchangerate($myconfig, $form->{currency}, $form->{"datepaid_$i"}, 'sell');
437 $form->{"exchangerate_$i"} = $exchangerate || $form->parse_amount($myconfig, $form->{"exchangerate_$i"});
440 # exchangerate difference
441 $form->{fx}{$accno}{ $form->{"datepaid_$i"} } += $form->{"paid_$i"} * ($form->{"exchangerate_$i"} - 1) + $paiddiff;
445 ($form->{"paid_$i"} * $form->{exchangerate}) -
446 ($form->{"paid_$i"} * $form->{"exchangerate_$i"});
448 $form->{fx}{ $form->{fxgain_accno} }{ $form->{"datepaid_$i"} } += $amount;
450 $form->{fx}{ $form->{fxloss_accno} }{ $form->{"datepaid_$i"} } += $amount;
455 # update exchange rate
456 $form->update_exchangerate($dbh, $form->{currency}, $form->{"datepaid_$i"}, 0, $form->{"exchangerate_$i"})
457 if ($form->{currency} ne $defaultcurrency) && !$exchangerate;
460 # record exchange rate differences and gains/losses
461 foreach my $accno (keys %{ $form->{fx} }) {
462 foreach my $transdate (keys %{ $form->{fx}{$accno} }) {
463 $form->{fx}{$accno}{$transdate} = $form->round_amount($form->{fx}{$accno}{$transdate}, 2);
464 next if ($form->{fx}{$accno}{$transdate} == 0);
466 $query = qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate, cleared, fx_transaction, taxkey, project_id)
467 VALUES (?, (SELECT id FROM chart WHERE accno = ?), ?, ?, '0', '1', 0, ?)|;
468 @values = (conv_i($form->{id}), $accno, $form->{fx}{$accno}{$transdate}, conv_date($transdate), $project_id);
469 do_query($form, $dbh, $query, @values);
473 if ($payments_only) {
474 $query = qq|UPDATE ap SET paid = ?, datepaid = ? WHERE id = ?|;
475 do_query($form, $dbh, $query, $form->{paid}, $form->{paid} ? conv_date($form->{datepaid}) : undef, conv_i($form->{id}));
477 if (!$provided_dbh) {
482 $main::lxdebug->leave_sub();
486 $amount = $netamount + $tax;
488 # set values which could be empty
489 my $taxzone_id = $form->{taxzone_id} * 1;
490 $form->{department_id} = (split /--/, $form->{department})[1];
491 $form->{invnumber} = $form->{id} unless $form->{invnumber};
493 $taxzone_id = 0 if (3 < $taxzone_id) || (0 > $taxzone_id);
496 $query = qq|UPDATE ap SET
497 invnumber = ?, ordnumber = ?, quonumber = ?, transdate = ?,
498 orddate = ?, quodate = ?, vendor_id = ?, amount = ?,
499 netamount = ?, paid = ?, duedate = ?, datepaid = ?,
500 invoice = ?, taxzone_id = ?, notes = ?, taxincluded = ?,
501 intnotes = ?, curr = ?, storno_id = ?, storno = ?,
502 cp_id = ?, employee_id = ?, department_id = ?,
506 $form->{invnumber}, $form->{ordnumber}, $form->{quonumber}, conv_date($form->{invdate}),
507 conv_date($form->{orddate}), conv_date($form->{quodate}), conv_i($form->{vendor_id}), $amount,
508 $netamount, $form->{paid}, conv_date($form->{duedate}), $form->{paid} ? conv_date($form->{datepaid}) : undef,
509 '1', $taxzone_id, $form->{notes}, $form->{taxincluded} ? 't' : 'f',
510 $form->{intnotes}, $form->{currency}, conv_i($form->{storno_id}), $form->{storno} ? 't' : 'f',
511 conv_i($form->{cp_id}), conv_i($form->{employee_id}), conv_i($form->{department_id}),
512 conv_i($form->{globalproject_id}),
515 do_query($form, $dbh, $query, @values);
517 if ($form->{storno}) {
518 $query = qq|UPDATE ap SET paid = paid + amount WHERE id = ?|;
519 do_query($form, $dbh, $query, conv_i($form->{storno_id}));
521 $query = qq|UPDATE ap SET storno = 't' WHERE id = ?|;
522 do_query($form, $dbh, $query, conv_i($form->{storno_id}));
524 $query = qq!UPDATE ap SET intnotes = ? || intnotes WHERE id = ?!;
525 do_query($form, $dbh, $query, 'Rechnung storniert am $form->{invdate} ', conv_i($form->{storno_id}));
527 $query = qq|UPDATE ap SET paid = amount WHERE id = ?|;
528 do_query($form, $dbh, $query, conv_i($form->{id}));
533 $form->{name} = $form->{vendor};
534 $form->{name} =~ s/--\Q$form->{vendor_id}\E//;
535 $form->add_shipto($dbh, $form->{id}, "AP");
537 # delete zero entries
538 do_query($form, $dbh, qq|DELETE FROM acc_trans WHERE amount = 0|);
540 Common::webdav_folder($form) if ($main::webdav);
542 # Link this record to the records it was created from.
543 RecordLinks->create_links('dbh' => $dbh,
545 'from_table' => 'oe',
546 'from_ids' => $form->{convert_from_oe_ids},
548 'to_id' => $form->{id},
550 delete $form->{convert_from_oe_ids};
552 my @convert_from_do_ids = map { $_ * 1 } grep { $_ } split m/\s+/, $form->{convert_from_do_ids};
553 if (scalar @convert_from_do_ids) {
554 DO->close_orders('dbh' => $dbh,
555 'ids' => \@convert_from_do_ids);
557 RecordLinks->create_links('dbh' => $dbh,
559 'from_table' => 'delivery_orders',
560 'from_ids' => \@convert_from_do_ids,
562 'to_id' => $form->{id},
567 if (!$provided_dbh) {
568 $rc = $dbh->commit();
572 $main::lxdebug->leave_sub();
577 sub reverse_invoice {
578 $main::lxdebug->enter_sub();
580 my ($dbh, $form) = @_;
582 # reverse inventory items
584 qq|SELECT i.parts_id, p.inventory_accno_id, p.expense_accno_id, i.qty, i.allocated, i.sellprice
585 FROM invoice i, parts p
586 WHERE (i.parts_id = p.id)
587 AND (i.trans_id = ?)|;
588 my $sth = prepare_execute_query($form, $dbh, $query, conv_i($form->{id}));
592 while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
593 $netamount += $form->round_amount($ref->{sellprice} * $ref->{qty} * -1, 2);
595 next unless $ref->{inventory_accno_id};
597 # if $ref->{allocated} > 0 than we sold that many items
598 next if ($ref->{allocated} <= 0);
600 # get references for sold items
602 qq|SELECT i.id, i.trans_id, i.allocated, a.transdate
604 WHERE (i.parts_id = ?)
605 AND (i.allocated < 0)
606 AND (i.trans_id = a.id)
607 ORDER BY transdate DESC|;
608 my $sth2 = prepare_execute_query($form, $dbh, $query, $ref->{parts_id});
610 while (my $pthref = $sth2->fetchrow_hashref(NAME_lc)) {
611 my $qty = $ref->{allocated};
612 if (($ref->{allocated} + $pthref->{allocated}) > 0) {
613 $qty = $pthref->{allocated} * -1;
616 my $amount = $form->round_amount($ref->{sellprice} * $qty, 2);
619 $form->update_balance($dbh, "invoice", "allocated", qq|id = $pthref->{id}|, $qty);
621 $form->update_balance($dbh, "acc_trans", "amount",
622 qq| (trans_id = $pthref->{trans_id})
623 AND (chart_id = $ref->{expense_accno_id})
624 AND (transdate = '$pthref->{transdate}')|,
627 $form->update_balance($dbh, "acc_trans", "amount",
628 qq| (trans_id = $pthref->{trans_id})
629 AND (chart_id = $ref->{inventory_accno_id})
630 AND (transdate = '$pthref->{transdate}')|,
633 last if (($ref->{allocated} -= $qty) <= 0);
639 my $id = conv_i($form->{id});
642 $query = qq|DELETE FROM acc_trans WHERE trans_id = ?|;
643 do_query($form, $dbh, $query, $id);
645 # delete invoice entries
646 $query = qq|DELETE FROM invoice WHERE trans_id = ?|;
647 do_query($form, $dbh, $query, $id);
649 $query = qq|DELETE FROM shipto WHERE (trans_id = ?) AND (module = 'AP')|;
650 do_query($form, $dbh, $query, $id);
652 $main::lxdebug->leave_sub();
656 $main::lxdebug->enter_sub();
658 my ($self, $myconfig, $form) = @_;
660 # connect to database
661 my $dbh = $form->dbconnect_noauto($myconfig);
663 &reverse_invoice($dbh, $form);
665 # delete zero entries
666 $query = qq|DELETE FROM acc_trans WHERE amount = 0|;
667 do_query($form, $dbh, $query);
670 $query = qq|DELETE FROM ap WHERE id = ?|;
671 do_query($form, $dbh, $query, conv_i($form->{id}));
673 my $rc = $dbh->commit;
676 $main::lxdebug->leave_sub();
681 sub retrieve_invoice {
682 $main::lxdebug->enter_sub();
684 my ($self, $myconfig, $form) = @_;
686 # connect to database
687 my $dbh = $form->dbconnect($myconfig);
689 my ($query, $sth, $ref, $q_invdate);
692 $q_invdate = qq|, COALESCE((SELECT transdate FROM ar WHERE id = (SELECT MAX(id) FROM ar)), current_date) AS invdate|;
693 if ($form->{vendor_id}) {
694 my $vendor_id = $dbh->quote($form->{vendor_id} * 1);
696 qq|, COALESCE((SELECT transdate FROM ar WHERE id = (SELECT MAX(id) FROM ar)), current_date) +
697 COALESCE((SELECT pt.terms_netto
699 LEFT JOIN payment_terms pt ON (v.payment_id = pt.id)
700 WHERE v.id = $vendor_id),
705 # get default accounts and last invoice number
708 (SELECT c.accno FROM chart c WHERE d.inventory_accno_id = c.id) AS inventory_accno,
709 (SELECT c.accno FROM chart c WHERE d.income_accno_id = c.id) AS income_accno,
710 (SELECT c.accno FROM chart c WHERE d.expense_accno_id = c.id) AS expense_accno,
711 (SELECT c.accno FROM chart c WHERE d.fxgain_accno_id = c.id) AS fxgain_accno,
712 (SELECT c.accno FROM chart c WHERE d.fxloss_accno_id = c.id) AS fxloss_accno,
716 $ref = selectfirst_hashref_query($form, $dbh, $query);
717 map { $form->{$_} = $ref->{$_} } keys %$ref;
721 $main::lxdebug->leave_sub();
727 $query = qq|SELECT cp_id, invnumber, transdate AS invdate, duedate,
728 orddate, quodate, globalproject_id,
729 ordnumber, quonumber, paid, taxincluded, notes, taxzone_id, storno, gldate,
730 intnotes, curr AS currency
733 $ref = selectfirst_hashref_query($form, $dbh, $query, conv_i($form->{id}));
734 map { $form->{$_} = $ref->{$_} } keys %$ref;
736 $form->{exchangerate} = $form->get_exchangerate($dbh, $form->{currency}, $form->{invdate}, "sell");
739 $query = qq|SELECT * FROM shipto WHERE (trans_id = ?) AND (module = 'AP')|;
740 $ref = selectfirst_hashref_query($form, $dbh, $query, conv_i($form->{id}));
742 map { $form->{$_} = $ref->{$_} } keys %$ref;
744 my $transdate = $form->{invdate} ? $dbh->quote($form->{invdate}) : "current_date";
745 my $taxzone_id = $form->{taxzone_id} * 1;
747 $taxzone_id = 0 if ((3 < $taxzone_id) || (0 > $taxzone_id));
749 # retrieve individual items
752 c1.accno AS inventory_accno, c1.new_chart_id AS inventory_new_chart, date($transdate) - c1.valid_from AS inventory_valid,
753 c2.accno AS income_accno, c2.new_chart_id AS income_new_chart, date($transdate) - c2.valid_from AS income_valid,
754 c3.accno AS expense_accno, c3.new_chart_id AS expense_new_chart, date($transdate) - c3.valid_from AS expense_valid,
756 i.description, i.qty, i.fxsellprice AS sellprice, i.parts_id AS id, i.unit, i.deliverydate, i.project_id, i.serialnumber,
757 i.price_factor_id, i.price_factor, i.marge_price_factor,
758 p.partnumber, p.inventory_accno_id AS part_inventory_accno_id, p.bin, pr.projectnumber, pg.partsgroup
761 JOIN parts p ON (i.parts_id = p.id)
762 LEFT JOIN chart c1 ON ((SELECT inventory_accno_id FROM buchungsgruppen WHERE id = p.buchungsgruppen_id) = c1.id)
763 LEFT JOIN chart c2 ON ((SELECT income_accno_id_${taxzone_id} FROM buchungsgruppen WHERE id = p.buchungsgruppen_id) = c2.id)
764 LEFT JOIN chart c3 ON ((SELECT expense_accno_id_${taxzone_id} FROM buchungsgruppen WHERE id = p.buchungsgruppen_id) = c3.id)
765 LEFT JOIN project pr ON (i.project_id = pr.id)
766 LEFT JOIN partsgroup pg ON (pg.id = p.partsgroup_id)
771 $sth = prepare_execute_query($form, $dbh, $query, conv_i($form->{id}));
773 while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
774 map({ delete($ref->{$_}); } qw(inventory_accno inventory_new_chart inventory_valid)) if !$ref->{"part_inventory_accno_id"};
775 delete($ref->{"part_inventory_accno_id"});
777 foreach my $type (qw(inventory income expense)) {
778 while ($ref->{"${type}_new_chart"} && ($ref->{"${type}_valid"} >=0)) {
779 my $query = qq|SELECT accno, new_chart_id, date($transdate) - valid_from FROM chart WHERE id = ?|;
780 @$ref{ map $type.$_, qw(_accno _new_chart _valid) } = selectrow_query($form, $dbh, $query, $ref->{"${type}_new_chart"});
784 # get tax rates and description
785 my $accno_id = ($form->{vc} eq "customer") ? $ref->{income_accno} : $ref->{expense_accno};
787 qq|SELECT c.accno, t.taxdescription, t.rate, t.taxnumber FROM tax t
788 LEFT JOIN chart c ON (c.id = t.chart_id)
790 (SELECT tk.tax_id FROM taxkeys tk
791 WHERE tk.chart_id = (SELECT id FROM chart WHERE accno = ?)
792 AND (startdate <= $transdate)
793 ORDER BY startdate DESC
796 my $stw = prepare_execute_query($form, $dbh, $query, $accno_id);
797 $ref->{taxaccounts} = "";
800 while ($ptr = $stw->fetchrow_hashref(NAME_lc)) {
801 if (($ptr->{accno} eq "") && ($ptr->{rate} == 0)) {
806 $ref->{taxaccounts} .= "$ptr->{accno} ";
808 if (!($form->{taxaccounts} =~ /\Q$ptr->{accno}\E/)) {
809 $form->{"$ptr->{accno}_rate"} = $ptr->{rate};
810 $form->{"$ptr->{accno}_description"} = $ptr->{taxdescription};
811 $form->{"$ptr->{accno}_taxnumber"} = $ptr->{taxnumber};
812 $form->{taxaccounts} .= "$ptr->{accno} ";
817 chop $ref->{taxaccounts};
818 push @{ $form->{invoice_details} }, $ref;
823 Common::webdav_folder($form) if ($main::webdav);
827 $main::lxdebug->leave_sub();
831 $main::lxdebug->enter_sub();
833 my ($self, $myconfig, $form, $params) = @_;
835 $params = $form unless defined $params && ref $params eq "HASH";
837 # connect to database
838 my $dbh = $form->dbconnect($myconfig);
840 my $dateformat = $myconfig->{dateformat};
841 $dateformat .= "yy" if $myconfig->{dateformat} !~ /^y/;
843 my $vid = conv_i($params->{vendor_id});
844 my $vnr = conv_i($params->{vendornumber});
848 ? "to_date(" . $dbh->quote($params->{invdate}) . ", '$dateformat')"
854 $where .= 'AND v.id = ?';
858 $where .= 'AND v.vendornumber = ?';
863 v.name AS vendor, v.creditlimit, v.terms, v.notes AS intnotes,
864 v.email, v.cc, v.bcc, v.language_id, v.payment_id,
865 v.street, v.zipcode, v.city, v.country, v.taxzone_id,
866 $duedate + COALESCE(pt.terms_netto, 0) AS duedate,
867 b.description AS business
869 LEFT JOIN business b ON (b.id = v.business_id)
870 LEFT JOIN payment_terms pt ON (v.payment_id = pt.id)
872 $ref = selectfirst_hashref_query($form, $dbh, $query, @values);
873 map { $params->{$_} = $ref->{$_} } keys %$ref;
875 $params->{creditremaining} = $params->{creditlimit};
877 $query = qq|SELECT SUM(amount - paid) FROM ap WHERE vendor_id = ?|;
878 my ($unpaid_invoices) = selectfirst_array_query($form, $dbh, $query, $vid);
879 $params->{creditremaining} -= $unpaid_invoices;
881 $query = qq|SELECT o.amount,
884 WHERE (e.curr = o.curr)
885 AND (e.transdate = o.transdate)) AS exch
887 WHERE (o.vendor_id = ?) AND (o.quotation = '0') AND (o.closed = '0')|;
888 my $sth = prepare_execute_query($form, $dbh, $query, $vid);
889 while (my ($amount, $exch) = $sth->fetchrow_array()) {
890 $exch = 1 unless $exch;
891 $params->{creditremaining} -= $amount * $exch;
895 # get shipto if we do not convert an order or invoice
896 if (!$params->{shipto}) {
897 delete @{$params}{qw(shiptoname shiptostreet shiptozipcode shiptocity shiptocountry shiptocontact shiptophone shiptofax shiptoemail)};
899 $query = qq|SELECT * FROM shipto WHERE (trans_id = ?) AND (module= 'CT')|;
900 $ref = selectfirst_hashref_query($form, $dbh, $query, $vid);
901 @{$params}{keys %$ref} = @{$ref}{keys %$ref};
902 map { $params->{$_} = $ref->{$_} } keys %$ref;
905 if (!$params->{id} && $params->{type} !~ /_(order|quotation)/) {
906 # setup last accounts used
908 qq|SELECT c.id, c.accno, c.description, c.link, c.category
910 JOIN acc_trans ac ON (ac.chart_id = c.id)
911 JOIN ap a ON (a.id = ac.trans_id)
912 WHERE (a.vendor_id = ?)
913 AND (NOT ((c.link LIKE '%_tax%') OR (c.link LIKE '%_paid%')))
914 AND (a.id IN (SELECT max(a2.id) FROM ap a2 WHERE a2.vendor_id = ?))|;
915 my $refs = selectall_hashref_query($form, $dbh, $query, $vid, $vid);
919 if ($ref->{category} eq 'E') {
922 if ($params->{initial_transdate}) {
923 my $tax_query = qq|SELECT tk.tax_id, t.rate FROM taxkeys tk
924 LEFT JOIN tax t ON (tk.tax_id = t.id)
925 WHERE (tk.chart_id = ?) AND (startdate <= ?)
926 ORDER BY tk.startdate DESC
928 my ($tax_id, $rate) = selectrow_query($form, $dbh, $tax_query, $ref->{id}, $params->{initial_transdate});
929 $params->{"taxchart_$i"} = "${tax_id}--${rate}";
932 $params->{"AP_amount_$i"} = "$ref->{accno}--$tax_id";
935 if ($ref->{category} eq 'L') {
936 $params->{APselected} = $params->{AP_1} = $ref->{accno};
939 $params->{rowcount} = $i if ($i && !$params->{type});
944 $main::lxdebug->leave_sub();
948 $main::lxdebug->enter_sub();
950 my ($self, $myconfig, $form) = @_;
952 # connect to database
953 my $dbh = $form->dbconnect($myconfig);
955 my $i = $form->{rowcount};
957 # don't include assemblies or obsolete parts
958 my $where = "NOT p.assembly = '1' AND NOT p.obsolete = '1'";
961 foreach my $table_column (qw(p.partnumber p.description pg.partsgroup)) {
962 my $field = (split m{\.}, $table_column)[1];
963 next unless $form->{"${field}_${i}"};
964 $where .= " AND lower(${table_column}) LIKE lower(?)";
965 push @values, '%' . $form->{"${field}_${i}"} . '%';
968 if ($form->{"description_$i"}) {
969 $where .= " ORDER BY p.description";
971 $where .= " ORDER BY p.partnumber";
975 if ($form->{type} eq "invoice") {
976 $transdate = $form->{invdate} ? $dbh->quote($form->{invdate}) : "current_date";
978 $transdate = $form->{transdate} ? $dbh->quote($form->{transdate}) : "current_date";
981 my $taxzone_id = $form->{taxzone_id} * 1;
982 $taxzone_id = 0 if ((3 < $taxzone_id) || (0 > $taxzone_id));
986 p.id, p.partnumber, p.description, p.lastcost AS sellprice, p.listprice,
987 p.unit, p.assembly, p.bin, p.onhand, p.formel,
988 p.notes AS partnotes, p.notes AS longdescription, p.not_discountable,
989 p.inventory_accno_id, p.price_factor_id,
991 pfac.factor AS price_factor,
993 c1.accno AS inventory_accno,
994 c1.new_chart_id AS inventory_new_chart,
995 date($transdate) - c1.valid_from AS inventory_valid,
997 c2.accno AS income_accno,
998 c2.new_chart_id AS income_new_chart,
999 date($transdate) - c2.valid_from AS income_valid,
1001 c3.accno AS expense_accno,
1002 c3.new_chart_id AS expense_new_chart,
1003 date($transdate) - c3.valid_from AS expense_valid,
1008 LEFT JOIN chart c1 ON
1009 ((SELECT inventory_accno_id
1010 FROM buchungsgruppen
1011 WHERE id = p.buchungsgruppen_id) = c1.id)
1012 LEFT JOIN chart c2 ON
1013 ((SELECT income_accno_id_${taxzone_id}
1014 FROM buchungsgruppen
1015 WHERE id = p.buchungsgruppen_id) = c2.id)
1016 LEFT JOIN chart c3 ON
1017 ((SELECT expense_accno_id_${taxzone_id}
1018 FROM buchungsgruppen
1019 WHERE id = p.buchungsgruppen_id) = c3.id)
1020 LEFT JOIN partsgroup pg ON (pg.id = p.partsgroup_id)
1021 LEFT JOIN price_factors pfac ON (pfac.id = p.price_factor_id)
1023 my $sth = prepare_execute_query($form, $dbh, $query, @values);
1025 $form->{item_list} = [];
1026 while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
1028 # In der Buchungsgruppe ist immer ein Bestandskonto verknuepft, auch wenn
1029 # es sich um eine Dienstleistung handelt. Bei Dienstleistungen muss das
1030 # Buchungskonto also aus dem Ergebnis rausgenommen werden.
1031 if (!$ref->{inventory_accno_id}) {
1032 map({ delete($ref->{"inventory_${_}"}); } qw(accno new_chart valid));
1034 delete($ref->{inventory_accno_id});
1036 # get tax rates and description
1037 $accno_id = ($form->{vc} eq "customer") ? $ref->{income_accno} : $ref->{expense_accno};
1039 qq|SELECT c.accno, t.taxdescription, t.rate, t.taxnumber
1041 LEFT JOIN chart c on (c.id = t.chart_id)
1049 AND (startdate <= $transdate)
1050 ORDER BY startdate DESC
1053 my $stw = prepare_execute_query($form, $dbh, $query, $accno_id);
1055 $ref->{taxaccounts} = "";
1057 while ($ptr = $stw->fetchrow_hashref(NAME_lc)) {
1059 # if ($customertax{$ref->{accno}}) {
1060 if (($ptr->{accno} eq "") && ($ptr->{rate} == 0)) {
1065 $ref->{taxaccounts} .= "$ptr->{accno} ";
1067 if (!($form->{taxaccounts} =~ /\Q$ptr->{accno}\E/)) {
1068 $form->{"$ptr->{accno}_rate"} = $ptr->{rate};
1069 $form->{"$ptr->{accno}_description"} = $ptr->{taxdescription};
1070 $form->{"$ptr->{accno}_taxnumber"} = $ptr->{taxnumber};
1071 $form->{taxaccounts} .= "$ptr->{accno} ";
1077 chop $ref->{taxaccounts};
1079 $ref->{onhand} *= 1;
1081 push @{ $form->{item_list} }, $ref;
1088 $main::lxdebug->leave_sub();
1091 sub vendor_details {
1092 $main::lxdebug->enter_sub();
1094 my ($self, $myconfig, $form, @wanted_vars) = @_;
1096 # connect to database
1097 my $dbh = $form->dbconnect($myconfig);
1101 # get contact id, set it if nessessary
1102 $form->{cp_id} *= 1;
1104 if ($form->{cp_id}) {
1105 $contact = "AND cp.cp_id = ?";
1106 push @values, $form->{cp_id};
1109 # get rest for the vendor
1110 # fax and phone and email as vendor*
1112 qq|SELECT ct.*, cp.*, ct.notes as vendornotes, phone as vendorphone, fax as vendorfax, email as vendoremail
1114 LEFT JOIN contacts cp ON (ct.id = cp.cp_cv_id)
1115 WHERE (ct.id = ?) $contact
1118 my $ref = selectfirst_hashref_query($form, $dbh, $query, $form->{vendor_id}, @values);
1120 # remove id and taxincluded before copy back
1121 delete @$ref{qw(id taxincluded)};
1123 @wanted_vars = grep({ $_ } @wanted_vars);
1124 if (scalar(@wanted_vars) > 0) {
1126 map({ $h_wanted_vars{$_} = 1; } @wanted_vars);
1127 map({ delete($ref->{$_}) unless ($h_wanted_vars{$_}); } keys(%{$ref}));
1130 map { $form->{$_} = $ref->{$_} } keys %$ref;
1132 my $custom_variables = CVar->get_custom_variables('dbh' => $dbh,
1134 'trans_id' => $form->{vendor_id});
1135 map { $form->{"vc_cvar_$_->{name}"} = $_->{value} } @{ $custom_variables };
1139 $main::lxdebug->leave_sub();
1143 $main::lxdebug->enter_sub();
1145 my ($self, $myconfig, $form) = @_;
1147 # connect to database
1148 my $dbh = $form->dbconnect($myconfig);
1151 qq|SELECT accno, description, link
1153 WHERE link LIKE '%IC%'
1155 my $sth = prepare_execute_query($query, $dbh, $query);
1157 while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
1158 foreach my $key (split(/:/, $ref->{link})) {
1160 push @{ $form->{IC_links}{$key} },
1161 { accno => $ref->{accno},
1162 description => $ref->{description} };
1170 $main::lxdebug->leave_sub();
1173 sub _delete_payments {
1174 $main::lxdebug->enter_sub();
1176 my ($self, $form, $dbh) = @_;
1180 # Delete old payment entries from acc_trans.
1184 WHERE (trans_id = ?) AND fx_transaction
1190 LEFT JOIN chart c ON (at.chart_id = c.id)
1191 WHERE (trans_id = ?) AND (c.link LIKE '%AP_paid%')|;
1192 push @delete_oids, selectall_array_query($form, $dbh, $query, conv_i($form->{id}), conv_i($form->{id}));
1197 LEFT JOIN chart c ON (at.chart_id = c.id)
1198 WHERE (trans_id = ?)
1199 AND ((c.link = 'AP') OR (c.link LIKE '%:AP') OR (c.link LIKE 'AP:%'))
1202 push @delete_oids, selectall_array_query($form, $dbh, $query, conv_i($form->{id}));
1205 $query = qq|DELETE FROM acc_trans WHERE oid IN (| . join(", ", @delete_oids) . qq|)|;
1206 do_query($form, $dbh, $query);
1209 $main::lxdebug->leave_sub();
1213 $main::lxdebug->enter_sub();
1215 my ($self, $myconfig, $form, $locale) = @_;
1217 # connect to database, turn off autocommit
1218 my $dbh = $form->dbconnect_noauto($myconfig);
1220 my (%payments, $old_form, $row, $item, $query, %keep_vars);
1222 $old_form = save_form();
1224 # Delete all entries in acc_trans from prior payments.
1225 $self->_delete_payments($form, $dbh);
1227 # Save the new payments the user made before cleaning up $form.
1228 map { $payments{$_} = $form->{$_} } grep m/^datepaid_\d+$|^memo_\d+$|^source_\d+$|^exchangerate_\d+$|^paid_\d+$|^AP_paid_\d+$|^paidaccounts$/, keys %{ $form };
1230 # Clean up $form so that old content won't tamper the results.
1231 %keep_vars = map { $_, 1 } qw(login password id);
1232 map { delete $form->{$_} unless $keep_vars{$_} } keys %{ $form };
1234 # Retrieve the invoice from the database.
1235 $self->retrieve_invoice($myconfig, $form);
1237 # Set up the content of $form in the way that IR::post_invoice() expects.
1238 $form->{exchangerate} = $form->format_amount($myconfig, $form->{exchangerate});
1240 for $row (1 .. scalar @{ $form->{invoice_details} }) {
1241 $item = $form->{invoice_details}->[$row - 1];
1243 map { $item->{$_} = $form->format_amount($myconfig, $item->{$_}) } qw(qty sellprice);
1245 map { $form->{"${_}_${row}"} = $item->{$_} } keys %{ $item };
1248 $form->{rowcount} = scalar @{ $form->{invoice_details} };
1250 delete @{$form}{qw(invoice_details paidaccounts storno paid)};
1252 # Restore the payment options from the user input.
1253 map { $form->{$_} = $payments{$_} } keys %payments;
1255 # Get the AP accno (which is normally done by Form::create_links()).
1259 LEFT JOIN chart c ON (at.chart_id = c.id)
1260 WHERE (trans_id = ?)
1261 AND ((c.link = 'AP') OR (c.link LIKE '%:AP') OR (c.link LIKE 'AP:%'))
1265 ($form->{AP}) = selectfirst_array_query($form, $dbh, $query, conv_i($form->{id}));
1267 # Post the new payments.
1268 $self->post_invoice($myconfig, $form, $dbh, 1);
1270 restore_form($old_form);
1272 my $rc = $dbh->commit();
1275 $main::lxdebug->leave_sub();