Eingangsrechnungen: Wird das Rechnungsdatum verändert, so wird per AJAX das Fälligkei...
[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   # Link this record to the records it was created from.
543   RecordLinks->create_links('dbh'        => $dbh,
544                             'mode'       => 'ids',
545                             'from_table' => 'oe',
546                             'from_ids'   => $form->{convert_from_oe_ids},
547                             'to_table'   => 'ap',
548                             'to_id'      => $form->{id},
549     );
550   delete $form->{convert_from_oe_ids};
551
552   my @convert_from_do_ids = map { $_ * 1 } grep { $_ } split m/\s+/, $form->{convert_from_do_ids};
553   if (scalar @convert_from_do_ids) {
554     DO->close_orders('dbh' => $dbh,
555                      'ids' => \@convert_from_do_ids);
556
557     RecordLinks->create_links('dbh'        => $dbh,
558                               'mode'       => 'ids',
559                               'from_table' => 'delivery_orders',
560                               'from_ids'   => \@convert_from_do_ids,
561                               'to_table'   => 'ap',
562                               'to_id'      => $form->{id},
563       );
564   }
565
566   my $rc = 1;
567   if (!$provided_dbh) {
568     $rc = $dbh->commit();
569     $dbh->disconnect();
570   }
571
572   $main::lxdebug->leave_sub();
573
574   return $rc;
575 }
576
577 sub reverse_invoice {
578   $main::lxdebug->enter_sub();
579
580   my ($dbh, $form) = @_;
581
582   # reverse inventory items
583   my $query =
584     qq|SELECT i.parts_id, p.inventory_accno_id, p.expense_accno_id, i.qty, i.allocated, i.sellprice
585        FROM invoice i, parts p
586        WHERE (i.parts_id = p.id)
587          AND (i.trans_id = ?)|;
588   my $sth = prepare_execute_query($form, $dbh, $query, conv_i($form->{id}));
589
590   my $netamount = 0;
591
592   while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
593     $netamount += $form->round_amount($ref->{sellprice} * $ref->{qty} * -1, 2);
594
595     next unless $ref->{inventory_accno_id};
596
597     # if $ref->{allocated} > 0 than we sold that many items
598     next if ($ref->{allocated} <= 0);
599
600     # get references for sold items
601     $query =
602       qq|SELECT i.id, i.trans_id, i.allocated, a.transdate
603          FROM invoice i, ar a
604          WHERE (i.parts_id = ?)
605            AND (i.allocated < 0)
606            AND (i.trans_id = a.id)
607          ORDER BY transdate DESC|;
608       my $sth2 = prepare_execute_query($form, $dbh, $query, $ref->{parts_id});
609
610       while (my $pthref = $sth2->fetchrow_hashref(NAME_lc)) {
611         my $qty = $ref->{allocated};
612         if (($ref->{allocated} + $pthref->{allocated}) > 0) {
613           $qty = $pthref->{allocated} * -1;
614         }
615
616         my $amount = $form->round_amount($ref->{sellprice} * $qty, 2);
617
618         #adjust allocated
619         $form->update_balance($dbh, "invoice", "allocated", qq|id = $pthref->{id}|, $qty);
620
621         $form->update_balance($dbh, "acc_trans", "amount",
622                               qq|    (trans_id = $pthref->{trans_id})
623                                  AND (chart_id = $ref->{expense_accno_id})
624                                  AND (transdate = '$pthref->{transdate}')|,
625                               $amount);
626
627         $form->update_balance($dbh, "acc_trans", "amount",
628                               qq|    (trans_id = $pthref->{trans_id})
629                                  AND (chart_id = $ref->{inventory_accno_id})
630                                  AND (transdate = '$pthref->{transdate}')|,
631                               $amount * -1);
632
633         last if (($ref->{allocated} -= $qty) <= 0);
634       }
635     $sth2->finish();
636   }
637   $sth->finish();
638
639   my $id = conv_i($form->{id});
640
641   # delete acc_trans
642   $query = qq|DELETE FROM acc_trans WHERE trans_id = ?|;
643   do_query($form, $dbh, $query, $id);
644
645   # delete invoice entries
646   $query = qq|DELETE FROM invoice WHERE trans_id = ?|;
647   do_query($form, $dbh, $query, $id);
648
649   $query = qq|DELETE FROM shipto WHERE (trans_id = ?) AND (module = 'AP')|;
650   do_query($form, $dbh, $query, $id);
651
652   $main::lxdebug->leave_sub();
653 }
654
655 sub delete_invoice {
656   $main::lxdebug->enter_sub();
657
658   my ($self, $myconfig, $form) = @_;
659   my $query;
660   # connect to database
661   my $dbh = $form->dbconnect_noauto($myconfig);
662
663   &reverse_invoice($dbh, $form);
664
665   # delete zero entries
666   $query = qq|DELETE FROM acc_trans WHERE amount = 0|;
667   do_query($form, $dbh, $query);
668
669   # delete AP record
670   $query = qq|DELETE FROM ap WHERE id = ?|;
671   do_query($form, $dbh, $query, conv_i($form->{id}));
672
673   my $rc = $dbh->commit;
674   $dbh->disconnect;
675
676   $main::lxdebug->leave_sub();
677
678   return $rc;
679 }
680
681 sub retrieve_invoice {
682   $main::lxdebug->enter_sub();
683
684   my ($self, $myconfig, $form) = @_;
685
686   # connect to database
687   my $dbh = $form->dbconnect($myconfig);
688
689   my ($query, $sth, $ref, $q_invdate);
690
691   if (!$form->{id}) {
692     $q_invdate = qq|, COALESCE((SELECT transdate FROM ar WHERE id = (SELECT MAX(id) FROM ar)), current_date) AS invdate|;
693     if ($form->{vendor_id}) {
694       my $vendor_id = $dbh->quote($form->{vendor_id} * 1);
695       $q_invdate .=
696         qq|, COALESCE((SELECT transdate FROM ar WHERE id = (SELECT MAX(id) FROM ar)), current_date) +
697              COALESCE((SELECT pt.terms_netto
698                        FROM vendor v
699                        LEFT JOIN payment_terms pt ON (v.payment_id = pt.id)
700                        WHERE v.id = $vendor_id),
701                       0) AS duedate|;
702     }
703   }
704
705   # get default accounts and last invoice number
706
707   $query = qq|SELECT
708                (SELECT c.accno FROM chart c WHERE d.inventory_accno_id = c.id) AS inventory_accno,
709                (SELECT c.accno FROM chart c WHERE d.income_accno_id = c.id)    AS income_accno,
710                (SELECT c.accno FROM chart c WHERE d.expense_accno_id = c.id)   AS expense_accno,
711                (SELECT c.accno FROM chart c WHERE d.fxgain_accno_id = c.id)    AS fxgain_accno,
712                (SELECT c.accno FROM chart c WHERE d.fxloss_accno_id = c.id)    AS fxloss_accno,
713                d.curr AS currencies
714                $q_invdate
715                FROM defaults d|;
716   $ref = selectfirst_hashref_query($form, $dbh, $query);
717   map { $form->{$_} = $ref->{$_} } keys %$ref;
718
719   if (!$form->{id}) {
720     $dbh->disconnect();
721     $main::lxdebug->leave_sub();
722
723     return;
724   }
725
726   # retrieve invoice
727   $query = qq|SELECT cp_id, invnumber, transdate AS invdate, duedate,
728                 orddate, quodate, globalproject_id,
729                 ordnumber, quonumber, paid, taxincluded, notes, taxzone_id, storno, gldate,
730                 intnotes, curr AS currency
731               FROM ap
732               WHERE id = ?|;
733   $ref = selectfirst_hashref_query($form, $dbh, $query, conv_i($form->{id}));
734   map { $form->{$_} = $ref->{$_} } keys %$ref;
735
736   $form->{exchangerate}  = $form->get_exchangerate($dbh, $form->{currency}, $form->{invdate}, "sell");
737
738   # get shipto
739   $query = qq|SELECT * FROM shipto WHERE (trans_id = ?) AND (module = 'AP')|;
740   $ref = selectfirst_hashref_query($form, $dbh, $query, conv_i($form->{id}));
741   delete $ref->{id};
742   map { $form->{$_} = $ref->{$_} } keys %$ref;
743
744   my $transdate  = $form->{invdate} ? $dbh->quote($form->{invdate}) : "current_date";
745   my $taxzone_id = $form->{taxzone_id} * 1;
746
747   $taxzone_id = 0 if ((3 < $taxzone_id) || (0 > $taxzone_id));
748
749   # retrieve individual items
750   $query =
751     qq|SELECT
752         c1.accno AS inventory_accno, c1.new_chart_id AS inventory_new_chart, date($transdate) - c1.valid_from AS inventory_valid,
753         c2.accno AS income_accno,    c2.new_chart_id AS income_new_chart,    date($transdate) - c2.valid_from AS income_valid,
754         c3.accno AS expense_accno,   c3.new_chart_id AS expense_new_chart,   date($transdate) - c3.valid_from AS expense_valid,
755
756         i.description, i.qty, i.fxsellprice AS sellprice, i.parts_id AS id, i.unit, i.deliverydate, i.project_id, i.serialnumber,
757         i.price_factor_id, i.price_factor, i.marge_price_factor,
758         p.partnumber, p.inventory_accno_id AS part_inventory_accno_id, p.bin, pr.projectnumber, pg.partsgroup
759
760         FROM invoice i
761         JOIN parts p ON (i.parts_id = p.id)
762         LEFT JOIN chart c1 ON ((SELECT inventory_accno_id             FROM buchungsgruppen WHERE id = p.buchungsgruppen_id) = c1.id)
763         LEFT JOIN chart c2 ON ((SELECT income_accno_id_${taxzone_id}  FROM buchungsgruppen WHERE id = p.buchungsgruppen_id) = c2.id)
764         LEFT JOIN chart c3 ON ((SELECT expense_accno_id_${taxzone_id} FROM buchungsgruppen WHERE id = p.buchungsgruppen_id) = c3.id)
765         LEFT JOIN project pr    ON (i.project_id = pr.id)
766         LEFT JOIN partsgroup pg ON (pg.id = p.partsgroup_id)
767
768         WHERE i.trans_id = ?
769
770         ORDER BY i.id|;
771   $sth = prepare_execute_query($form, $dbh, $query, conv_i($form->{id}));
772
773   while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
774     map({ delete($ref->{$_}); } qw(inventory_accno inventory_new_chart inventory_valid)) if !$ref->{"part_inventory_accno_id"};
775     delete($ref->{"part_inventory_accno_id"});
776
777     foreach my $type (qw(inventory income expense)) {
778       while ($ref->{"${type}_new_chart"} && ($ref->{"${type}_valid"} >=0)) {
779         my $query = qq|SELECT accno, new_chart_id, date($transdate) - valid_from FROM chart WHERE id = ?|;
780         @$ref{ map $type.$_, qw(_accno _new_chart _valid) } = selectrow_query($form, $dbh, $query, $ref->{"${type}_new_chart"});
781       }
782     }
783
784     # get tax rates and description
785     my $accno_id = ($form->{vc} eq "customer") ? $ref->{income_accno} : $ref->{expense_accno};
786     $query =
787       qq|SELECT c.accno, t.taxdescription, t.rate, t.taxnumber FROM tax t
788          LEFT JOIN chart c ON (c.id = t.chart_id)
789          WHERE t.id in
790            (SELECT tk.tax_id FROM taxkeys tk
791             WHERE tk.chart_id = (SELECT id FROM chart WHERE accno = ?)
792               AND (startdate <= $transdate)
793             ORDER BY startdate DESC
794             LIMIT 1)
795          ORDER BY c.accno|;
796     my $stw = prepare_execute_query($form, $dbh, $query, $accno_id);
797     $ref->{taxaccounts} = "";
798
799     my $i = 0;
800     while ($ptr = $stw->fetchrow_hashref(NAME_lc)) {
801       if (($ptr->{accno} eq "") && ($ptr->{rate} == 0)) {
802         $i++;
803         $ptr->{accno} = $i;
804       }
805
806       $ref->{taxaccounts} .= "$ptr->{accno} ";
807
808       if (!($form->{taxaccounts} =~ /\Q$ptr->{accno}\E/)) {
809         $form->{"$ptr->{accno}_rate"}         = $ptr->{rate};
810         $form->{"$ptr->{accno}_description"}  = $ptr->{taxdescription};
811         $form->{"$ptr->{accno}_taxnumber"}    = $ptr->{taxnumber};
812         $form->{taxaccounts}                 .= "$ptr->{accno} ";
813       }
814
815     }
816
817     chop $ref->{taxaccounts};
818     push @{ $form->{invoice_details} }, $ref;
819     $stw->finish();
820   }
821   $sth->finish();
822
823   Common::webdav_folder($form) if ($main::webdav);
824
825   $dbh->disconnect();
826
827   $main::lxdebug->leave_sub();
828 }
829
830 sub get_vendor {
831   $main::lxdebug->enter_sub();
832
833   my ($self, $myconfig, $form, $params) = @_;
834
835   $params = $form unless defined $params && ref $params eq "HASH";
836
837   # connect to database
838   my $dbh = $form->dbconnect($myconfig);
839
840   my $dateformat = $myconfig->{dateformat};
841   $dateformat .= "yy" if $myconfig->{dateformat} !~ /^y/;
842
843   my $vid = conv_i($params->{vendor_id});
844   my $vnr = conv_i($params->{vendornumber});
845
846   my $duedate =
847     ($params->{invdate})
848     ? "to_date(" . $dbh->quote($params->{invdate}) . ", '$dateformat')"
849     : "current_date";
850
851   # get vendor
852   @values = ();
853   if ($vid) {
854     $where .= 'AND v.id = ?';
855     push @values, $vid;
856   }
857   if ($vnr) {
858     $where .= 'AND v.vendornumber = ?';
859     push @values, $vnr;
860   }
861   my $query =
862     qq|SELECT
863          v.name AS vendor, v.creditlimit, v.terms, v.notes AS intnotes,
864          v.email, v.cc, v.bcc, v.language_id, v.payment_id,
865          v.street, v.zipcode, v.city, v.country, v.taxzone_id,
866          $duedate + COALESCE(pt.terms_netto, 0) AS duedate,
867          b.description AS business
868        FROM vendor v
869        LEFT JOIN business b       ON (b.id = v.business_id)
870        LEFT JOIN payment_terms pt ON (v.payment_id = pt.id)
871        WHERE 1=1 $where|;
872   $ref = selectfirst_hashref_query($form, $dbh, $query, @values);
873   map { $params->{$_} = $ref->{$_} } keys %$ref;
874
875   $params->{creditremaining} = $params->{creditlimit};
876
877   $query = qq|SELECT SUM(amount - paid) FROM ap WHERE vendor_id = ?|;
878   my ($unpaid_invoices) = selectfirst_array_query($form, $dbh, $query, $vid);
879   $params->{creditremaining} -= $unpaid_invoices;
880
881   $query = qq|SELECT o.amount,
882                 (SELECT e.sell
883                  FROM exchangerate e
884                  WHERE (e.curr = o.curr)
885                    AND (e.transdate = o.transdate)) AS exch
886               FROM oe o
887               WHERE (o.vendor_id = ?) AND (o.quotation = '0') AND (o.closed = '0')|;
888   my $sth = prepare_execute_query($form, $dbh, $query, $vid);
889   while (my ($amount, $exch) = $sth->fetchrow_array()) {
890     $exch = 1 unless $exch;
891     $params->{creditremaining} -= $amount * $exch;
892   }
893   $sth->finish();
894
895   # get shipto if we do not convert an order or invoice
896   if (!$params->{shipto}) {
897     delete @{$params}{qw(shiptoname shiptostreet shiptozipcode shiptocity shiptocountry shiptocontact shiptophone shiptofax shiptoemail)};
898
899     $query = qq|SELECT * FROM shipto WHERE (trans_id = ?) AND (module= 'CT')|;
900     $ref = selectfirst_hashref_query($form, $dbh, $query, $vid);
901     @{$params}{keys %$ref} = @{$ref}{keys %$ref};
902     map { $params->{$_} = $ref->{$_} } keys %$ref;
903   }
904
905   if (!$params->{id} && $params->{type} !~ /_(order|quotation)/) {
906     # setup last accounts used
907     $query =
908       qq|SELECT c.id, c.accno, c.description, c.link, c.category
909          FROM chart c
910          JOIN acc_trans ac ON (ac.chart_id = c.id)
911          JOIN ap a         ON (a.id = ac.trans_id)
912          WHERE (a.vendor_id = ?)
913            AND (NOT ((c.link LIKE '%_tax%') OR (c.link LIKE '%_paid%')))
914            AND (a.id IN (SELECT max(a2.id) FROM ap a2 WHERE a2.vendor_id = ?))|;
915     my $refs = selectall_hashref_query($form, $dbh, $query, $vid, $vid);
916
917     my $i = 0;
918     for $ref (@$refs) {
919       if ($ref->{category} eq 'E') {
920         $i++;
921
922         if ($params->{initial_transdate}) {
923           my $tax_query = qq|SELECT tk.tax_id, t.rate FROM taxkeys tk
924                              LEFT JOIN tax t ON (tk.tax_id = t.id)
925                              WHERE (tk.chart_id = ?) AND (startdate <= ?)
926                              ORDER BY tk.startdate DESC
927                              LIMIT 1|;
928           my ($tax_id, $rate) = selectrow_query($form, $dbh, $tax_query, $ref->{id}, $params->{initial_transdate});
929           $params->{"taxchart_$i"} = "${tax_id}--${rate}";
930         }
931
932         $params->{"AP_amount_$i"} = "$ref->{accno}--$tax_id";
933       }
934
935       if ($ref->{category} eq 'L') {
936         $params->{APselected} = $params->{AP_1} = $ref->{accno};
937       }
938     }
939     $params->{rowcount} = $i if ($i && !$params->{type});
940   }
941
942   $dbh->disconnect();
943
944   $main::lxdebug->leave_sub();
945 }
946
947 sub retrieve_item {
948   $main::lxdebug->enter_sub();
949
950   my ($self, $myconfig, $form) = @_;
951
952   # connect to database
953   my $dbh = $form->dbconnect($myconfig);
954
955   my $i = $form->{rowcount};
956
957   # don't include assemblies or obsolete parts
958   my $where = "NOT p.assembly = '1' AND NOT p.obsolete = '1'";
959   my @values;
960
961   foreach my $table_column (qw(p.partnumber p.description pg.partsgroup)) {
962     my $field = (split m{\.}, $table_column)[1];
963     next unless $form->{"${field}_${i}"};
964     $where .= " AND lower(${table_column}) LIKE lower(?)";
965     push @values, '%' . $form->{"${field}_${i}"} . '%';
966   }
967
968   if ($form->{"description_$i"}) {
969     $where .= " ORDER BY p.description";
970   } else {
971     $where .= " ORDER BY p.partnumber";
972   }
973
974   my $transdate = "";
975   if ($form->{type} eq "invoice") {
976     $transdate = $form->{invdate} ? $dbh->quote($form->{invdate}) : "current_date";
977   } else {
978     $transdate = $form->{transdate} ? $dbh->quote($form->{transdate}) : "current_date";
979   }
980
981   my $taxzone_id = $form->{taxzone_id} * 1;
982   $taxzone_id    = 0 if ((3 < $taxzone_id) || (0 > $taxzone_id));
983
984   my $query =
985     qq|SELECT
986          p.id, p.partnumber, p.description, p.lastcost AS sellprice, p.listprice,
987          p.unit, p.assembly, p.bin, p.onhand, p.formel,
988          p.notes AS partnotes, p.notes AS longdescription, p.not_discountable,
989          p.inventory_accno_id, p.price_factor_id,
990
991          pfac.factor AS price_factor,
992
993          c1.accno                         AS inventory_accno,
994          c1.new_chart_id                  AS inventory_new_chart,
995          date($transdate) - c1.valid_from AS inventory_valid,
996
997          c2.accno                         AS income_accno,
998          c2.new_chart_id                  AS income_new_chart,
999          date($transdate) - c2.valid_from AS income_valid,
1000
1001          c3.accno                         AS expense_accno,
1002          c3.new_chart_id                  AS expense_new_chart,
1003          date($transdate) - c3.valid_from AS expense_valid,
1004
1005          pg.partsgroup
1006
1007        FROM parts p
1008        LEFT JOIN chart c1 ON
1009          ((SELECT inventory_accno_id
1010            FROM buchungsgruppen
1011            WHERE id = p.buchungsgruppen_id) = c1.id)
1012        LEFT JOIN chart c2 ON
1013          ((SELECT income_accno_id_${taxzone_id}
1014            FROM buchungsgruppen
1015            WHERE id = p.buchungsgruppen_id) = c2.id)
1016        LEFT JOIN chart c3 ON
1017          ((SELECT expense_accno_id_${taxzone_id}
1018            FROM buchungsgruppen
1019            WHERE id = p.buchungsgruppen_id) = c3.id)
1020        LEFT JOIN partsgroup pg ON (pg.id = p.partsgroup_id)
1021        LEFT JOIN price_factors pfac ON (pfac.id = p.price_factor_id)
1022        WHERE $where|;
1023   my $sth = prepare_execute_query($form, $dbh, $query, @values);
1024
1025   $form->{item_list} = [];
1026   while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
1027
1028     # In der Buchungsgruppe ist immer ein Bestandskonto verknuepft, auch wenn
1029     # es sich um eine Dienstleistung handelt. Bei Dienstleistungen muss das
1030     # Buchungskonto also aus dem Ergebnis rausgenommen werden.
1031     if (!$ref->{inventory_accno_id}) {
1032       map({ delete($ref->{"inventory_${_}"}); } qw(accno new_chart valid));
1033     }
1034     delete($ref->{inventory_accno_id});
1035
1036     # get tax rates and description
1037     $accno_id = ($form->{vc} eq "customer") ? $ref->{income_accno} : $ref->{expense_accno};
1038     $query =
1039       qq|SELECT c.accno, t.taxdescription, t.rate, t.taxnumber
1040          FROM tax t
1041          LEFT JOIN chart c on (c.id = t.chart_id)
1042          WHERE t.id IN
1043            (SELECT tk.tax_id
1044             FROM taxkeys tk
1045             WHERE tk.chart_id =
1046               (SELECT id
1047                FROM chart
1048                WHERE accno = ?)
1049               AND (startdate <= $transdate)
1050             ORDER BY startdate DESC
1051             LIMIT 1)
1052          ORDER BY c.accno|;
1053     my $stw = prepare_execute_query($form, $dbh, $query, $accno_id);
1054
1055     $ref->{taxaccounts} = "";
1056     my $i = 0;
1057     while ($ptr = $stw->fetchrow_hashref(NAME_lc)) {
1058
1059       #    if ($customertax{$ref->{accno}}) {
1060       if (($ptr->{accno} eq "") && ($ptr->{rate} == 0)) {
1061         $i++;
1062         $ptr->{accno} = $i;
1063       }
1064
1065       $ref->{taxaccounts} .= "$ptr->{accno} ";
1066
1067       if (!($form->{taxaccounts} =~ /\Q$ptr->{accno}\E/)) {
1068         $form->{"$ptr->{accno}_rate"}         = $ptr->{rate};
1069         $form->{"$ptr->{accno}_description"}  = $ptr->{taxdescription};
1070         $form->{"$ptr->{accno}_taxnumber"}    = $ptr->{taxnumber};
1071         $form->{taxaccounts}                 .= "$ptr->{accno} ";
1072       }
1073
1074     }
1075
1076     $stw->finish();
1077     chop $ref->{taxaccounts};
1078
1079     $ref->{onhand} *= 1;
1080
1081     push @{ $form->{item_list} }, $ref;
1082
1083   }
1084
1085   $sth->finish();
1086   $dbh->disconnect();
1087
1088   $main::lxdebug->leave_sub();
1089 }
1090
1091 sub vendor_details {
1092   $main::lxdebug->enter_sub();
1093
1094   my ($self, $myconfig, $form, @wanted_vars) = @_;
1095
1096   # connect to database
1097   my $dbh = $form->dbconnect($myconfig);
1098
1099   my @values;
1100
1101   # get contact id, set it if nessessary
1102   $form->{cp_id} *= 1;
1103   my $contact = "";
1104   if ($form->{cp_id}) {
1105     $contact = "AND cp.cp_id = ?";
1106     push @values, $form->{cp_id};
1107   }
1108
1109   # get rest for the vendor
1110   # fax and phone and email as vendor*
1111   my $query =
1112     qq|SELECT ct.*, cp.*, ct.notes as vendornotes, phone as vendorphone, fax as vendorfax, email as vendoremail
1113        FROM vendor ct
1114        LEFT JOIN contacts cp ON (ct.id = cp.cp_cv_id)
1115        WHERE (ct.id = ?) $contact
1116        ORDER BY cp.cp_id
1117        LIMIT 1|;
1118   my $ref = selectfirst_hashref_query($form, $dbh, $query, $form->{vendor_id}, @values);
1119
1120   # remove id and taxincluded before copy back
1121   delete @$ref{qw(id taxincluded)};
1122
1123   @wanted_vars = grep({ $_ } @wanted_vars);
1124   if (scalar(@wanted_vars) > 0) {
1125     my %h_wanted_vars;
1126     map({ $h_wanted_vars{$_} = 1; } @wanted_vars);
1127     map({ delete($ref->{$_}) unless ($h_wanted_vars{$_}); } keys(%{$ref}));
1128   }
1129
1130   map { $form->{$_} = $ref->{$_} } keys %$ref;
1131
1132   my $custom_variables = CVar->get_custom_variables('dbh'      => $dbh,
1133                                                     'module'   => 'CT',
1134                                                     'trans_id' => $form->{vendor_id});
1135   map { $form->{"vc_cvar_$_->{name}"} = $_->{value} } @{ $custom_variables };
1136
1137   $dbh->disconnect();
1138
1139   $main::lxdebug->leave_sub();
1140 }
1141
1142 sub item_links {
1143   $main::lxdebug->enter_sub();
1144
1145   my ($self, $myconfig, $form) = @_;
1146
1147   # connect to database
1148   my $dbh = $form->dbconnect($myconfig);
1149
1150   my $query =
1151     qq|SELECT accno, description, link
1152        FROM chart
1153        WHERE link LIKE '%IC%'
1154        ORDER BY accno|;
1155   my $sth = prepare_execute_query($query, $dbh, $query);
1156
1157   while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
1158     foreach my $key (split(/:/, $ref->{link})) {
1159       if ($key =~ /IC/) {
1160         push @{ $form->{IC_links}{$key} },
1161           { accno       => $ref->{accno},
1162             description => $ref->{description} };
1163       }
1164     }
1165   }
1166
1167   $sth->finish();
1168   $dbh->disconnect();
1169
1170   $main::lxdebug->leave_sub();
1171 }
1172
1173 sub _delete_payments {
1174   $main::lxdebug->enter_sub();
1175
1176   my ($self, $form, $dbh) = @_;
1177
1178   my @delete_oids;
1179
1180   # Delete old payment entries from acc_trans.
1181   my $query =
1182     qq|SELECT oid
1183        FROM acc_trans
1184        WHERE (trans_id = ?) AND fx_transaction
1185
1186        UNION
1187
1188        SELECT at.oid
1189        FROM acc_trans at
1190        LEFT JOIN chart c ON (at.chart_id = c.id)
1191        WHERE (trans_id = ?) AND (c.link LIKE '%AP_paid%')|;
1192   push @delete_oids, selectall_array_query($form, $dbh, $query, conv_i($form->{id}), conv_i($form->{id}));
1193
1194   $query =
1195     qq|SELECT at.oid
1196        FROM acc_trans at
1197        LEFT JOIN chart c ON (at.chart_id = c.id)
1198        WHERE (trans_id = ?)
1199          AND ((c.link = 'AP') OR (c.link LIKE '%:AP') OR (c.link LIKE 'AP:%'))
1200        ORDER BY at.oid
1201        OFFSET 1|;
1202   push @delete_oids, selectall_array_query($form, $dbh, $query, conv_i($form->{id}));
1203
1204   if (@delete_oids) {
1205     $query = qq|DELETE FROM acc_trans WHERE oid IN (| . join(", ", @delete_oids) . qq|)|;
1206     do_query($form, $dbh, $query);
1207   }
1208
1209   $main::lxdebug->leave_sub();
1210 }
1211
1212 sub post_payment {
1213   $main::lxdebug->enter_sub();
1214
1215   my ($self, $myconfig, $form, $locale) = @_;
1216
1217   # connect to database, turn off autocommit
1218   my $dbh = $form->dbconnect_noauto($myconfig);
1219
1220   my (%payments, $old_form, $row, $item, $query, %keep_vars);
1221
1222   $old_form = save_form();
1223
1224   # Delete all entries in acc_trans from prior payments.
1225   $self->_delete_payments($form, $dbh);
1226
1227   # Save the new payments the user made before cleaning up $form.
1228   map { $payments{$_} = $form->{$_} } grep m/^datepaid_\d+$|^memo_\d+$|^source_\d+$|^exchangerate_\d+$|^paid_\d+$|^AP_paid_\d+$|^paidaccounts$/, keys %{ $form };
1229
1230   # Clean up $form so that old content won't tamper the results.
1231   %keep_vars = map { $_, 1 } qw(login password id);
1232   map { delete $form->{$_} unless $keep_vars{$_} } keys %{ $form };
1233
1234   # Retrieve the invoice from the database.
1235   $self->retrieve_invoice($myconfig, $form);
1236
1237   # Set up the content of $form in the way that IR::post_invoice() expects.
1238   $form->{exchangerate} = $form->format_amount($myconfig, $form->{exchangerate});
1239
1240   for $row (1 .. scalar @{ $form->{invoice_details} }) {
1241     $item = $form->{invoice_details}->[$row - 1];
1242
1243     map { $item->{$_} = $form->format_amount($myconfig, $item->{$_}) } qw(qty sellprice);
1244
1245     map { $form->{"${_}_${row}"} = $item->{$_} } keys %{ $item };
1246   }
1247
1248   $form->{rowcount} = scalar @{ $form->{invoice_details} };
1249
1250   delete @{$form}{qw(invoice_details paidaccounts storno paid)};
1251
1252   # Restore the payment options from the user input.
1253   map { $form->{$_} = $payments{$_} } keys %payments;
1254
1255   # Get the AP accno (which is normally done by Form::create_links()).
1256   $query =
1257     qq|SELECT c.accno
1258        FROM acc_trans at
1259        LEFT JOIN chart c ON (at.chart_id = c.id)
1260        WHERE (trans_id = ?)
1261          AND ((c.link = 'AP') OR (c.link LIKE '%:AP') OR (c.link LIKE 'AP:%'))
1262        ORDER BY at.oid
1263        LIMIT 1|;
1264
1265   ($form->{AP}) = selectfirst_array_query($form, $dbh, $query, conv_i($form->{id}));
1266
1267   # Post the new payments.
1268   $self->post_invoice($myconfig, $form, $dbh, 1);
1269
1270   restore_form($old_form);
1271
1272   my $rc = $dbh->commit();
1273   $dbh->disconnect();
1274
1275   $main::lxdebug->leave_sub();
1276
1277   return $rc;
1278 }
1279
1280 sub get_duedate {
1281   $main::lxdebug->enter_sub();
1282
1283   my $self     = shift;
1284   my %params   = @_;
1285
1286   if (!$params{vendor_id} || !$params{invdate}) {
1287     $main::lxdebug->leave_sub();
1288     return $params{default};
1289   }
1290
1291   my $myconfig = \%main::myconfig;
1292   my $form     = $main::form;
1293
1294   my $dbh      = $params{dbh} || $form->get_standard_dbh($myconfig);
1295
1296   my $query    = qq|SELECT ?::date + pt.terms_netto
1297                     FROM vendor v
1298                     LEFT JOIN payment_terms pt ON (pt.id = v.payment_id)
1299                     WHERE v.id = ?|;
1300
1301   my ($sth, $duedate);
1302
1303   if (($sth = $dbh->prepare($query)) && $sth->execute($params{invdate}, conv_i($params{vendor_id}))) {
1304     ($duedate) = $sth->fetchrow_array();
1305     $sth->finish();
1306   } else {
1307     $dbh->rollback();
1308   }
1309
1310   $duedate ||= $params{default};
1311
1312   $main::lxdebug->leave_sub();
1313
1314   return $duedate;
1315 }
1316
1317
1318 1;