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