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