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;
134 #####################################################################
135 # das ist aus IS.pm kopiert. schlimm. jb 7.10.2009
136 # ich würde mir wünschen, dass diese vier stellen zusammengefasst werden
137 # ... vier stellen = (einkauf + verkauf) * (maske + backend)
138 # ansonsten stolpert man immer wieder viermal statt einmal heftig
139 # und auch das undo discount formatting ist nicht besonders wartungsfreundlich
141 # keep entered selling price
142 my $fxsellprice = $form->parse_amount($myconfig, $form->{"sellprice_$i"});
144 # keine ahnung wofür das in IS.pm gemacht wird:
145 # my ($dec) = ($fxsellprice =~ /\.(\d+)/);
146 # $dec = length $dec;
147 # my $decimalplaces = ($dec > 2) ? $dec : 2;
149 # undo discount formatting
150 $form->{"discount_$i"} = $form->parse_amount($myconfig, $form->{"discount_$i"}) / 100;
152 $form->{"sellprice_$i"} = $fxsellprice * (1 - $form->{"discount_$i"});
154 ######################################################################
155 if ($form->{"inventory_accno_$i"}) {
157 $linetotal = $form->round_amount($form->{"sellprice_$i"} * $form->{"qty_$i"} / $price_factor, 2);
159 if ($form->{taxincluded}) {
160 $taxamount = $linetotal * ($taxrate / (1 + $taxrate));
161 $form->{"sellprice_$i"} = $form->{"sellprice_$i"} * (1 / (1 + $taxrate));
163 $taxamount = $linetotal * $taxrate;
166 $netamount += $linetotal;
168 if ($form->round_amount($taxrate, 7) == 0) {
169 if ($form->{taxincluded}) {
170 foreach $item (@taxaccounts) {
172 $form->round_amount($linetotal * $form->{"${item}_rate"} / (1 + abs($form->{"${item}_rate"})), 2);
173 $taxdiff += $taxamount;
174 $form->{amount}{ $form->{id} }{$item} -= $taxamount;
176 $form->{amount}{ $form->{id} }{ $taxaccounts[0] } += $taxdiff;
179 map { $form->{amount}{ $form->{id} }{$_} -= $linetotal * $form->{"${_}_rate"} } @taxaccounts;
183 map { $form->{amount}{ $form->{id} }{$_} -= $taxamount * $form->{"${_}_rate"} / $taxrate } @taxaccounts;
186 # add purchase to inventory, this one is without the tax!
187 $amount = $form->{"sellprice_$i"} * $form->{"qty_$i"} * $form->{exchangerate} / $price_factor;
188 $linetotal = $form->round_amount($form->{"sellprice_$i"} * $form->{"qty_$i"} / $price_factor, 2) * $form->{exchangerate};
189 $linetotal = $form->round_amount($linetotal, 2);
191 # this is the difference for the inventory
192 $invoicediff += ($amount - $linetotal);
194 $form->{amount}{ $form->{id} }{ $form->{"inventory_accno_$i"} } -= $linetotal;
196 # adjust and round sellprice
197 $form->{"sellprice_$i"} = $form->round_amount($form->{"sellprice_$i"} * $form->{exchangerate}, $decimalplaces);
199 $lastinventoryaccno = $form->{"inventory_accno_$i"};
201 next if $payments_only;
204 $query = qq|UPDATE parts SET lastcost = ? WHERE id = ?|;
205 @values = ($form->{"sellprice_$i"}, conv_i($form->{"id_$i"}));
206 do_query($form, $dbh, $query, @values);
208 # check if we sold the item already and
209 # make an entry for the expense and inventory
211 qq|SELECT i.id, i.qty, i.allocated, i.trans_id,
212 p.inventory_accno_id, p.expense_accno_id, a.transdate
213 FROM invoice i, ar a, parts p
214 WHERE (i.parts_id = p.id)
216 AND ((i.base_qty + i.allocated) > 0)
217 AND (i.trans_id = a.id)
219 $sth = prepare_execute_query($form, $dbh, $query, conv_i($form->{"id_$i"}));
221 my $totalqty = $base_qty;
223 while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
224 my $qty = min $totalqty, ($ref->{base_qty} + $ref->{allocated});
225 $linetotal = $form->round_amount(($form->{"sellprice_$i"} * $qty) / $basefactor, 2);
227 if ($ref->{allocated} < 0) {
229 # we have an entry for it already, adjust amount
230 $form->update_balance($dbh, "acc_trans", "amount",
231 qq| (trans_id = $ref->{trans_id})
232 AND (chart_id = $ref->{inventory_accno_id})
233 AND (transdate = '$ref->{transdate}')|,
236 $form->update_balance($dbh, "acc_trans", "amount",
237 qq| (trans_id = $ref->{trans_id})
238 AND (chart_id = $ref->{expense_accno_id})
239 AND (transdate = '$ref->{transdate}')|,
242 } elsif ($linetotal != 0) {
243 # add entry for inventory, this one is for the sold item
244 $query = qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate, taxkey) VALUES (?, ?, ?, ?, (SELECT taxkey_id FROM chart WHERE id = ?))|;
245 @values = ($ref->{trans_id}, $ref->{inventory_accno_id}, $linetotal, $ref->{transdate}, $ref->{inventory_accno_id});
246 do_query($form, $dbh, $query, @values);
249 $query = qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate, taxkey) VALUES (?, ?, ?, ?, (SELECT taxkey from tax WHERE chart_id = ?))|;
250 @values = ($ref->{trans_id}, $ref->{expense_accno_id}, ($linetotal * -1), $ref->{transdate}, $ref->{expense_accno_id});
251 do_query($form, $dbh, $query, @values);
254 # update allocated for sold item
255 $form->update_balance($dbh, "invoice", "allocated", qq|id = $ref->{id}|, $qty * -1);
259 last if ($totalqty -= $qty) <= 0;
264 } else { # if ($form->{"inventory_accno_id_$i"})
266 $linetotal = $form->round_amount($form->{"sellprice_$i"} * $form->{"qty_$i"} / $price_factor, 2);
268 if ($form->{taxincluded}) {
269 $taxamount = $linetotal * ($taxrate / (1 + $taxrate));
270 $form->{"sellprice_$i"} = $form->{"sellprice_$i"} * (1 / (1 + $taxrate));
273 $taxamount = $linetotal * $taxrate;
276 $netamount += $linetotal;
278 if ($form->round_amount($taxrate, 7) == 0) {
279 if ($form->{taxincluded}) {
280 foreach $item (@taxaccounts) {
281 $taxamount = $linetotal * $form->{"${item}_rate"} / (1 + abs($form->{"${item}_rate"}));
282 $totaltax += $taxamount;
283 $form->{amount}{ $form->{id} }{$item} -= $taxamount;
286 map { $form->{amount}{ $form->{id} }{$_} -= $linetotal * $form->{"${_}_rate"} } @taxaccounts;
289 map { $form->{amount}{ $form->{id} }{$_} -= $taxamount * $form->{"${_}_rate"} / $taxrate } @taxaccounts;
292 $amount = $form->{"sellprice_$i"} * $form->{"qty_$i"} * $form->{exchangerate} / $price_factor;
293 $linetotal = $form->round_amount($form->{"sellprice_$i"} * $form->{"qty_$i"} / $price_factor, 2) * $form->{exchangerate};
294 $linetotal = $form->round_amount($linetotal, 2);
296 # this is the difference for expense
297 $expensediff += ($amount - $linetotal);
299 # add amount to expense
300 $form->{amount}{ $form->{id} }{ $form->{"expense_accno_$i"} } -= $linetotal;
302 $lastexpenseaccno = $form->{"expense_accno_$i"};
304 # adjust and round sellprice
305 $form->{"sellprice_$i"} = $form->round_amount($form->{"sellprice_$i"} * $form->{exchangerate}, $decimalplaces);
307 next if $payments_only;
310 $query = qq|UPDATE parts SET lastcost = ? WHERE id = ?|;
311 do_query($form, $dbh, $query, $form->{"sellprice_$i"}, conv_i($form->{"id_$i"}));
314 next if $payments_only;
316 # save detail record in invoice table
317 my ($invoice_id) = selectfirst_array_query($form, $dbh, qq|SELECT nextval('invoiceid')|);
320 qq|INSERT INTO invoice (id, trans_id, parts_id, description, qty, base_qty,
321 sellprice, fxsellprice, discount, allocated, unit, deliverydate,
322 project_id, serialnumber, price_factor_id, price_factor, marge_price_factor)
323 VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, (SELECT factor FROM price_factors WHERE id = ?), ?)|;
324 @values = ($invoice_id, conv_i($form->{id}), conv_i($form->{"id_$i"}),
325 $form->{"description_$i"}, $form->{"qty_$i"} * -1,
326 $baseqty * -1, $form->{"sellprice_$i"}, $fxsellprice, $form->{"discount_$i"}, $allocated,
327 $form->{"unit_$i"}, conv_date($form->{deliverydate}),
328 conv_i($form->{"project_id_$i"}), $form->{"serialnumber_$i"},
329 conv_i($form->{"price_factor_id_$i"}), conv_i($form->{"price_factor_id_$i"}), conv_i($form->{"marge_price_factor_$i"}));
330 do_query($form, $dbh, $query, @values);
332 CVar->save_custom_variables(module => 'IC',
333 sub_module => 'invoice',
334 trans_id => $invoice_id,
335 configs => $ic_cvar_configs,
337 name_prefix => 'ic_',
338 name_postfix => "_$i",
342 $h_item_unit->finish();
344 $project_id = conv_i($form->{"globalproject_id"});
346 $form->{datepaid} = $form->{invdate};
348 # all amounts are in natural state, netamount includes the taxes
349 # if tax is included, netamount is rounded to 2 decimal places,
353 for my $i (1 .. $form->{paidaccounts}) {
354 $form->{"paid_$i"} = $form->parse_amount($myconfig, $form->{"paid_$i"});
355 $form->{paid} += $form->{"paid_$i"};
356 $form->{datepaid} = $form->{"datepaid_$i"} if $form->{"datepaid_$i"};
359 my ($tax, $paiddiff) = (0, 0);
361 $netamount = $form->round_amount($netamount, 2);
363 # figure out rounding errors for amount paid and total amount
364 if ($form->{taxincluded}) {
366 $amount = $form->round_amount($netamount * $form->{exchangerate}, 2);
367 $paiddiff = $amount - $netamount * $form->{exchangerate};
368 $netamount = $amount;
370 foreach $item (split / /, $form->{taxaccounts}) {
371 $amount = $form->{amount}{ $form->{id} }{$item} * $form->{exchangerate};
372 $form->{amount}{ $form->{id} }{$item} = $form->round_amount($amount, 2);
374 $amount = $form->{amount}{ $form->{id} }{$item} * -1;
376 $netamount -= $amount;
379 $invoicediff += $paiddiff;
380 $expensediff += $paiddiff;
382 ######## this only applies to tax included
384 $form->{amount}{ $form->{id} }{$lastinventoryaccno} -= $invoicediff if $lastinventoryaccno;
385 $form->{amount}{ $form->{id} }{$lastexpenseaccno} -= $expensediff if $lastexpenseaccno;
388 $amount = $form->round_amount($netamount * $form->{exchangerate}, 2);
389 $paiddiff = $amount - $netamount * $form->{exchangerate};
390 $netamount = $amount;
392 foreach my $item (split / /, $form->{taxaccounts}) {
393 $form->{amount}{ $form->{id} }{$item} = $form->round_amount($form->{amount}{ $form->{id} }{$item}, 2);
394 $amount = $form->round_amount( $form->{amount}{ $form->{id} }{$item} * $form->{exchangerate} * -1, 2);
395 $paiddiff += $amount - $form->{amount}{ $form->{id} }{$item} * $form->{exchangerate} * -1;
396 $form->{amount}{ $form->{id} }{$item} = $form->round_amount($amount * -1, 2);
397 $amount = $form->{amount}{ $form->{id} }{$item} * -1;
402 $form->{amount}{ $form->{id} }{ $form->{AP} } = $netamount + $tax;
405 $form->{paid} = $form->round_amount($form->{paid} * $form->{exchangerate} + $paiddiff, 2) if $form->{paid} != 0;
407 # update exchangerate
409 $form->update_exchangerate($dbh, $form->{currency}, $form->{invdate}, 0, $form->{exchangerate})
410 if ($form->{currency} ne $defaultcurrency) && !$exchangerate;
412 # record acc_trans transactions
413 foreach my $trans_id (keys %{ $form->{amount} }) {
414 foreach my $accno (keys %{ $form->{amount}{$trans_id} }) {
415 $form->{amount}{$trans_id}{$accno} = $form->round_amount($form->{amount}{$trans_id}{$accno}, 2);
417 next if $payments_only || !$form->{amount}{$trans_id}{$accno};
419 $query = qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate, taxkey, project_id)
420 VALUES (?, (SELECT id FROM chart WHERE accno = ?), ?, ?,
421 (SELECT taxkey_id FROM chart WHERE accno = ?), ?)|;
422 @values = ($trans_id, $accno, $form->{amount}{$trans_id}{$accno},
423 conv_date($form->{invdate}), $accno, $project_id);
424 do_query($form, $dbh, $query, @values);
428 # deduct payment differences from paiddiff
429 for my $i (1 .. $form->{paidaccounts}) {
430 if ($form->{"paid_$i"} != 0) {
431 $amount = $form->round_amount($form->{"paid_$i"} * $form->{exchangerate}, 2);
432 $paiddiff -= $amount - $form->{"paid_$i"} * $form->{exchangerate};
436 # force AP entry if 0
438 $form->{amount}{ $form->{id} }{ $form->{AP} } = $form->{paid} if $form->{amount}{$form->{id}}{$form->{AP}} == 0;
440 # record payments and offsetting AP
441 for my $i (1 .. $form->{paidaccounts}) {
442 next if $form->{"paid_$i"} == 0;
444 my ($accno) = split /--/, $form->{"AP_paid_$i"};
445 $form->{"datepaid_$i"} = $form->{invdate} unless ($form->{"datepaid_$i"});
446 $form->{datepaid} = $form->{"datepaid_$i"};
448 $amount = $form->round_amount($form->{"paid_$i"} * $form->{exchangerate} + $paiddiff, 2) * -1;
451 if ($form->{amount}{ $form->{id} }{ $form->{AP} } != 0) {
452 $query = qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate, taxkey, project_id)
453 VALUES (?, (SELECT id FROM chart WHERE accno = ?), ?, ?,
454 (SELECT taxkey_id FROM chart WHERE accno = ?), ?)|;
455 @values = (conv_i($form->{id}), $form->{AP}, $amount,
456 $form->{"datepaid_$i"}, $form->{AP}, $project_id);
457 do_query($form, $dbh, $query, @values);
461 $query = qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate, source, memo, taxkey, project_id)
462 VALUES (?, (SELECT id FROM chart WHERE accno = ?), ?, ?, ?, ?,
463 (SELECT taxkey_id FROM chart WHERE accno = ?), ?)|;
464 @values = (conv_i($form->{id}), $accno, $form->{"paid_$i"}, $form->{"datepaid_$i"},
465 $form->{"source_$i"}, $form->{"memo_$i"}, $accno, $project_id);
466 do_query($form, $dbh, $query, @values);
470 if ($form->{currency} eq $defaultcurrency) {
471 $form->{"exchangerate_$i"} = 1;
473 $exchangerate = $form->check_exchangerate($myconfig, $form->{currency}, $form->{"datepaid_$i"}, 'sell');
474 $form->{"exchangerate_$i"} = $exchangerate || $form->parse_amount($myconfig, $form->{"exchangerate_$i"});
477 # exchangerate difference
478 $form->{fx}{$accno}{ $form->{"datepaid_$i"} } += $form->{"paid_$i"} * ($form->{"exchangerate_$i"} - 1) + $paiddiff;
482 ($form->{"paid_$i"} * $form->{exchangerate}) -
483 ($form->{"paid_$i"} * $form->{"exchangerate_$i"});
485 $form->{fx}{ $form->{fxgain_accno} }{ $form->{"datepaid_$i"} } += $amount;
487 $form->{fx}{ $form->{fxloss_accno} }{ $form->{"datepaid_$i"} } += $amount;
492 # update exchange rate
493 $form->update_exchangerate($dbh, $form->{currency}, $form->{"datepaid_$i"}, 0, $form->{"exchangerate_$i"})
494 if ($form->{currency} ne $defaultcurrency) && !$exchangerate;
497 # record exchange rate differences and gains/losses
498 foreach my $accno (keys %{ $form->{fx} }) {
499 foreach my $transdate (keys %{ $form->{fx}{$accno} }) {
500 $form->{fx}{$accno}{$transdate} = $form->round_amount($form->{fx}{$accno}{$transdate}, 2);
501 next if ($form->{fx}{$accno}{$transdate} == 0);
503 $query = qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate, cleared, fx_transaction, taxkey, project_id)
504 VALUES (?, (SELECT id FROM chart WHERE accno = ?), ?, ?, '0', '1', 0, ?)|;
505 @values = (conv_i($form->{id}), $accno, $form->{fx}{$accno}{$transdate}, conv_date($transdate), $project_id);
506 do_query($form, $dbh, $query, @values);
510 if ($payments_only) {
511 $query = qq|UPDATE ap SET paid = ?, datepaid = ? WHERE id = ?|;
512 do_query($form, $dbh, $query, $form->{paid}, $form->{paid} ? conv_date($form->{datepaid}) : undef, conv_i($form->{id}));
514 if (!$provided_dbh) {
519 $main::lxdebug->leave_sub();
523 $amount = $netamount + $tax;
525 # set values which could be empty
526 my $taxzone_id = $form->{taxzone_id} * 1;
527 $form->{department_id} = (split /--/, $form->{department})[1];
528 $form->{invnumber} = $form->{id} unless $form->{invnumber};
530 $taxzone_id = 0 if (3 < $taxzone_id) || (0 > $taxzone_id);
533 $query = qq|UPDATE ap SET
534 invnumber = ?, ordnumber = ?, quonumber = ?, transdate = ?,
535 orddate = ?, quodate = ?, vendor_id = ?, amount = ?,
536 netamount = ?, paid = ?, duedate = ?, datepaid = ?,
537 invoice = ?, taxzone_id = ?, notes = ?, taxincluded = ?,
538 intnotes = ?, curr = ?, storno_id = ?, storno = ?,
539 cp_id = ?, employee_id = ?, department_id = ?,
543 $form->{invnumber}, $form->{ordnumber}, $form->{quonumber}, conv_date($form->{invdate}),
544 conv_date($form->{orddate}), conv_date($form->{quodate}), conv_i($form->{vendor_id}), $amount,
545 $netamount, $form->{paid}, conv_date($form->{duedate}), $form->{paid} ? conv_date($form->{datepaid}) : undef,
546 '1', $taxzone_id, $form->{notes}, $form->{taxincluded} ? 't' : 'f',
547 $form->{intnotes}, $form->{currency}, conv_i($form->{storno_id}), $form->{storno} ? 't' : 'f',
548 conv_i($form->{cp_id}), conv_i($form->{employee_id}), conv_i($form->{department_id}),
549 conv_i($form->{globalproject_id}),
552 do_query($form, $dbh, $query, @values);
554 if ($form->{storno}) {
555 $query = qq|UPDATE ap SET paid = paid + amount WHERE id = ?|;
556 do_query($form, $dbh, $query, conv_i($form->{storno_id}));
558 $query = qq|UPDATE ap SET storno = 't' WHERE id = ?|;
559 do_query($form, $dbh, $query, conv_i($form->{storno_id}));
561 $query = qq!UPDATE ap SET intnotes = ? || intnotes WHERE id = ?!;
562 do_query($form, $dbh, $query, "Rechnung storniert am $form->{invdate} ", conv_i($form->{storno_id}));
564 $query = qq|UPDATE ap SET paid = amount WHERE id = ?|;
565 do_query($form, $dbh, $query, conv_i($form->{id}));
570 $form->{name} = $form->{vendor};
571 $form->{name} =~ s/--\Q$form->{vendor_id}\E//;
572 $form->add_shipto($dbh, $form->{id}, "AP");
574 # delete zero entries
575 do_query($form, $dbh, qq|DELETE FROM acc_trans WHERE amount = 0|);
577 Common::webdav_folder($form) if ($main::webdav);
579 # Link this record to the records it was created from.
580 RecordLinks->create_links('dbh' => $dbh,
582 'from_table' => 'oe',
583 'from_ids' => $form->{convert_from_oe_ids},
585 'to_id' => $form->{id},
587 delete $form->{convert_from_oe_ids};
589 my @convert_from_do_ids = map { $_ * 1 } grep { $_ } split m/\s+/, $form->{convert_from_do_ids};
590 if (scalar @convert_from_do_ids) {
591 DO->close_orders('dbh' => $dbh,
592 'ids' => \@convert_from_do_ids);
594 RecordLinks->create_links('dbh' => $dbh,
596 'from_table' => 'delivery_orders',
597 'from_ids' => \@convert_from_do_ids,
599 'to_id' => $form->{id},
602 delete $form->{convert_from_do_ids};
604 ARAP->close_orders_if_billed('dbh' => $dbh,
605 'arap_id' => $form->{id},
609 if (!$provided_dbh) {
610 $rc = $dbh->commit();
614 $main::lxdebug->leave_sub();
619 sub reverse_invoice {
620 $main::lxdebug->enter_sub();
622 my ($dbh, $form) = @_;
624 # reverse inventory items
626 qq|SELECT i.parts_id, p.inventory_accno_id, p.expense_accno_id, i.qty, i.allocated, i.sellprice
627 FROM invoice i, parts p
628 WHERE (i.parts_id = p.id)
629 AND (i.trans_id = ?)|;
630 my $sth = prepare_execute_query($form, $dbh, $query, conv_i($form->{id}));
634 while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
635 $netamount += $form->round_amount($ref->{sellprice} * $ref->{qty} * -1, 2);
637 next unless $ref->{inventory_accno_id};
639 # if $ref->{allocated} > 0 than we sold that many items
640 next if ($ref->{allocated} <= 0);
642 # get references for sold items
644 qq|SELECT i.id, i.trans_id, i.allocated, a.transdate
646 WHERE (i.parts_id = ?)
647 AND (i.allocated < 0)
648 AND (i.trans_id = a.id)
649 ORDER BY transdate DESC|;
650 my $sth2 = prepare_execute_query($form, $dbh, $query, $ref->{parts_id});
652 while (my $pthref = $sth2->fetchrow_hashref(NAME_lc)) {
653 my $qty = $ref->{allocated};
654 if (($ref->{allocated} + $pthref->{allocated}) > 0) {
655 $qty = $pthref->{allocated} * -1;
658 my $amount = $form->round_amount($ref->{sellprice} * $qty, 2);
661 $form->update_balance($dbh, "invoice", "allocated", qq|id = $pthref->{id}|, $qty);
663 $form->update_balance($dbh, "acc_trans", "amount",
664 qq| (trans_id = $pthref->{trans_id})
665 AND (chart_id = $ref->{expense_accno_id})
666 AND (transdate = '$pthref->{transdate}')|,
669 $form->update_balance($dbh, "acc_trans", "amount",
670 qq| (trans_id = $pthref->{trans_id})
671 AND (chart_id = $ref->{inventory_accno_id})
672 AND (transdate = '$pthref->{transdate}')|,
675 last if (($ref->{allocated} -= $qty) <= 0);
681 my $id = conv_i($form->{id});
684 $query = qq|DELETE FROM acc_trans WHERE trans_id = ?|;
685 do_query($form, $dbh, $query, $id);
687 # delete invoice entries
688 $query = qq|DELETE FROM invoice WHERE trans_id = ?|;
689 do_query($form, $dbh, $query, $id);
691 $query = qq|DELETE FROM shipto WHERE (trans_id = ?) AND (module = 'AP')|;
692 do_query($form, $dbh, $query, $id);
694 $main::lxdebug->leave_sub();
698 $main::lxdebug->enter_sub();
700 my ($self, $myconfig, $form) = @_;
702 # connect to database
703 my $dbh = $form->dbconnect_noauto($myconfig);
705 &reverse_invoice($dbh, $form);
707 # delete zero entries
708 $query = qq|DELETE FROM acc_trans WHERE amount = 0|;
709 do_query($form, $dbh, $query);
712 $query = qq|DELETE FROM ap WHERE id = ?|;
713 do_query($form, $dbh, $query, conv_i($form->{id}));
715 my $rc = $dbh->commit;
718 $main::lxdebug->leave_sub();
723 sub retrieve_invoice {
724 $main::lxdebug->enter_sub();
726 my ($self, $myconfig, $form) = @_;
728 # connect to database
729 my $dbh = $form->dbconnect($myconfig);
731 my ($query, $sth, $ref, $q_invdate);
734 $q_invdate = qq|, COALESCE((SELECT transdate FROM ar WHERE id = (SELECT MAX(id) FROM ar)), current_date) AS invdate|;
735 if ($form->{vendor_id}) {
736 my $vendor_id = $dbh->quote($form->{vendor_id} * 1);
738 qq|, COALESCE((SELECT transdate FROM ar WHERE id = (SELECT MAX(id) FROM ar)), current_date) +
739 COALESCE((SELECT pt.terms_netto
741 LEFT JOIN payment_terms pt ON (v.payment_id = pt.id)
742 WHERE v.id = $vendor_id),
747 # get default accounts and last invoice number
750 (SELECT c.accno FROM chart c WHERE d.inventory_accno_id = c.id) AS inventory_accno,
751 (SELECT c.accno FROM chart c WHERE d.income_accno_id = c.id) AS income_accno,
752 (SELECT c.accno FROM chart c WHERE d.expense_accno_id = c.id) AS expense_accno,
753 (SELECT c.accno FROM chart c WHERE d.fxgain_accno_id = c.id) AS fxgain_accno,
754 (SELECT c.accno FROM chart c WHERE d.fxloss_accno_id = c.id) AS fxloss_accno,
758 $ref = selectfirst_hashref_query($form, $dbh, $query);
759 map { $form->{$_} = $ref->{$_} } keys %$ref;
763 $main::lxdebug->leave_sub();
769 $query = qq|SELECT cp_id, invnumber, transdate AS invdate, duedate,
770 orddate, quodate, globalproject_id,
771 ordnumber, quonumber, paid, taxincluded, notes, taxzone_id, storno, gldate,
772 intnotes, curr AS currency
775 $ref = selectfirst_hashref_query($form, $dbh, $query, conv_i($form->{id}));
776 map { $form->{$_} = $ref->{$_} } keys %$ref;
778 $form->{exchangerate} = $form->get_exchangerate($dbh, $form->{currency}, $form->{invdate}, "sell");
781 $query = qq|SELECT * FROM shipto WHERE (trans_id = ?) AND (module = 'AP')|;
782 $ref = selectfirst_hashref_query($form, $dbh, $query, conv_i($form->{id}));
784 map { $form->{$_} = $ref->{$_} } keys %$ref;
786 my $transdate = $form->{invdate} ? $dbh->quote($form->{invdate}) : "current_date";
787 my $taxzone_id = $form->{taxzone_id} * 1;
789 $taxzone_id = 0 if ((3 < $taxzone_id) || (0 > $taxzone_id));
791 # retrieve individual items
794 c1.accno AS inventory_accno, c1.new_chart_id AS inventory_new_chart, date($transdate) - c1.valid_from AS inventory_valid,
795 c2.accno AS income_accno, c2.new_chart_id AS income_new_chart, date($transdate) - c2.valid_from AS income_valid,
796 c3.accno AS expense_accno, c3.new_chart_id AS expense_new_chart, date($transdate) - c3.valid_from AS expense_valid,
799 i.description, i.qty, i.fxsellprice AS sellprice, i.parts_id AS id, i.unit, i.deliverydate, i.project_id, i.serialnumber,
800 i.price_factor_id, i.price_factor, i.marge_price_factor, i.discount,
801 p.partnumber, p.inventory_accno_id AS part_inventory_accno_id, p.bin, pr.projectnumber, pg.partsgroup
804 JOIN parts p ON (i.parts_id = p.id)
805 LEFT JOIN chart c1 ON ((SELECT inventory_accno_id FROM buchungsgruppen WHERE id = p.buchungsgruppen_id) = c1.id)
806 LEFT JOIN chart c2 ON ((SELECT income_accno_id_${taxzone_id} FROM buchungsgruppen WHERE id = p.buchungsgruppen_id) = c2.id)
807 LEFT JOIN chart c3 ON ((SELECT expense_accno_id_${taxzone_id} FROM buchungsgruppen WHERE id = p.buchungsgruppen_id) = c3.id)
808 LEFT JOIN project pr ON (i.project_id = pr.id)
809 LEFT JOIN partsgroup pg ON (pg.id = p.partsgroup_id)
814 $sth = prepare_execute_query($form, $dbh, $query, conv_i($form->{id}));
816 while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
817 # Retrieve custom variables.
818 my $cvars = CVar->get_custom_variables(dbh => $dbh,
820 sub_module => 'invoice',
821 trans_id => $ref->{invoice_id},
823 map { $ref->{"ic_cvar_$_->{name}"} = $_->{value} } @{ $cvars };
824 delete $ref->{invoice_id};
826 map({ delete($ref->{$_}); } qw(inventory_accno inventory_new_chart inventory_valid)) if !$ref->{"part_inventory_accno_id"};
827 delete($ref->{"part_inventory_accno_id"});
829 foreach my $type (qw(inventory income expense)) {
830 while ($ref->{"${type}_new_chart"} && ($ref->{"${type}_valid"} >=0)) {
831 my $query = qq|SELECT accno, new_chart_id, date($transdate) - valid_from FROM chart WHERE id = ?|;
832 @$ref{ map $type.$_, qw(_accno _new_chart _valid) } = selectrow_query($form, $dbh, $query, $ref->{"${type}_new_chart"});
836 # get tax rates and description
837 my $accno_id = ($form->{vc} eq "customer") ? $ref->{income_accno} : $ref->{expense_accno};
839 qq|SELECT c.accno, t.taxdescription, t.rate, t.taxnumber FROM tax t
840 LEFT JOIN chart c ON (c.id = t.chart_id)
842 (SELECT tk.tax_id FROM taxkeys tk
843 WHERE tk.chart_id = (SELECT id FROM chart WHERE accno = ?)
844 AND (startdate <= $transdate)
845 ORDER BY startdate DESC
848 my $stw = prepare_execute_query($form, $dbh, $query, $accno_id);
849 $ref->{taxaccounts} = "";
852 while ($ptr = $stw->fetchrow_hashref(NAME_lc)) {
853 if (($ptr->{accno} eq "") && ($ptr->{rate} == 0)) {
858 $ref->{taxaccounts} .= "$ptr->{accno} ";
860 if (!($form->{taxaccounts} =~ /\Q$ptr->{accno}\E/)) {
861 $form->{"$ptr->{accno}_rate"} = $ptr->{rate};
862 $form->{"$ptr->{accno}_description"} = $ptr->{taxdescription};
863 $form->{"$ptr->{accno}_taxnumber"} = $ptr->{taxnumber};
864 $form->{taxaccounts} .= "$ptr->{accno} ";
869 chop $ref->{taxaccounts};
870 push @{ $form->{invoice_details} }, $ref;
875 Common::webdav_folder($form) if ($main::webdav);
879 $main::lxdebug->leave_sub();
883 $main::lxdebug->enter_sub();
885 my ($self, $myconfig, $form, $params) = @_;
887 $params = $form unless defined $params && ref $params eq "HASH";
889 # connect to database
890 my $dbh = $form->dbconnect($myconfig);
892 my $dateformat = $myconfig->{dateformat};
893 $dateformat .= "yy" if $myconfig->{dateformat} !~ /^y/;
895 my $vid = conv_i($params->{vendor_id});
896 my $vnr = conv_i($params->{vendornumber});
900 ? "to_date(" . $dbh->quote($params->{invdate}) . ", '$dateformat')"
907 $where .= 'AND v.id = ?';
911 $where .= 'AND v.vendornumber = ?';
916 v.id AS vendor_id, v.name AS vendor, v.discount as vendor_discount,
917 v.creditlimit, v.terms, v.notes AS intnotes,
918 v.email, v.cc, v.bcc, v.language_id, v.payment_id,
919 v.street, v.zipcode, v.city, v.country, v.taxzone_id,
920 $duedate + COALESCE(pt.terms_netto, 0) AS duedate,
921 b.description AS business
923 LEFT JOIN business b ON (b.id = v.business_id)
924 LEFT JOIN payment_terms pt ON (v.payment_id = pt.id)
926 $ref = selectfirst_hashref_query($form, $dbh, $query, @values);
927 map { $params->{$_} = $ref->{$_} } keys %$ref;
929 $params->{creditremaining} = $params->{creditlimit};
931 $query = qq|SELECT SUM(amount - paid) FROM ap WHERE vendor_id = ?|;
932 my ($unpaid_invoices) = selectfirst_array_query($form, $dbh, $query, $vid);
933 $params->{creditremaining} -= $unpaid_invoices;
935 $query = qq|SELECT o.amount,
938 WHERE (e.curr = o.curr)
939 AND (e.transdate = o.transdate)) AS exch
941 WHERE (o.vendor_id = ?) AND (o.quotation = '0') AND (o.closed = '0')|;
942 my $sth = prepare_execute_query($form, $dbh, $query, $vid);
943 while (my ($amount, $exch) = $sth->fetchrow_array()) {
944 $exch = 1 unless $exch;
945 $params->{creditremaining} -= $amount * $exch;
949 # get shipto if we do not convert an order or invoice
950 if (!$params->{shipto}) {
951 delete @{$params}{qw(shiptoname shiptostreet shiptozipcode shiptocity shiptocountry shiptocontact shiptophone shiptofax shiptoemail)};
953 $query = qq|SELECT * FROM shipto WHERE (trans_id = ?) AND (module= 'CT')|;
954 $ref = selectfirst_hashref_query($form, $dbh, $query, $vid);
955 @{$params}{keys %$ref} = @{$ref}{keys %$ref};
956 map { $params->{$_} = $ref->{$_} } keys %$ref;
959 if (!$params->{id} && $params->{type} !~ /_(order|quotation)/) {
960 # setup last accounts used
962 qq|SELECT c.id, c.accno, c.description, c.link, c.category
964 JOIN acc_trans ac ON (ac.chart_id = c.id)
965 JOIN ap a ON (a.id = ac.trans_id)
966 WHERE (a.vendor_id = ?)
967 AND (NOT ((c.link LIKE '%_tax%') OR (c.link LIKE '%_paid%')))
968 AND (a.id IN (SELECT max(a2.id) FROM ap a2 WHERE a2.vendor_id = ?))|;
969 my $refs = selectall_hashref_query($form, $dbh, $query, $vid, $vid);
973 if ($ref->{category} eq 'E') {
976 if ($params->{initial_transdate}) {
977 my $tax_query = qq|SELECT tk.tax_id, t.rate FROM taxkeys tk
978 LEFT JOIN tax t ON (tk.tax_id = t.id)
979 WHERE (tk.chart_id = ?) AND (startdate <= ?)
980 ORDER BY tk.startdate DESC
982 my ($tax_id, $rate) = selectrow_query($form, $dbh, $tax_query, $ref->{id}, $params->{initial_transdate});
983 $params->{"taxchart_$i"} = "${tax_id}--${rate}";
986 $params->{"AP_amount_$i"} = "$ref->{accno}--$tax_id";
989 if ($ref->{category} eq 'L') {
990 $params->{APselected} = $params->{AP_1} = $ref->{accno};
993 $params->{rowcount} = $i if ($i && !$params->{type});
998 $main::lxdebug->leave_sub();
1002 $main::lxdebug->enter_sub();
1004 my ($self, $myconfig, $form) = @_;
1006 # connect to database
1007 my $dbh = $form->dbconnect($myconfig);
1009 my $i = $form->{rowcount};
1011 # don't include assemblies or obsolete parts
1012 my $where = "NOT p.assembly = '1' AND NOT p.obsolete = '1'";
1015 foreach my $table_column (qw(p.partnumber p.description pg.partsgroup)) {
1016 my $field = (split m{\.}, $table_column)[1];
1017 next unless $form->{"${field}_${i}"};
1018 $where .= " AND lower(${table_column}) LIKE lower(?)";
1019 push @values, '%' . $form->{"${field}_${i}"} . '%';
1021 #Es soll auch nach EAN gesucht werden, ohne Einschränkung durch Beschreibung
1022 if ($form->{"partnumber_$i"} && !$form->{"description_$i"}) {
1023 $where .= qq| OR (NOT p.obsolete = '1' AND p.ean = ? )|;
1024 push @values, $form->{"partnumber_$i"};
1027 if ($form->{"description_$i"}) {
1028 $where .= " ORDER BY p.description";
1030 $where .= " ORDER BY p.partnumber";
1034 if ($form->{type} eq "invoice") {
1035 $transdate = $form->{invdate} ? $dbh->quote($form->{invdate}) : "current_date";
1037 $transdate = $form->{transdate} ? $dbh->quote($form->{transdate}) : "current_date";
1040 my $taxzone_id = $form->{taxzone_id} * 1;
1041 $taxzone_id = 0 if ((3 < $taxzone_id) || (0 > $taxzone_id));
1045 p.id, p.partnumber, p.description, p.lastcost AS sellprice, p.listprice,
1046 p.unit, p.assembly, p.bin, p.onhand, p.formel,
1047 p.notes AS partnotes, p.notes AS longdescription, p.not_discountable,
1048 p.inventory_accno_id, p.price_factor_id,
1050 pfac.factor AS price_factor,
1052 c1.accno AS inventory_accno,
1053 c1.new_chart_id AS inventory_new_chart,
1054 date($transdate) - c1.valid_from AS inventory_valid,
1056 c2.accno AS income_accno,
1057 c2.new_chart_id AS income_new_chart,
1058 date($transdate) - c2.valid_from AS income_valid,
1060 c3.accno AS expense_accno,
1061 c3.new_chart_id AS expense_new_chart,
1062 date($transdate) - c3.valid_from AS expense_valid,
1067 LEFT JOIN chart c1 ON
1068 ((SELECT inventory_accno_id
1069 FROM buchungsgruppen
1070 WHERE id = p.buchungsgruppen_id) = c1.id)
1071 LEFT JOIN chart c2 ON
1072 ((SELECT income_accno_id_${taxzone_id}
1073 FROM buchungsgruppen
1074 WHERE id = p.buchungsgruppen_id) = c2.id)
1075 LEFT JOIN chart c3 ON
1076 ((SELECT expense_accno_id_${taxzone_id}
1077 FROM buchungsgruppen
1078 WHERE id = p.buchungsgruppen_id) = c3.id)
1079 LEFT JOIN partsgroup pg ON (pg.id = p.partsgroup_id)
1080 LEFT JOIN price_factors pfac ON (pfac.id = p.price_factor_id)
1082 my $sth = prepare_execute_query($form, $dbh, $query, @values);
1084 $form->{item_list} = [];
1085 while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
1087 # In der Buchungsgruppe ist immer ein Bestandskonto verknuepft, auch wenn
1088 # es sich um eine Dienstleistung handelt. Bei Dienstleistungen muss das
1089 # Buchungskonto also aus dem Ergebnis rausgenommen werden.
1090 if (!$ref->{inventory_accno_id}) {
1091 map({ delete($ref->{"inventory_${_}"}); } qw(accno new_chart valid));
1093 delete($ref->{inventory_accno_id});
1095 # get tax rates and description
1096 $accno_id = ($form->{vc} eq "customer") ? $ref->{income_accno} : $ref->{expense_accno};
1098 qq|SELECT c.accno, t.taxdescription, t.rate, t.taxnumber
1100 LEFT JOIN chart c on (c.id = t.chart_id)
1108 AND (startdate <= $transdate)
1109 ORDER BY startdate DESC
1112 my $stw = prepare_execute_query($form, $dbh, $query, $accno_id);
1114 $ref->{taxaccounts} = "";
1116 while ($ptr = $stw->fetchrow_hashref(NAME_lc)) {
1118 # if ($customertax{$ref->{accno}}) {
1119 if (($ptr->{accno} eq "") && ($ptr->{rate} == 0)) {
1124 $ref->{taxaccounts} .= "$ptr->{accno} ";
1126 if (!($form->{taxaccounts} =~ /\Q$ptr->{accno}\E/)) {
1127 $form->{"$ptr->{accno}_rate"} = $ptr->{rate};
1128 $form->{"$ptr->{accno}_description"} = $ptr->{taxdescription};
1129 $form->{"$ptr->{accno}_taxnumber"} = $ptr->{taxnumber};
1130 $form->{taxaccounts} .= "$ptr->{accno} ";
1136 chop $ref->{taxaccounts};
1138 $ref->{onhand} *= 1;
1140 push @{ $form->{item_list} }, $ref;
1146 foreach my $item (@{ $form->{item_list} }) {
1147 my $custom_variables = CVar->get_custom_variables(module => 'IC',
1148 trans_id => $item->{id},
1152 map { $item->{"ic_cvar_" . $_->{name} } = $_->{value} } @{ $custom_variables };
1157 $main::lxdebug->leave_sub();
1160 sub vendor_details {
1161 $main::lxdebug->enter_sub();
1163 my ($self, $myconfig, $form, @wanted_vars) = @_;
1165 # connect to database
1166 my $dbh = $form->dbconnect($myconfig);
1170 # get contact id, set it if nessessary
1171 $form->{cp_id} *= 1;
1173 if ($form->{cp_id}) {
1174 $contact = "AND cp.cp_id = ?";
1175 push @values, $form->{cp_id};
1178 # get rest for the vendor
1179 # fax and phone and email as vendor*
1181 qq|SELECT ct.*, cp.*, ct.notes as vendornotes, phone as vendorphone, fax as vendorfax, email as vendoremail
1183 LEFT JOIN contacts cp ON (ct.id = cp.cp_cv_id)
1184 WHERE (ct.id = ?) $contact
1187 my $ref = selectfirst_hashref_query($form, $dbh, $query, $form->{vendor_id}, @values);
1189 # remove id and taxincluded before copy back
1190 delete @$ref{qw(id taxincluded)};
1192 @wanted_vars = grep({ $_ } @wanted_vars);
1193 if (scalar(@wanted_vars) > 0) {
1195 map({ $h_wanted_vars{$_} = 1; } @wanted_vars);
1196 map({ delete($ref->{$_}) unless ($h_wanted_vars{$_}); } keys(%{$ref}));
1199 map { $form->{$_} = $ref->{$_} } keys %$ref;
1201 my $custom_variables = CVar->get_custom_variables('dbh' => $dbh,
1203 'trans_id' => $form->{vendor_id});
1204 map { $form->{"vc_cvar_$_->{name}"} = $_->{value} } @{ $custom_variables };
1206 $form->{cp_greeting} = GenericTranslations->get('dbh' => $dbh,
1207 'translation_type' => 'greetings::' . ($form->{cp_gender} eq 'f' ? 'female' : 'male'),
1208 'allow_fallback' => 1);
1212 $main::lxdebug->leave_sub();
1216 $main::lxdebug->enter_sub();
1218 my ($self, $myconfig, $form) = @_;
1220 # connect to database
1221 my $dbh = $form->dbconnect($myconfig);
1224 qq|SELECT accno, description, link
1226 WHERE link LIKE '%IC%'
1228 my $sth = prepare_execute_query($query, $dbh, $query);
1230 while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
1231 foreach my $key (split(/:/, $ref->{link})) {
1233 push @{ $form->{IC_links}{$key} },
1234 { accno => $ref->{accno},
1235 description => $ref->{description} };
1243 $main::lxdebug->leave_sub();
1246 sub _delete_payments {
1247 $main::lxdebug->enter_sub();
1249 my ($self, $form, $dbh) = @_;
1251 my @delete_acc_trans_ids;
1253 # Delete old payment entries from acc_trans.
1255 qq|SELECT acc_trans_id
1257 WHERE (trans_id = ?) AND fx_transaction
1261 SELECT at.acc_trans_id
1263 LEFT JOIN chart c ON (at.chart_id = c.id)
1264 WHERE (trans_id = ?) AND (c.link LIKE '%AP_paid%')|;
1265 push @delete_acc_trans_ids, selectall_array_query($form, $dbh, $query, conv_i($form->{id}), conv_i($form->{id}));
1268 qq|SELECT at.acc_trans_id
1270 LEFT JOIN chart c ON (at.chart_id = c.id)
1271 WHERE (trans_id = ?)
1272 AND ((c.link = 'AP') OR (c.link LIKE '%:AP') OR (c.link LIKE 'AP:%'))
1273 ORDER BY at.acc_trans_id
1275 push @delete_acc_trans_ids, selectall_array_query($form, $dbh, $query, conv_i($form->{id}));
1277 if (@delete_acc_trans_ids) {
1278 $query = qq|DELETE FROM acc_trans WHERE acc_trans_id IN (| . join(", ", @delete_acc_trans_ids) . qq|)|;
1279 do_query($form, $dbh, $query);
1282 $main::lxdebug->leave_sub();
1286 $main::lxdebug->enter_sub();
1288 my ($self, $myconfig, $form, $locale) = @_;
1290 # connect to database, turn off autocommit
1291 my $dbh = $form->dbconnect_noauto($myconfig);
1293 my (%payments, $old_form, $row, $item, $query, %keep_vars);
1295 $old_form = save_form();
1297 # Delete all entries in acc_trans from prior payments.
1298 $self->_delete_payments($form, $dbh);
1300 # Save the new payments the user made before cleaning up $form.
1301 map { $payments{$_} = $form->{$_} } grep m/^datepaid_\d+$|^memo_\d+$|^source_\d+$|^exchangerate_\d+$|^paid_\d+$|^AP_paid_\d+$|^paidaccounts$/, keys %{ $form };
1303 # Clean up $form so that old content won't tamper the results.
1304 %keep_vars = map { $_, 1 } qw(login password id);
1305 map { delete $form->{$_} unless $keep_vars{$_} } keys %{ $form };
1307 # Retrieve the invoice from the database.
1308 $self->retrieve_invoice($myconfig, $form);
1310 # Set up the content of $form in the way that IR::post_invoice() expects.
1311 $form->{exchangerate} = $form->format_amount($myconfig, $form->{exchangerate});
1313 for $row (1 .. scalar @{ $form->{invoice_details} }) {
1314 $item = $form->{invoice_details}->[$row - 1];
1316 map { $item->{$_} = $form->format_amount($myconfig, $item->{$_}) } qw(qty sellprice);
1318 map { $form->{"${_}_${row}"} = $item->{$_} } keys %{ $item };
1321 $form->{rowcount} = scalar @{ $form->{invoice_details} };
1323 delete @{$form}{qw(invoice_details paidaccounts storno paid)};
1325 # Restore the payment options from the user input.
1326 map { $form->{$_} = $payments{$_} } keys %payments;
1328 # Get the AP accno (which is normally done by Form::create_links()).
1332 LEFT JOIN chart c ON (at.chart_id = c.id)
1333 WHERE (trans_id = ?)
1334 AND ((c.link = 'AP') OR (c.link LIKE '%:AP') OR (c.link LIKE 'AP:%'))
1335 ORDER BY at.acc_trans_id
1338 ($form->{AP}) = selectfirst_array_query($form, $dbh, $query, conv_i($form->{id}));
1340 # Post the new payments.
1341 $self->post_invoice($myconfig, $form, $dbh, 1);
1343 restore_form($old_form);
1345 my $rc = $dbh->commit();
1348 $main::lxdebug->leave_sub();
1354 $main::lxdebug->enter_sub();
1359 if (!$params{vendor_id} || !$params{invdate}) {
1360 $main::lxdebug->leave_sub();
1361 return $params{default};
1364 my $myconfig = \%main::myconfig;
1365 my $form = $main::form;
1367 my $dbh = $params{dbh} || $form->get_standard_dbh($myconfig);
1369 my $query = qq|SELECT ?::date + pt.terms_netto
1371 LEFT JOIN payment_terms pt ON (pt.id = v.payment_id)
1374 my ($sth, $duedate);
1376 if (($sth = $dbh->prepare($query)) && $sth->execute($params{invdate}, conv_i($params{vendor_id}))) {
1377 ($duedate) = $sth->fetchrow_array();
1383 $duedate ||= $params{default};
1385 $main::lxdebug->leave_sub();