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