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