1 #=====================================================================
4 # Based on SQL-Ledger Version 2.1.9
5 # Web http://www.lx-office.org
7 #=====================================================================
8 # SQL-Ledger Accounting
11 # Author: Dieter Simader
12 # Email: dsimader@sql-ledger.org
13 # Web: http://www.sql-ledger.org
17 # This program is free software; you can redistribute it and/or modify
18 # it under the terms of the GNU General Public License as published by
19 # the Free Software Foundation; either version 2 of the License, or
20 # (at your option) any later version.
22 # This program is distributed in the hope that it will be useful,
23 # but WITHOUT ANY WARRANTY; without even the implied warranty of
24 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
25 # GNU General Public License for more details.
26 # You should have received a copy of the GNU General Public License
27 # along with this program; if not, write to the Free Software
28 # Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
29 #======================================================================
31 # Inventory received module
33 #======================================================================
43 use SL::GenericTranslations;
45 use List::Util qw(min);
48 $main::lxdebug->enter_sub();
50 my ($self, $myconfig, $form, $provided_dbh, $payments_only) = @_;
52 # connect to database, turn off autocommit
53 my $dbh = $provided_dbh ? $provided_dbh : $form->dbconnect_noauto($myconfig);
54 $form->{defaultcurrency} = $form->get_default_currency($myconfig);
56 my $ic_cvar_configs = CVar->get_configs(module => 'IC',
59 my ($query, $sth, @values, $project_id);
60 my ($allocated, $taxrate, $taxamount, $taxdiff, $item);
61 my ($amount, $linetotal, $lastinventoryaccno, $lastexpenseaccno);
62 my ($netamount, $invoicediff, $expensediff) = (0, 0, 0);
65 my $all_units = AM->retrieve_units($myconfig, $form);
67 if (!$payments_only) {
69 &reverse_invoice($dbh, $form);
71 ($form->{id}) = selectrow_query($form, $dbh, qq|SELECT nextval('glid')|);
72 do_query($form, $dbh, qq|INSERT INTO ap (id, invnumber) VALUES (?, '')|, $form->{id});
76 my ($currencies) = selectfirst_array_query($form, $dbh, qq|SELECT curr FROM defaults|);
77 my $defaultcurrency = (split m/:/, $currencies)[0];
79 if ($form->{currency} eq $defaultcurrency) {
80 $form->{exchangerate} = 1;
82 $exchangerate = $form->check_exchangerate($myconfig, $form->{currency}, $form->{transdate}, 'sell');
85 $form->{exchangerate} = $exchangerate || $form->parse_amount($myconfig, $form->{exchangerate});
86 $form->{exchangerate} = 1 unless ($form->{exchangerate} * 1);
89 my $q_item_unit = qq|SELECT unit FROM parts WHERE id = ?|;
90 my $h_item_unit = prepare_query($form, $dbh, $q_item_unit);
92 $form->get_lists('price_factors' => 'ALL_PRICE_FACTORS');
93 my %price_factors = map { $_->{id} => $_->{factor} } @{ $form->{ALL_PRICE_FACTORS} };
96 for my $i (1 .. $form->{rowcount}) {
97 next unless $form->{"id_$i"};
99 $form->{"qty_$i"} = $form->parse_amount($myconfig, $form->{"qty_$i"});
100 $form->{"qty_$i"} *= -1 if $form->{storno};
102 $form->{"inventory_accno_$i"} = $form->{"expense_accno_$i"} if $main::eur;
105 if (!$item_units{$form->{"id_$i"}}) {
106 do_statement($form, $h_item_unit, $q_item_unit, $form->{"id_$i"});
107 ($item_units{$form->{"id_$i"}}) = $h_item_unit->fetchrow_array();
110 my $item_unit = $item_units{$form->{"id_$i"}};
112 if (defined($all_units->{$item_unit}->{factor})
113 && ($all_units->{$item_unit}->{factor} ne '')
114 && ($all_units->{$item_unit}->{factor} * 1 != 0)) {
115 $basefactor = $all_units->{$form->{"unit_$i"}}->{factor} / $all_units->{$item_unit}->{factor};
119 $baseqty = $form->{"qty_$i"} * $basefactor;
121 @taxaccounts = split / /, $form->{"taxaccounts_$i"};
126 $form->{"sellprice_$i"} = $form->parse_amount($myconfig, $form->{"sellprice_$i"});
127 (my $fxsellprice = $form->{"sellprice_$i"}) =~ /\.(\d+)/;
129 my $decimalplaces = ($dec > 2) ? $dec : 2;
131 map { $taxrate += $form->{"${_}_rate"} } @taxaccounts;
133 $price_factor = $price_factors{ $form->{"price_factor_id_$i"} } || 1;
135 if ($form->{"inventory_accno_$i"}) {
137 $linetotal = $form->round_amount($form->{"sellprice_$i"} * $form->{"qty_$i"} / $price_factor, 2);
139 if ($form->{taxincluded}) {
140 $taxamount = $linetotal * ($taxrate / (1 + $taxrate));
141 $form->{"sellprice_$i"} = $form->{"sellprice_$i"} * (1 / (1 + $taxrate));
143 $taxamount = $linetotal * $taxrate;
146 $netamount += $linetotal;
148 if ($form->round_amount($taxrate, 7) == 0) {
149 if ($form->{taxincluded}) {
150 foreach $item (@taxaccounts) {
152 $form->round_amount($linetotal * $form->{"${item}_rate"} / (1 + abs($form->{"${item}_rate"})), 2);
153 $taxdiff += $taxamount;
154 $form->{amount}{ $form->{id} }{$item} -= $taxamount;
156 $form->{amount}{ $form->{id} }{ $taxaccounts[0] } += $taxdiff;
159 map { $form->{amount}{ $form->{id} }{$_} -= $linetotal * $form->{"${_}_rate"} } @taxaccounts;
163 map { $form->{amount}{ $form->{id} }{$_} -= $taxamount * $form->{"${_}_rate"} / $taxrate } @taxaccounts;
166 # add purchase to inventory, this one is without the tax!
167 $amount = $form->{"sellprice_$i"} * $form->{"qty_$i"} * $form->{exchangerate} / $price_factor;
168 $linetotal = $form->round_amount($form->{"sellprice_$i"} * $form->{"qty_$i"} / $price_factor, 2) * $form->{exchangerate};
169 $linetotal = $form->round_amount($linetotal, 2);
171 # this is the difference for the inventory
172 $invoicediff += ($amount - $linetotal);
174 $form->{amount}{ $form->{id} }{ $form->{"inventory_accno_$i"} } -= $linetotal;
176 # adjust and round sellprice
177 $form->{"sellprice_$i"} = $form->round_amount($form->{"sellprice_$i"} * $form->{exchangerate}, $decimalplaces);
179 $lastinventoryaccno = $form->{"inventory_accno_$i"};
181 next if $payments_only;
184 $query = qq|UPDATE parts SET lastcost = ? WHERE id = ?|;
185 @values = ($form->{"sellprice_$i"}, conv_i($form->{"id_$i"}));
186 do_query($form, $dbh, $query, @values);
188 # check if we sold the item already and
189 # make an entry for the expense and inventory
191 qq|SELECT i.id, i.qty, i.allocated, i.trans_id,
192 p.inventory_accno_id, p.expense_accno_id, a.transdate
193 FROM invoice i, ar a, parts p
194 WHERE (i.parts_id = p.id)
196 AND ((i.base_qty + i.allocated) > 0)
197 AND (i.trans_id = a.id)
199 $sth = prepare_execute_query($form, $dbh, $query, conv_i($form->{"id_$i"}));
201 my $totalqty = $base_qty;
203 while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
204 my $qty = min $totalqty, ($ref->{base_qty} + $ref->{allocated});
205 $linetotal = $form->round_amount(($form->{"sellprice_$i"} * $qty) / $basefactor, 2);
207 if ($ref->{allocated} < 0) {
209 # we have an entry for it already, adjust amount
210 $form->update_balance($dbh, "acc_trans", "amount",
211 qq| (trans_id = $ref->{trans_id})
212 AND (chart_id = $ref->{inventory_accno_id})
213 AND (transdate = '$ref->{transdate}')|,
216 $form->update_balance($dbh, "acc_trans", "amount",
217 qq| (trans_id = $ref->{trans_id})
218 AND (chart_id = $ref->{expense_accno_id})
219 AND (transdate = '$ref->{transdate}')|,
222 } elsif ($linetotal != 0) {
223 # add entry for inventory, this one is for the sold item
224 $query = qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate, taxkey) VALUES (?, ?, ?, ?, (SELECT taxkey_id FROM chart WHERE id = ?))|;
225 @values = ($ref->{trans_id}, $ref->{inventory_accno_id}, $linetotal, $ref->{transdate}, $ref->{inventory_accno_id});
226 do_query($form, $dbh, $query, @values);
229 $query = qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate, taxkey) VALUES (?, ?, ?, ?, (SELECT taxkey from tax WHERE chart_id = ?))|;
230 @values = ($ref->{trans_id}, $ref->{expense_accno_id}, ($linetotal * -1), $ref->{transdate}, $ref->{expense_accno_id});
231 do_query($form, $dbh, $query, @values);
234 # update allocated for sold item
235 $form->update_balance($dbh, "invoice", "allocated", qq|id = $ref->{id}|, $qty * -1);
239 last if ($totalqty -= $qty) <= 0;
244 } else { # if ($form->{"inventory_accno_id_$i"})
246 $linetotal = $form->round_amount($form->{"sellprice_$i"} * $form->{"qty_$i"} / $price_factor, 2);
248 if ($form->{taxincluded}) {
249 $taxamount = $linetotal * ($taxrate / (1 + $taxrate));
250 $form->{"sellprice_$i"} = $form->{"sellprice_$i"} * (1 / (1 + $taxrate));
253 $taxamount = $linetotal * $taxrate;
256 $netamount += $linetotal;
258 if ($form->round_amount($taxrate, 7) == 0) {
259 if ($form->{taxincluded}) {
260 foreach $item (@taxaccounts) {
261 $taxamount = $linetotal * $form->{"${item}_rate"} / (1 + abs($form->{"${item}_rate"}));
262 $totaltax += $taxamount;
263 $form->{amount}{ $form->{id} }{$item} -= $taxamount;
266 map { $form->{amount}{ $form->{id} }{$_} -= $linetotal * $form->{"${_}_rate"} } @taxaccounts;
269 map { $form->{amount}{ $form->{id} }{$_} -= $taxamount * $form->{"${_}_rate"} / $taxrate } @taxaccounts;
272 $amount = $form->{"sellprice_$i"} * $form->{"qty_$i"} * $form->{exchangerate} / $price_factor;
273 $linetotal = $form->round_amount($form->{"sellprice_$i"} * $form->{"qty_$i"} / $price_factor, 2) * $form->{exchangerate};
274 $linetotal = $form->round_amount($linetotal, 2);
276 # this is the difference for expense
277 $expensediff += ($amount - $linetotal);
279 # add amount to expense
280 $form->{amount}{ $form->{id} }{ $form->{"expense_accno_$i"} } -= $linetotal;
282 $lastexpenseaccno = $form->{"expense_accno_$i"};
284 # adjust and round sellprice
285 $form->{"sellprice_$i"} = $form->round_amount($form->{"sellprice_$i"} * $form->{exchangerate}, $decimalplaces);
287 next if $payments_only;
290 $query = qq|UPDATE parts SET lastcost = ? WHERE id = ?|;
291 do_query($form, $dbh, $query, $form->{"sellprice_$i"}, conv_i($form->{"id_$i"}));
294 next if $payments_only;
296 # save detail record in invoice table
297 my ($invoice_id) = selectfirst_array_query($form, $dbh, qq|SELECT nextval('invoiceid')|);
300 qq|INSERT INTO invoice (id, trans_id, parts_id, description, qty, base_qty,
301 sellprice, fxsellprice, allocated, unit, deliverydate,
302 project_id, serialnumber, price_factor_id, price_factor, marge_price_factor)
303 VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, (SELECT factor FROM price_factors WHERE id = ?), ?)|;
304 @values = ($invoice_id, conv_i($form->{id}), conv_i($form->{"id_$i"}),
305 $form->{"description_$i"}, $form->{"qty_$i"} * -1,
306 $baseqty * -1, $form->{"sellprice_$i"}, $fxsellprice, $allocated,
307 $form->{"unit_$i"}, conv_date($form->{deliverydate}),
308 conv_i($form->{"project_id_$i"}), $form->{"serialnumber_$i"},
309 conv_i($form->{"price_factor_id_$i"}), conv_i($form->{"price_factor_id_$i"}), conv_i($form->{"marge_price_factor_$i"}));
310 do_query($form, $dbh, $query, @values);
312 CVar->save_custom_variables(module => 'IC',
313 sub_module => 'invoice',
314 trans_id => $invoice_id,
315 configs => $ic_cvar_configs,
317 name_prefix => 'ic_',
318 name_postfix => "_$i",
322 $h_item_unit->finish();
324 $project_id = conv_i($form->{"globalproject_id"});
326 $form->{datepaid} = $form->{invdate};
328 # all amounts are in natural state, netamount includes the taxes
329 # if tax is included, netamount is rounded to 2 decimal places,
333 for my $i (1 .. $form->{paidaccounts}) {
334 $form->{"paid_$i"} = $form->parse_amount($myconfig, $form->{"paid_$i"});
335 $form->{paid} += $form->{"paid_$i"};
336 $form->{datepaid} = $form->{"datepaid_$i"} if $form->{"datepaid_$i"};
339 my ($tax, $paiddiff) = (0, 0);
341 $netamount = $form->round_amount($netamount, 2);
343 # figure out rounding errors for amount paid and total amount
344 if ($form->{taxincluded}) {
346 $amount = $form->round_amount($netamount * $form->{exchangerate}, 2);
347 $paiddiff = $amount - $netamount * $form->{exchangerate};
348 $netamount = $amount;
350 foreach $item (split / /, $form->{taxaccounts}) {
351 $amount = $form->{amount}{ $form->{id} }{$item} * $form->{exchangerate};
352 $form->{amount}{ $form->{id} }{$item} = $form->round_amount($amount, 2);
354 $amount = $form->{amount}{ $form->{id} }{$item} * -1;
356 $netamount -= $amount;
359 $invoicediff += $paiddiff;
360 $expensediff += $paiddiff;
362 ######## this only applies to tax included
364 $form->{amount}{ $form->{id} }{$lastinventoryaccno} -= $invoicediff if $lastinventoryaccno;
365 $form->{amount}{ $form->{id} }{$lastexpenseaccno} -= $expensediff if $lastexpenseaccno;
368 $amount = $form->round_amount($netamount * $form->{exchangerate}, 2);
369 $paiddiff = $amount - $netamount * $form->{exchangerate};
370 $netamount = $amount;
372 foreach my $item (split / /, $form->{taxaccounts}) {
373 $form->{amount}{ $form->{id} }{$item} = $form->round_amount($form->{amount}{ $form->{id} }{$item}, 2);
374 $amount = $form->round_amount( $form->{amount}{ $form->{id} }{$item} * $form->{exchangerate} * -1, 2);
375 $paiddiff += $amount - $form->{amount}{ $form->{id} }{$item} * $form->{exchangerate} * -1;
376 $form->{amount}{ $form->{id} }{$item} = $form->round_amount($amount * -1, 2);
377 $amount = $form->{amount}{ $form->{id} }{$item} * -1;
382 $form->{amount}{ $form->{id} }{ $form->{AP} } = $netamount + $tax;
385 $form->{paid} = $form->round_amount($form->{paid} * $form->{exchangerate} + $paiddiff, 2) if $form->{paid} != 0;
387 # update exchangerate
389 $form->update_exchangerate($dbh, $form->{currency}, $form->{invdate}, 0, $form->{exchangerate})
390 if ($form->{currency} ne $defaultcurrency) && !$exchangerate;
392 # record acc_trans transactions
393 foreach my $trans_id (keys %{ $form->{amount} }) {
394 foreach my $accno (keys %{ $form->{amount}{$trans_id} }) {
395 $form->{amount}{$trans_id}{$accno} = $form->round_amount($form->{amount}{$trans_id}{$accno}, 2);
397 next if $payments_only || !$form->{amount}{$trans_id}{$accno};
399 $query = qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate, taxkey, project_id)
400 VALUES (?, (SELECT id FROM chart WHERE accno = ?), ?, ?,
401 (SELECT taxkey_id FROM chart WHERE accno = ?), ?)|;
402 @values = ($trans_id, $accno, $form->{amount}{$trans_id}{$accno},
403 conv_date($form->{invdate}), $accno, $project_id);
404 do_query($form, $dbh, $query, @values);
408 # deduct payment differences from paiddiff
409 for my $i (1 .. $form->{paidaccounts}) {
410 if ($form->{"paid_$i"} != 0) {
411 $amount = $form->round_amount($form->{"paid_$i"} * $form->{exchangerate}, 2);
412 $paiddiff -= $amount - $form->{"paid_$i"} * $form->{exchangerate};
416 # force AP entry if 0
418 $form->{amount}{ $form->{id} }{ $form->{AP} } = $form->{paid} if $form->{amount}{$form->{id}}{$form->{AP}} == 0;
420 # record payments and offsetting AP
421 for my $i (1 .. $form->{paidaccounts}) {
422 next if $form->{"paid_$i"} == 0;
424 my ($accno) = split /--/, $form->{"AP_paid_$i"};
425 $form->{"datepaid_$i"} = $form->{invdate} unless ($form->{"datepaid_$i"});
426 $form->{datepaid} = $form->{"datepaid_$i"};
428 $amount = $form->round_amount($form->{"paid_$i"} * $form->{exchangerate} + $paiddiff, 2) * -1;
431 if ($form->{amount}{ $form->{id} }{ $form->{AP} } != 0) {
432 $query = qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate, taxkey, project_id)
433 VALUES (?, (SELECT id FROM chart WHERE accno = ?), ?, ?,
434 (SELECT taxkey_id FROM chart WHERE accno = ?), ?)|;
435 @values = (conv_i($form->{id}), $form->{AP}, $amount,
436 $form->{"datepaid_$i"}, $form->{AP}, $project_id);
437 do_query($form, $dbh, $query, @values);
441 $query = qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate, source, memo, taxkey, project_id)
442 VALUES (?, (SELECT id FROM chart WHERE accno = ?), ?, ?, ?, ?,
443 (SELECT taxkey_id FROM chart WHERE accno = ?), ?)|;
444 @values = (conv_i($form->{id}), $accno, $form->{"paid_$i"}, $form->{"datepaid_$i"},
445 $form->{"source_$i"}, $form->{"memo_$i"}, $accno, $project_id);
446 do_query($form, $dbh, $query, @values);
450 if ($form->{currency} eq $defaultcurrency) {
451 $form->{"exchangerate_$i"} = 1;
453 $exchangerate = $form->check_exchangerate($myconfig, $form->{currency}, $form->{"datepaid_$i"}, 'sell');
454 $form->{"exchangerate_$i"} = $exchangerate || $form->parse_amount($myconfig, $form->{"exchangerate_$i"});
457 # exchangerate difference
458 $form->{fx}{$accno}{ $form->{"datepaid_$i"} } += $form->{"paid_$i"} * ($form->{"exchangerate_$i"} - 1) + $paiddiff;
462 ($form->{"paid_$i"} * $form->{exchangerate}) -
463 ($form->{"paid_$i"} * $form->{"exchangerate_$i"});
465 $form->{fx}{ $form->{fxgain_accno} }{ $form->{"datepaid_$i"} } += $amount;
467 $form->{fx}{ $form->{fxloss_accno} }{ $form->{"datepaid_$i"} } += $amount;
472 # update exchange rate
473 $form->update_exchangerate($dbh, $form->{currency}, $form->{"datepaid_$i"}, 0, $form->{"exchangerate_$i"})
474 if ($form->{currency} ne $defaultcurrency) && !$exchangerate;
477 # record exchange rate differences and gains/losses
478 foreach my $accno (keys %{ $form->{fx} }) {
479 foreach my $transdate (keys %{ $form->{fx}{$accno} }) {
480 $form->{fx}{$accno}{$transdate} = $form->round_amount($form->{fx}{$accno}{$transdate}, 2);
481 next if ($form->{fx}{$accno}{$transdate} == 0);
483 $query = qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate, cleared, fx_transaction, taxkey, project_id)
484 VALUES (?, (SELECT id FROM chart WHERE accno = ?), ?, ?, '0', '1', 0, ?)|;
485 @values = (conv_i($form->{id}), $accno, $form->{fx}{$accno}{$transdate}, conv_date($transdate), $project_id);
486 do_query($form, $dbh, $query, @values);
490 if ($payments_only) {
491 $query = qq|UPDATE ap SET paid = ?, datepaid = ? WHERE id = ?|;
492 do_query($form, $dbh, $query, $form->{paid}, $form->{paid} ? conv_date($form->{datepaid}) : undef, conv_i($form->{id}));
494 if (!$provided_dbh) {
499 $main::lxdebug->leave_sub();
503 $amount = $netamount + $tax;
505 # set values which could be empty
506 my $taxzone_id = $form->{taxzone_id} * 1;
507 $form->{department_id} = (split /--/, $form->{department})[1];
508 $form->{invnumber} = $form->{id} unless $form->{invnumber};
510 $taxzone_id = 0 if (3 < $taxzone_id) || (0 > $taxzone_id);
513 $query = qq|UPDATE ap SET
514 invnumber = ?, ordnumber = ?, quonumber = ?, transdate = ?,
515 orddate = ?, quodate = ?, vendor_id = ?, amount = ?,
516 netamount = ?, paid = ?, duedate = ?, datepaid = ?,
517 invoice = ?, taxzone_id = ?, notes = ?, taxincluded = ?,
518 intnotes = ?, curr = ?, storno_id = ?, storno = ?,
519 cp_id = ?, employee_id = ?, department_id = ?,
523 $form->{invnumber}, $form->{ordnumber}, $form->{quonumber}, conv_date($form->{invdate}),
524 conv_date($form->{orddate}), conv_date($form->{quodate}), conv_i($form->{vendor_id}), $amount,
525 $netamount, $form->{paid}, conv_date($form->{duedate}), $form->{paid} ? conv_date($form->{datepaid}) : undef,
526 '1', $taxzone_id, $form->{notes}, $form->{taxincluded} ? 't' : 'f',
527 $form->{intnotes}, $form->{currency}, conv_i($form->{storno_id}), $form->{storno} ? 't' : 'f',
528 conv_i($form->{cp_id}), conv_i($form->{employee_id}), conv_i($form->{department_id}),
529 conv_i($form->{globalproject_id}),
532 do_query($form, $dbh, $query, @values);
534 if ($form->{storno}) {
535 $query = qq|UPDATE ap SET paid = paid + amount WHERE id = ?|;
536 do_query($form, $dbh, $query, conv_i($form->{storno_id}));
538 $query = qq|UPDATE ap SET storno = 't' WHERE id = ?|;
539 do_query($form, $dbh, $query, conv_i($form->{storno_id}));
541 $query = qq!UPDATE ap SET intnotes = ? || intnotes WHERE id = ?!;
542 do_query($form, $dbh, $query, "Rechnung storniert am $form->{invdate} ", conv_i($form->{storno_id}));
544 $query = qq|UPDATE ap SET paid = amount WHERE id = ?|;
545 do_query($form, $dbh, $query, conv_i($form->{id}));
550 $form->{name} = $form->{vendor};
551 $form->{name} =~ s/--\Q$form->{vendor_id}\E//;
552 $form->add_shipto($dbh, $form->{id}, "AP");
554 # delete zero entries
555 do_query($form, $dbh, qq|DELETE FROM acc_trans WHERE amount = 0|);
557 Common::webdav_folder($form) if ($main::webdav);
559 # Link this record to the records it was created from.
560 RecordLinks->create_links('dbh' => $dbh,
562 'from_table' => 'oe',
563 'from_ids' => $form->{convert_from_oe_ids},
565 'to_id' => $form->{id},
567 delete $form->{convert_from_oe_ids};
569 my @convert_from_do_ids = map { $_ * 1 } grep { $_ } split m/\s+/, $form->{convert_from_do_ids};
570 if (scalar @convert_from_do_ids) {
571 DO->close_orders('dbh' => $dbh,
572 'ids' => \@convert_from_do_ids);
574 RecordLinks->create_links('dbh' => $dbh,
576 'from_table' => 'delivery_orders',
577 'from_ids' => \@convert_from_do_ids,
579 'to_id' => $form->{id},
582 delete $form->{convert_from_do_ids};
584 ARAP->close_orders_if_billed('dbh' => $dbh,
585 'arap_id' => $form->{id},
589 if (!$provided_dbh) {
590 $rc = $dbh->commit();
594 $main::lxdebug->leave_sub();
599 sub reverse_invoice {
600 $main::lxdebug->enter_sub();
602 my ($dbh, $form) = @_;
604 # reverse inventory items
606 qq|SELECT i.parts_id, p.inventory_accno_id, p.expense_accno_id, i.qty, i.allocated, i.sellprice
607 FROM invoice i, parts p
608 WHERE (i.parts_id = p.id)
609 AND (i.trans_id = ?)|;
610 my $sth = prepare_execute_query($form, $dbh, $query, conv_i($form->{id}));
614 while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
615 $netamount += $form->round_amount($ref->{sellprice} * $ref->{qty} * -1, 2);
617 next unless $ref->{inventory_accno_id};
619 # if $ref->{allocated} > 0 than we sold that many items
620 next if ($ref->{allocated} <= 0);
622 # get references for sold items
624 qq|SELECT i.id, i.trans_id, i.allocated, a.transdate
626 WHERE (i.parts_id = ?)
627 AND (i.allocated < 0)
628 AND (i.trans_id = a.id)
629 ORDER BY transdate DESC|;
630 my $sth2 = prepare_execute_query($form, $dbh, $query, $ref->{parts_id});
632 while (my $pthref = $sth2->fetchrow_hashref(NAME_lc)) {
633 my $qty = $ref->{allocated};
634 if (($ref->{allocated} + $pthref->{allocated}) > 0) {
635 $qty = $pthref->{allocated} * -1;
638 my $amount = $form->round_amount($ref->{sellprice} * $qty, 2);
641 $form->update_balance($dbh, "invoice", "allocated", qq|id = $pthref->{id}|, $qty);
643 $form->update_balance($dbh, "acc_trans", "amount",
644 qq| (trans_id = $pthref->{trans_id})
645 AND (chart_id = $ref->{expense_accno_id})
646 AND (transdate = '$pthref->{transdate}')|,
649 $form->update_balance($dbh, "acc_trans", "amount",
650 qq| (trans_id = $pthref->{trans_id})
651 AND (chart_id = $ref->{inventory_accno_id})
652 AND (transdate = '$pthref->{transdate}')|,
655 last if (($ref->{allocated} -= $qty) <= 0);
661 my $id = conv_i($form->{id});
664 $query = qq|DELETE FROM acc_trans WHERE trans_id = ?|;
665 do_query($form, $dbh, $query, $id);
667 # delete invoice entries
668 $query = qq|DELETE FROM invoice WHERE trans_id = ?|;
669 do_query($form, $dbh, $query, $id);
671 $query = qq|DELETE FROM shipto WHERE (trans_id = ?) AND (module = 'AP')|;
672 do_query($form, $dbh, $query, $id);
674 $main::lxdebug->leave_sub();
678 $main::lxdebug->enter_sub();
680 my ($self, $myconfig, $form) = @_;
682 # connect to database
683 my $dbh = $form->dbconnect_noauto($myconfig);
685 &reverse_invoice($dbh, $form);
687 # delete zero entries
688 $query = qq|DELETE FROM acc_trans WHERE amount = 0|;
689 do_query($form, $dbh, $query);
692 $query = qq|DELETE FROM ap WHERE id = ?|;
693 do_query($form, $dbh, $query, conv_i($form->{id}));
695 my $rc = $dbh->commit;
698 $main::lxdebug->leave_sub();
703 sub retrieve_invoice {
704 $main::lxdebug->enter_sub();
706 my ($self, $myconfig, $form) = @_;
708 # connect to database
709 my $dbh = $form->dbconnect($myconfig);
711 my ($query, $sth, $ref, $q_invdate);
714 $q_invdate = qq|, COALESCE((SELECT transdate FROM ar WHERE id = (SELECT MAX(id) FROM ar)), current_date) AS invdate|;
715 if ($form->{vendor_id}) {
716 my $vendor_id = $dbh->quote($form->{vendor_id} * 1);
718 qq|, COALESCE((SELECT transdate FROM ar WHERE id = (SELECT MAX(id) FROM ar)), current_date) +
719 COALESCE((SELECT pt.terms_netto
721 LEFT JOIN payment_terms pt ON (v.payment_id = pt.id)
722 WHERE v.id = $vendor_id),
727 # get default accounts and last invoice number
730 (SELECT c.accno FROM chart c WHERE d.inventory_accno_id = c.id) AS inventory_accno,
731 (SELECT c.accno FROM chart c WHERE d.income_accno_id = c.id) AS income_accno,
732 (SELECT c.accno FROM chart c WHERE d.expense_accno_id = c.id) AS expense_accno,
733 (SELECT c.accno FROM chart c WHERE d.fxgain_accno_id = c.id) AS fxgain_accno,
734 (SELECT c.accno FROM chart c WHERE d.fxloss_accno_id = c.id) AS fxloss_accno,
738 $ref = selectfirst_hashref_query($form, $dbh, $query);
739 map { $form->{$_} = $ref->{$_} } keys %$ref;
743 $main::lxdebug->leave_sub();
749 $query = qq|SELECT cp_id, invnumber, transdate AS invdate, duedate,
750 orddate, quodate, globalproject_id,
751 ordnumber, quonumber, paid, taxincluded, notes, taxzone_id, storno, gldate,
752 intnotes, curr AS currency
755 $ref = selectfirst_hashref_query($form, $dbh, $query, conv_i($form->{id}));
756 map { $form->{$_} = $ref->{$_} } keys %$ref;
758 $form->{exchangerate} = $form->get_exchangerate($dbh, $form->{currency}, $form->{invdate}, "sell");
761 $query = qq|SELECT * FROM shipto WHERE (trans_id = ?) AND (module = 'AP')|;
762 $ref = selectfirst_hashref_query($form, $dbh, $query, conv_i($form->{id}));
764 map { $form->{$_} = $ref->{$_} } keys %$ref;
766 my $transdate = $form->{invdate} ? $dbh->quote($form->{invdate}) : "current_date";
767 my $taxzone_id = $form->{taxzone_id} * 1;
769 $taxzone_id = 0 if ((3 < $taxzone_id) || (0 > $taxzone_id));
771 # retrieve individual items
774 c1.accno AS inventory_accno, c1.new_chart_id AS inventory_new_chart, date($transdate) - c1.valid_from AS inventory_valid,
775 c2.accno AS income_accno, c2.new_chart_id AS income_new_chart, date($transdate) - c2.valid_from AS income_valid,
776 c3.accno AS expense_accno, c3.new_chart_id AS expense_new_chart, date($transdate) - c3.valid_from AS expense_valid,
779 i.description, i.qty, i.fxsellprice AS sellprice, i.parts_id AS id, i.unit, i.deliverydate, i.project_id, i.serialnumber,
780 i.price_factor_id, i.price_factor, i.marge_price_factor,
781 p.partnumber, p.inventory_accno_id AS part_inventory_accno_id, p.bin, pr.projectnumber, pg.partsgroup
784 JOIN parts p ON (i.parts_id = p.id)
785 LEFT JOIN chart c1 ON ((SELECT inventory_accno_id FROM buchungsgruppen WHERE id = p.buchungsgruppen_id) = c1.id)
786 LEFT JOIN chart c2 ON ((SELECT income_accno_id_${taxzone_id} FROM buchungsgruppen WHERE id = p.buchungsgruppen_id) = c2.id)
787 LEFT JOIN chart c3 ON ((SELECT expense_accno_id_${taxzone_id} FROM buchungsgruppen WHERE id = p.buchungsgruppen_id) = c3.id)
788 LEFT JOIN project pr ON (i.project_id = pr.id)
789 LEFT JOIN partsgroup pg ON (pg.id = p.partsgroup_id)
794 $sth = prepare_execute_query($form, $dbh, $query, conv_i($form->{id}));
796 while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
797 # Retrieve custom variables.
798 my $cvars = CVar->get_custom_variables(dbh => $dbh,
800 sub_module => 'invoice',
801 trans_id => $ref->{invoice_id},
803 map { $ref->{"ic_cvar_$_->{name}"} = $_->{value} } @{ $cvars };
804 delete $ref->{invoice_id};
806 map({ delete($ref->{$_}); } qw(inventory_accno inventory_new_chart inventory_valid)) if !$ref->{"part_inventory_accno_id"};
807 delete($ref->{"part_inventory_accno_id"});
809 foreach my $type (qw(inventory income expense)) {
810 while ($ref->{"${type}_new_chart"} && ($ref->{"${type}_valid"} >=0)) {
811 my $query = qq|SELECT accno, new_chart_id, date($transdate) - valid_from FROM chart WHERE id = ?|;
812 @$ref{ map $type.$_, qw(_accno _new_chart _valid) } = selectrow_query($form, $dbh, $query, $ref->{"${type}_new_chart"});
816 # get tax rates and description
817 my $accno_id = ($form->{vc} eq "customer") ? $ref->{income_accno} : $ref->{expense_accno};
819 qq|SELECT c.accno, t.taxdescription, t.rate, t.taxnumber FROM tax t
820 LEFT JOIN chart c ON (c.id = t.chart_id)
822 (SELECT tk.tax_id FROM taxkeys tk
823 WHERE tk.chart_id = (SELECT id FROM chart WHERE accno = ?)
824 AND (startdate <= $transdate)
825 ORDER BY startdate DESC
828 my $stw = prepare_execute_query($form, $dbh, $query, $accno_id);
829 $ref->{taxaccounts} = "";
832 while ($ptr = $stw->fetchrow_hashref(NAME_lc)) {
833 if (($ptr->{accno} eq "") && ($ptr->{rate} == 0)) {
838 $ref->{taxaccounts} .= "$ptr->{accno} ";
840 if (!($form->{taxaccounts} =~ /\Q$ptr->{accno}\E/)) {
841 $form->{"$ptr->{accno}_rate"} = $ptr->{rate};
842 $form->{"$ptr->{accno}_description"} = $ptr->{taxdescription};
843 $form->{"$ptr->{accno}_taxnumber"} = $ptr->{taxnumber};
844 $form->{taxaccounts} .= "$ptr->{accno} ";
849 chop $ref->{taxaccounts};
850 push @{ $form->{invoice_details} }, $ref;
855 Common::webdav_folder($form) if ($main::webdav);
859 $main::lxdebug->leave_sub();
863 $main::lxdebug->enter_sub();
865 my ($self, $myconfig, $form, $params) = @_;
867 $params = $form unless defined $params && ref $params eq "HASH";
869 # connect to database
870 my $dbh = $form->dbconnect($myconfig);
872 my $dateformat = $myconfig->{dateformat};
873 $dateformat .= "yy" if $myconfig->{dateformat} !~ /^y/;
875 my $vid = conv_i($params->{vendor_id});
876 my $vnr = conv_i($params->{vendornumber});
880 ? "to_date(" . $dbh->quote($params->{invdate}) . ", '$dateformat')"
887 $where .= 'AND v.id = ?';
891 $where .= 'AND v.vendornumber = ?';
896 v.id AS vendor_id, v.name AS vendor, v.discount as vendor_discount,
897 v.creditlimit, v.terms, v.notes AS intnotes,
898 v.email, v.cc, v.bcc, v.language_id, v.payment_id,
899 v.street, v.zipcode, v.city, v.country, v.taxzone_id,
900 $duedate + COALESCE(pt.terms_netto, 0) AS duedate,
901 b.description AS business
903 LEFT JOIN business b ON (b.id = v.business_id)
904 LEFT JOIN payment_terms pt ON (v.payment_id = pt.id)
906 $ref = selectfirst_hashref_query($form, $dbh, $query, @values);
907 map { $params->{$_} = $ref->{$_} } keys %$ref;
909 $params->{creditremaining} = $params->{creditlimit};
911 $query = qq|SELECT SUM(amount - paid) FROM ap WHERE vendor_id = ?|;
912 my ($unpaid_invoices) = selectfirst_array_query($form, $dbh, $query, $vid);
913 $params->{creditremaining} -= $unpaid_invoices;
915 $query = qq|SELECT o.amount,
918 WHERE (e.curr = o.curr)
919 AND (e.transdate = o.transdate)) AS exch
921 WHERE (o.vendor_id = ?) AND (o.quotation = '0') AND (o.closed = '0')|;
922 my $sth = prepare_execute_query($form, $dbh, $query, $vid);
923 while (my ($amount, $exch) = $sth->fetchrow_array()) {
924 $exch = 1 unless $exch;
925 $params->{creditremaining} -= $amount * $exch;
929 # get shipto if we do not convert an order or invoice
930 if (!$params->{shipto}) {
931 delete @{$params}{qw(shiptoname shiptostreet shiptozipcode shiptocity shiptocountry shiptocontact shiptophone shiptofax shiptoemail)};
933 $query = qq|SELECT * FROM shipto WHERE (trans_id = ?) AND (module= 'CT')|;
934 $ref = selectfirst_hashref_query($form, $dbh, $query, $vid);
935 @{$params}{keys %$ref} = @{$ref}{keys %$ref};
936 map { $params->{$_} = $ref->{$_} } keys %$ref;
939 if (!$params->{id} && $params->{type} !~ /_(order|quotation)/) {
940 # setup last accounts used
942 qq|SELECT c.id, c.accno, c.description, c.link, c.category
944 JOIN acc_trans ac ON (ac.chart_id = c.id)
945 JOIN ap a ON (a.id = ac.trans_id)
946 WHERE (a.vendor_id = ?)
947 AND (NOT ((c.link LIKE '%_tax%') OR (c.link LIKE '%_paid%')))
948 AND (a.id IN (SELECT max(a2.id) FROM ap a2 WHERE a2.vendor_id = ?))|;
949 my $refs = selectall_hashref_query($form, $dbh, $query, $vid, $vid);
953 if ($ref->{category} eq 'E') {
956 if ($params->{initial_transdate}) {
957 my $tax_query = qq|SELECT tk.tax_id, t.rate FROM taxkeys tk
958 LEFT JOIN tax t ON (tk.tax_id = t.id)
959 WHERE (tk.chart_id = ?) AND (startdate <= ?)
960 ORDER BY tk.startdate DESC
962 my ($tax_id, $rate) = selectrow_query($form, $dbh, $tax_query, $ref->{id}, $params->{initial_transdate});
963 $params->{"taxchart_$i"} = "${tax_id}--${rate}";
966 $params->{"AP_amount_$i"} = "$ref->{accno}--$tax_id";
969 if ($ref->{category} eq 'L') {
970 $params->{APselected} = $params->{AP_1} = $ref->{accno};
973 $params->{rowcount} = $i if ($i && !$params->{type});
978 $main::lxdebug->leave_sub();
982 $main::lxdebug->enter_sub();
984 my ($self, $myconfig, $form) = @_;
986 # connect to database
987 my $dbh = $form->dbconnect($myconfig);
989 my $i = $form->{rowcount};
991 # don't include assemblies or obsolete parts
992 my $where = "NOT p.assembly = '1' AND NOT p.obsolete = '1'";
995 foreach my $table_column (qw(p.partnumber p.description pg.partsgroup)) {
996 my $field = (split m{\.}, $table_column)[1];
997 next unless $form->{"${field}_${i}"};
998 $where .= " AND lower(${table_column}) LIKE lower(?)";
999 push @values, '%' . $form->{"${field}_${i}"} . '%';
1001 #Es soll auch nach EAN gesucht werden, ohne Einschränkung durch Beschreibung
1002 if ($form->{"partnumber_$i"} && !$form->{"description_$i"}) {
1003 $where .= qq| OR (NOT p.obsolete = '1' AND p.ean = ? )|;
1004 push @values, $form->{"partnumber_$i"};
1007 if ($form->{"description_$i"}) {
1008 $where .= " ORDER BY p.description";
1010 $where .= " ORDER BY p.partnumber";
1014 if ($form->{type} eq "invoice") {
1015 $transdate = $form->{invdate} ? $dbh->quote($form->{invdate}) : "current_date";
1017 $transdate = $form->{transdate} ? $dbh->quote($form->{transdate}) : "current_date";
1020 my $taxzone_id = $form->{taxzone_id} * 1;
1021 $taxzone_id = 0 if ((3 < $taxzone_id) || (0 > $taxzone_id));
1025 p.id, p.partnumber, p.description, p.lastcost AS sellprice, p.listprice,
1026 p.unit, p.assembly, p.bin, p.onhand, p.formel,
1027 p.notes AS partnotes, p.notes AS longdescription, p.not_discountable,
1028 p.inventory_accno_id, p.price_factor_id,
1030 pfac.factor AS price_factor,
1032 c1.accno AS inventory_accno,
1033 c1.new_chart_id AS inventory_new_chart,
1034 date($transdate) - c1.valid_from AS inventory_valid,
1036 c2.accno AS income_accno,
1037 c2.new_chart_id AS income_new_chart,
1038 date($transdate) - c2.valid_from AS income_valid,
1040 c3.accno AS expense_accno,
1041 c3.new_chart_id AS expense_new_chart,
1042 date($transdate) - c3.valid_from AS expense_valid,
1047 LEFT JOIN chart c1 ON
1048 ((SELECT inventory_accno_id
1049 FROM buchungsgruppen
1050 WHERE id = p.buchungsgruppen_id) = c1.id)
1051 LEFT JOIN chart c2 ON
1052 ((SELECT income_accno_id_${taxzone_id}
1053 FROM buchungsgruppen
1054 WHERE id = p.buchungsgruppen_id) = c2.id)
1055 LEFT JOIN chart c3 ON
1056 ((SELECT expense_accno_id_${taxzone_id}
1057 FROM buchungsgruppen
1058 WHERE id = p.buchungsgruppen_id) = c3.id)
1059 LEFT JOIN partsgroup pg ON (pg.id = p.partsgroup_id)
1060 LEFT JOIN price_factors pfac ON (pfac.id = p.price_factor_id)
1062 my $sth = prepare_execute_query($form, $dbh, $query, @values);
1064 $form->{item_list} = [];
1065 while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
1067 # In der Buchungsgruppe ist immer ein Bestandskonto verknuepft, auch wenn
1068 # es sich um eine Dienstleistung handelt. Bei Dienstleistungen muss das
1069 # Buchungskonto also aus dem Ergebnis rausgenommen werden.
1070 if (!$ref->{inventory_accno_id}) {
1071 map({ delete($ref->{"inventory_${_}"}); } qw(accno new_chart valid));
1073 delete($ref->{inventory_accno_id});
1075 # get tax rates and description
1076 $accno_id = ($form->{vc} eq "customer") ? $ref->{income_accno} : $ref->{expense_accno};
1078 qq|SELECT c.accno, t.taxdescription, t.rate, t.taxnumber
1080 LEFT JOIN chart c on (c.id = t.chart_id)
1088 AND (startdate <= $transdate)
1089 ORDER BY startdate DESC
1092 my $stw = prepare_execute_query($form, $dbh, $query, $accno_id);
1094 $ref->{taxaccounts} = "";
1096 while ($ptr = $stw->fetchrow_hashref(NAME_lc)) {
1098 # if ($customertax{$ref->{accno}}) {
1099 if (($ptr->{accno} eq "") && ($ptr->{rate} == 0)) {
1104 $ref->{taxaccounts} .= "$ptr->{accno} ";
1106 if (!($form->{taxaccounts} =~ /\Q$ptr->{accno}\E/)) {
1107 $form->{"$ptr->{accno}_rate"} = $ptr->{rate};
1108 $form->{"$ptr->{accno}_description"} = $ptr->{taxdescription};
1109 $form->{"$ptr->{accno}_taxnumber"} = $ptr->{taxnumber};
1110 $form->{taxaccounts} .= "$ptr->{accno} ";
1116 chop $ref->{taxaccounts};
1118 $ref->{onhand} *= 1;
1120 push @{ $form->{item_list} }, $ref;
1126 foreach my $item (@{ $form->{item_list} }) {
1127 my $custom_variables = CVar->get_custom_variables(module => 'IC',
1128 trans_id => $item->{id},
1132 map { $item->{"ic_cvar_" . $_->{name} } = $_->{value} } @{ $custom_variables };
1137 $main::lxdebug->leave_sub();
1140 sub vendor_details {
1141 $main::lxdebug->enter_sub();
1143 my ($self, $myconfig, $form, @wanted_vars) = @_;
1145 # connect to database
1146 my $dbh = $form->dbconnect($myconfig);
1150 # get contact id, set it if nessessary
1151 $form->{cp_id} *= 1;
1153 if ($form->{cp_id}) {
1154 $contact = "AND cp.cp_id = ?";
1155 push @values, $form->{cp_id};
1158 # get rest for the vendor
1159 # fax and phone and email as vendor*
1161 qq|SELECT ct.*, cp.*, ct.notes as vendornotes, phone as vendorphone, fax as vendorfax, email as vendoremail
1163 LEFT JOIN contacts cp ON (ct.id = cp.cp_cv_id)
1164 WHERE (ct.id = ?) $contact
1167 my $ref = selectfirst_hashref_query($form, $dbh, $query, $form->{vendor_id}, @values);
1169 # remove id and taxincluded before copy back
1170 delete @$ref{qw(id taxincluded)};
1172 @wanted_vars = grep({ $_ } @wanted_vars);
1173 if (scalar(@wanted_vars) > 0) {
1175 map({ $h_wanted_vars{$_} = 1; } @wanted_vars);
1176 map({ delete($ref->{$_}) unless ($h_wanted_vars{$_}); } keys(%{$ref}));
1179 map { $form->{$_} = $ref->{$_} } keys %$ref;
1181 my $custom_variables = CVar->get_custom_variables('dbh' => $dbh,
1183 'trans_id' => $form->{vendor_id});
1184 map { $form->{"vc_cvar_$_->{name}"} = $_->{value} } @{ $custom_variables };
1186 $form->{cp_greeting} = GenericTranslations->get('dbh' => $dbh,
1187 'translation_type' => 'greetings::' . ($form->{cp_gender} eq 'f' ? 'female' : 'male'),
1188 'allow_fallback' => 1);
1192 $main::lxdebug->leave_sub();
1196 $main::lxdebug->enter_sub();
1198 my ($self, $myconfig, $form) = @_;
1200 # connect to database
1201 my $dbh = $form->dbconnect($myconfig);
1204 qq|SELECT accno, description, link
1206 WHERE link LIKE '%IC%'
1208 my $sth = prepare_execute_query($query, $dbh, $query);
1210 while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
1211 foreach my $key (split(/:/, $ref->{link})) {
1213 push @{ $form->{IC_links}{$key} },
1214 { accno => $ref->{accno},
1215 description => $ref->{description} };
1223 $main::lxdebug->leave_sub();
1226 sub _delete_payments {
1227 $main::lxdebug->enter_sub();
1229 my ($self, $form, $dbh) = @_;
1231 my @delete_acc_trans_ids;
1233 # Delete old payment entries from acc_trans.
1235 qq|SELECT acc_trans_id
1237 WHERE (trans_id = ?) AND fx_transaction
1241 SELECT at.acc_trans_id
1243 LEFT JOIN chart c ON (at.chart_id = c.id)
1244 WHERE (trans_id = ?) AND (c.link LIKE '%AP_paid%')|;
1245 push @delete_acc_trans_ids, selectall_array_query($form, $dbh, $query, conv_i($form->{id}), conv_i($form->{id}));
1248 qq|SELECT at.acc_trans_id
1250 LEFT JOIN chart c ON (at.chart_id = c.id)
1251 WHERE (trans_id = ?)
1252 AND ((c.link = 'AP') OR (c.link LIKE '%:AP') OR (c.link LIKE 'AP:%'))
1253 ORDER BY at.acc_trans_id
1255 push @delete_acc_trans_ids, selectall_array_query($form, $dbh, $query, conv_i($form->{id}));
1257 if (@delete_acc_trans_ids) {
1258 $query = qq|DELETE FROM acc_trans WHERE acc_trans_id IN (| . join(", ", @delete_acc_trans_ids) . qq|)|;
1259 do_query($form, $dbh, $query);
1262 $main::lxdebug->leave_sub();
1266 $main::lxdebug->enter_sub();
1268 my ($self, $myconfig, $form, $locale) = @_;
1270 # connect to database, turn off autocommit
1271 my $dbh = $form->dbconnect_noauto($myconfig);
1273 my (%payments, $old_form, $row, $item, $query, %keep_vars);
1275 $old_form = save_form();
1277 # Delete all entries in acc_trans from prior payments.
1278 $self->_delete_payments($form, $dbh);
1280 # Save the new payments the user made before cleaning up $form.
1281 map { $payments{$_} = $form->{$_} } grep m/^datepaid_\d+$|^memo_\d+$|^source_\d+$|^exchangerate_\d+$|^paid_\d+$|^AP_paid_\d+$|^paidaccounts$/, keys %{ $form };
1283 # Clean up $form so that old content won't tamper the results.
1284 %keep_vars = map { $_, 1 } qw(login password id);
1285 map { delete $form->{$_} unless $keep_vars{$_} } keys %{ $form };
1287 # Retrieve the invoice from the database.
1288 $self->retrieve_invoice($myconfig, $form);
1290 # Set up the content of $form in the way that IR::post_invoice() expects.
1291 $form->{exchangerate} = $form->format_amount($myconfig, $form->{exchangerate});
1293 for $row (1 .. scalar @{ $form->{invoice_details} }) {
1294 $item = $form->{invoice_details}->[$row - 1];
1296 map { $item->{$_} = $form->format_amount($myconfig, $item->{$_}) } qw(qty sellprice);
1298 map { $form->{"${_}_${row}"} = $item->{$_} } keys %{ $item };
1301 $form->{rowcount} = scalar @{ $form->{invoice_details} };
1303 delete @{$form}{qw(invoice_details paidaccounts storno paid)};
1305 # Restore the payment options from the user input.
1306 map { $form->{$_} = $payments{$_} } keys %payments;
1308 # Get the AP accno (which is normally done by Form::create_links()).
1312 LEFT JOIN chart c ON (at.chart_id = c.id)
1313 WHERE (trans_id = ?)
1314 AND ((c.link = 'AP') OR (c.link LIKE '%:AP') OR (c.link LIKE 'AP:%'))
1315 ORDER BY at.acc_trans_id
1318 ($form->{AP}) = selectfirst_array_query($form, $dbh, $query, conv_i($form->{id}));
1320 # Post the new payments.
1321 $self->post_invoice($myconfig, $form, $dbh, 1);
1323 restore_form($old_form);
1325 my $rc = $dbh->commit();
1328 $main::lxdebug->leave_sub();
1334 $main::lxdebug->enter_sub();
1339 if (!$params{vendor_id} || !$params{invdate}) {
1340 $main::lxdebug->leave_sub();
1341 return $params{default};
1344 my $myconfig = \%main::myconfig;
1345 my $form = $main::form;
1347 my $dbh = $params{dbh} || $form->get_standard_dbh($myconfig);
1349 my $query = qq|SELECT ?::date + pt.terms_netto
1351 LEFT JOIN payment_terms pt ON (pt.id = v.payment_id)
1354 my ($sth, $duedate);
1356 if (($sth = $dbh->prepare($query)) && $sth->execute($params{invdate}, conv_i($params{vendor_id}))) {
1357 ($duedate) = $sth->fetchrow_array();
1363 $duedate ||= $params{default};
1365 $main::lxdebug->leave_sub();