Kosmetikmerge aus Revisionen 5187, 5191, 5193, 5194, 5218, 5219, 5222, 5228, 5229
[kivitendo-erp.git] / SL / IR.pm
1 #=====================================================================
2 # LX-Office ERP
3 # Copyright (C) 2004
4 # Based on SQL-Ledger Version 2.1.9
5 # Web http://www.lx-office.org
6 #
7 #=====================================================================
8 # SQL-Ledger Accounting
9 # Copyright (C) 2001
10 #
11 #  Author: Dieter Simader
12 #   Email: dsimader@sql-ledger.org
13 #     Web: http://www.sql-ledger.org
14 #
15 #  Contributors:
16 #
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.
21 #
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 #======================================================================
30 #
31 # Inventory received module
32 #
33 #======================================================================
34
35 package IR;
36
37 use SL::AM;
38 use SL::Common;
39 use SL::DBUtils;
40 use SL::MoreCommon;
41 use List::Util qw(min);
42
43 sub post_invoice {
44   $main::lxdebug->enter_sub();
45
46   my ($self, $myconfig, $form, $provided_dbh, $payments_only) = @_;
47
48   # connect to database, turn off autocommit
49   my $dbh = $provided_dbh ? $provided_dbh : $form->dbconnect_noauto($myconfig);
50   $form->{defaultcurrency} = $form->get_default_currency($myconfig);
51
52   my ($query, $sth, @values, $project_id);
53   my ($allocated, $taxrate, $taxamount, $taxdiff, $item);
54   my ($amount, $linetotal, $lastinventoryaccno, $lastexpenseaccno);
55   my ($netamount, $invoicediff, $expensediff) = (0, 0, 0);
56   my $exchangerate = 0;
57
58   my $all_units = AM->retrieve_units($myconfig, $form);
59
60   if (!$payments_only) {
61     if ($form->{id}) {
62       &reverse_invoice($dbh, $form);
63     } else {
64       ($form->{id}) = selectrow_query($form, $dbh, qq|SELECT nextval('glid')|);
65       do_query($form, $dbh, qq|INSERT INTO ap (id, invnumber) VALUES (?, '')|, $form->{id});
66     }
67   }
68
69   my ($currencies)    = selectfirst_array_query($form, $dbh, qq|SELECT curr FROM defaults|);
70   my $defaultcurrency = (split m/:/, $currencies)[0];
71
72   if ($form->{currency} eq $defaultcurrency) {
73     $form->{exchangerate} = 1;
74   } else {
75     $exchangerate = $form->check_exchangerate($myconfig, $form->{currency}, $form->{transdate}, 'sell');
76   }
77
78   $form->{exchangerate} = $exchangerate || $form->parse_amount($myconfig, $form->{exchangerate});
79   $form->{exchangerate} = 1 unless ($form->{exchangerate} * 1);
80
81   my %item_units;
82   my $q_item_unit = qq|SELECT unit FROM parts WHERE id = ?|;
83   my $h_item_unit = prepare_query($form, $dbh, $q_item_unit);
84
85   for my $i (1 .. $form->{rowcount}) {
86     next unless $form->{"id_$i"};
87
88     $form->{"qty_$i"}  = $form->parse_amount($myconfig, $form->{"qty_$i"});
89     $form->{"qty_$i"} *= -1 if $form->{storno};
90
91     $form->{"inventory_accno_$i"} = $form->{"expense_accno_$i"} if $main::eur;
92
93     # get item baseunit
94     if (!$item_units{$form->{"id_$i"}}) {
95       do_statement($form, $h_item_unit, $q_item_unit, $form->{"id_$i"});
96       ($item_units{$form->{"id_$i"}}) = $h_item_unit->fetchrow_array();
97     }
98
99     my $item_unit = $item_units{$form->{"id_$i"}};
100
101     if (defined($all_units->{$item_unit}->{factor})
102             && ($all_units->{$item_unit}->{factor} ne '')
103             && ($all_units->{$item_unit}->{factor} * 1 != 0)) {
104       $basefactor = $all_units->{$form->{"unit_$i"}}->{factor} / $all_units->{$item_unit}->{factor};
105     } else {
106       $basefactor = 1;
107     }
108     $baseqty = $form->{"qty_$i"} * $basefactor;
109
110     @taxaccounts = split / /, $form->{"taxaccounts_$i"};
111     $taxdiff     = 0;
112     $allocated   = 0;
113     $taxrate     = 0;
114
115     $form->{"sellprice_$i"} = $form->parse_amount($myconfig, $form->{"sellprice_$i"});
116     (my $fxsellprice = $form->{"sellprice_$i"}) =~ /\.(\d+)/;
117     my $dec = length $1;
118     my $decimalplaces = ($dec > 2) ? $dec : 2;
119
120     map { $taxrate += $form->{"${_}_rate"} } @taxaccounts;
121
122     if ($form->{"inventory_accno_$i"}) {
123
124       $linetotal = $form->round_amount($form->{"sellprice_$i"} * $form->{"qty_$i"}, 2);
125
126       if ($form->{taxincluded}) {
127         $taxamount              = $linetotal * ($taxrate / (1 + $taxrate));
128         $form->{"sellprice_$i"} = $form->{"sellprice_$i"} * (1 / (1 + $taxrate));
129       } else {
130         $taxamount = $linetotal * $taxrate;
131       }
132
133       $netamount += $linetotal;
134
135       if ($form->round_amount($taxrate, 7) == 0) {
136         if ($form->{taxincluded}) {
137           foreach $item (@taxaccounts) {
138             $taxamount =
139               $form->round_amount($linetotal * $form->{"${item}_rate"} / (1 + abs($form->{"${item}_rate"})), 2);
140             $taxdiff                              += $taxamount;
141             $form->{amount}{ $form->{id} }{$item} -= $taxamount;
142           }
143           $form->{amount}{ $form->{id} }{ $taxaccounts[0] } += $taxdiff;
144
145         } else {
146           map { $form->{amount}{ $form->{id} }{$_} -= $linetotal * $form->{"${_}_rate"} } @taxaccounts;
147         }
148
149       } else {
150         map { $form->{amount}{ $form->{id} }{$_} -= $taxamount * $form->{"${_}_rate"} / $taxrate } @taxaccounts;
151       }
152
153       # add purchase to inventory, this one is without the tax!
154       $amount    = $form->{"sellprice_$i"} * $form->{"qty_$i"} * $form->{exchangerate};
155       $linetotal = $form->round_amount($form->{"sellprice_$i"} * $form->{"qty_$i"}, 2) * $form->{exchangerate};
156       $linetotal = $form->round_amount($linetotal, 2);
157
158       # this is the difference for the inventory
159       $invoicediff += ($amount - $linetotal);
160
161       $form->{amount}{ $form->{id} }{ $form->{"inventory_accno_$i"} } -= $linetotal;
162
163       # adjust and round sellprice
164       $form->{"sellprice_$i"} = $form->round_amount($form->{"sellprice_$i"} * $form->{exchangerate}, $decimalplaces);
165
166       $lastinventoryaccno = $form->{"inventory_accno_$i"};
167
168       next if $payments_only;
169
170       # update parts table
171       $query = qq|UPDATE parts SET lastcost = ? WHERE id = ?|;
172       @values = ($form->{"sellprice_$i"}, conv_i($form->{"id_$i"}));
173       do_query($form, $dbh, $query, @values);
174
175       $form->update_balance($dbh, "parts", "onhand", qq|id = ?|, $baseqty, $form->{"id_$i"}) if !$form->{shipped};
176
177       # check if we sold the item already and
178       # make an entry for the expense and inventory
179       $query =
180         qq|SELECT i.id, i.qty, i.allocated, i.trans_id,
181              p.inventory_accno_id, p.expense_accno_id, a.transdate
182            FROM invoice i, ar a, parts p
183            WHERE (i.parts_id = p.id)
184              AND (i.parts_id = ?)
185              AND ((i.base_qty + i.allocated) > 0)
186              AND (i.trans_id = a.id)
187            ORDER BY transdate|;
188       $sth = prepare_execute_query($form, $dbh, $query, conv_i($form->{"id_$i"}));
189
190       my $totalqty = $base_qty;
191
192       while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
193         my $qty    = min $totalqty, ($ref->{base_qty} + $ref->{allocated});
194         $linetotal = $form->round_amount(($form->{"sellprice_$i"} * $qty) / $basefactor, 2);
195
196         if ($ref->{allocated} < 0) {
197
198           # we have an entry for it already, adjust amount
199           $form->update_balance($dbh, "acc_trans", "amount",
200                                 qq|    (trans_id = $ref->{trans_id})
201                                    AND (chart_id = $ref->{inventory_accno_id})
202                                    AND (transdate = '$ref->{transdate}')|,
203                                 $linetotal);
204
205           $form->update_balance($dbh, "acc_trans", "amount",
206                                 qq|    (trans_id = $ref->{trans_id})
207                                    AND (chart_id = $ref->{expense_accno_id})
208                                    AND (transdate = '$ref->{transdate}')|,
209                                 $linetotal * -1);
210
211         } elsif ($linetotal != 0) {
212           # add entry for inventory, this one is for the sold item
213           $query = qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate, taxkey) VALUES (?, ?, ?, ?, (SELECT taxkey_id FROM chart WHERE id = ?))|;
214           @values = ($ref->{trans_id},  $ref->{inventory_accno_id}, $linetotal, $ref->{transdate}, $ref->{inventory_accno_id});
215           do_query($form, $dbh, $query, @values);
216
217           # add expense
218           $query = qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate, taxkey) VALUES (?, ?, ?, ?, (SELECT taxkey from tax WHERE chart_id = ?))|;
219           @values = ($ref->{trans_id},  $ref->{expense_accno_id}, ($linetotal * -1), $ref->{transdate}, $ref->{expense_accno_id});
220           do_query($form, $dbh, $query, @values);
221         }
222
223         # update allocated for sold item
224         $form->update_balance($dbh, "invoice", "allocated", qq|id = $ref->{id}|, $qty * -1);
225
226         $allocated += $qty;
227
228         last if ($totalqty -= $qty) <= 0;
229       }
230
231       $sth->finish();
232
233     } else {
234
235       $linetotal = $form->round_amount($form->{"sellprice_$i"} * $form->{"qty_$i"}, 2);
236
237       if ($form->{taxincluded}) {
238         $taxamount              = $linetotal * ($taxrate / (1 + $taxrate));
239         $form->{"sellprice_$i"} = $form->{"sellprice_$i"} * (1 / (1 + $taxrate));
240
241       } else {
242         $taxamount = $linetotal * $taxrate;
243       }
244
245       $netamount += $linetotal;
246
247       if ($form->round_amount($taxrate, 7) == 0) {
248         if ($form->{taxincluded}) {
249           foreach $item (@taxaccounts) {
250             $taxamount = $linetotal * $form->{"${item}_rate"} / (1 + abs($form->{"${item}_rate"}));
251             $totaltax += $taxamount;
252             $form->{amount}{ $form->{id} }{$item} -= $taxamount;
253           }
254         } else {
255           map { $form->{amount}{ $form->{id} }{$_} -= $linetotal * $form->{"${_}_rate"} } @taxaccounts;
256         }
257       } else {
258         map { $form->{amount}{ $form->{id} }{$_} -= $taxamount * $form->{"${_}_rate"} / $taxrate } @taxaccounts;
259       }
260
261       $amount    = $form->{"sellprice_$i"} * $form->{"qty_$i"} * $form->{exchangerate};
262       $linetotal = $form->round_amount($form->{"sellprice_$i"} * $form->{"qty_$i"}, 2) * $form->{exchangerate};
263       $linetotal = $form->round_amount($linetotal, 2);
264
265       # this is the difference for expense
266       $expensediff += ($amount - $linetotal);
267
268       # add amount to expense
269       $form->{amount}{ $form->{id} }{ $form->{"expense_accno_$i"} } -= $linetotal;
270
271       $lastexpenseaccno = $form->{"expense_accno_$i"};
272
273       # adjust and round sellprice
274       $form->{"sellprice_$i"} = $form->round_amount($form->{"sellprice_$i"} * $form->{exchangerate}, $decimalplaces);
275
276       next if $payments_only;
277
278       # update lastcost
279       $query = qq|UPDATE parts SET lastcost = ? WHERE id = ?|;
280       do_query($form, $dbh, $query, $form->{"sellprice_$i"}, conv_i($form->{"id_$i"}));
281     }
282
283     next if $payments_only;
284
285     # save detail record in invoice table
286     $query =
287       qq|INSERT INTO invoice (trans_id, parts_id, description, qty, base_qty,
288                               sellprice, fxsellprice, allocated, unit, deliverydate,
289                               project_id, serialnumber)
290          VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)|;
291     @values = (conv_i($form->{id}), conv_i($form->{"id_$i"}),
292                $form->{"description_$i"}, $form->{"qty_$i"} * -1,
293                $baseqty * -1, $form->{"sellprice_$i"}, $fxsellprice, $allocated,
294                $form->{"unit_$i"}, conv_date($form->{deliverydate}),
295                conv_i($form->{"project_id_$i"}), $form->{"serialnumber_$i"});
296     do_query($form, $dbh, $query, @values);
297   }
298
299   $h_item_unit->finish();
300
301   my $project_id = conv_i($form->{"globalproject_id"});
302
303   $form->{datepaid} = $form->{invdate};
304
305   # all amounts are in natural state, netamount includes the taxes
306   # if tax is included, netamount is rounded to 2 decimal places,
307   # taxes are not
308
309   # total payments
310   for my $i (1 .. $form->{paidaccounts}) {
311     $form->{"paid_$i"}  = $form->parse_amount($myconfig, $form->{"paid_$i"});
312     $form->{paid}      += $form->{"paid_$i"};
313     $form->{datepaid}   = $form->{"datepaid_$i"} if $form->{"datepaid_$i"};
314   }
315
316   my ($tax, $paiddiff) = (0, 0);
317
318   $netamount = $form->round_amount($netamount, 2);
319
320   # figure out rounding errors for amount paid and total amount
321   if ($form->{taxincluded}) {
322
323     $amount    = $form->round_amount($netamount * $form->{exchangerate}, 2);
324     $paiddiff  = $amount - $netamount * $form->{exchangerate};
325     $netamount = $amount;
326
327     foreach $item (split / /, $form->{taxaccounts}) {
328       $amount                               = $form->{amount}{ $form->{id} }{$item} * $form->{exchangerate};
329       $form->{amount}{ $form->{id} }{$item} = $form->round_amount($amount, 2);
330
331       $amount     = $form->{amount}{ $form->{id} }{$item} * -1;
332       $tax       += $amount;
333       $netamount -= $amount;
334     }
335
336     $invoicediff += $paiddiff;
337     $expensediff += $paiddiff;
338
339     ######## this only applies to tax included
340     
341     $form->{amount}{ $form->{id} }{$lastinventoryaccno} -= $invoicediff if $lastinventoryaccno;
342     $form->{amount}{ $form->{id} }{$lastexpenseaccno}   -= $expensediff if $lastexpenseaccno;
343
344   } else {
345     $amount    = $form->round_amount($netamount * $form->{exchangerate}, 2);
346     $paiddiff  = $amount - $netamount * $form->{exchangerate};
347     $netamount = $amount;
348
349     foreach my $item (split / /, $form->{taxaccounts}) {
350       $form->{amount}{ $form->{id} }{$item}  = $form->round_amount($form->{amount}{ $form->{id} }{$item}, 2);
351       $amount                                = $form->round_amount( $form->{amount}{ $form->{id} }{$item} * $form->{exchangerate} * -1, 2);
352       $paiddiff                             += $amount - $form->{amount}{ $form->{id} }{$item} * $form->{exchangerate} * -1;
353       $form->{amount}{ $form->{id} }{$item}  = $form->round_amount($amount * -1, 2);
354       $amount                                = $form->{amount}{ $form->{id} }{$item} * -1;
355       $tax                                  += $amount;
356     }
357   }
358
359   $form->{amount}{ $form->{id} }{ $form->{AP} } = $netamount + $tax;
360
361   
362   $form->{paid} = $form->round_amount($form->{paid} * $form->{exchangerate} + $paiddiff, 2) if $form->{paid} != 0;
363
364   # update exchangerate
365   
366   $form->update_exchangerate($dbh, $form->{currency}, $form->{invdate}, 0, $form->{exchangerate})
367     if ($form->{currency} ne $defaultcurrency) && !$exchangerate;
368
369   # record acc_trans transactions
370   foreach my $trans_id (keys %{ $form->{amount} }) {
371     foreach my $accno (keys %{ $form->{amount}{$trans_id} }) {
372       $form->{amount}{$trans_id}{$accno} = $form->round_amount($form->{amount}{$trans_id}{$accno}, 2);
373
374       next if $payments_only || !$form->{amount}{$trans_id}{$accno};
375
376       $query = qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate, taxkey, project_id)
377                   VALUES (?, (SELECT id FROM chart WHERE accno = ?), ?, ?,
378                           (SELECT taxkey_id  FROM chart WHERE accno = ?), ?)|;
379       @values = ($trans_id, $accno, $form->{amount}{$trans_id}{$accno},
380                  conv_date($form->{invdate}), $accno, $project_id);
381       do_query($form, $dbh, $query, @values);
382     }
383   }
384
385   # deduct payment differences from paiddiff
386   for my $i (1 .. $form->{paidaccounts}) {
387     if ($form->{"paid_$i"} != 0) {
388       $amount    = $form->round_amount($form->{"paid_$i"} * $form->{exchangerate}, 2);
389       $paiddiff -= $amount - $form->{"paid_$i"} * $form->{exchangerate};
390     }
391   }
392
393   # force AP entry if 0
394   
395   $form->{amount}{ $form->{id} }{ $form->{AP} } = $form->{paid} if $form->{amount}{$form->{id}}{$form->{AP}} == 0;
396
397   # record payments and offsetting AP
398   for my $i (1 .. $form->{paidaccounts}) {
399     next if $form->{"paid_$i"} == 0;
400
401     my ($accno)            = split /--/, $form->{"AP_paid_$i"};
402     $form->{"datepaid_$i"} = $form->{invdate} unless ($form->{"datepaid_$i"});
403     $form->{datepaid}      = $form->{"datepaid_$i"};
404
405     $amount = $form->round_amount($form->{"paid_$i"} * $form->{exchangerate} + $paiddiff, 2) * -1;
406
407     # record AP
408     if ($form->{amount}{ $form->{id} }{ $form->{AP} } != 0) {
409       $query = qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate, taxkey, project_id)
410                   VALUES (?, (SELECT id FROM chart WHERE accno = ?), ?, ?,
411                           (SELECT taxkey_id FROM chart WHERE accno = ?), ?)|;
412       @values = (conv_i($form->{id}), $form->{AP}, $amount,
413                  $form->{"datepaid_$i"}, $form->{AP}, $project_id);
414       do_query($form, $dbh, $query, @values);
415     }
416
417     # record payment
418     $query = qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate, source, memo, taxkey, project_id)
419                 VALUES (?, (SELECT id FROM chart WHERE accno = ?), ?, ?, ?, ?,
420                 (SELECT taxkey_id FROM chart WHERE accno = ?), ?)|;
421     @values = (conv_i($form->{id}), $accno, $form->{"paid_$i"}, $form->{"datepaid_$i"},
422                $form->{"source_$i"}, $form->{"memo_$i"}, $accno, $project_id);
423     do_query($form, $dbh, $query, @values);
424
425     $exchangerate = 0;
426
427     if ($form->{currency} eq $defaultcurrency) {
428       $form->{"exchangerate_$i"} = 1;
429     } else {
430       $exchangerate              = $form->check_exchangerate($myconfig, $form->{currency}, $form->{"datepaid_$i"}, 'sell');
431       $form->{"exchangerate_$i"} = $exchangerate || $form->parse_amount($myconfig, $form->{"exchangerate_$i"});
432     }
433
434     # exchangerate difference
435     $form->{fx}{$accno}{ $form->{"datepaid_$i"} } += $form->{"paid_$i"} * ($form->{"exchangerate_$i"} - 1) + $paiddiff;
436
437     # gain/loss
438     $amount =
439       ($form->{"paid_$i"} * $form->{exchangerate}) -
440       ($form->{"paid_$i"} * $form->{"exchangerate_$i"});
441     if ($amount > 0) {
442       $form->{fx}{ $form->{fxgain_accno} }{ $form->{"datepaid_$i"} } += $amount;
443     } else {
444       $form->{fx}{ $form->{fxloss_accno} }{ $form->{"datepaid_$i"} } += $amount;
445     }
446
447     $paiddiff = 0;
448
449     # update exchange rate
450     $form->update_exchangerate($dbh, $form->{currency}, $form->{"datepaid_$i"}, 0, $form->{"exchangerate_$i"})
451       if ($form->{currency} ne $defaultcurrency) && !$exchangerate;
452   }
453
454   # record exchange rate differences and gains/losses
455   foreach my $accno (keys %{ $form->{fx} }) {
456     foreach my $transdate (keys %{ $form->{fx}{$accno} }) {
457       $form->{fx}{$accno}{$transdate} = $form->round_amount($form->{fx}{$accno}{$transdate}, 2);
458       next if ($form->{fx}{$accno}{$transdate} == 0);
459
460       $query = qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate, cleared, fx_transaction, taxkey, project_id)
461                   VALUES (?, (SELECT id FROM chart WHERE accno = ?), ?, ?, '0', '1', 0, ?)|;
462       @values = (conv_i($form->{id}), $accno, $form->{fx}{$accno}{$transdate}, conv_date($transdate), $project_id);
463       do_query($form, $dbh, $query, @values);
464     }
465   }
466
467   if ($payments_only) {
468     $query = qq|UPDATE ap SET paid = ?, datepaid = ? WHERE id = ?|;
469     do_query($form, $dbh, $query,  $form->{paid}, $form->{paid} ? conv_date($form->{datepaid}) : undef, conv_i($form->{id}));
470
471     if (!$provided_dbh) {
472       $dbh->commit();
473       $dbh->disconnect();
474     }
475
476     $main::lxdebug->leave_sub();
477     return;
478   }
479
480   $amount = $netamount + $tax;
481
482   # set values which could be empty
483   my $taxzone_id         = $form->{taxzone_id} * 1;
484   $form->{department_id} = (split /--/, $form->{department})[1];
485   $form->{invnumber}     = $form->{id} unless $form->{invnumber};
486
487   $taxzone_id = 0 if (3 < $taxzone_id) || (0 > $taxzone_id);
488
489   # save AP record
490   $query = qq|UPDATE ap SET
491                 invnumber    = ?, ordnumber   = ?, quonumber     = ?, transdate   = ?,
492                 orddate      = ?, quodate     = ?, vendor_id     = ?, amount      = ?,
493                 netamount    = ?, paid        = ?, duedate       = ?, datepaid    = ?,
494                 invoice      = ?, taxzone_id  = ?, notes         = ?, taxincluded = ?,
495                 intnotes     = ?, curr        = ?, storno_id     = ?, storno      = ?,
496                 cp_id        = ?, employee_id = ?, department_id = ?, 
497                 globalproject_id = ?
498               WHERE id = ?|;
499   @values = (
500                 $form->{invnumber},          $form->{ordnumber},           $form->{quonumber},      conv_date($form->{invdate}),
501       conv_date($form->{orddate}), conv_date($form->{quodate}),     conv_i($form->{vendor_id}),               $amount,
502                 $netamount,                  $form->{paid},      conv_date($form->{duedate}),       $form->{paid} ? conv_date($form->{datepaid}) : undef,
503             '1',                             $taxzone_id,                  $form->{notes},          $form->{taxincluded} ? 't' : 'f',
504                 $form->{intnotes},           $form->{currency},     conv_i($form->{storno_id}),     $form->{storno}      ? 't' : 'f',
505          conv_i($form->{cp_id}),      conv_i($form->{employee_id}), conv_i($form->{department_id}), 
506          conv_i($form->{globalproject_id}),
507          conv_i($form->{id})
508   );
509   do_query($form, $dbh, $query, @values);
510
511   if ($form->{storno}) {
512     $query = qq|UPDATE ap SET paid = paid + amount WHERE id = ?|;
513     do_query($form, $dbh, $query, conv_i($form->{storno_id}));
514
515     $query = qq|UPDATE ap SET storno = 't' WHERE id = ?|;
516     do_query($form, $dbh, $query, conv_i($form->{storno_id}));
517
518     $query = qq!UPDATE ap SET intnotes = ? || intnotes WHERE id = ?!;
519     do_query($form, $dbh, $query, 'Rechnung storniert am $form->{invdate} ', conv_i($form->{storno_id}));
520
521     $query = qq|UPDATE ap SET paid = amount WHERE id = ?|;
522     do_query($form, $dbh, $query, conv_i($form->{id}));
523   }
524
525
526   # add shipto
527   $form->{name} = $form->{vendor};
528   $form->{name} =~ s/--$form->{vendor_id}//;
529   $form->add_shipto($dbh, $form->{id}, "AP");
530
531   # delete zero entries
532   do_query($form, $dbh, qq|DELETE FROM acc_trans WHERE amount = 0|);
533
534   Common::webdav_folder($form) if ($main::webdav);
535
536   my $rc = 1;
537
538   if (!$provided_dbh) {
539     $rc = $dbh->commit();
540     $dbh->disconnect();
541   }
542
543   $main::lxdebug->leave_sub();
544
545   return $rc;
546 }
547
548 sub reverse_invoice {
549   $main::lxdebug->enter_sub();
550
551   my ($dbh, $form) = @_;
552
553   # reverse inventory items
554   my $query =
555     qq|SELECT i.parts_id, p.inventory_accno_id, p.expense_accno_id, i.qty, i.allocated, i.sellprice
556        FROM invoice i, parts p
557        WHERE (i.parts_id = p.id)
558          AND (i.trans_id = ?)|;
559   my $sth = prepare_execute_query($form, $dbh, $query, conv_i($form->{id}));
560
561   my $netamount = 0;
562
563   while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
564     $netamount += $form->round_amount($ref->{sellprice} * $ref->{qty} * -1, 2);
565
566     next unless $ref->{inventory_accno_id};
567
568     # update onhand
569     $form->update_balance($dbh, "parts", "onhand", qq|id = $ref->{parts_id}|, $ref->{qty});
570
571     # if $ref->{allocated} > 0 than we sold that many items
572     next if ($ref->{allocated} <= 0);
573
574     # get references for sold items
575     $query =
576       qq|SELECT i.id, i.trans_id, i.allocated, a.transdate
577          FROM invoice i, ar a
578          WHERE (i.parts_id = ?)
579            AND (i.allocated < 0)
580            AND (i.trans_id = a.id)
581          ORDER BY transdate DESC|;
582       my $sth2 = prepare_execute_query($form, $dbh, $query, $ref->{parts_id});
583
584       while (my $pthref = $sth2->fetchrow_hashref(NAME_lc)) {
585         my $qty = $ref->{allocated};
586         if (($ref->{allocated} + $pthref->{allocated}) > 0) {
587           $qty = $pthref->{allocated} * -1;
588         }
589
590         my $amount = $form->round_amount($ref->{sellprice} * $qty, 2);
591
592         #adjust allocated
593         $form->update_balance($dbh, "invoice", "allocated", qq|id = $pthref->{id}|, $qty);
594
595         $form->update_balance($dbh, "acc_trans", "amount",
596                               qq|    (trans_id = $pthref->{trans_id})
597                                  AND (chart_id = $ref->{expense_accno_id})
598                                  AND (transdate = '$pthref->{transdate}')|,
599                               $amount);
600
601         $form->update_balance($dbh, "acc_trans", "amount",
602                               qq|    (trans_id = $pthref->{trans_id})
603                                  AND (chart_id = $ref->{inventory_accno_id})
604                                  AND (transdate = '$pthref->{transdate}')|,
605                               $amount * -1);
606
607         last if (($ref->{allocated} -= $qty) <= 0);
608       }
609     $sth2->finish();
610   }
611   $sth->finish();
612
613   my $id = conv_i($form->{id});
614
615   # delete acc_trans
616   $query = qq|DELETE FROM acc_trans WHERE trans_id = ?|;
617   do_query($form, $dbh, $query, $id);
618
619   # delete invoice entries
620   $query = qq|DELETE FROM invoice WHERE trans_id = ?|;
621   do_query($form, $dbh, $query, $id);
622
623   $query = qq|DELETE FROM shipto WHERE (trans_id = ?) AND (module = 'AP')|;
624   do_query($form, $dbh, $query, $id);
625
626   $main::lxdebug->leave_sub();
627 }
628
629 sub delete_invoice {
630   $main::lxdebug->enter_sub();
631
632   my ($self, $myconfig, $form) = @_;
633
634   # connect to database
635   my $dbh = $form->dbconnect_noauto($myconfig);
636
637   &reverse_invoice($dbh, $form);
638
639   # delete zero entries
640   my $query = qq|DELETE FROM acc_trans WHERE amount = 0|;
641   do_query($form, $dbh, $query);
642
643   # delete AP record
644   my $query = qq|DELETE FROM ap WHERE id = ?|;
645   do_query($form, $dbh, $query, conv_i($form->{id}));
646
647   my $rc = $dbh->commit;
648   $dbh->disconnect;
649
650   $main::lxdebug->leave_sub();
651
652   return $rc;
653 }
654
655 sub retrieve_invoice {
656   $main::lxdebug->enter_sub();
657
658   my ($self, $myconfig, $form) = @_;
659
660   # connect to database
661   my $dbh = $form->dbconnect($myconfig);
662
663   my ($query, $sth, $ref, $q_invdate);
664
665   if (!$form->{id}) {
666     $q_invdate = qq|, COALESCE((SELECT transdate FROM ar WHERE id = (SELECT MAX(id) FROM ar)), current_date) AS invdate|;
667     if ($form->{vendor_id}) {
668       my $vendor_id = $dbh->quote($form->{vendor_id} * 1);
669       $q_invdate .=
670         qq|, COALESCE((SELECT transdate FROM ar WHERE id = (SELECT MAX(id) FROM ar)), current_date) +
671              COALESCE((SELECT pt.terms_netto
672                        FROM vendor v
673                        LEFT JOIN payment_terms pt ON (v.payment_id = pt.id)
674                        WHERE v.id = $vendor_id),
675                       0) AS duedate|;
676     }
677   }
678
679   # get default accounts and last invoice number
680
681   $query = qq|SELECT
682                (SELECT c.accno FROM chart c WHERE d.inventory_accno_id = c.id) AS inventory_accno,
683                (SELECT c.accno FROM chart c WHERE d.income_accno_id = c.id)    AS income_accno,
684                (SELECT c.accno FROM chart c WHERE d.expense_accno_id = c.id)   AS expense_accno,
685                (SELECT c.accno FROM chart c WHERE d.fxgain_accno_id = c.id)    AS fxgain_accno,
686                (SELECT c.accno FROM chart c WHERE d.fxloss_accno_id = c.id)    AS fxloss_accno,
687                d.curr AS currencies
688                $q_invdate
689                FROM defaults d|;
690   $ref = selectfirst_hashref_query($form, $dbh, $query);
691   map { $form->{$_} = $ref->{$_} } keys %$ref;
692
693   if (!$form->{id}) {
694     $dbh->disconnect();
695     $main::lxdebug->leave_sub();
696
697     return;
698   }
699
700   # retrieve invoice
701   $query = qq|SELECT cp_id, invnumber, transdate AS invdate, duedate,
702                 orddate, quodate, globalproject_id,
703                 ordnumber, quonumber, paid, taxincluded, notes, taxzone_id, storno, gldate,
704                 intnotes, curr AS currency
705               FROM ap
706               WHERE id = ?|;
707   $ref = selectfirst_hashref_query($form, $dbh, $query, conv_i($form->{id}));
708   map { $form->{$_} = $ref->{$_} } keys %$ref;
709
710   $form->{exchangerate}  = $form->get_exchangerate($dbh, $form->{currency}, $form->{invdate}, "sell");
711
712   # get shipto
713   $query = qq|SELECT * FROM shipto WHERE (trans_id = ?) AND (module = 'AP')|;
714   $ref = selectfirst_hashref_query($form, $dbh, $query, conv_i($form->{id}));
715   delete $ref->{id};
716   map { $form->{$_} = $ref->{$_} } keys %$ref;
717
718   my $transdate  = $form->{invdate} ? $dbh->quote($form->{invdate}) : "current_date";
719   my $taxzone_id = $form->{taxzone_id} * 1;
720
721   $taxzone_id = 0 if ((3 < $taxzone_id) || (0 > $taxzone_id));
722
723   # retrieve individual items
724   $query =
725     qq|SELECT
726         c1.accno AS inventory_accno, c1.new_chart_id AS inventory_new_chart, date($transdate) - c1.valid_from AS inventory_valid,
727         c2.accno AS income_accno,    c2.new_chart_id AS income_new_chart,    date($transdate) - c2.valid_from AS income_valid,
728         c3.accno AS expense_accno,   c3.new_chart_id AS expense_new_chart,   date($transdate) - c3.valid_from AS expense_valid,
729
730         i.description, i.qty, i.fxsellprice AS sellprice, i.parts_id AS id, i.unit, i.deliverydate, i.project_id, i.serialnumber,
731         p.partnumber, p.inventory_accno_id AS part_inventory_accno_id, p.bin, pr.projectnumber, pg.partsgroup 
732
733         FROM invoice i
734         JOIN parts p ON (i.parts_id = p.id)
735         LEFT JOIN chart c1 ON ((SELECT inventory_accno_id             FROM buchungsgruppen WHERE id = p.buchungsgruppen_id) = c1.id)
736         LEFT JOIN chart c2 ON ((SELECT income_accno_id_${taxzone_id}  FROM buchungsgruppen WHERE id = p.buchungsgruppen_id) = c2.id)
737         LEFT JOIN chart c3 ON ((SELECT expense_accno_id_${taxzone_id} FROM buchungsgruppen WHERE id = p.buchungsgruppen_id) = c3.id)
738         LEFT JOIN project pr    ON (i.project_id = pr.id)
739         LEFT JOIN partsgroup pg ON (pg.id = p.partsgroup_id)
740
741         WHERE i.trans_id = ?
742
743         ORDER BY i.id|;
744   $sth = prepare_execute_query($form, $dbh, $query, conv_i($form->{id}));
745
746   while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
747     map({ delete($ref->{$_}); } qw(inventory_accno inventory_new_chart inventory_valid)) if !$ref->{"part_inventory_accno_id"};
748     delete($ref->{"part_inventory_accno_id"});
749
750     foreach my $type (qw(inventory income expense)) {
751       while ($ref->{"${type}_new_chart"} && ($ref->{"${type}_valid"} >=0)) {
752         my $query = qq|SELECT accno, new_chart_id, date($transdate) - valid_from FROM chart WHERE id = ?|;
753         @$ref{ map $type.$_, qw(_accno _new_chart _valid) } = selectrow_query($form, $dbh, $query, $ref->{"${type}_new_chart"});
754       }
755     }
756
757     # get tax rates and description
758     my $accno_id = ($form->{vc} eq "customer") ? $ref->{income_accno} : $ref->{expense_accno};
759     $query =
760       qq|SELECT c.accno, t.taxdescription, t.rate, t.taxnumber FROM tax t
761          LEFT JOIN chart c ON (c.id = t.chart_id)
762          WHERE t.id in
763            (SELECT tk.tax_id FROM taxkeys tk
764             WHERE tk.chart_id = (SELECT id FROM chart WHERE accno = ?)
765               AND (startdate <= $transdate)
766             ORDER BY startdate DESC
767             LIMIT 1)
768          ORDER BY c.accno|;
769     my $stw = prepare_execute_query($form, $dbh, $query, $accno_id);
770     $ref->{taxaccounts} = "";
771
772     my $i = 0;
773     while ($ptr = $stw->fetchrow_hashref(NAME_lc)) {
774       if (($ptr->{accno} eq "") && ($ptr->{rate} == 0)) {
775         $i++;
776         $ptr->{accno} = $i;
777       }
778
779       $ref->{taxaccounts} .= "$ptr->{accno} ";
780
781       if (!($form->{taxaccounts} =~ /$ptr->{accno}/)) {
782         $form->{"$ptr->{accno}_rate"}         = $ptr->{rate};
783         $form->{"$ptr->{accno}_description"}  = $ptr->{taxdescription};
784         $form->{"$ptr->{accno}_taxnumber"}    = $ptr->{taxnumber};
785         $form->{taxaccounts}                 .= "$ptr->{accno} ";
786       }
787
788     }
789
790     chop $ref->{taxaccounts};
791     push @{ $form->{invoice_details} }, $ref;
792     $stw->finish();
793   }
794   $sth->finish();
795
796   Common::webdav_folder($form) if ($main::webdav);
797
798   $dbh->disconnect();
799
800   $main::lxdebug->leave_sub();
801 }
802
803 sub get_vendor {
804   $main::lxdebug->enter_sub();
805
806   my ($self, $myconfig, $form) = @_;
807
808   # connect to database
809   my $dbh = $form->dbconnect($myconfig);
810
811   my $dateformat = $myconfig->{dateformat};
812   $dateformat .= "yy" if $myconfig->{dateformat} !~ /^y/;
813
814   my $vid = conv_i($form->{vendor_id});
815
816   my $duedate =
817     ($form->{invdate})
818     ? "to_date(" . $dbh->quote($form->{invdate}) . ", '$dateformat')"
819     : "current_date";
820
821   # get vendor
822   my $query =
823     qq|SELECT
824          v.name AS vendor, v.creditlimit, v.terms, v.notes AS intnotes,
825          v.email, v.cc, v.bcc, v.language_id, v.payment_id,
826          v.street, v.zipcode, v.city, v.country, v.taxzone_id,
827          $duedate + COALESCE(pt.terms_netto, 0) AS duedate,
828          b.description AS business
829        FROM vendor v
830        LEFT JOIN business b       ON (b.id = v.business_id)
831        LEFT JOIN payment_terms pt ON (v.payment_id = pt.id)
832        WHERE v.id = ?|;
833   $ref = selectfirst_hashref_query($form, $dbh, $query, $vid);
834   map { $form->{$_} = $ref->{$_} } keys %$ref;
835
836   $form->{creditremaining} = $form->{creditlimit};
837
838   $query = qq|SELECT SUM(amount - paid) FROM ap WHERE vendor_id = ?|;
839   my ($unpaid_invoices) = selectfirst_array_query($form, $dbh, $query, $vid);
840   $form->{creditremaining} -= $unpaid_invoices;
841
842   $query = qq|SELECT o.amount,
843                 (SELECT e.sell
844                  FROM exchangerate e
845                  WHERE (e.curr = o.curr)
846                    AND (e.transdate = o.transdate)) AS exch
847               FROM oe o
848               WHERE (o.vendor_id = ?) AND (o.quotation = '0') AND (o.closed = '0')|;
849   my $sth = prepare_execute_query($form, $dbh, $query, $vid);
850   while (my ($amount, $exch) = $sth->fetchrow_array()) {
851     $exch = 1 unless $exch;
852     $form->{creditremaining} -= $amount * $exch;
853   }
854   $sth->finish();
855
856   # get shipto if we do not convert an order or invoice
857   if (!$form->{shipto}) {
858     delete @{$form}{qw(shiptoname shiptostreet shiptozipcode shiptocity shiptocountry shiptocontact shiptophone shiptofax shiptoemail)};
859
860     $query = qq|SELECT * FROM shipto WHERE (trans_id = ?) AND (module= 'CT')|;
861     $ref = selectfirst_hashref_query($form, $dbh, $query, $vid);
862     @{$form}{keys %$ref} = @{$ref}{keys %$ref};
863     map { $form->{$_} = $ref->{$_} } keys %$ref;
864   }
865
866   if (!$form->{id} && $form->{type} !~ /_(order|quotation)/) {
867     # setup last accounts used
868     $query =
869       qq|SELECT c.id, c.accno, c.description, c.link, c.category
870          FROM chart c
871          JOIN acc_trans ac ON (ac.chart_id = c.id)
872          JOIN ap a         ON (a.id = ac.trans_id)
873          WHERE (a.vendor_id = ?)
874            AND (NOT ((c.link LIKE '%_tax%') OR (c.link LIKE '%_paid%')))
875            AND (a.id IN (SELECT max(a2.id) FROM ap a2 WHERE a2.vendor_id = ?))|;
876     my $refs = selectall_hashref_query($form, $dbh, $query, $vid, $vid);
877
878     my $i = 0;
879     for $ref (@$refs) {
880       if ($ref->{category} eq 'E') {
881         $i++;
882
883         if ($form->{initial_transdate}) {
884           my $tax_query = qq|SELECT tk.tax_id, t.rate FROM taxkeys tk
885                              LEFT JOIN tax t ON (tk.tax_id = t.id)
886                              WHERE (tk.chart_id = ?) AND (startdate <= ?)
887                              ORDER BY tk.startdate DESC
888                              LIMIT 1|;
889           my ($tax_id, $rate) = selectrow_query($form, $dbh, $tax_query, $ref->{id}, $form->{initial_transdate});
890           $form->{"taxchart_$i"} = "${tax_id}--${rate}";
891         }
892
893         $form->{"AP_amount_$i"} = "$ref->{accno}--$tax_id";
894       }
895
896       if ($ref->{category} eq 'L') {
897         $form->{APselected} = $form->{AP_1} = $ref->{accno};
898       }
899     }
900     $form->{rowcount} = $i if ($i && !$form->{type});
901   }
902
903   $dbh->disconnect();
904
905   $main::lxdebug->leave_sub();
906 }
907
908 sub retrieve_item {
909   $main::lxdebug->enter_sub();
910
911   my ($self, $myconfig, $form) = @_;
912
913   # connect to database
914   my $dbh = $form->dbconnect($myconfig);
915
916   my $i = $form->{rowcount};
917
918   # don't include assemblies or obsolete parts
919   my $where = "NOT p.assembly = '1' AND NOT p.obsolete = '1'";
920   my @values;
921
922   foreach my $table_column (qw(p.partnumber p.description pg.partsgroup)) {
923     my $field = (split m{\.}, $table_column)[1];
924     next unless $form->{"${field}_${i}"};
925     $where .= " AND lower(${table_column}) LIKE lower(?)";
926     push @values, '%' . $form->{"${field}_${i}"} . '%';
927   }
928
929   if ($form->{"description_$i"}) {
930     $where .= " ORDER BY p.description";
931   } else {
932     $where .= " ORDER BY p.partnumber";
933   }
934
935   my $transdate = "";
936   if ($form->{type} eq "invoice") {
937     $transdate = $form->{invdate} ? $dbh->quote($form->{invdate}) : "current_date";
938   } else {
939     $transdate = $form->{transdate} ? $dbh->quote($form->{transdate}) : "current_date";
940   }
941
942   my $taxzone_id = $form->{taxzone_id} * 1;
943   $taxzone_id    = 0 if ((3 < $taxzone_id) || (0 > $taxzone_id));
944
945   my $query =
946     qq|SELECT
947          p.id, p.partnumber, p.description, p.lastcost AS sellprice, p.listprice,
948          p.unit, p.assembly, p.bin, p.onhand, p.formel,
949          p.notes AS partnotes, p.notes AS longdescription, p.not_discountable,
950          p.inventory_accno_id,
951
952          c1.accno                         AS inventory_accno,
953          c1.new_chart_id                  AS inventory_new_chart,
954          date($transdate) - c1.valid_from AS inventory_valid,
955
956          c2.accno                         AS income_accno,
957          c2.new_chart_id                  AS income_new_chart,
958          date($transdate) - c2.valid_from AS income_valid,
959
960          c3.accno                         AS expense_accno,
961          c3.new_chart_id                  AS expense_new_chart,
962          date($transdate) - c3.valid_from AS expense_valid,
963
964          pg.partsgroup
965
966        FROM parts p
967        LEFT JOIN chart c1 ON
968          ((SELECT inventory_accno_id
969            FROM buchungsgruppen
970            WHERE id = p.buchungsgruppen_id) = c1.id)
971        LEFT JOIN chart c2 ON
972          ((SELECT income_accno_id_${taxzone_id}
973            FROM buchungsgruppen
974            WHERE id = p.buchungsgruppen_id) = c2.id)
975        LEFT JOIN chart c3 ON
976          ((SELECT expense_accno_id_${taxzone_id}
977            FROM buchungsgruppen
978            WHERE id = p.buchungsgruppen_id) = c3.id)
979        LEFT JOIN partsgroup pg ON (pg.id = p.partsgroup_id)
980        WHERE $where|;
981   my $sth = prepare_execute_query($form, $dbh, $query, @values);
982
983   $form->{item_list} = [];
984   while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
985
986     # In der Buchungsgruppe ist immer ein Bestandskonto verknuepft, auch wenn
987     # es sich um eine Dienstleistung handelt. Bei Dienstleistungen muss das
988     # Buchungskonto also aus dem Ergebnis rausgenommen werden.
989     if (!$ref->{inventory_accno_id}) {
990       map({ delete($ref->{"inventory_${_}"}); } qw(accno new_chart valid));
991     }
992     delete($ref->{inventory_accno_id});
993
994     # get tax rates and description
995     $accno_id = ($form->{vc} eq "customer") ? $ref->{income_accno} : $ref->{expense_accno};
996     $query =
997       qq|SELECT c.accno, t.taxdescription, t.rate, t.taxnumber
998          FROM tax t
999          LEFT JOIN chart c on (c.id = t.chart_id)
1000          WHERE t.id IN
1001            (SELECT tk.tax_id
1002             FROM taxkeys tk
1003             WHERE tk.chart_id =
1004               (SELECT id
1005                FROM chart
1006                WHERE accno = ?)
1007               AND (startdate <= $transdate)
1008             ORDER BY startdate DESC
1009             LIMIT 1)
1010          ORDER BY c.accno|;
1011     my $stw = prepare_execute_query($form, $dbh, $query, $accno_id);
1012
1013     $ref->{taxaccounts} = "";
1014     my $i = 0;
1015     while ($ptr = $stw->fetchrow_hashref(NAME_lc)) {
1016
1017       #    if ($customertax{$ref->{accno}}) {
1018       if (($ptr->{accno} eq "") && ($ptr->{rate} == 0)) {
1019         $i++;
1020         $ptr->{accno} = $i;
1021       }
1022
1023       $ref->{taxaccounts} .= "$ptr->{accno} ";
1024
1025       if (!($form->{taxaccounts} =~ /$ptr->{accno}/)) {
1026         $form->{"$ptr->{accno}_rate"}         = $ptr->{rate};
1027         $form->{"$ptr->{accno}_description"}  = $ptr->{taxdescription};
1028         $form->{"$ptr->{accno}_taxnumber"}    = $ptr->{taxnumber};
1029         $form->{taxaccounts}                 .= "$ptr->{accno} ";
1030       }
1031
1032     }
1033
1034     $stw->finish();
1035     chop $ref->{taxaccounts};
1036
1037     push @{ $form->{item_list} }, $ref;
1038
1039   }
1040
1041   $sth->finish();
1042   $dbh->disconnect();
1043
1044   $main::lxdebug->leave_sub();
1045 }
1046
1047 sub vendor_details {
1048   $main::lxdebug->enter_sub();
1049
1050   my ($self, $myconfig, $form, @wanted_vars) = @_;
1051
1052   # connect to database
1053   my $dbh = $form->dbconnect($myconfig);
1054
1055   my @values;
1056
1057   # get contact id, set it if nessessary
1058   $form->{cp_id} = (split /--/, $form->{contact})[1];
1059   my $contact = "";
1060   if ($form->{cp_id}) {
1061     $contact = "AND cp.cp_id = ?";
1062     push @values, $form->{cp_id};
1063   }
1064
1065   # get rest for the vendor
1066   # fax and phone and email as vendor*
1067   my $query =
1068     qq|SELECT ct.*, cp.*, ct.notes as vendornotes, phone as vendorphone, fax as vendorfax, email as vendoremail
1069        FROM vendor ct
1070        LEFT JOIN contacts cp ON (ct.id = cp.cp_cv_id)
1071        WHERE (ct.id = ?) $contact
1072        ORDER BY cp.cp_id
1073        LIMIT 1|;
1074   my $ref = selectfirst_hashref_query($form, $dbh, $query, $form->{vendor_id}, @values);
1075
1076   # remove id and taxincluded before copy back
1077   delete @$ref{qw(id taxincluded)};
1078
1079   @wanted_vars = grep({ $_ } @wanted_vars);
1080   if (scalar(@wanted_vars) > 0) {
1081     my %h_wanted_vars;
1082     map({ $h_wanted_vars{$_} = 1; } @wanted_vars);
1083     map({ delete($ref->{$_}) unless ($h_wanted_vars{$_}); } keys(%{$ref}));
1084   }
1085
1086   map { $form->{$_} = $ref->{$_} } keys %$ref;
1087
1088   $dbh->disconnect();
1089
1090   $main::lxdebug->leave_sub();
1091 }
1092
1093 sub item_links {
1094   $main::lxdebug->enter_sub();
1095
1096   my ($self, $myconfig, $form) = @_;
1097
1098   # connect to database
1099   my $dbh = $form->dbconnect($myconfig);
1100
1101   my $query =
1102     qq|SELECT accno, description, link
1103        FROM chart
1104        WHERE link LIKE '%IC%'
1105        ORDER BY accno|;
1106   my $sth = prepare_execute_query($query, $dbh, $query);
1107
1108   while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
1109     foreach my $key (split(/:/, $ref->{link})) {
1110       if ($key =~ /IC/) {
1111         push @{ $form->{IC_links}{$key} },
1112           { accno       => $ref->{accno},
1113             description => $ref->{description} };
1114       }
1115     }
1116   }
1117
1118   $sth->finish();
1119   $dbh->disconnect();
1120
1121   $main::lxdebug->leave_sub();
1122 }
1123
1124 sub _delete_payments {
1125   $main::lxdebug->enter_sub();
1126
1127   my ($self, $form, $dbh) = @_;
1128
1129   my @delete_oids;
1130
1131   # Delete old payment entries from acc_trans.
1132   my $query =
1133     qq|SELECT oid
1134        FROM acc_trans
1135        WHERE (trans_id = ?) AND fx_transaction
1136
1137        UNION
1138
1139        SELECT at.oid
1140        FROM acc_trans at
1141        LEFT JOIN chart c ON (at.chart_id = c.id)
1142        WHERE (trans_id = ?) AND (c.link LIKE '%AP_paid%')|;
1143   push @delete_oids, selectall_array_query($form, $dbh, $query, conv_i($form->{id}), conv_i($form->{id}));
1144
1145   $query =
1146     qq|SELECT at.oid
1147        FROM acc_trans at
1148        LEFT JOIN chart c ON (at.chart_id = c.id)
1149        WHERE (trans_id = ?)
1150          AND ((c.link = 'AP') OR (c.link LIKE '%:AP') OR (c.link LIKE 'AP:%'))
1151        ORDER BY at.oid
1152        OFFSET 1|;
1153   push @delete_oids, selectall_array_query($form, $dbh, $query, conv_i($form->{id}));
1154
1155   if (@delete_oids) {
1156     $query = qq|DELETE FROM acc_trans WHERE oid IN (| . join(", ", @delete_oids) . qq|)|;
1157     do_query($form, $dbh, $query);
1158   }
1159
1160   $main::lxdebug->leave_sub();
1161 }
1162
1163 sub post_payment {
1164   $main::lxdebug->enter_sub();
1165
1166   my ($self, $myconfig, $form, $locale) = @_;
1167
1168   # connect to database, turn off autocommit
1169   my $dbh = $form->dbconnect_noauto($myconfig);
1170
1171   my (%payments, $old_form, $row, $item, $query, %keep_vars);
1172
1173   $old_form = save_form();
1174
1175   # Delete all entries in acc_trans from prior payments.
1176   $self->_delete_payments($form, $dbh);
1177
1178   # Save the new payments the user made before cleaning up $form.
1179   map { $payments{$_} = $form->{$_} } grep m/^datepaid_\d+$|^memo_\d+$|^source_\d+$|^exchangerate_\d+$|^paid_\d+$|^AP_paid_\d+$|^paidaccounts$/, keys %{ $form };
1180
1181   # Clean up $form so that old content won't tamper the results.
1182   %keep_vars = map { $_, 1 } qw(login password id);
1183   map { delete $form->{$_} unless $keep_vars{$_} } keys %{ $form };
1184
1185   # Retrieve the invoice from the database.
1186   $self->retrieve_invoice($myconfig, $form);
1187
1188   # Set up the content of $form in the way that IR::post_invoice() expects.
1189   $form->{exchangerate} = $form->format_amount($myconfig, $form->{exchangerate});
1190
1191   for $row (1 .. scalar @{ $form->{invoice_details} }) {
1192     $item = $form->{invoice_details}->[$row - 1];
1193
1194     map { $item->{$_} = $form->format_amount($myconfig, $item->{$_}) } qw(qty sellprice);
1195
1196     map { $form->{"${_}_${row}"} = $item->{$_} } keys %{ $item };
1197   }
1198
1199   $form->{rowcount} = scalar @{ $form->{invoice_details} };
1200
1201   delete @{$form}{qw(invoice_details paidaccounts storno paid)};
1202
1203   # Restore the payment options from the user input.
1204   map { $form->{$_} = $payments{$_} } keys %payments;
1205
1206   # Get the AP accno (which is normally done by Form::create_links()).
1207   $query =
1208     qq|SELECT c.accno
1209        FROM acc_trans at
1210        LEFT JOIN chart c ON (at.chart_id = c.id)
1211        WHERE (trans_id = ?)
1212          AND ((c.link = 'AP') OR (c.link LIKE '%:AP') OR (c.link LIKE 'AP:%'))
1213        ORDER BY at.oid
1214        LIMIT 1|;
1215
1216   ($form->{AP}) = selectfirst_array_query($form, $dbh, $query, conv_i($form->{id}));
1217
1218   # Post the new payments.
1219   $self->post_invoice($myconfig, $form, $dbh, 1);
1220
1221   restore_form($old_form);
1222
1223   my $rc = $dbh->commit();
1224   $dbh->disconnect();
1225
1226   $main::lxdebug->leave_sub();
1227
1228   return $rc;
1229 }
1230
1231 1;