------------------------------------------------------------------------
[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::DO;
41 use SL::MoreCommon;
42 use List::Util qw(min);
43
44 sub post_invoice {
45   $main::lxdebug->enter_sub();
46
47   my ($self, $myconfig, $form, $provided_dbh, $payments_only) = @_;
48
49   # connect to database, turn off autocommit
50   my $dbh = $provided_dbh ? $provided_dbh : $form->dbconnect_noauto($myconfig);
51   $form->{defaultcurrency} = $form->get_default_currency($myconfig);
52
53   my ($query, $sth, @values, $project_id);
54   my ($allocated, $taxrate, $taxamount, $taxdiff, $item);
55   my ($amount, $linetotal, $lastinventoryaccno, $lastexpenseaccno);
56   my ($netamount, $invoicediff, $expensediff) = (0, 0, 0);
57   my $exchangerate = 0;
58
59   my $all_units = AM->retrieve_units($myconfig, $form);
60
61   if (!$payments_only) {
62     if ($form->{id}) {
63       &reverse_invoice($dbh, $form);
64     } else {
65       ($form->{id}) = selectrow_query($form, $dbh, qq|SELECT nextval('glid')|);
66       do_query($form, $dbh, qq|INSERT INTO ap (id, invnumber) VALUES (?, '')|, $form->{id});
67     }
68   }
69
70   my ($currencies)    = selectfirst_array_query($form, $dbh, qq|SELECT curr FROM defaults|);
71   my $defaultcurrency = (split m/:/, $currencies)[0];
72
73   if ($form->{currency} eq $defaultcurrency) {
74     $form->{exchangerate} = 1;
75   } else {
76     $exchangerate = $form->check_exchangerate($myconfig, $form->{currency}, $form->{transdate}, 'sell');
77   }
78
79   $form->{exchangerate} = $exchangerate || $form->parse_amount($myconfig, $form->{exchangerate});
80   $form->{exchangerate} = 1 unless ($form->{exchangerate} * 1);
81
82   my %item_units;
83   my $q_item_unit = qq|SELECT unit FROM parts WHERE id = ?|;
84   my $h_item_unit = prepare_query($form, $dbh, $q_item_unit);
85
86   $form->get_lists('price_factors' => 'ALL_PRICE_FACTORS');
87   my %price_factors = map { $_->{id} => $_->{factor} } @{ $form->{ALL_PRICE_FACTORS} };
88   my $price_factor;
89
90   for my $i (1 .. $form->{rowcount}) {
91     next unless $form->{"id_$i"};
92
93     $form->{"qty_$i"}  = $form->parse_amount($myconfig, $form->{"qty_$i"});
94     $form->{"qty_$i"} *= -1 if $form->{storno};
95
96     $form->{"inventory_accno_$i"} = $form->{"expense_accno_$i"} if $main::eur;
97
98     # get item baseunit
99     if (!$item_units{$form->{"id_$i"}}) {
100       do_statement($form, $h_item_unit, $q_item_unit, $form->{"id_$i"});
101       ($item_units{$form->{"id_$i"}}) = $h_item_unit->fetchrow_array();
102     }
103
104     my $item_unit = $item_units{$form->{"id_$i"}};
105
106     if (defined($all_units->{$item_unit}->{factor})
107             && ($all_units->{$item_unit}->{factor} ne '')
108             && ($all_units->{$item_unit}->{factor} * 1 != 0)) {
109       $basefactor = $all_units->{$form->{"unit_$i"}}->{factor} / $all_units->{$item_unit}->{factor};
110     } else {
111       $basefactor = 1;
112     }
113     $baseqty = $form->{"qty_$i"} * $basefactor;
114
115     @taxaccounts = split / /, $form->{"taxaccounts_$i"};
116     $taxdiff     = 0;
117     $allocated   = 0;
118     $taxrate     = 0;
119
120     $form->{"sellprice_$i"} = $form->parse_amount($myconfig, $form->{"sellprice_$i"});
121     (my $fxsellprice = $form->{"sellprice_$i"}) =~ /\.(\d+)/;
122     my $dec = length $1;
123     my $decimalplaces = ($dec > 2) ? $dec : 2;
124
125     map { $taxrate += $form->{"${_}_rate"} } @taxaccounts;
126
127     $price_factor = $price_factors{ $form->{"price_factor_id_$i"} } || 1;
128
129     if ($form->{"inventory_accno_$i"}) {
130
131       $linetotal = $form->round_amount($form->{"sellprice_$i"} * $form->{"qty_$i"} / $price_factor, 2);
132
133       if ($form->{taxincluded}) {
134         $taxamount              = $linetotal * ($taxrate / (1 + $taxrate));
135         $form->{"sellprice_$i"} = $form->{"sellprice_$i"} * (1 / (1 + $taxrate));
136       } else {
137         $taxamount = $linetotal * $taxrate;
138       }
139
140       $netamount += $linetotal;
141
142       if ($form->round_amount($taxrate, 7) == 0) {
143         if ($form->{taxincluded}) {
144           foreach $item (@taxaccounts) {
145             $taxamount =
146               $form->round_amount($linetotal * $form->{"${item}_rate"} / (1 + abs($form->{"${item}_rate"})), 2);
147             $taxdiff                              += $taxamount;
148             $form->{amount}{ $form->{id} }{$item} -= $taxamount;
149           }
150           $form->{amount}{ $form->{id} }{ $taxaccounts[0] } += $taxdiff;
151
152         } else {
153           map { $form->{amount}{ $form->{id} }{$_} -= $linetotal * $form->{"${_}_rate"} } @taxaccounts;
154         }
155
156       } else {
157         map { $form->{amount}{ $form->{id} }{$_} -= $taxamount * $form->{"${_}_rate"} / $taxrate } @taxaccounts;
158       }
159
160       # add purchase to inventory, this one is without the tax!
161       $amount    = $form->{"sellprice_$i"} * $form->{"qty_$i"} * $form->{exchangerate} / $price_factor;
162       $linetotal = $form->round_amount($form->{"sellprice_$i"} * $form->{"qty_$i"} / $price_factor, 2) * $form->{exchangerate};
163       $linetotal = $form->round_amount($linetotal, 2);
164
165       # this is the difference for the inventory
166       $invoicediff += ($amount - $linetotal);
167
168       $form->{amount}{ $form->{id} }{ $form->{"inventory_accno_$i"} } -= $linetotal;
169
170       # adjust and round sellprice
171       $form->{"sellprice_$i"} = $form->round_amount($form->{"sellprice_$i"} * $form->{exchangerate}, $decimalplaces);
172
173       $lastinventoryaccno = $form->{"inventory_accno_$i"};
174
175       next if $payments_only;
176
177       # update parts table
178       $query = qq|UPDATE parts SET lastcost = ? WHERE id = ?|;
179       @values = ($form->{"sellprice_$i"}, conv_i($form->{"id_$i"}));
180       do_query($form, $dbh, $query, @values);
181
182       # check if we sold the item already and
183       # make an entry for the expense and inventory
184       $query =
185         qq|SELECT i.id, i.qty, i.allocated, i.trans_id,
186              p.inventory_accno_id, p.expense_accno_id, a.transdate
187            FROM invoice i, ar a, parts p
188            WHERE (i.parts_id = p.id)
189              AND (i.parts_id = ?)
190              AND ((i.base_qty + i.allocated) > 0)
191              AND (i.trans_id = a.id)
192            ORDER BY transdate|;
193       $sth = prepare_execute_query($form, $dbh, $query, conv_i($form->{"id_$i"}));
194
195       my $totalqty = $base_qty;
196
197       while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
198         my $qty    = min $totalqty, ($ref->{base_qty} + $ref->{allocated});
199         $linetotal = $form->round_amount(($form->{"sellprice_$i"} * $qty) / $basefactor, 2);
200
201         if ($ref->{allocated} < 0) {
202
203           # we have an entry for it already, adjust amount
204           $form->update_balance($dbh, "acc_trans", "amount",
205                                 qq|    (trans_id = $ref->{trans_id})
206                                    AND (chart_id = $ref->{inventory_accno_id})
207                                    AND (transdate = '$ref->{transdate}')|,
208                                 $linetotal);
209
210           $form->update_balance($dbh, "acc_trans", "amount",
211                                 qq|    (trans_id = $ref->{trans_id})
212                                    AND (chart_id = $ref->{expense_accno_id})
213                                    AND (transdate = '$ref->{transdate}')|,
214                                 $linetotal * -1);
215
216         } elsif ($linetotal != 0) {
217           # add entry for inventory, this one is for the sold item
218           $query = qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate, taxkey) VALUES (?, ?, ?, ?, (SELECT taxkey_id FROM chart WHERE id = ?))|;
219           @values = ($ref->{trans_id},  $ref->{inventory_accno_id}, $linetotal, $ref->{transdate}, $ref->{inventory_accno_id});
220           do_query($form, $dbh, $query, @values);
221
222           # add expense
223           $query = qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate, taxkey) VALUES (?, ?, ?, ?, (SELECT taxkey from tax WHERE chart_id = ?))|;
224           @values = ($ref->{trans_id},  $ref->{expense_accno_id}, ($linetotal * -1), $ref->{transdate}, $ref->{expense_accno_id});
225           do_query($form, $dbh, $query, @values);
226         }
227
228         # update allocated for sold item
229         $form->update_balance($dbh, "invoice", "allocated", qq|id = $ref->{id}|, $qty * -1);
230
231         $allocated += $qty;
232
233         last if ($totalqty -= $qty) <= 0;
234       }
235
236       $sth->finish();
237
238     } else {                    # if ($form->{"inventory_accno_id_$i"})
239
240       $linetotal = $form->round_amount($form->{"sellprice_$i"} * $form->{"qty_$i"} / $price_factor, 2);
241
242       if ($form->{taxincluded}) {
243         $taxamount              = $linetotal * ($taxrate / (1 + $taxrate));
244         $form->{"sellprice_$i"} = $form->{"sellprice_$i"} * (1 / (1 + $taxrate));
245
246       } else {
247         $taxamount = $linetotal * $taxrate;
248       }
249
250       $netamount += $linetotal;
251
252       if ($form->round_amount($taxrate, 7) == 0) {
253         if ($form->{taxincluded}) {
254           foreach $item (@taxaccounts) {
255             $taxamount = $linetotal * $form->{"${item}_rate"} / (1 + abs($form->{"${item}_rate"}));
256             $totaltax += $taxamount;
257             $form->{amount}{ $form->{id} }{$item} -= $taxamount;
258           }
259         } else {
260           map { $form->{amount}{ $form->{id} }{$_} -= $linetotal * $form->{"${_}_rate"} } @taxaccounts;
261         }
262       } else {
263         map { $form->{amount}{ $form->{id} }{$_} -= $taxamount * $form->{"${_}_rate"} / $taxrate } @taxaccounts;
264       }
265
266       $amount    = $form->{"sellprice_$i"} * $form->{"qty_$i"} * $form->{exchangerate} / $price_factor;
267       $linetotal = $form->round_amount($form->{"sellprice_$i"} * $form->{"qty_$i"} / $price_factor, 2) * $form->{exchangerate};
268       $linetotal = $form->round_amount($linetotal, 2);
269
270       # this is the difference for expense
271       $expensediff += ($amount - $linetotal);
272
273       # add amount to expense
274       $form->{amount}{ $form->{id} }{ $form->{"expense_accno_$i"} } -= $linetotal;
275
276       $lastexpenseaccno = $form->{"expense_accno_$i"};
277
278       # adjust and round sellprice
279       $form->{"sellprice_$i"} = $form->round_amount($form->{"sellprice_$i"} * $form->{exchangerate}, $decimalplaces);
280
281       next if $payments_only;
282
283       # update lastcost
284       $query = qq|UPDATE parts SET lastcost = ? WHERE id = ?|;
285       do_query($form, $dbh, $query, $form->{"sellprice_$i"}, conv_i($form->{"id_$i"}));
286     }
287
288     next if $payments_only;
289
290     # save detail record in invoice table
291     $query =
292       qq|INSERT INTO invoice (trans_id, parts_id, description, qty, base_qty,
293                               sellprice, fxsellprice, allocated, unit, deliverydate,
294                               project_id, serialnumber, price_factor_id, price_factor, marge_price_factor)
295          VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, (SELECT factor FROM price_factors WHERE id = ?), ?)|;
296     @values = (conv_i($form->{id}), conv_i($form->{"id_$i"}),
297                $form->{"description_$i"}, $form->{"qty_$i"} * -1,
298                $baseqty * -1, $form->{"sellprice_$i"}, $fxsellprice, $allocated,
299                $form->{"unit_$i"}, conv_date($form->{deliverydate}),
300                conv_i($form->{"project_id_$i"}), $form->{"serialnumber_$i"},
301                conv_i($form->{"price_factor_id_$i"}), conv_i($form->{"price_factor_id_$i"}), conv_i($form->{"marge_price_factor_$i"}));
302     do_query($form, $dbh, $query, @values);
303   }
304
305   $h_item_unit->finish();
306
307   $project_id = conv_i($form->{"globalproject_id"});
308
309   $form->{datepaid} = $form->{invdate};
310
311   # all amounts are in natural state, netamount includes the taxes
312   # if tax is included, netamount is rounded to 2 decimal places,
313   # taxes are not
314
315   # total payments
316   for my $i (1 .. $form->{paidaccounts}) {
317     $form->{"paid_$i"}  = $form->parse_amount($myconfig, $form->{"paid_$i"});
318     $form->{paid}      += $form->{"paid_$i"};
319     $form->{datepaid}   = $form->{"datepaid_$i"} if $form->{"datepaid_$i"};
320   }
321
322   my ($tax, $paiddiff) = (0, 0);
323
324   $netamount = $form->round_amount($netamount, 2);
325
326   # figure out rounding errors for amount paid and total amount
327   if ($form->{taxincluded}) {
328
329     $amount    = $form->round_amount($netamount * $form->{exchangerate}, 2);
330     $paiddiff  = $amount - $netamount * $form->{exchangerate};
331     $netamount = $amount;
332
333     foreach $item (split / /, $form->{taxaccounts}) {
334       $amount                               = $form->{amount}{ $form->{id} }{$item} * $form->{exchangerate};
335       $form->{amount}{ $form->{id} }{$item} = $form->round_amount($amount, 2);
336
337       $amount     = $form->{amount}{ $form->{id} }{$item} * -1;
338       $tax       += $amount;
339       $netamount -= $amount;
340     }
341
342     $invoicediff += $paiddiff;
343     $expensediff += $paiddiff;
344
345     ######## this only applies to tax included
346     
347     $form->{amount}{ $form->{id} }{$lastinventoryaccno} -= $invoicediff if $lastinventoryaccno;
348     $form->{amount}{ $form->{id} }{$lastexpenseaccno}   -= $expensediff if $lastexpenseaccno;
349
350   } else {
351     $amount    = $form->round_amount($netamount * $form->{exchangerate}, 2);
352     $paiddiff  = $amount - $netamount * $form->{exchangerate};
353     $netamount = $amount;
354
355     foreach my $item (split / /, $form->{taxaccounts}) {
356       $form->{amount}{ $form->{id} }{$item}  = $form->round_amount($form->{amount}{ $form->{id} }{$item}, 2);
357       $amount                                = $form->round_amount( $form->{amount}{ $form->{id} }{$item} * $form->{exchangerate} * -1, 2);
358       $paiddiff                             += $amount - $form->{amount}{ $form->{id} }{$item} * $form->{exchangerate} * -1;
359       $form->{amount}{ $form->{id} }{$item}  = $form->round_amount($amount * -1, 2);
360       $amount                                = $form->{amount}{ $form->{id} }{$item} * -1;
361       $tax                                  += $amount;
362     }
363   }
364
365   $form->{amount}{ $form->{id} }{ $form->{AP} } = $netamount + $tax;
366
367   
368   $form->{paid} = $form->round_amount($form->{paid} * $form->{exchangerate} + $paiddiff, 2) if $form->{paid} != 0;
369
370   # update exchangerate
371   
372   $form->update_exchangerate($dbh, $form->{currency}, $form->{invdate}, 0, $form->{exchangerate})
373     if ($form->{currency} ne $defaultcurrency) && !$exchangerate;
374
375   # record acc_trans transactions
376   foreach my $trans_id (keys %{ $form->{amount} }) {
377     foreach my $accno (keys %{ $form->{amount}{$trans_id} }) {
378       $form->{amount}{$trans_id}{$accno} = $form->round_amount($form->{amount}{$trans_id}{$accno}, 2);
379
380       next if $payments_only || !$form->{amount}{$trans_id}{$accno};
381
382       $query = qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate, taxkey, project_id)
383                   VALUES (?, (SELECT id FROM chart WHERE accno = ?), ?, ?,
384                           (SELECT taxkey_id  FROM chart WHERE accno = ?), ?)|;
385       @values = ($trans_id, $accno, $form->{amount}{$trans_id}{$accno},
386                  conv_date($form->{invdate}), $accno, $project_id);
387       do_query($form, $dbh, $query, @values);
388     }
389   }
390
391   # deduct payment differences from paiddiff
392   for my $i (1 .. $form->{paidaccounts}) {
393     if ($form->{"paid_$i"} != 0) {
394       $amount    = $form->round_amount($form->{"paid_$i"} * $form->{exchangerate}, 2);
395       $paiddiff -= $amount - $form->{"paid_$i"} * $form->{exchangerate};
396     }
397   }
398
399   # force AP entry if 0
400   
401   $form->{amount}{ $form->{id} }{ $form->{AP} } = $form->{paid} if $form->{amount}{$form->{id}}{$form->{AP}} == 0;
402
403   # record payments and offsetting AP
404   for my $i (1 .. $form->{paidaccounts}) {
405     next if $form->{"paid_$i"} == 0;
406
407     my ($accno)            = split /--/, $form->{"AP_paid_$i"};
408     $form->{"datepaid_$i"} = $form->{invdate} unless ($form->{"datepaid_$i"});
409     $form->{datepaid}      = $form->{"datepaid_$i"};
410
411     $amount = $form->round_amount($form->{"paid_$i"} * $form->{exchangerate} + $paiddiff, 2) * -1;
412
413     # record AP
414     if ($form->{amount}{ $form->{id} }{ $form->{AP} } != 0) {
415       $query = qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate, taxkey, project_id)
416                   VALUES (?, (SELECT id FROM chart WHERE accno = ?), ?, ?,
417                           (SELECT taxkey_id FROM chart WHERE accno = ?), ?)|;
418       @values = (conv_i($form->{id}), $form->{AP}, $amount,
419                  $form->{"datepaid_$i"}, $form->{AP}, $project_id);
420       do_query($form, $dbh, $query, @values);
421     }
422
423     # record payment
424     $query = qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate, source, memo, taxkey, project_id)
425                 VALUES (?, (SELECT id FROM chart WHERE accno = ?), ?, ?, ?, ?,
426                 (SELECT taxkey_id FROM chart WHERE accno = ?), ?)|;
427     @values = (conv_i($form->{id}), $accno, $form->{"paid_$i"}, $form->{"datepaid_$i"},
428                $form->{"source_$i"}, $form->{"memo_$i"}, $accno, $project_id);
429     do_query($form, $dbh, $query, @values);
430
431     $exchangerate = 0;
432
433     if ($form->{currency} eq $defaultcurrency) {
434       $form->{"exchangerate_$i"} = 1;
435     } else {
436       $exchangerate              = $form->check_exchangerate($myconfig, $form->{currency}, $form->{"datepaid_$i"}, 'sell');
437       $form->{"exchangerate_$i"} = $exchangerate || $form->parse_amount($myconfig, $form->{"exchangerate_$i"});
438     }
439
440     # exchangerate difference
441     $form->{fx}{$accno}{ $form->{"datepaid_$i"} } += $form->{"paid_$i"} * ($form->{"exchangerate_$i"} - 1) + $paiddiff;
442
443     # gain/loss
444     $amount =
445       ($form->{"paid_$i"} * $form->{exchangerate}) -
446       ($form->{"paid_$i"} * $form->{"exchangerate_$i"});
447     if ($amount > 0) {
448       $form->{fx}{ $form->{fxgain_accno} }{ $form->{"datepaid_$i"} } += $amount;
449     } else {
450       $form->{fx}{ $form->{fxloss_accno} }{ $form->{"datepaid_$i"} } += $amount;
451     }
452
453     $paiddiff = 0;
454
455     # update exchange rate
456     $form->update_exchangerate($dbh, $form->{currency}, $form->{"datepaid_$i"}, 0, $form->{"exchangerate_$i"})
457       if ($form->{currency} ne $defaultcurrency) && !$exchangerate;
458   }
459
460   # record exchange rate differences and gains/losses
461   foreach my $accno (keys %{ $form->{fx} }) {
462     foreach my $transdate (keys %{ $form->{fx}{$accno} }) {
463       $form->{fx}{$accno}{$transdate} = $form->round_amount($form->{fx}{$accno}{$transdate}, 2);
464       next if ($form->{fx}{$accno}{$transdate} == 0);
465
466       $query = qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate, cleared, fx_transaction, taxkey, project_id)
467                   VALUES (?, (SELECT id FROM chart WHERE accno = ?), ?, ?, '0', '1', 0, ?)|;
468       @values = (conv_i($form->{id}), $accno, $form->{fx}{$accno}{$transdate}, conv_date($transdate), $project_id);
469       do_query($form, $dbh, $query, @values);
470     }
471   }
472
473   if ($payments_only) {
474     $query = qq|UPDATE ap SET paid = ?, datepaid = ? WHERE id = ?|;
475     do_query($form, $dbh, $query,  $form->{paid}, $form->{paid} ? conv_date($form->{datepaid}) : undef, conv_i($form->{id}));
476
477     if (!$provided_dbh) {
478       $dbh->commit();
479       $dbh->disconnect();
480     }
481
482     $main::lxdebug->leave_sub();
483     return;
484   }
485
486   $amount = $netamount + $tax;
487
488   # set values which could be empty
489   my $taxzone_id         = $form->{taxzone_id} * 1;
490   $form->{department_id} = (split /--/, $form->{department})[1];
491   $form->{invnumber}     = $form->{id} unless $form->{invnumber};
492
493   $taxzone_id = 0 if (3 < $taxzone_id) || (0 > $taxzone_id);
494
495   # save AP record
496   $query = qq|UPDATE ap SET
497                 invnumber    = ?, ordnumber   = ?, quonumber     = ?, transdate   = ?,
498                 orddate      = ?, quodate     = ?, vendor_id     = ?, amount      = ?,
499                 netamount    = ?, paid        = ?, duedate       = ?, datepaid    = ?,
500                 invoice      = ?, taxzone_id  = ?, notes         = ?, taxincluded = ?,
501                 intnotes     = ?, curr        = ?, storno_id     = ?, storno      = ?,
502                 cp_id        = ?, employee_id = ?, department_id = ?, 
503                 globalproject_id = ?
504               WHERE id = ?|;
505   @values = (
506                 $form->{invnumber},          $form->{ordnumber},           $form->{quonumber},      conv_date($form->{invdate}),
507       conv_date($form->{orddate}), conv_date($form->{quodate}),     conv_i($form->{vendor_id}),               $amount,
508                 $netamount,                  $form->{paid},      conv_date($form->{duedate}),       $form->{paid} ? conv_date($form->{datepaid}) : undef,
509             '1',                             $taxzone_id,                  $form->{notes},          $form->{taxincluded} ? 't' : 'f',
510                 $form->{intnotes},           $form->{currency},     conv_i($form->{storno_id}),     $form->{storno}      ? 't' : 'f',
511          conv_i($form->{cp_id}),      conv_i($form->{employee_id}), conv_i($form->{department_id}), 
512          conv_i($form->{globalproject_id}),
513          conv_i($form->{id})
514   );
515   do_query($form, $dbh, $query, @values);
516
517   if ($form->{storno}) {
518     $query = qq|UPDATE ap SET paid = paid + amount WHERE id = ?|;
519     do_query($form, $dbh, $query, conv_i($form->{storno_id}));
520
521     $query = qq|UPDATE ap SET storno = 't' WHERE id = ?|;
522     do_query($form, $dbh, $query, conv_i($form->{storno_id}));
523
524     $query = qq!UPDATE ap SET intnotes = ? || intnotes WHERE id = ?!;
525     do_query($form, $dbh, $query, 'Rechnung storniert am $form->{invdate} ', conv_i($form->{storno_id}));
526
527     $query = qq|UPDATE ap SET paid = amount WHERE id = ?|;
528     do_query($form, $dbh, $query, conv_i($form->{id}));
529   }
530
531
532   # add shipto
533   $form->{name} = $form->{vendor};
534   $form->{name} =~ s/--\Q$form->{vendor_id}\E//;
535   $form->add_shipto($dbh, $form->{id}, "AP");
536
537   # delete zero entries
538   do_query($form, $dbh, qq|DELETE FROM acc_trans WHERE amount = 0|);
539
540   Common::webdav_folder($form) if ($main::webdav);
541
542   my @close_do_ids = map { $_ * 1 } grep { $_ } split m/\s+/, $form->{close_do_ids};
543   if (scalar @close_do_ids) {
544     DO->close_orders('dbh' => $dbh,
545                      'ids' => \@close_do_ids);
546   }
547
548   my $rc = 1;
549   if (!$provided_dbh) {
550     $rc = $dbh->commit();
551     $dbh->disconnect();
552   }
553
554   $main::lxdebug->leave_sub();
555
556   return $rc;
557 }
558
559 sub reverse_invoice {
560   $main::lxdebug->enter_sub();
561
562   my ($dbh, $form) = @_;
563
564   # reverse inventory items
565   my $query =
566     qq|SELECT i.parts_id, p.inventory_accno_id, p.expense_accno_id, i.qty, i.allocated, i.sellprice
567        FROM invoice i, parts p
568        WHERE (i.parts_id = p.id)
569          AND (i.trans_id = ?)|;
570   my $sth = prepare_execute_query($form, $dbh, $query, conv_i($form->{id}));
571
572   my $netamount = 0;
573
574   while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
575     $netamount += $form->round_amount($ref->{sellprice} * $ref->{qty} * -1, 2);
576
577     next unless $ref->{inventory_accno_id};
578
579     # if $ref->{allocated} > 0 than we sold that many items
580     next if ($ref->{allocated} <= 0);
581
582     # get references for sold items
583     $query =
584       qq|SELECT i.id, i.trans_id, i.allocated, a.transdate
585          FROM invoice i, ar a
586          WHERE (i.parts_id = ?)
587            AND (i.allocated < 0)
588            AND (i.trans_id = a.id)
589          ORDER BY transdate DESC|;
590       my $sth2 = prepare_execute_query($form, $dbh, $query, $ref->{parts_id});
591
592       while (my $pthref = $sth2->fetchrow_hashref(NAME_lc)) {
593         my $qty = $ref->{allocated};
594         if (($ref->{allocated} + $pthref->{allocated}) > 0) {
595           $qty = $pthref->{allocated} * -1;
596         }
597
598         my $amount = $form->round_amount($ref->{sellprice} * $qty, 2);
599
600         #adjust allocated
601         $form->update_balance($dbh, "invoice", "allocated", qq|id = $pthref->{id}|, $qty);
602
603         $form->update_balance($dbh, "acc_trans", "amount",
604                               qq|    (trans_id = $pthref->{trans_id})
605                                  AND (chart_id = $ref->{expense_accno_id})
606                                  AND (transdate = '$pthref->{transdate}')|,
607                               $amount);
608
609         $form->update_balance($dbh, "acc_trans", "amount",
610                               qq|    (trans_id = $pthref->{trans_id})
611                                  AND (chart_id = $ref->{inventory_accno_id})
612                                  AND (transdate = '$pthref->{transdate}')|,
613                               $amount * -1);
614
615         last if (($ref->{allocated} -= $qty) <= 0);
616       }
617     $sth2->finish();
618   }
619   $sth->finish();
620
621   my $id = conv_i($form->{id});
622
623   # delete acc_trans
624   $query = qq|DELETE FROM acc_trans WHERE trans_id = ?|;
625   do_query($form, $dbh, $query, $id);
626
627   # delete invoice entries
628   $query = qq|DELETE FROM invoice WHERE trans_id = ?|;
629   do_query($form, $dbh, $query, $id);
630
631   $query = qq|DELETE FROM shipto WHERE (trans_id = ?) AND (module = 'AP')|;
632   do_query($form, $dbh, $query, $id);
633
634   $main::lxdebug->leave_sub();
635 }
636
637 sub delete_invoice {
638   $main::lxdebug->enter_sub();
639
640   my ($self, $myconfig, $form) = @_;
641   my $query;
642   # connect to database
643   my $dbh = $form->dbconnect_noauto($myconfig);
644
645   &reverse_invoice($dbh, $form);
646
647   # delete zero entries
648   $query = qq|DELETE FROM acc_trans WHERE amount = 0|;
649   do_query($form, $dbh, $query);
650
651   # delete AP record
652   $query = qq|DELETE FROM ap WHERE id = ?|;
653   do_query($form, $dbh, $query, conv_i($form->{id}));
654
655   my $rc = $dbh->commit;
656   $dbh->disconnect;
657
658   $main::lxdebug->leave_sub();
659
660   return $rc;
661 }
662
663 sub retrieve_invoice {
664   $main::lxdebug->enter_sub();
665
666   my ($self, $myconfig, $form) = @_;
667
668   # connect to database
669   my $dbh = $form->dbconnect($myconfig);
670
671   my ($query, $sth, $ref, $q_invdate);
672
673   if (!$form->{id}) {
674     $q_invdate = qq|, COALESCE((SELECT transdate FROM ar WHERE id = (SELECT MAX(id) FROM ar)), current_date) AS invdate|;
675     if ($form->{vendor_id}) {
676       my $vendor_id = $dbh->quote($form->{vendor_id} * 1);
677       $q_invdate .=
678         qq|, COALESCE((SELECT transdate FROM ar WHERE id = (SELECT MAX(id) FROM ar)), current_date) +
679              COALESCE((SELECT pt.terms_netto
680                        FROM vendor v
681                        LEFT JOIN payment_terms pt ON (v.payment_id = pt.id)
682                        WHERE v.id = $vendor_id),
683                       0) AS duedate|;
684     }
685   }
686
687   # get default accounts and last invoice number
688
689   $query = qq|SELECT
690                (SELECT c.accno FROM chart c WHERE d.inventory_accno_id = c.id) AS inventory_accno,
691                (SELECT c.accno FROM chart c WHERE d.income_accno_id = c.id)    AS income_accno,
692                (SELECT c.accno FROM chart c WHERE d.expense_accno_id = c.id)   AS expense_accno,
693                (SELECT c.accno FROM chart c WHERE d.fxgain_accno_id = c.id)    AS fxgain_accno,
694                (SELECT c.accno FROM chart c WHERE d.fxloss_accno_id = c.id)    AS fxloss_accno,
695                d.curr AS currencies
696                $q_invdate
697                FROM defaults d|;
698   $ref = selectfirst_hashref_query($form, $dbh, $query);
699   map { $form->{$_} = $ref->{$_} } keys %$ref;
700
701   if (!$form->{id}) {
702     $dbh->disconnect();
703     $main::lxdebug->leave_sub();
704
705     return;
706   }
707
708   # retrieve invoice
709   $query = qq|SELECT cp_id, invnumber, transdate AS invdate, duedate,
710                 orddate, quodate, globalproject_id,
711                 ordnumber, quonumber, paid, taxincluded, notes, taxzone_id, storno, gldate,
712                 intnotes, curr AS currency
713               FROM ap
714               WHERE id = ?|;
715   $ref = selectfirst_hashref_query($form, $dbh, $query, conv_i($form->{id}));
716   map { $form->{$_} = $ref->{$_} } keys %$ref;
717
718   $form->{exchangerate}  = $form->get_exchangerate($dbh, $form->{currency}, $form->{invdate}, "sell");
719
720   # get shipto
721   $query = qq|SELECT * FROM shipto WHERE (trans_id = ?) AND (module = 'AP')|;
722   $ref = selectfirst_hashref_query($form, $dbh, $query, conv_i($form->{id}));
723   delete $ref->{id};
724   map { $form->{$_} = $ref->{$_} } keys %$ref;
725
726   my $transdate  = $form->{invdate} ? $dbh->quote($form->{invdate}) : "current_date";
727   my $taxzone_id = $form->{taxzone_id} * 1;
728
729   $taxzone_id = 0 if ((3 < $taxzone_id) || (0 > $taxzone_id));
730
731   # retrieve individual items
732   $query =
733     qq|SELECT
734         c1.accno AS inventory_accno, c1.new_chart_id AS inventory_new_chart, date($transdate) - c1.valid_from AS inventory_valid,
735         c2.accno AS income_accno,    c2.new_chart_id AS income_new_chart,    date($transdate) - c2.valid_from AS income_valid,
736         c3.accno AS expense_accno,   c3.new_chart_id AS expense_new_chart,   date($transdate) - c3.valid_from AS expense_valid,
737
738         i.description, i.qty, i.fxsellprice AS sellprice, i.parts_id AS id, i.unit, i.deliverydate, i.project_id, i.serialnumber,
739         i.price_factor_id, i.price_factor, i.marge_price_factor,
740         p.partnumber, p.inventory_accno_id AS part_inventory_accno_id, p.bin, pr.projectnumber, pg.partsgroup
741
742         FROM invoice i
743         JOIN parts p ON (i.parts_id = p.id)
744         LEFT JOIN chart c1 ON ((SELECT inventory_accno_id             FROM buchungsgruppen WHERE id = p.buchungsgruppen_id) = c1.id)
745         LEFT JOIN chart c2 ON ((SELECT income_accno_id_${taxzone_id}  FROM buchungsgruppen WHERE id = p.buchungsgruppen_id) = c2.id)
746         LEFT JOIN chart c3 ON ((SELECT expense_accno_id_${taxzone_id} FROM buchungsgruppen WHERE id = p.buchungsgruppen_id) = c3.id)
747         LEFT JOIN project pr    ON (i.project_id = pr.id)
748         LEFT JOIN partsgroup pg ON (pg.id = p.partsgroup_id)
749
750         WHERE i.trans_id = ?
751
752         ORDER BY i.id|;
753   $sth = prepare_execute_query($form, $dbh, $query, conv_i($form->{id}));
754
755   while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
756     map({ delete($ref->{$_}); } qw(inventory_accno inventory_new_chart inventory_valid)) if !$ref->{"part_inventory_accno_id"};
757     delete($ref->{"part_inventory_accno_id"});
758
759     foreach my $type (qw(inventory income expense)) {
760       while ($ref->{"${type}_new_chart"} && ($ref->{"${type}_valid"} >=0)) {
761         my $query = qq|SELECT accno, new_chart_id, date($transdate) - valid_from FROM chart WHERE id = ?|;
762         @$ref{ map $type.$_, qw(_accno _new_chart _valid) } = selectrow_query($form, $dbh, $query, $ref->{"${type}_new_chart"});
763       }
764     }
765
766     # get tax rates and description
767     my $accno_id = ($form->{vc} eq "customer") ? $ref->{income_accno} : $ref->{expense_accno};
768     $query =
769       qq|SELECT c.accno, t.taxdescription, t.rate, t.taxnumber FROM tax t
770          LEFT JOIN chart c ON (c.id = t.chart_id)
771          WHERE t.id in
772            (SELECT tk.tax_id FROM taxkeys tk
773             WHERE tk.chart_id = (SELECT id FROM chart WHERE accno = ?)
774               AND (startdate <= $transdate)
775             ORDER BY startdate DESC
776             LIMIT 1)
777          ORDER BY c.accno|;
778     my $stw = prepare_execute_query($form, $dbh, $query, $accno_id);
779     $ref->{taxaccounts} = "";
780
781     my $i = 0;
782     while ($ptr = $stw->fetchrow_hashref(NAME_lc)) {
783       if (($ptr->{accno} eq "") && ($ptr->{rate} == 0)) {
784         $i++;
785         $ptr->{accno} = $i;
786       }
787
788       $ref->{taxaccounts} .= "$ptr->{accno} ";
789
790       if (!($form->{taxaccounts} =~ /\Q$ptr->{accno}\E/)) {
791         $form->{"$ptr->{accno}_rate"}         = $ptr->{rate};
792         $form->{"$ptr->{accno}_description"}  = $ptr->{taxdescription};
793         $form->{"$ptr->{accno}_taxnumber"}    = $ptr->{taxnumber};
794         $form->{taxaccounts}                 .= "$ptr->{accno} ";
795       }
796
797     }
798
799     chop $ref->{taxaccounts};
800     push @{ $form->{invoice_details} }, $ref;
801     $stw->finish();
802   }
803   $sth->finish();
804
805   Common::webdav_folder($form) if ($main::webdav);
806
807   $dbh->disconnect();
808
809   $main::lxdebug->leave_sub();
810 }
811
812 sub get_vendor {
813   $main::lxdebug->enter_sub();
814
815   my ($self, $myconfig, $form, $params) = @_;
816
817   $params = $form unless defined $params && ref $params eq "HASH";
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.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     $ref->{onhand} *= 1;
1062
1063     push @{ $form->{item_list} }, $ref;
1064
1065   }
1066
1067   $sth->finish();
1068   $dbh->disconnect();
1069
1070   $main::lxdebug->leave_sub();
1071 }
1072
1073 sub vendor_details {
1074   $main::lxdebug->enter_sub();
1075
1076   my ($self, $myconfig, $form, @wanted_vars) = @_;
1077
1078   # connect to database
1079   my $dbh = $form->dbconnect($myconfig);
1080
1081   my @values;
1082
1083   # get contact id, set it if nessessary
1084   $form->{cp_id} *= 1;
1085   my $contact = "";
1086   if ($form->{cp_id}) {
1087     $contact = "AND cp.cp_id = ?";
1088     push @values, $form->{cp_id};
1089   }
1090
1091   # get rest for the vendor
1092   # fax and phone and email as vendor*
1093   my $query =
1094     qq|SELECT ct.*, cp.*, ct.notes as vendornotes, phone as vendorphone, fax as vendorfax, email as vendoremail
1095        FROM vendor ct
1096        LEFT JOIN contacts cp ON (ct.id = cp.cp_cv_id)
1097        WHERE (ct.id = ?) $contact
1098        ORDER BY cp.cp_id
1099        LIMIT 1|;
1100   my $ref = selectfirst_hashref_query($form, $dbh, $query, $form->{vendor_id}, @values);
1101
1102   # remove id and taxincluded before copy back
1103   delete @$ref{qw(id taxincluded)};
1104
1105   @wanted_vars = grep({ $_ } @wanted_vars);
1106   if (scalar(@wanted_vars) > 0) {
1107     my %h_wanted_vars;
1108     map({ $h_wanted_vars{$_} = 1; } @wanted_vars);
1109     map({ delete($ref->{$_}) unless ($h_wanted_vars{$_}); } keys(%{$ref}));
1110   }
1111
1112   map { $form->{$_} = $ref->{$_} } keys %$ref;
1113
1114   my $custom_variables = CVar->get_custom_variables('dbh'      => $dbh,
1115                                                     'module'   => 'CT',
1116                                                     'trans_id' => $form->{vendor_id});
1117   map { $form->{"vc_cvar_$_->{name}"} = $_->{value} } @{ $custom_variables };
1118
1119   $dbh->disconnect();
1120
1121   $main::lxdebug->leave_sub();
1122 }
1123
1124 sub item_links {
1125   $main::lxdebug->enter_sub();
1126
1127   my ($self, $myconfig, $form) = @_;
1128
1129   # connect to database
1130   my $dbh = $form->dbconnect($myconfig);
1131
1132   my $query =
1133     qq|SELECT accno, description, link
1134        FROM chart
1135        WHERE link LIKE '%IC%'
1136        ORDER BY accno|;
1137   my $sth = prepare_execute_query($query, $dbh, $query);
1138
1139   while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
1140     foreach my $key (split(/:/, $ref->{link})) {
1141       if ($key =~ /IC/) {
1142         push @{ $form->{IC_links}{$key} },
1143           { accno       => $ref->{accno},
1144             description => $ref->{description} };
1145       }
1146     }
1147   }
1148
1149   $sth->finish();
1150   $dbh->disconnect();
1151
1152   $main::lxdebug->leave_sub();
1153 }
1154
1155 sub _delete_payments {
1156   $main::lxdebug->enter_sub();
1157
1158   my ($self, $form, $dbh) = @_;
1159
1160   my @delete_oids;
1161
1162   # Delete old payment entries from acc_trans.
1163   my $query =
1164     qq|SELECT oid
1165        FROM acc_trans
1166        WHERE (trans_id = ?) AND fx_transaction
1167
1168        UNION
1169
1170        SELECT at.oid
1171        FROM acc_trans at
1172        LEFT JOIN chart c ON (at.chart_id = c.id)
1173        WHERE (trans_id = ?) AND (c.link LIKE '%AP_paid%')|;
1174   push @delete_oids, selectall_array_query($form, $dbh, $query, conv_i($form->{id}), conv_i($form->{id}));
1175
1176   $query =
1177     qq|SELECT at.oid
1178        FROM acc_trans at
1179        LEFT JOIN chart c ON (at.chart_id = c.id)
1180        WHERE (trans_id = ?)
1181          AND ((c.link = 'AP') OR (c.link LIKE '%:AP') OR (c.link LIKE 'AP:%'))
1182        ORDER BY at.oid
1183        OFFSET 1|;
1184   push @delete_oids, selectall_array_query($form, $dbh, $query, conv_i($form->{id}));
1185
1186   if (@delete_oids) {
1187     $query = qq|DELETE FROM acc_trans WHERE oid IN (| . join(", ", @delete_oids) . qq|)|;
1188     do_query($form, $dbh, $query);
1189   }
1190
1191   $main::lxdebug->leave_sub();
1192 }
1193
1194 sub post_payment {
1195   $main::lxdebug->enter_sub();
1196
1197   my ($self, $myconfig, $form, $locale) = @_;
1198
1199   # connect to database, turn off autocommit
1200   my $dbh = $form->dbconnect_noauto($myconfig);
1201
1202   my (%payments, $old_form, $row, $item, $query, %keep_vars);
1203
1204   $old_form = save_form();
1205
1206   # Delete all entries in acc_trans from prior payments.
1207   $self->_delete_payments($form, $dbh);
1208
1209   # Save the new payments the user made before cleaning up $form.
1210   map { $payments{$_} = $form->{$_} } grep m/^datepaid_\d+$|^memo_\d+$|^source_\d+$|^exchangerate_\d+$|^paid_\d+$|^AP_paid_\d+$|^paidaccounts$/, keys %{ $form };
1211
1212   # Clean up $form so that old content won't tamper the results.
1213   %keep_vars = map { $_, 1 } qw(login password id);
1214   map { delete $form->{$_} unless $keep_vars{$_} } keys %{ $form };
1215
1216   # Retrieve the invoice from the database.
1217   $self->retrieve_invoice($myconfig, $form);
1218
1219   # Set up the content of $form in the way that IR::post_invoice() expects.
1220   $form->{exchangerate} = $form->format_amount($myconfig, $form->{exchangerate});
1221
1222   for $row (1 .. scalar @{ $form->{invoice_details} }) {
1223     $item = $form->{invoice_details}->[$row - 1];
1224
1225     map { $item->{$_} = $form->format_amount($myconfig, $item->{$_}) } qw(qty sellprice);
1226
1227     map { $form->{"${_}_${row}"} = $item->{$_} } keys %{ $item };
1228   }
1229
1230   $form->{rowcount} = scalar @{ $form->{invoice_details} };
1231
1232   delete @{$form}{qw(invoice_details paidaccounts storno paid)};
1233
1234   # Restore the payment options from the user input.
1235   map { $form->{$_} = $payments{$_} } keys %payments;
1236
1237   # Get the AP accno (which is normally done by Form::create_links()).
1238   $query =
1239     qq|SELECT c.accno
1240        FROM acc_trans at
1241        LEFT JOIN chart c ON (at.chart_id = c.id)
1242        WHERE (trans_id = ?)
1243          AND ((c.link = 'AP') OR (c.link LIKE '%:AP') OR (c.link LIKE 'AP:%'))
1244        ORDER BY at.oid
1245        LIMIT 1|;
1246
1247   ($form->{AP}) = selectfirst_array_query($form, $dbh, $query, conv_i($form->{id}));
1248
1249   # Post the new payments.
1250   $self->post_invoice($myconfig, $form, $dbh, 1);
1251
1252   restore_form($old_form);
1253
1254   my $rc = $dbh->commit();
1255   $dbh->disconnect();
1256
1257   $main::lxdebug->leave_sub();
1258
1259   return $rc;
1260 }
1261
1262 1;