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