Anpassung des letzten is_title();
[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=
682     qq|SELECT
683          (SELECT c.accno FROM chart c WHERE d.inventory_accno_id = c.id) AS inventory_accno,
684          (SELECT c.accno FROM chart c WHERE d.income_accno_id = c.id)    AS income_accno,
685          (SELECT c.accno FROM chart c WHERE d.expense_accno_id = c.id)   AS expense_accno,
686          (SELECT c.accno FROM chart c WHERE d.fxgain_accno_id = c.id)    AS fxgain_accno,
687          (SELECT c.accno FROM chart c WHERE d.fxloss_accno_id = c.id)    AS fxloss_accno,
688          d.curr AS currencies
689          $q_invdate
690          FROM defaults d|;
691   $ref = selectfirst_hashref_query($form, $dbh, $query);
692   map { $form->{$_} = $ref->{$_} } keys %$ref;
693
694   if (!$form->{id}) {
695     $dbh->disconnect();
696     $main::lxdebug->leave_sub();
697
698     return;
699   }
700
701   # retrieve invoice
702   $query =
703     qq|SELECT cp_id, invnumber, transdate AS invdate, duedate,
704          orddate, quodate, globalproject_id,
705          ordnumber, quonumber, paid, taxincluded, notes, taxzone_id, storno, gldate,
706          intnotes, curr AS currency
707        FROM ap
708        WHERE id = ?|;
709   $ref = selectfirst_hashref_query($form, $dbh, $query, conv_i($form->{id}));
710   map { $form->{$_} = $ref->{$_} } keys %$ref;
711
712   $form->{exchangerate} = $form->get_exchangerate($dbh, $form->{currency}, $form->{invdate}, "sell");
713
714   # get shipto
715   $query = qq|SELECT * FROM shipto WHERE (trans_id = ?) AND (module = 'AP')|;
716   $ref = selectfirst_hashref_query($form, $dbh, $query, conv_i($form->{id}));
717   delete $ref->{id};
718   map { $form->{$_} = $ref->{$_} } keys %$ref;
719
720   my $transdate  = $form->{invdate} ? $dbh->quote($form->{invdate}) : "current_date";
721   my $taxzone_id = $form->{taxzone_id} * 1;
722
723   $taxzone_id = 0 if ((3 < $taxzone_id) || (0 > $taxzone_id));
724
725   # retrieve individual items
726   $query =
727     qq|SELECT
728         c1.accno                         AS inventory_accno,
729         c1.new_chart_id                  AS inventory_new_chart,
730         date($transdate) - c1.valid_from AS inventory_valid,
731
732         c2.accno                         AS income_accno,
733         c2.new_chart_id                  AS income_new_chart,
734         date($transdate) - c2.valid_from AS income_valid,
735
736         c3.accno                         AS expense_accno,
737         c3.new_chart_id                  AS expense_new_chart,
738         date($transdate) - c3.valid_from AS expense_valid,
739
740         i.description, i.qty, i.fxsellprice AS sellprice,
741         i.parts_id AS id, i.unit, i.deliverydate, i.project_id, i.serialnumber,
742
743         p.partnumber, p.inventory_accno_id AS part_inventory_accno_id, p.bin,
744         pr.projectnumber,
745         pg.partsgroup
746
747         FROM invoice i
748         JOIN parts p ON (i.parts_id = p.id)
749         LEFT JOIN chart c1 ON
750           ((SELECT inventory_accno_id
751             FROM buchungsgruppen
752             WHERE id = p.buchungsgruppen_id) = c1.id)
753         LEFT JOIN chart c2 ON
754           ((SELECT income_accno_id_${taxzone_id}
755             FROM buchungsgruppen
756             WHERE id = p.buchungsgruppen_id) = c2.id)
757         LEFT JOIN chart c3 ON
758           ((SELECT expense_accno_id_${taxzone_id}
759             FROM buchungsgruppen
760             WHERE id = p.buchungsgruppen_id) = c3.id)
761         LEFT JOIN project pr    ON (i.project_id = pr.id)
762         LEFT JOIN partsgroup pg ON (pg.id = p.partsgroup_id)
763
764         WHERE i.trans_id = ?
765
766         ORDER BY i.id|;
767   $sth = prepare_execute_query($form, $dbh, $query, conv_i($form->{id}));
768
769   while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
770     if (!$ref->{"part_inventory_accno_id"}) {
771       map({ delete($ref->{$_}); } qw(inventory_accno inventory_new_chart inventory_valid));
772     }
773     delete($ref->{"part_inventory_accno_id"});
774
775     foreach my $type (qw(inventory income expense)) {
776       while ($ref->{"${type}_new_chart"} && ($ref->{"${type}_valid"} >=0)) {
777         my $query =
778           qq|SELECT accno, new_chart_id, date($transdate) - valid_from
779              FROM chart
780              WHERE id = ?|;
781         ($ref->{"${type}_accno"},
782          $ref->{"${type}_new_chart"},
783          $ref->{"${type}_valid"})
784           = selectrow_query($form, $dbh, $query, $ref->{"${type}_new_chart"});
785       }
786     }
787
788     # get tax rates and description
789     my $accno_id = ($form->{vc} eq "customer") ? $ref->{income_accno} : $ref->{expense_accno};
790     $query =
791       qq|SELECT c.accno, t.taxdescription, t.rate, t.taxnumber
792          FROM tax t
793          LEFT JOIN chart c ON (c.id = t.chart_id)
794          WHERE t.id in
795            (SELECT tk.tax_id
796             FROM taxkeys tk
797             WHERE tk.chart_id =
798               (SELECT id
799                FROM chart
800                WHERE accno = ?)
801               AND (startdate <= $transdate)
802             ORDER BY startdate DESC
803             LIMIT 1)
804          ORDER BY c.accno|;
805     my $stw = prepare_execute_query($form, $dbh, $query, $accno_id);
806     $ref->{taxaccounts} = "";
807
808     my $i = 0;
809     while ($ptr = $stw->fetchrow_hashref(NAME_lc)) {
810       if (($ptr->{accno} eq "") && ($ptr->{rate} == 0)) {
811         $i++;
812         $ptr->{accno} = $i;
813       }
814
815       $ref->{taxaccounts} .= "$ptr->{accno} ";
816
817       if (!($form->{taxaccounts} =~ /$ptr->{accno}/)) {
818         $form->{"$ptr->{accno}_rate"}         = $ptr->{rate};
819         $form->{"$ptr->{accno}_description"}  = $ptr->{taxdescription};
820         $form->{"$ptr->{accno}_taxnumber"}    = $ptr->{taxnumber};
821         $form->{taxaccounts}                 .= "$ptr->{accno} ";
822       }
823
824     }
825
826     chop $ref->{taxaccounts};
827     push @{ $form->{invoice_details} }, $ref;
828     $stw->finish();
829   }
830   $sth->finish();
831
832   Common::webdav_folder($form) if ($main::webdav);
833
834   $dbh->disconnect();
835
836   $main::lxdebug->leave_sub();
837 }
838
839 sub get_vendor {
840   $main::lxdebug->enter_sub();
841
842   my ($self, $myconfig, $form) = @_;
843
844   # connect to database
845   my $dbh = $form->dbconnect($myconfig);
846
847   my $dateformat = $myconfig->{dateformat};
848   $dateformat .= "yy" if $myconfig->{dateformat} !~ /^y/;
849
850   my $vid = conv_i($form->{vendor_id});
851
852   my $duedate =
853     ($form->{invdate})
854     ? "to_date(" . $dbh->quote($form->{invdate}) . ", '$dateformat')"
855     : "current_date";
856
857   # get vendor
858   my $query =
859     qq|SELECT
860          v.name AS vendor, v.creditlimit, v.terms, v.notes AS intnotes,
861          v.email, v.cc, v.bcc, v.language_id, v.payment_id,
862          v.street, v.zipcode, v.city, v.country, v.taxzone_id,
863          $duedate + COALESCE(pt.terms_netto, 0) AS duedate,
864          b.description AS business
865        FROM vendor v
866        LEFT JOIN business b       ON (b.id = v.business_id)
867        LEFT JOIN payment_terms pt ON (v.payment_id = pt.id)
868        WHERE v.id = ?|;
869   $ref = selectfirst_hashref_query($form, $dbh, $query, $vid);
870   map { $form->{$_} = $ref->{$_} } keys %$ref;
871
872   $form->{creditremaining} = $form->{creditlimit};
873
874   $query = qq|SELECT SUM(amount - paid) FROM ap WHERE vendor_id = ?|;
875   my ($unpaid_invoices) = selectfirst_array_query($form, $dbh, $query, $vid);
876   $form->{creditremaining} -= $unpaid_invoices;
877
878   $query = qq|SELECT o.amount,
879                 (SELECT e.sell
880                  FROM exchangerate e
881                  WHERE (e.curr = o.curr)
882                    AND (e.transdate = o.transdate)) AS exch
883               FROM oe o
884               WHERE (o.vendor_id = ?) AND (o.quotation = '0') AND (o.closed = '0')|;
885   my $sth = prepare_execute_query($form, $dbh, $query, $vid);
886   while (my ($amount, $exch) = $sth->fetchrow_array()) {
887     $exch = 1 unless $exch;
888     $form->{creditremaining} -= $amount * $exch;
889   }
890   $sth->finish();
891
892   # get shipto if we do not convert an order or invoice
893   if (!$form->{shipto}) {
894     delete @{$form}{qw(shiptoname shiptostreet shiptozipcode shiptocity shiptocountry shiptocontact shiptophone shiptofax shiptoemail)};
895
896     $query = qq|SELECT * FROM shipto WHERE (trans_id = ?) AND (module= 'CT')|;
897     $ref = selectfirst_hashref_query($form, $dbh, $query, $vid);
898     @{$form}{keys %$ref} = @{$ref}{keys %$ref};
899     map { $form->{$_} = $ref->{$_} } keys %$ref;
900   }
901
902   if (!$form->{id} && $form->{type} !~ /_(order|quotation)/) {
903     # setup last accounts used
904     $query =
905       qq|SELECT c.id, c.accno, c.description, c.link, c.category
906          FROM chart c
907          JOIN acc_trans ac ON (ac.chart_id = c.id)
908          JOIN ap a         ON (a.id = ac.trans_id)
909          WHERE (a.vendor_id = ?)
910            AND (NOT ((c.link LIKE '%_tax%') OR (c.link LIKE '%_paid%')))
911            AND (a.id IN (SELECT max(a2.id) FROM ap a2 WHERE a2.vendor_id = ?))|;
912     my $refs = selectall_hashref_query($form, $dbh, $query, $vid, $vid);
913
914     my $i = 0;
915     for $ref (@$refs) {
916       if ($ref->{category} eq 'E') {
917         $i++;
918
919         if ($form->{initial_transdate}) {
920           my $tax_query = qq|SELECT tk.tax_id, t.rate FROM taxkeys tk
921                              LEFT JOIN tax t ON (tk.tax_id = t.id)
922                              WHERE (tk.chart_id = ?) AND (startdate <= ?)
923                              ORDER BY tk.startdate DESC
924                              LIMIT 1|;
925           my ($tax_id, $rate) = selectrow_query($form, $dbh, $tax_query, $ref->{id}, $form->{initial_transdate});
926           $form->{"taxchart_$i"} = "${tax_id}--${rate}";
927         }
928
929         $form->{"AP_amount_$i"} = "$ref->{accno}--$tax_id";
930       }
931
932       if ($ref->{category} eq 'L') {
933         $form->{APselected} = $form->{AP_1} = $ref->{accno};
934       }
935     }
936     $form->{rowcount} = $i if ($i && !$form->{type});
937   }
938
939   $dbh->disconnect();
940
941   $main::lxdebug->leave_sub();
942 }
943
944 sub retrieve_item {
945   $main::lxdebug->enter_sub();
946
947   my ($self, $myconfig, $form) = @_;
948
949   # connect to database
950   my $dbh = $form->dbconnect($myconfig);
951
952   my $i = $form->{rowcount};
953
954   # don't include assemblies or obsolete parts
955   my $where = "NOT p.assembly = '1' AND NOT p.obsolete = '1'";
956   my @values;
957
958   foreach my $table_column (qw(p.partnumber p.description pg.partsgroup)) {
959     my $field = (split m{\.}, $table_column)[1];
960     next unless $form->{"${field}_${i}"};
961     $where .= " AND lower(${table_column}) LIKE lower(?)";
962     push @values, '%' . $form->{"${field}_${i}"} . '%';
963   }
964
965   if ($form->{"description_$i"}) {
966     $where .= " ORDER BY p.description";
967   } else {
968     $where .= " ORDER BY p.partnumber";
969   }
970
971   my $transdate = "";
972   if ($form->{type} eq "invoice") {
973     $transdate = $form->{invdate} ? $dbh->quote($form->{invdate}) : "current_date";
974   } else {
975     $transdate = $form->{transdate} ? $dbh->quote($form->{transdate}) : "current_date";
976   }
977
978   my $taxzone_id = $form->{taxzone_id} * 1;
979   $taxzone_id    = 0 if ((3 < $taxzone_id) || (0 > $taxzone_id));
980
981   my $query =
982     qq|SELECT
983          p.id, p.partnumber, p.description, p.lastcost AS sellprice, p.listprice,
984          p.unit, p.assembly, p.bin, p.onhand, p.formel,
985          p.notes AS partnotes, p.notes AS longdescription, p.not_discountable,
986          p.inventory_accno_id,
987
988          c1.accno                         AS inventory_accno,
989          c1.new_chart_id                  AS inventory_new_chart,
990          date($transdate) - c1.valid_from AS inventory_valid,
991
992          c2.accno                         AS income_accno,
993          c2.new_chart_id                  AS income_new_chart,
994          date($transdate) - c2.valid_from AS income_valid,
995
996          c3.accno                         AS expense_accno,
997          c3.new_chart_id                  AS expense_new_chart,
998          date($transdate) - c3.valid_from AS expense_valid,
999
1000          pg.partsgroup
1001
1002        FROM parts p
1003        LEFT JOIN chart c1 ON
1004          ((SELECT inventory_accno_id
1005            FROM buchungsgruppen
1006            WHERE id = p.buchungsgruppen_id) = c1.id)
1007        LEFT JOIN chart c2 ON
1008          ((SELECT income_accno_id_${taxzone_id}
1009            FROM buchungsgruppen
1010            WHERE id = p.buchungsgruppen_id) = c2.id)
1011        LEFT JOIN chart c3 ON
1012          ((SELECT expense_accno_id_${taxzone_id}
1013            FROM buchungsgruppen
1014            WHERE id = p.buchungsgruppen_id) = c3.id)
1015        LEFT JOIN partsgroup pg ON (pg.id = p.partsgroup_id)
1016        WHERE $where|;
1017   my $sth = prepare_execute_query($form, $dbh, $query, @values);
1018
1019   $form->{item_list} = [];
1020   while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
1021
1022     # In der Buchungsgruppe ist immer ein Bestandskonto verknuepft, auch wenn
1023     # es sich um eine Dienstleistung handelt. Bei Dienstleistungen muss das
1024     # Buchungskonto also aus dem Ergebnis rausgenommen werden.
1025     if (!$ref->{inventory_accno_id}) {
1026       map({ delete($ref->{"inventory_${_}"}); } qw(accno new_chart valid));
1027     }
1028     delete($ref->{inventory_accno_id});
1029
1030     # get tax rates and description
1031     $accno_id = ($form->{vc} eq "customer") ? $ref->{income_accno} : $ref->{expense_accno};
1032     $query =
1033       qq|SELECT c.accno, t.taxdescription, t.rate, t.taxnumber
1034          FROM tax t
1035          LEFT JOIN chart c on (c.id = t.chart_id)
1036          WHERE t.id IN
1037            (SELECT tk.tax_id
1038             FROM taxkeys tk
1039             WHERE tk.chart_id =
1040               (SELECT id
1041                FROM chart
1042                WHERE accno = ?)
1043               AND (startdate <= $transdate)
1044             ORDER BY startdate DESC
1045             LIMIT 1)
1046          ORDER BY c.accno|;
1047     my $stw = prepare_execute_query($form, $dbh, $query, $accno_id);
1048
1049     $ref->{taxaccounts} = "";
1050     my $i = 0;
1051     while ($ptr = $stw->fetchrow_hashref(NAME_lc)) {
1052
1053       #    if ($customertax{$ref->{accno}}) {
1054       if (($ptr->{accno} eq "") && ($ptr->{rate} == 0)) {
1055         $i++;
1056         $ptr->{accno} = $i;
1057       }
1058
1059       $ref->{taxaccounts} .= "$ptr->{accno} ";
1060
1061       if (!($form->{taxaccounts} =~ /$ptr->{accno}/)) {
1062         $form->{"$ptr->{accno}_rate"}         = $ptr->{rate};
1063         $form->{"$ptr->{accno}_description"}  = $ptr->{taxdescription};
1064         $form->{"$ptr->{accno}_taxnumber"}    = $ptr->{taxnumber};
1065         $form->{taxaccounts}                 .= "$ptr->{accno} ";
1066       }
1067
1068     }
1069
1070     $stw->finish();
1071     chop $ref->{taxaccounts};
1072
1073     push @{ $form->{item_list} }, $ref;
1074
1075   }
1076
1077   $sth->finish();
1078   $dbh->disconnect();
1079
1080   $main::lxdebug->leave_sub();
1081 }
1082
1083 sub vendor_details {
1084   $main::lxdebug->enter_sub();
1085
1086   my ($self, $myconfig, $form, @wanted_vars) = @_;
1087
1088   # connect to database
1089   my $dbh = $form->dbconnect($myconfig);
1090
1091   my @values;
1092
1093   # get contact id, set it if nessessary
1094   $form->{cp_id} = (split /--/, $form->{contact})[1];
1095   my $contact = "";
1096   if ($form->{cp_id}) {
1097     $contact = "AND cp.cp_id = ?";
1098     push @values, $form->{cp_id};
1099   }
1100
1101   # get rest for the vendor
1102   # fax and phone and email as vendor*
1103   my $query =
1104     qq|SELECT ct.*, cp.*, ct.notes as vendornotes, phone as vendorphone, fax as vendorfax, email as vendoremail
1105        FROM vendor ct
1106        LEFT JOIN contacts cp ON (ct.id = cp.cp_cv_id)
1107        WHERE (ct.id = ?) $contact
1108        ORDER BY cp.cp_id
1109        LIMIT 1|;
1110   my $ref = selectfirst_hashref_query($form, $dbh, $query, $form->{vendor_id}, @values);
1111
1112   # remove id and taxincluded before copy back
1113   delete @$ref{qw(id taxincluded)};
1114
1115   @wanted_vars = grep({ $_ } @wanted_vars);
1116   if (scalar(@wanted_vars) > 0) {
1117     my %h_wanted_vars;
1118     map({ $h_wanted_vars{$_} = 1; } @wanted_vars);
1119     map({ delete($ref->{$_}) unless ($h_wanted_vars{$_}); } keys(%{$ref}));
1120   }
1121
1122   map { $form->{$_} = $ref->{$_} } keys %$ref;
1123
1124   $dbh->disconnect();
1125
1126   $main::lxdebug->leave_sub();
1127 }
1128
1129 sub item_links {
1130   $main::lxdebug->enter_sub();
1131
1132   my ($self, $myconfig, $form) = @_;
1133
1134   # connect to database
1135   my $dbh = $form->dbconnect($myconfig);
1136
1137   my $query =
1138     qq|SELECT accno, description, link
1139        FROM chart
1140        WHERE link LIKE '%IC%'
1141        ORDER BY accno|;
1142   my $sth = prepare_execute_query($query, $dbh, $query);
1143
1144   while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
1145     foreach my $key (split(/:/, $ref->{link})) {
1146       if ($key =~ /IC/) {
1147         push @{ $form->{IC_links}{$key} },
1148           { accno       => $ref->{accno},
1149             description => $ref->{description} };
1150       }
1151     }
1152   }
1153
1154   $sth->finish();
1155   $dbh->disconnect();
1156
1157   $main::lxdebug->leave_sub();
1158 }
1159
1160 sub _delete_payments {
1161   $main::lxdebug->enter_sub();
1162
1163   my ($self, $form, $dbh) = @_;
1164
1165   my @delete_oids;
1166
1167   # Delete old payment entries from acc_trans.
1168   my $query =
1169     qq|SELECT oid
1170        FROM acc_trans
1171        WHERE (trans_id = ?) AND fx_transaction
1172
1173        UNION
1174
1175        SELECT at.oid
1176        FROM acc_trans at
1177        LEFT JOIN chart c ON (at.chart_id = c.id)
1178        WHERE (trans_id = ?) AND (c.link LIKE '%AP_paid%')|;
1179   push @delete_oids, selectall_array_query($form, $dbh, $query, conv_i($form->{id}), conv_i($form->{id}));
1180
1181   $query =
1182     qq|SELECT at.oid
1183        FROM acc_trans at
1184        LEFT JOIN chart c ON (at.chart_id = c.id)
1185        WHERE (trans_id = ?)
1186          AND ((c.link = 'AP') OR (c.link LIKE '%:AP') OR (c.link LIKE 'AP:%'))
1187        ORDER BY at.oid
1188        OFFSET 1|;
1189   push @delete_oids, selectall_array_query($form, $dbh, $query, conv_i($form->{id}));
1190
1191   if (@delete_oids) {
1192     $query = qq|DELETE FROM acc_trans WHERE oid IN (| . join(", ", @delete_oids) . qq|)|;
1193     do_query($form, $dbh, $query);
1194   }
1195
1196   $main::lxdebug->leave_sub();
1197 }
1198
1199 sub post_payment {
1200   $main::lxdebug->enter_sub();
1201
1202   my ($self, $myconfig, $form, $locale) = @_;
1203
1204   # connect to database, turn off autocommit
1205   my $dbh = $form->dbconnect_noauto($myconfig);
1206
1207   my (%payments, $old_form, $row, $item, $query, %keep_vars);
1208
1209   $old_form = save_form();
1210
1211   # Delete all entries in acc_trans from prior payments.
1212   $self->_delete_payments($form, $dbh);
1213
1214   # Save the new payments the user made before cleaning up $form.
1215   map { $payments{$_} = $form->{$_} } grep m/^datepaid_\d+$|^memo_\d+$|^source_\d+$|^exchangerate_\d+$|^paid_\d+$|^AP_paid_\d+$|^paidaccounts$/, keys %{ $form };
1216
1217   # Clean up $form so that old content won't tamper the results.
1218   %keep_vars = map { $_, 1 } qw(login password id);
1219   map { delete $form->{$_} unless $keep_vars{$_} } keys %{ $form };
1220
1221   # Retrieve the invoice from the database.
1222   $self->retrieve_invoice($myconfig, $form);
1223
1224   # Set up the content of $form in the way that IR::post_invoice() expects.
1225   $form->{exchangerate} = $form->format_amount($myconfig, $form->{exchangerate});
1226
1227   for $row (1 .. scalar @{ $form->{invoice_details} }) {
1228     $item = $form->{invoice_details}->[$row - 1];
1229
1230     map { $item->{$_} = $form->format_amount($myconfig, $item->{$_}) } qw(qty sellprice);
1231
1232     map { $form->{"${_}_${row}"} = $item->{$_} } keys %{ $item };
1233   }
1234
1235   $form->{rowcount} = scalar @{ $form->{invoice_details} };
1236
1237   delete @{$form}{qw(invoice_details paidaccounts storno paid)};
1238
1239   # Restore the payment options from the user input.
1240   map { $form->{$_} = $payments{$_} } keys %payments;
1241
1242   # Get the AP accno (which is normally done by Form::create_links()).
1243   $query =
1244     qq|SELECT c.accno
1245        FROM acc_trans at
1246        LEFT JOIN chart c ON (at.chart_id = c.id)
1247        WHERE (trans_id = ?)
1248          AND ((c.link = 'AP') OR (c.link LIKE '%:AP') OR (c.link LIKE 'AP:%'))
1249        ORDER BY at.oid
1250        LIMIT 1|;
1251
1252   ($form->{AP}) = selectfirst_array_query($form, $dbh, $query, conv_i($form->{id}));
1253
1254   # Post the new payments.
1255   $self->post_invoice($myconfig, $form, $dbh, 1);
1256
1257   restore_form($old_form);
1258
1259   my $rc = $dbh->commit();
1260   $dbh->disconnect();
1261
1262   $main::lxdebug->leave_sub();
1263
1264   return $rc;
1265 }
1266
1267 1;