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