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