6c5c5019bd5c9844cd156f54834790b1ebe6cf3e
[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::CVar;
41 use SL::DATEV qw(:CONSTANTS);
42 use SL::DBUtils;
43 use SL::DO;
44 use SL::GenericTranslations;
45 use SL::HTML::Restrict;
46 use SL::IO;
47 use SL::MoreCommon;
48 use SL::DB::Default;
49 use SL::DB::TaxZone;
50 use List::Util qw(min);
51
52 use strict;
53
54 sub post_invoice {
55   $main::lxdebug->enter_sub();
56
57   my ($self, $myconfig, $form, $provided_dbh, $payments_only) = @_;
58
59   # connect to database, turn off autocommit
60   my $dbh = $provided_dbh ? $provided_dbh : $form->dbconnect_noauto($myconfig);
61   my $restricter = SL::HTML::Restrict->create;
62
63   $form->{defaultcurrency} = $form->get_default_currency($myconfig);
64   my $defaultcurrency = $form->{defaultcurrency};
65
66   my $ic_cvar_configs = CVar->get_configs(module => 'IC',
67                                           dbh    => $dbh);
68
69   my ($query, $sth, @values, $project_id);
70   my ($allocated, $taxrate, $taxamount, $taxdiff, $item);
71   my ($amount, $linetotal, $lastinventoryaccno, $lastexpenseaccno);
72   my ($netamount, $invoicediff, $expensediff) = (0, 0, 0);
73   my $exchangerate = 0;
74   my ($basefactor, $baseqty, @taxaccounts, $totaltax);
75
76   my $all_units = AM->retrieve_units($myconfig, $form);
77
78 #markierung
79   if (!$payments_only) {
80     if ($form->{id}) {
81       &reverse_invoice($dbh, $form);
82     } else {
83       ($form->{id}) = selectrow_query($form, $dbh, qq|SELECT nextval('glid')|);
84       do_query($form, $dbh, qq|INSERT INTO ap (id, invnumber, currency_id, taxzone_id) VALUES (?, '', (SELECT id FROM currencies WHERE name=?), ?)|, $form->{id}, $form->{currency}, $form->{taxzone_id});
85     }
86   }
87
88   if ($form->{currency} eq $defaultcurrency) {
89     $form->{exchangerate} = 1;
90   } else {
91     $exchangerate = $form->check_exchangerate($myconfig, $form->{currency}, $form->{invdate}, 'sell');
92   }
93
94   $form->{exchangerate} = $exchangerate || $form->parse_amount($myconfig, $form->{exchangerate});
95   $form->{exchangerate} = 1 unless ($form->{exchangerate} * 1);
96
97   my %item_units;
98   my $q_item_unit = qq|SELECT unit FROM parts WHERE id = ?|;
99   my $h_item_unit = prepare_query($form, $dbh, $q_item_unit);
100
101   $form->get_lists('price_factors' => 'ALL_PRICE_FACTORS');
102   my %price_factors = map { $_->{id} => $_->{factor} } @{ $form->{ALL_PRICE_FACTORS} };
103   my $price_factor;
104
105   for my $i (1 .. $form->{rowcount}) {
106     next unless $form->{"id_$i"};
107
108     $form->{"qty_$i"}  = $form->parse_amount($myconfig, $form->{"qty_$i"});
109     $form->{"qty_$i"} *= -1 if $form->{storno};
110
111     if ( $::instance_conf->get_inventory_system eq 'periodic') {
112       # inventory account number is overwritten with expense account number, so
113       # never book incoming to inventory account but always to expense account
114       $form->{"inventory_accno_$i"} = $form->{"expense_accno_$i"}
115     };
116
117     # get item baseunit
118     if (!$item_units{$form->{"id_$i"}}) {
119       do_statement($form, $h_item_unit, $q_item_unit, $form->{"id_$i"});
120       ($item_units{$form->{"id_$i"}}) = $h_item_unit->fetchrow_array();
121     }
122
123     my $item_unit = $item_units{$form->{"id_$i"}};
124
125     if (defined($all_units->{$item_unit}->{factor})
126             && ($all_units->{$item_unit}->{factor} ne '')
127             && ($all_units->{$item_unit}->{factor} * 1 != 0)) {
128       $basefactor = $all_units->{$form->{"unit_$i"}}->{factor} / $all_units->{$item_unit}->{factor};
129     } else {
130       $basefactor = 1;
131     }
132     $baseqty = $form->{"qty_$i"} * $basefactor;
133
134     @taxaccounts = split / /, $form->{"taxaccounts_$i"};
135     $taxdiff     = 0;
136     $allocated   = 0;
137     $taxrate     = 0;
138
139     $form->{"sellprice_$i"} = $form->parse_amount($myconfig, $form->{"sellprice_$i"});
140     (my $fxsellprice = $form->{"sellprice_$i"}) =~ /\.(\d+)/;
141     my $dec = length $1;
142     my $decimalplaces = ($dec > 2) ? $dec : 2;
143
144     map { $taxrate += $form->{"${_}_rate"} } @taxaccounts;
145
146     $price_factor = $price_factors{ $form->{"price_factor_id_$i"} } || 1;
147     #####################################################################
148     # das ist aus IS.pm kopiert. schlimm. jb 7.10.2009
149     # ich würde mir wünschen, dass diese vier stellen zusammengefasst werden
150     # ... vier stellen = (einkauf + verkauf) * (maske + backend)
151     # ansonsten stolpert man immer wieder viermal statt einmal heftig
152     # und auch das undo discount formatting ist nicht besonders wartungsfreundlich
153
154     # keine ahnung wofür das in IS.pm gemacht wird:
155     #      my ($dec) = ($fxsellprice =~ /\.(\d+)/);
156     #  $dec = length $dec;
157     #  my $decimalplaces = ($dec > 2) ? $dec : 2;
158
159     # undo discount formatting
160     $form->{"discount_$i"} = $form->parse_amount($myconfig, $form->{"discount_$i"}) / 100;
161     # deduct discount
162     $form->{"sellprice_$i"} = $fxsellprice * (1 - $form->{"discount_$i"});
163
164     ######################################################################
165     if ($form->{"inventory_accno_$i"}) {
166
167       $linetotal = $form->round_amount($form->{"sellprice_$i"} * $form->{"qty_$i"} / $price_factor, 2);
168
169       if ($form->{taxincluded}) {
170
171         $taxamount              = $linetotal * ($taxrate / (1 + $taxrate));
172         $form->{"sellprice_$i"} = $form->{"sellprice_$i"} * (1 / (1 + $taxrate));
173
174       } else {
175         $taxamount = $linetotal * $taxrate;
176       }
177
178       $netamount += $linetotal;
179
180       if ($form->round_amount($taxrate, 7) == 0) {
181         if ($form->{taxincluded}) {
182           foreach $item (@taxaccounts) {
183             $taxamount =
184               $form->round_amount($linetotal * $form->{"${item}_rate"} / (1 + abs($form->{"${item}_rate"})), 2);
185             $taxdiff                              += $taxamount;
186             $form->{amount}{ $form->{id} }{$item} -= $taxamount;
187           }
188           $form->{amount}{ $form->{id} }{ $taxaccounts[0] } += $taxdiff;
189
190         } else {
191           map { $form->{amount}{ $form->{id} }{$_} -= $linetotal * $form->{"${_}_rate"} } @taxaccounts;
192         }
193
194       } else {
195         map { $form->{amount}{ $form->{id} }{$_} -= $taxamount * $form->{"${_}_rate"} / $taxrate } @taxaccounts;
196       }
197
198       # add purchase to inventory, this one is without the tax!
199       $amount    = $form->{"sellprice_$i"} * $form->{"qty_$i"} * $form->{exchangerate} / $price_factor;
200       $linetotal = $form->round_amount($form->{"sellprice_$i"} * $form->{"qty_$i"} / $price_factor, 2) * $form->{exchangerate};
201       $linetotal = $form->round_amount($linetotal, 2);
202
203       # this is the difference for the inventory
204       $invoicediff += ($amount - $linetotal);
205
206       $form->{amount}{ $form->{id} }{ $form->{"inventory_accno_$i"} } -= $linetotal;
207
208       # adjust and round sellprice
209       $form->{"sellprice_$i"} = $form->round_amount($form->{"sellprice_$i"} * $form->{exchangerate}, $decimalplaces);
210
211       $lastinventoryaccno = $form->{"inventory_accno_$i"};
212
213       next if $payments_only;
214
215       # update parts table by setting lastcost to current price, don't allow negative values by using abs
216       $query = qq|UPDATE parts SET lastcost = ? WHERE id = ?|;
217       @values = (abs($fxsellprice * $form->{exchangerate} / $basefactor), conv_i($form->{"id_$i"}));
218       do_query($form, $dbh, $query, @values);
219
220       # check if we sold the item already and
221       # make an entry for the expense and inventory
222       my $taxzone = $form->{taxzone_id} * 1;
223       $query =
224         qq|SELECT i.id, i.qty, i.allocated, i.trans_id, i.base_qty,
225              bg.inventory_accno_id, tc.expense_accno_id AS expense_accno_id, a.transdate
226            FROM invoice i, ar a, parts p, buchungsgruppen bg, taxzone_charts tc
227            WHERE (i.parts_id = p.id)
228              AND (i.parts_id = ?)
229              AND ((i.base_qty + i.allocated) > 0)
230              AND (i.trans_id = a.id)
231              AND (p.buchungsgruppen_id = bg.id)
232              AND (tc.buchungsgruppen_id = p.buchungsgruppen_id)
233              AND (tc.taxzone_id = ${taxzone})
234            ORDER BY transdate|;
235            # ORDER BY transdate guarantees FIFO
236
237 # sold two items without having bought them yet, example result of query:
238 # id | qty | allocated | trans_id | inventory_accno_id | expense_accno_id | transdate
239 # ---+-----+-----------+----------+--------------------+------------------+------------
240 #  9 |   2 |         0 |        9 |                 15 |              151 | 2011-01-05
241
242 # base_qty + allocated > 0 if article has already been sold but not bought yet
243
244 # select qty,allocated,base_qty,sellprice from invoice where trans_id = 9;
245 #  qty | allocated | base_qty | sellprice
246 # -----+-----------+----------+------------
247 #    2 |         0 |        2 | 1000.00000
248
249       $sth = prepare_execute_query($form, $dbh, $query, conv_i($form->{"id_$i"}));
250
251       my $totalqty = $baseqty;
252
253       while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
254         my $qty    = min $totalqty, ($ref->{base_qty} + $ref->{allocated});
255         $linetotal = $form->round_amount(($form->{"sellprice_$i"} * $qty) / $basefactor, 2);
256
257         if  ( $::instance_conf->get_inventory_system eq 'perpetual' ) {
258         # Warenbestandsbuchungen nur bei Bestandsmethode
259
260           if ($ref->{allocated} < 0) {
261
262 # we have an entry for it already, adjust amount
263             $form->update_balance($dbh, "acc_trans", "amount",
264                 qq|    (trans_id = $ref->{trans_id})
265                 AND (chart_id = $ref->{inventory_accno_id})
266                 AND (transdate = '$ref->{transdate}')|,
267                 $linetotal);
268
269             $form->update_balance($dbh, "acc_trans", "amount",
270                 qq|    (trans_id = $ref->{trans_id})
271                 AND (chart_id = $ref->{expense_accno_id})
272                 AND (transdate = '$ref->{transdate}')|,
273                 $linetotal * -1);
274
275           } elsif ($linetotal != 0) {
276
277             # allocated >= 0
278             # add entry for inventory, this one is for the sold item
279             $query = qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate, taxkey, tax_id, chart_link) VALUES (?, ?, ?, ?,
280                                (SELECT taxkey_id
281                                 FROM taxkeys
282                                 WHERE chart_id= ?
283                                 AND startdate <= ?
284                                 ORDER BY startdate DESC LIMIT 1),
285                                (SELECT tax_id
286                                 FROM taxkeys
287                                 WHERE chart_id= ?
288                                 AND startdate <= ?
289                                 ORDER BY startdate DESC LIMIT 1),
290                                (SELECT link FROM chart WHERE id = ?))|;
291             @values = ($ref->{trans_id},  $ref->{inventory_accno_id}, $linetotal, $ref->{transdate}, $ref->{inventory_accno_id}, $ref->{transdate}, $ref->{inventory_accno_id}, $ref->{transdate},
292                        $ref->{inventory_accno_id});
293             do_query($form, $dbh, $query, @values);
294
295 # add expense
296             $query = qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate, taxkey, tax_id, chart_link) VALUES (?, ?, ?, ?,
297                                 (SELECT taxkey_id
298                                  FROM taxkeys
299                                  WHERE chart_id= ?
300                                  AND startdate <= ?
301                                  ORDER BY startdate DESC LIMIT 1),
302                                 (SELECT tax_id
303                                  FROM taxkeys
304                                  WHERE chart_id= ?
305                                  AND startdate <= ?
306                                  ORDER BY startdate DESC LIMIT 1),
307                                 (SELECT link FROM chart WHERE id = ?))|;
308             @values = ($ref->{trans_id},  $ref->{expense_accno_id}, ($linetotal * -1), $ref->{transdate}, $ref->{expense_accno_id}, $ref->{transdate}, $ref->{expense_accno_id}, $ref->{transdate},
309                        $ref->{expense_accno_id});
310             do_query($form, $dbh, $query, @values);
311           }
312         };
313
314         # update allocated for sold item
315         $form->update_balance($dbh, "invoice", "allocated", qq|id = $ref->{id}|, $qty * -1);
316
317         $allocated += $qty;
318
319         last if ($totalqty -= $qty) <= 0;
320       }
321
322       $sth->finish();
323
324     } else {                    # if ($form->{"inventory_accno_id_$i"})
325       # part doesn't have an inventory_accno_id
326       # lastcost of the part is updated at the end
327
328       $linetotal = $form->round_amount($form->{"sellprice_$i"} * $form->{"qty_$i"} / $price_factor, 2);
329
330       if ($form->{taxincluded}) {
331         $taxamount              = $linetotal * ($taxrate / (1 + $taxrate));
332         $form->{"sellprice_$i"} = $form->{"sellprice_$i"} * (1 / (1 + $taxrate));
333
334       } else {
335         $taxamount = $linetotal * $taxrate;
336       }
337
338       $netamount += $linetotal;
339
340       if ($form->round_amount($taxrate, 7) == 0) {
341         if ($form->{taxincluded}) {
342           foreach $item (@taxaccounts) {
343             $taxamount = $linetotal * $form->{"${item}_rate"} / (1 + abs($form->{"${item}_rate"}));
344             $totaltax += $taxamount;
345             $form->{amount}{ $form->{id} }{$item} -= $taxamount;
346           }
347         } else {
348           map { $form->{amount}{ $form->{id} }{$_} -= $linetotal * $form->{"${_}_rate"} } @taxaccounts;
349         }
350       } else {
351         map { $form->{amount}{ $form->{id} }{$_} -= $taxamount * $form->{"${_}_rate"} / $taxrate } @taxaccounts;
352       }
353
354       $amount    = $form->{"sellprice_$i"} * $form->{"qty_$i"} * $form->{exchangerate} / $price_factor;
355       $linetotal = $form->round_amount($form->{"sellprice_$i"} * $form->{"qty_$i"} / $price_factor, 2) * $form->{exchangerate};
356       $linetotal = $form->round_amount($linetotal, 2);
357
358       # this is the difference for expense
359       $expensediff += ($amount - $linetotal);
360
361       # add amount to expense
362       $form->{amount}{ $form->{id} }{ $form->{"expense_accno_$i"} } -= $linetotal;
363
364       $lastexpenseaccno = $form->{"expense_accno_$i"};
365
366       # adjust and round sellprice
367       $form->{"sellprice_$i"} = $form->round_amount($form->{"sellprice_$i"} * $form->{exchangerate}, $decimalplaces);
368
369       next if $payments_only;
370
371       # update lastcost
372       $query = qq|UPDATE parts SET lastcost = ? WHERE id = ?|;
373       do_query($form, $dbh, $query, $form->{"sellprice_$i"} / $basefactor, conv_i($form->{"id_$i"}));
374     }
375
376     next if $payments_only;
377
378     # save detail record in invoice table
379     my ($invoice_id) = selectfirst_array_query($form, $dbh, qq|SELECT nextval('invoiceid')|);
380
381     $query =
382       qq|INSERT INTO invoice (id, trans_id, parts_id, description, longdescription, qty, base_qty,
383                               sellprice, fxsellprice, discount, allocated, unit, deliverydate,
384                               project_id, serialnumber, price_factor_id, price_factor, marge_price_factor)
385          VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, (SELECT factor FROM price_factors WHERE id = ?), ?, ?)|;
386     @values = ($invoice_id, conv_i($form->{id}), conv_i($form->{"id_$i"}),
387                $form->{"description_$i"}, $restricter->process($form->{"longdescription_$i"}), $form->{"qty_$i"} * -1,
388                $baseqty * -1, $form->{"sellprice_$i"}, $fxsellprice, $form->{"discount_$i"}, $allocated,
389                $form->{"unit_$i"}, conv_date($form->{deliverydate}),
390                conv_i($form->{"project_id_$i"}), $form->{"serialnumber_$i"},
391                conv_i($form->{"price_factor_id_$i"}), conv_i($form->{"price_factor_id_$i"}), conv_i($form->{"marge_price_factor_$i"}),
392                conv_i($form->{"active_price_source_$i"}),
393                );
394     do_query($form, $dbh, $query, @values);
395
396     CVar->save_custom_variables(module       => 'IC',
397                                 sub_module   => 'invoice',
398                                 trans_id     => $invoice_id,
399                                 configs      => $ic_cvar_configs,
400                                 variables    => $form,
401                                 name_prefix  => 'ic_',
402                                 name_postfix => "_$i",
403                                 dbh          => $dbh);
404   }
405
406   $h_item_unit->finish();
407
408   $project_id = conv_i($form->{"globalproject_id"});
409
410   $form->{datepaid} = $form->{invdate};
411
412   # all amounts are in natural state, netamount includes the taxes
413   # if tax is included, netamount is rounded to 2 decimal places,
414   # taxes are not
415
416   # total payments
417   for my $i (1 .. $form->{paidaccounts}) {
418     $form->{"paid_$i"}  = $form->parse_amount($myconfig, $form->{"paid_$i"});
419     $form->{paid}      += $form->{"paid_$i"};
420     $form->{datepaid}   = $form->{"datepaid_$i"} if $form->{"datepaid_$i"};
421   }
422
423   my ($tax, $paiddiff) = (0, 0);
424
425   $netamount = $form->round_amount($netamount, 2);
426
427   # figure out rounding errors for amount paid and total amount
428   if ($form->{taxincluded}) {
429
430     $amount    = $form->round_amount($netamount * $form->{exchangerate}, 2);
431     $paiddiff  = $amount - $netamount * $form->{exchangerate};
432     $netamount = $amount;
433
434     foreach $item (split / /, $form->{taxaccounts}) {
435       $amount                               = $form->{amount}{ $form->{id} }{$item} * $form->{exchangerate};
436       $form->{amount}{ $form->{id} }{$item} = $form->round_amount($amount, 2);
437
438       $amount     = $form->{amount}{ $form->{id} }{$item} * -1;
439       $tax       += $amount;
440       $netamount -= $amount;
441     }
442
443     $invoicediff += $paiddiff;
444     $expensediff += $paiddiff;
445
446 ######## this only applies to tax included
447
448     # in the sales invoice case rounding errors only have to be corrected for
449     # income accounts, it is enough to add the total rounding error to one of
450     # the income accounts, with the one assigned to the last row being used
451     # (lastinventoryaccno)
452
453     # in the purchase invoice case rounding errors may be split between
454     # inventory accounts and expense accounts. After rounding, an error of 1
455     # cent is introduced if the total rounding error exceeds 0.005. The total
456     # error is made up of $invoicediff and $expensediff, however, so if both
457     # values are below 0.005, but add up to a total >= 0.005, correcting
458     # lastinventoryaccno and lastexpenseaccno separately has no effect after
459     # rounding. This caused bug 1579. Therefore when the combined total exceeds
460     # 0.005, but neither do individually, the account with the larger value
461     # shall receive the total rounding error, and the next time it is rounded
462     # the 1 cent correction will be introduced.
463
464     $form->{amount}{ $form->{id} }{$lastinventoryaccno} -= $invoicediff if $lastinventoryaccno;
465     $form->{amount}{ $form->{id} }{$lastexpenseaccno}   -= $expensediff if $lastexpenseaccno;
466
467     if ( (abs($expensediff)+abs($invoicediff)) >= 0.005 and abs($expensediff) < 0.005 and abs($invoicediff) < 0.005 ) {
468
469       # in total the rounding error adds up to 1 cent effectively, correct the
470       # larger of the two numbers
471
472       if ( abs($form->{amount}{ $form->{id} }{$lastinventoryaccno}) > abs($form->{amount}{ $form->{id} }{$lastexpenseaccno}) ) {
473         # $invoicediff has already been deducted, now also deduct expensediff
474         $form->{amount}{ $form->{id} }{$lastinventoryaccno}   -= $expensediff;
475       } else {
476         # expensediff has already been deducted, now also deduct invoicediff
477         $form->{amount}{ $form->{id} }{$lastexpenseaccno}   -= $invoicediff;
478       };
479     };
480
481   } else {
482     $amount    = $form->round_amount($netamount * $form->{exchangerate}, 2);
483     $paiddiff  = $amount - $netamount * $form->{exchangerate};
484     $netamount = $amount;
485
486     foreach my $item (split / /, $form->{taxaccounts}) {
487       $form->{amount}{ $form->{id} }{$item}  = $form->round_amount($form->{amount}{ $form->{id} }{$item}, 2);
488       $amount                                = $form->round_amount( $form->{amount}{ $form->{id} }{$item} * $form->{exchangerate} * -1, 2);
489       $paiddiff                             += $amount - $form->{amount}{ $form->{id} }{$item} * $form->{exchangerate} * -1;
490       $form->{amount}{ $form->{id} }{$item}  = $form->round_amount($amount * -1, 2);
491       $amount                                = $form->{amount}{ $form->{id} }{$item} * -1;
492       $tax                                  += $amount;
493     }
494   }
495
496   $form->{amount}{ $form->{id} }{ $form->{AP} } = $netamount + $tax;
497
498
499   $form->{paid} = $form->round_amount($form->{paid} * $form->{exchangerate} + $paiddiff, 2) if $form->{paid} != 0;
500
501 # update exchangerate
502
503   $form->update_exchangerate($dbh, $form->{currency}, $form->{invdate}, 0, $form->{exchangerate})
504     if ($form->{currency} ne $defaultcurrency) && !$exchangerate;
505
506 # record acc_trans transactions
507   foreach my $trans_id (keys %{ $form->{amount} }) {
508     foreach my $accno (keys %{ $form->{amount}{$trans_id} }) {
509       $form->{amount}{$trans_id}{$accno} = $form->round_amount($form->{amount}{$trans_id}{$accno}, 2);
510
511
512       next if $payments_only || !$form->{amount}{$trans_id}{$accno};
513
514       $query = qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate, taxkey, project_id, tax_id, chart_link)
515                   VALUES (?, (SELECT id FROM chart WHERE accno = ?), ?, ?,
516                   (SELECT taxkey_id
517                    FROM taxkeys
518                    WHERE chart_id= (SELECT id
519                                     FROM chart
520                                     WHERE accno = ?)
521                    AND startdate <= ?
522                    ORDER BY startdate DESC LIMIT 1),
523                   ?,
524                   (SELECT tax_id
525                    FROM taxkeys
526                    WHERE chart_id= (SELECT id
527                                     FROM chart
528                                     WHERE accno = ?)
529                    AND startdate <= ?
530                    ORDER BY startdate DESC LIMIT 1),
531                   (SELECT link FROM chart WHERE accno = ?))|;
532       @values = ($trans_id, $accno, $form->{amount}{$trans_id}{$accno},
533                  conv_date($form->{invdate}), $accno, conv_date($form->{invdate}), $project_id, $accno, conv_date($form->{invdate}), $accno);
534       do_query($form, $dbh, $query, @values);
535     }
536   }
537
538   # deduct payment differences from paiddiff
539   for my $i (1 .. $form->{paidaccounts}) {
540     if ($form->{"paid_$i"} != 0) {
541       $amount    = $form->round_amount($form->{"paid_$i"} * $form->{exchangerate}, 2);
542       $paiddiff -= $amount - $form->{"paid_$i"} * $form->{exchangerate};
543     }
544   }
545
546   # force AP entry if 0
547
548   $form->{amount}{ $form->{id} }{ $form->{AP} } = $form->{paid} if $form->{amount}{$form->{id}}{$form->{AP}} == 0;
549
550   # record payments and offsetting AP
551   for my $i (1 .. $form->{paidaccounts}) {
552     if ($form->{"acc_trans_id_$i"}
553         && $payments_only
554         && (SL::DB::Default->get->payments_changeable == 0)) {
555       next;
556     }
557
558     next if $form->{"paid_$i"} == 0;
559
560     my ($accno)            = split /--/, $form->{"AP_paid_$i"};
561     $form->{"datepaid_$i"} = $form->{invdate} unless ($form->{"datepaid_$i"});
562     $form->{datepaid}      = $form->{"datepaid_$i"};
563
564     $amount = $form->round_amount($form->{"paid_$i"} * $form->{exchangerate} + $paiddiff, 2) * -1;
565
566     # record AP
567     if ($form->{amount}{ $form->{id} }{ $form->{AP} } != 0) {
568       $query = qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate, taxkey, project_id, tax_id, chart_link)
569                   VALUES (?, (SELECT id FROM chart WHERE accno = ?), ?, ?,
570                           (SELECT taxkey_id
571                            FROM taxkeys
572                            WHERE chart_id= (SELECT id
573                                             FROM chart
574                                             WHERE accno = ?)
575                            AND startdate <= ?
576                            ORDER BY startdate DESC LIMIT 1),
577                           ?,
578                           (SELECT tax_id
579                            FROM taxkeys
580                            WHERE chart_id= (SELECT id
581                                             FROM chart
582                                             WHERE accno = ?)
583                            AND startdate <= ?
584                            ORDER BY startdate DESC LIMIT 1),
585                           (SELECT link FROM chart WHERE accno = ?))|;
586       @values = (conv_i($form->{id}), $form->{AP}, $amount,
587                  $form->{"datepaid_$i"}, $form->{AP}, conv_date($form->{"datepaid_$i"}), $project_id, $form->{AP}, conv_date($form->{"datepaid_$i"}), $form->{AP});
588       do_query($form, $dbh, $query, @values);
589     }
590
591     # record payment
592     my $gldate = (conv_date($form->{"gldate_$i"}))? conv_date($form->{"gldate_$i"}) : conv_date($form->current_date($myconfig));
593
594     $query =
595       qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate, gldate, source, memo, taxkey, project_id, tax_id, chart_link)
596                 VALUES (?, (SELECT id FROM chart WHERE accno = ?), ?, ?, ?, ?, ?,
597                 (SELECT taxkey_id
598                  FROM taxkeys
599                  WHERE chart_id= (SELECT id
600                                   FROM chart WHERE accno = ?)
601                  AND startdate <= ?
602                  ORDER BY startdate DESC LIMIT 1),
603                 ?,
604                 (SELECT tax_id
605                  FROM taxkeys
606                  WHERE chart_id= (SELECT id
607                                   FROM chart WHERE accno = ?)
608                  AND startdate <= ?
609                  ORDER BY startdate DESC LIMIT 1),
610                 (SELECT link FROM chart WHERE accno = ?))|;
611     @values = (conv_i($form->{id}), $accno, $form->{"paid_$i"}, $form->{"datepaid_$i"},
612                $gldate, $form->{"source_$i"}, $form->{"memo_$i"}, $accno, conv_date($form->{"datepaid_$i"}), $project_id, $accno, conv_date($form->{"datepaid_$i"}), $accno);
613     do_query($form, $dbh, $query, @values);
614
615     $exchangerate = 0;
616
617     if ($form->{currency} eq $defaultcurrency) {
618       $form->{"exchangerate_$i"} = 1;
619     } else {
620       $exchangerate              = $form->check_exchangerate($myconfig, $form->{currency}, $form->{"datepaid_$i"}, 'sell');
621       $form->{"exchangerate_$i"} = $exchangerate || $form->parse_amount($myconfig, $form->{"exchangerate_$i"});
622     }
623
624     # exchangerate difference
625     $form->{fx}{$accno}{ $form->{"datepaid_$i"} } += $form->{"paid_$i"} * ($form->{"exchangerate_$i"} - 1) + $paiddiff;
626
627     # gain/loss
628     $amount =
629       ($form->{"paid_$i"} * $form->{exchangerate}) -
630       ($form->{"paid_$i"} * $form->{"exchangerate_$i"});
631     if ($amount > 0) {
632       $form->{fx}{ $form->{fxgain_accno} }{ $form->{"datepaid_$i"} } += $amount;
633     } else {
634       $form->{fx}{ $form->{fxloss_accno} }{ $form->{"datepaid_$i"} } += $amount;
635     }
636
637     $paiddiff = 0;
638
639     # update exchange rate
640     $form->update_exchangerate($dbh, $form->{currency}, $form->{"datepaid_$i"}, 0, $form->{"exchangerate_$i"})
641       if ($form->{currency} ne $defaultcurrency) && !$exchangerate;
642   }
643
644   # record exchange rate differences and gains/losses
645   foreach my $accno (keys %{ $form->{fx} }) {
646     foreach my $transdate (keys %{ $form->{fx}{$accno} }) {
647       $form->{fx}{$accno}{$transdate} = $form->round_amount($form->{fx}{$accno}{$transdate}, 2);
648       next if ($form->{fx}{$accno}{$transdate} == 0);
649
650       $query = qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate, cleared, fx_transaction, taxkey, project_id, tax_id, chart_link)
651                   VALUES (?, (SELECT id FROM chart WHERE accno = ?), ?, ?, '0', '1', 0, ?,
652                   (SELECT id FROM tax WHERE taxkey=0 LIMIT 1),
653                   (SELECT link FROM chart WHERE accno = ?))|;
654       @values = (conv_i($form->{id}), $accno, $form->{fx}{$accno}{$transdate}, conv_date($transdate), $project_id, $accno);
655       do_query($form, $dbh, $query, @values);
656     }
657   }
658
659   IO->set_datepaid(table => 'ap', id => $form->{id}, dbh => $dbh);
660
661   if ($payments_only) {
662     $query = qq|UPDATE ap SET paid = ? WHERE id = ?|;
663     do_query($form, $dbh, $query, $form->{paid}, conv_i($form->{id}));
664
665     if (!$provided_dbh) {
666       $dbh->commit();
667       $dbh->disconnect();
668     }
669
670     $main::lxdebug->leave_sub();
671     return;
672   }
673
674   $amount = $netamount + $tax;
675
676   # set values which could be empty
677   my $taxzone_id         = $form->{taxzone_id} * 1;
678   $taxzone_id = SL::DB::Manager::TaxZone->get_default->id unless SL::DB::Manager::TaxZone->find_by(id => $taxzone_id);
679
680   # Seit neuestem wird die department_id schon übergeben UND $form->department nicht mehr
681   # korrekt zusammengebaut. Sehr wahrscheinlich beim Umstieg auf T8 kaputt gegangen
682   # Ich lass den Code von 2005 erstmal noch stehen ;-) jb 03-2011
683   # copy & paste von IS.pm
684   if (!$form->{department_id}){
685     $form->{department_id} = (split /--/, $form->{department})[1];
686   }
687   $form->{invnumber}     = $form->{id} unless $form->{invnumber};
688
689   # save AP record
690   $query = qq|UPDATE ap SET
691                 invnumber    = ?, ordnumber   = ?, quonumber     = ?, transdate   = ?,
692                 orddate      = ?, quodate     = ?, vendor_id     = ?, amount      = ?,
693                 netamount    = ?, paid        = ?, duedate       = ?,
694                 invoice      = ?, taxzone_id  = ?, notes         = ?, taxincluded = ?,
695                 intnotes     = ?, storno_id   = ?, storno        = ?,
696                 cp_id        = ?, employee_id = ?, department_id = ?, delivery_term_id = ?,
697                 globalproject_id = ?, direct_debit = ?
698               WHERE id = ?|;
699   @values = (
700                 $form->{invnumber},          $form->{ordnumber},           $form->{quonumber},      conv_date($form->{invdate}),
701       conv_date($form->{orddate}), conv_date($form->{quodate}),     conv_i($form->{vendor_id}),               $amount,
702                 $netamount,                  $form->{paid},      conv_date($form->{duedate}),
703             '1',                             $taxzone_id,                  $form->{notes},          $form->{taxincluded} ? 't' : 'f',
704                 $form->{intnotes},           conv_i($form->{storno_id}),     $form->{storno}      ? 't' : 'f',
705          conv_i($form->{cp_id}),      conv_i($form->{employee_id}), conv_i($form->{department_id}), conv_i($form->{delivery_term_id}),
706          conv_i($form->{globalproject_id}),
707                 $form->{direct_debit} ? 't' : 'f',
708          conv_i($form->{id})
709   );
710   do_query($form, $dbh, $query, @values);
711
712   if ($form->{storno}) {
713     $query = qq|UPDATE ap SET paid = paid + amount WHERE id = ?|;
714     do_query($form, $dbh, $query, conv_i($form->{storno_id}));
715
716     $query = qq|UPDATE ap SET storno = 't' WHERE id = ?|;
717     do_query($form, $dbh, $query, conv_i($form->{storno_id}));
718
719     $query = qq!UPDATE ap SET intnotes = ? || intnotes WHERE id = ?!;
720     do_query($form, $dbh, $query, "Rechnung storniert am $form->{invdate} ", conv_i($form->{storno_id}));
721
722     $query = qq|UPDATE ap SET paid = amount WHERE id = ?|;
723     do_query($form, $dbh, $query, conv_i($form->{id}));
724   }
725
726
727   $form->{name} = $form->{vendor};
728   $form->{name} =~ s/--\Q$form->{vendor_id}\E//;
729
730   # add shipto
731   $form->add_shipto($dbh, $form->{id}, "AP");
732
733   # delete zero entries
734   do_query($form, $dbh, qq|DELETE FROM acc_trans WHERE amount = 0|);
735
736   Common::webdav_folder($form);
737
738   # Link this record to the records it was created from.
739   RecordLinks->create_links('dbh'        => $dbh,
740                             'mode'       => 'ids',
741                             'from_table' => 'oe',
742                             'from_ids'   => $form->{convert_from_oe_ids},
743                             'to_table'   => 'ap',
744                             'to_id'      => $form->{id},
745     );
746   delete $form->{convert_from_oe_ids};
747
748   my @convert_from_do_ids = map { $_ * 1 } grep { $_ } split m/\s+/, $form->{convert_from_do_ids};
749   if (scalar @convert_from_do_ids) {
750     DO->close_orders('dbh' => $dbh,
751                      'ids' => \@convert_from_do_ids);
752
753     RecordLinks->create_links('dbh'        => $dbh,
754                               'mode'       => 'ids',
755                               'from_table' => 'delivery_orders',
756                               'from_ids'   => \@convert_from_do_ids,
757                               'to_table'   => 'ap',
758                               'to_id'      => $form->{id},
759       );
760   }
761   delete $form->{convert_from_do_ids};
762
763   ARAP->close_orders_if_billed('dbh'     => $dbh,
764                                'arap_id' => $form->{id},
765                                'table'   => 'ap',);
766
767   # safety check datev export
768   if ($::instance_conf->get_datev_check_on_purchase_invoice) {
769     my $transdate = $::form->{invdate} ? DateTime->from_lxoffice($::form->{invdate}) : undef;
770     $transdate  ||= DateTime->today;
771
772     my $datev = SL::DATEV->new(
773       exporttype => DATEV_ET_BUCHUNGEN,
774       format     => DATEV_FORMAT_KNE,
775       dbh        => $dbh,
776       from       => $transdate,
777       to         => $transdate,
778       trans_id   => $form->{id},
779     );
780
781     $datev->export;
782
783     if ($datev->errors) {
784       $dbh->rollback;
785       die join "\n", $::locale->text('DATEV check returned errors:'), $datev->errors;
786     }
787   }
788
789   my $rc = 1;
790   if (!$provided_dbh) {
791     $rc = $dbh->commit();
792     $dbh->disconnect();
793   }
794
795   $main::lxdebug->leave_sub();
796
797   return $rc;
798 }
799
800 sub reverse_invoice {
801   $main::lxdebug->enter_sub();
802
803   my ($dbh, $form) = @_;
804
805   # reverse inventory items
806   my $query =
807     qq|SELECT i.parts_id, p.inventory_accno_id, p.expense_accno_id, i.qty, i.allocated, i.sellprice
808        FROM invoice i, parts p
809        WHERE (i.parts_id = p.id)
810          AND (i.trans_id = ?)|;
811   my $sth = prepare_execute_query($form, $dbh, $query, conv_i($form->{id}));
812
813   my $netamount = 0;
814
815   while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
816     $netamount += $form->round_amount($ref->{sellprice} * $ref->{qty} * -1, 2);
817
818     next unless $ref->{inventory_accno_id};
819
820     # if $ref->{allocated} > 0 than we sold that many items
821     next if ($ref->{allocated} <= 0);
822
823     # get references for sold items
824     $query =
825       qq|SELECT i.id, i.trans_id, i.allocated, a.transdate
826          FROM invoice i, ar a
827          WHERE (i.parts_id = ?)
828            AND (i.allocated < 0)
829            AND (i.trans_id = a.id)
830          ORDER BY transdate DESC|;
831       my $sth2 = prepare_execute_query($form, $dbh, $query, $ref->{parts_id});
832
833       while (my $pthref = $sth2->fetchrow_hashref("NAME_lc")) {
834         my $qty = $ref->{allocated};
835         if (($ref->{allocated} + $pthref->{allocated}) > 0) {
836           $qty = $pthref->{allocated} * -1;
837         }
838
839         my $amount = $form->round_amount($ref->{sellprice} * $qty, 2);
840
841         #adjust allocated
842         $form->update_balance($dbh, "invoice", "allocated", qq|id = $pthref->{id}|, $qty);
843
844         $form->update_balance($dbh, "acc_trans", "amount",
845                               qq|    (trans_id = $pthref->{trans_id})
846                                  AND (chart_id = $ref->{expense_accno_id})
847                                  AND (transdate = '$pthref->{transdate}')|,
848                               $amount);
849
850         $form->update_balance($dbh, "acc_trans", "amount",
851                               qq|    (trans_id = $pthref->{trans_id})
852                                  AND (chart_id = $ref->{inventory_accno_id})
853                                  AND (transdate = '$pthref->{transdate}')|,
854                               $amount * -1);
855
856         last if (($ref->{allocated} -= $qty) <= 0);
857       }
858     $sth2->finish();
859   }
860   $sth->finish();
861
862   my $id = conv_i($form->{id});
863
864   # delete acc_trans
865   $query = qq|DELETE FROM acc_trans WHERE trans_id = ?|;
866   do_query($form, $dbh, $query, $id);
867
868   # delete invoice entries
869   $query = qq|DELETE FROM invoice WHERE trans_id = ?|;
870   do_query($form, $dbh, $query, $id);
871
872   $query = qq|DELETE FROM shipto WHERE (trans_id = ?) AND (module = 'AP')|;
873   do_query($form, $dbh, $query, $id);
874
875   $main::lxdebug->leave_sub();
876 }
877
878 sub delete_invoice {
879   $main::lxdebug->enter_sub();
880
881   my ($self, $myconfig, $form) = @_;
882   my $query;
883   # connect to database
884   my $dbh = $form->dbconnect_noauto($myconfig);
885
886   &reverse_invoice($dbh, $form);
887
888   # delete zero entries
889   $query = qq|DELETE FROM acc_trans WHERE amount = 0|;
890   do_query($form, $dbh, $query);
891
892   # delete AP record
893   $query = qq|DELETE FROM ap WHERE id = ?|;
894   do_query($form, $dbh, $query, conv_i($form->{id}));
895
896   my $rc = $dbh->commit;
897   $dbh->disconnect;
898
899   $main::lxdebug->leave_sub();
900
901   return $rc;
902 }
903
904 sub retrieve_invoice {
905   $main::lxdebug->enter_sub();
906
907   my ($self, $myconfig, $form) = @_;
908
909   # connect to database
910   my $dbh = $form->dbconnect($myconfig);
911
912   my ($query, $sth, $ref, $q_invdate);
913
914   if (!$form->{id}) {
915     $q_invdate = qq|, COALESCE((SELECT transdate FROM ar WHERE id = (SELECT MAX(id) FROM ar)), current_date) AS invdate|;
916     if ($form->{vendor_id}) {
917       my $vendor_id = $dbh->quote($form->{vendor_id} * 1);
918       $q_invdate .=
919         qq|, COALESCE((SELECT transdate FROM ar WHERE id = (SELECT MAX(id) FROM ar)), current_date) +
920              COALESCE((SELECT pt.terms_netto
921                        FROM vendor v
922                        LEFT JOIN payment_terms pt ON (v.payment_id = pt.id)
923                        WHERE v.id = $vendor_id),
924                       0) AS duedate|;
925     }
926   }
927
928   # get default accounts and last invoice number
929
930   $query = qq|SELECT
931                (SELECT c.accno FROM chart c WHERE d.inventory_accno_id = c.id) AS inventory_accno,
932                (SELECT c.accno FROM chart c WHERE d.income_accno_id = c.id)    AS income_accno,
933                (SELECT c.accno FROM chart c WHERE d.expense_accno_id = c.id)   AS expense_accno,
934                (SELECT c.accno FROM chart c WHERE d.fxgain_accno_id = c.id)    AS fxgain_accno,
935                (SELECT c.accno FROM chart c WHERE d.fxloss_accno_id = c.id)    AS fxloss_accno
936                $q_invdate
937                FROM defaults d|;
938   $ref = selectfirst_hashref_query($form, $dbh, $query);
939   map { $form->{$_} = $ref->{$_} } keys %$ref;
940
941   if (!$form->{id}) {
942     $dbh->disconnect();
943     $main::lxdebug->leave_sub();
944
945     return;
946   }
947
948   # retrieve invoice
949   $query = qq|SELECT cp_id, invnumber, transdate AS invdate, duedate,
950                 orddate, quodate, globalproject_id,
951                 ordnumber, quonumber, paid, taxincluded, notes, taxzone_id, storno, gldate,
952                 intnotes, (SELECT cu.name FROM currencies cu WHERE cu.id=ap.currency_id) AS currency, direct_debit,
953                 delivery_term_id
954               FROM ap
955               WHERE id = ?|;
956   $ref = selectfirst_hashref_query($form, $dbh, $query, conv_i($form->{id}));
957   map { $form->{$_} = $ref->{$_} } keys %$ref;
958
959   $form->{exchangerate}  = $form->get_exchangerate($dbh, $form->{currency}, $form->{invdate}, "sell");
960
961   # get shipto
962   $query = qq|SELECT * FROM shipto WHERE (trans_id = ?) AND (module = 'AP')|;
963   $ref = selectfirst_hashref_query($form, $dbh, $query, conv_i($form->{id}));
964   delete $ref->{id};
965   map { $form->{$_} = $ref->{$_} } keys %$ref;
966
967   my $transdate  = $form->{invdate} ? $dbh->quote($form->{invdate}) : "current_date";
968
969   my $taxzone_id = $form->{taxzone_id} * 1;
970   $taxzone_id = SL::DB::Manager::TaxZone->get_default->id unless SL::DB::Manager::TaxZone->find_by(id => $taxzone_id);
971
972   # retrieve individual items
973   $query =
974     qq|SELECT
975         c1.accno AS inventory_accno, c1.new_chart_id AS inventory_new_chart, date($transdate) - c1.valid_from AS inventory_valid,
976         c2.accno AS income_accno,    c2.new_chart_id AS income_new_chart,    date($transdate) - c2.valid_from AS income_valid,
977         c3.accno AS expense_accno,   c3.new_chart_id AS expense_new_chart,   date($transdate) - c3.valid_from AS expense_valid,
978
979         i.id AS invoice_id,
980         i.description, i.longdescription, i.qty, i.fxsellprice AS sellprice, i.parts_id AS id, i.unit, i.deliverydate, i.project_id, i.serialnumber,
981         i.price_factor_id, i.price_factor, i.marge_price_factor, i.discount, i.active_price_source,
982         p.partnumber, p.inventory_accno_id AS part_inventory_accno_id,  pr.projectnumber, pg.partsgroup
983
984         FROM invoice i
985         JOIN parts p ON (i.parts_id = p.id)
986         LEFT JOIN chart c1 ON ((SELECT inventory_accno_id             FROM buchungsgruppen WHERE id = p.buchungsgruppen_id) = c1.id)
987         LEFT JOIN chart c2 ON ((SELECT tc.income_accno_id FROM taxzone_charts tc where tc.taxzone_id = '$taxzone_id' and tc.buchungsgruppen_id = p.buchungsgruppen_id) = c2.id)
988         LEFT JOIN chart c3 ON ((SELECT tc.expense_accno_id FROM taxzone_charts tc where tc.taxzone_id = '$taxzone_id' and tc.buchungsgruppen_id = p.buchungsgruppen_id) = c3.id)
989         LEFT JOIN project pr    ON (i.project_id = pr.id)
990         LEFT JOIN partsgroup pg ON (pg.id = p.partsgroup_id)
991
992         WHERE i.trans_id = ?
993
994         ORDER BY i.id|;
995   $sth = prepare_execute_query($form, $dbh, $query, conv_i($form->{id}));
996
997   while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
998     # Retrieve custom variables.
999     my $cvars = CVar->get_custom_variables(dbh        => $dbh,
1000                                            module     => 'IC',
1001                                            sub_module => 'invoice',
1002                                            trans_id   => $ref->{invoice_id},
1003                                           );
1004     map { $ref->{"ic_cvar_$_->{name}"} = $_->{value} } @{ $cvars };
1005     delete $ref->{invoice_id};
1006
1007     map({ delete($ref->{$_}); } qw(inventory_accno inventory_new_chart inventory_valid)) if !$ref->{"part_inventory_accno_id"};
1008     delete($ref->{"part_inventory_accno_id"});
1009
1010     foreach my $type (qw(inventory income expense)) {
1011       while ($ref->{"${type}_new_chart"} && ($ref->{"${type}_valid"} >=0)) {
1012         my $query = qq|SELECT accno, new_chart_id, date($transdate) - valid_from FROM chart WHERE id = ?|;
1013         @$ref{ map $type.$_, qw(_accno _new_chart _valid) } = selectrow_query($form, $dbh, $query, $ref->{"${type}_new_chart"});
1014       }
1015     }
1016
1017     # get tax rates and description
1018     my $accno_id = ($form->{vc} eq "customer") ? $ref->{income_accno} : $ref->{expense_accno};
1019     $query =
1020       qq|SELECT c.accno, t.taxdescription, t.rate, t.taxnumber FROM tax t
1021          LEFT JOIN chart c ON (c.id = t.chart_id)
1022          WHERE t.id in
1023            (SELECT tk.tax_id FROM taxkeys tk
1024             WHERE tk.chart_id = (SELECT id FROM chart WHERE accno = ?)
1025               AND (startdate <= $transdate)
1026             ORDER BY startdate DESC
1027             LIMIT 1)
1028          ORDER BY c.accno|;
1029     my $stw = prepare_execute_query($form, $dbh, $query, $accno_id);
1030     $ref->{taxaccounts} = "";
1031
1032     my $i = 0;
1033     while (my $ptr = $stw->fetchrow_hashref("NAME_lc")) {
1034       if (($ptr->{accno} eq "") && ($ptr->{rate} == 0)) {
1035         $i++;
1036         $ptr->{accno} = $i;
1037       }
1038
1039       $ref->{taxaccounts} .= "$ptr->{accno} ";
1040
1041       if (!($form->{taxaccounts} =~ /\Q$ptr->{accno}\E/)) {
1042         $form->{"$ptr->{accno}_rate"}         = $ptr->{rate};
1043         $form->{"$ptr->{accno}_description"}  = $ptr->{taxdescription};
1044         $form->{"$ptr->{accno}_taxnumber"}    = $ptr->{taxnumber};
1045         $form->{taxaccounts}                 .= "$ptr->{accno} ";
1046       }
1047
1048     }
1049
1050     chop $ref->{taxaccounts};
1051     push @{ $form->{invoice_details} }, $ref;
1052     $stw->finish();
1053   }
1054   $sth->finish();
1055
1056   Common::webdav_folder($form);
1057
1058   $dbh->disconnect();
1059
1060   $main::lxdebug->leave_sub();
1061 }
1062
1063 sub get_vendor {
1064   $main::lxdebug->enter_sub();
1065
1066   my ($self, $myconfig, $form, $params) = @_;
1067
1068   $params = $form unless defined $params && ref $params eq "HASH";
1069
1070   # connect to database
1071   my $dbh = $form->dbconnect($myconfig);
1072
1073   my $dateformat = $myconfig->{dateformat};
1074   $dateformat .= "yy" if $myconfig->{dateformat} !~ /^y/;
1075
1076   my $vid = conv_i($params->{vendor_id});
1077   my $vnr = conv_i($params->{vendornumber});
1078
1079   my $duedate =
1080     ($params->{invdate})
1081     ? "to_date(" . $dbh->quote($params->{invdate}) . ", '$dateformat')"
1082     : "current_date";
1083
1084   # get vendor
1085   my @values = ();
1086   my $where = '';
1087   if ($vid) {
1088     $where .= 'AND v.id = ?';
1089     push @values, $vid;
1090   }
1091   if ($vnr) {
1092     $where .= 'AND v.vendornumber = ?';
1093     push @values, $vnr;
1094   }
1095   my $query =
1096     qq|SELECT
1097          v.id AS vendor_id, v.name AS vendor, v.discount as vendor_discount,
1098          v.creditlimit, v.terms, v.notes AS intnotes,
1099          v.email, v.cc, v.bcc, v.language_id, v.payment_id, v.delivery_term_id,
1100          v.street, v.zipcode, v.city, v.country, v.taxzone_id, cu.name AS curr, v.direct_debit,
1101          $duedate + COALESCE(pt.terms_netto, 0) AS duedate,
1102          b.description AS business
1103        FROM vendor v
1104        LEFT JOIN business b       ON (b.id = v.business_id)
1105        LEFT JOIN payment_terms pt ON (v.payment_id = pt.id)
1106        LEFT JOIN currencies cu    ON (v.currency_id = cu.id)
1107        WHERE 1=1 $where|;
1108   my $ref = selectfirst_hashref_query($form, $dbh, $query, @values);
1109   map { $params->{$_} = $ref->{$_} } keys %$ref;
1110
1111   # use vendor currency
1112   $form->{currency} = $form->{curr};
1113
1114   $params->{creditremaining} = $params->{creditlimit};
1115
1116   $query = qq|SELECT SUM(amount - paid) FROM ap WHERE vendor_id = ?|;
1117   my ($unpaid_invoices) = selectfirst_array_query($form, $dbh, $query, $vid);
1118   $params->{creditremaining} -= $unpaid_invoices;
1119
1120   $query = qq|SELECT o.amount,
1121                 (SELECT e.sell
1122                  FROM exchangerate e
1123                  WHERE (e.currency_id = o.currency_id)
1124                    AND (e.transdate = o.transdate)) AS exch
1125               FROM oe o
1126               WHERE (o.vendor_id = ?) AND (o.quotation = '0') AND (o.closed = '0')|;
1127   my $sth = prepare_execute_query($form, $dbh, $query, $vid);
1128   while (my ($amount, $exch) = $sth->fetchrow_array()) {
1129     $exch = 1 unless $exch;
1130     $params->{creditremaining} -= $amount * $exch;
1131   }
1132   $sth->finish();
1133
1134   if (!$params->{id} && $params->{type} !~ /_(order|quotation)/) {
1135     # setup last accounts used
1136     $query =
1137       qq|SELECT c.id, c.accno, c.description, c.link, c.category
1138          FROM chart c
1139          JOIN acc_trans ac ON (ac.chart_id = c.id)
1140          JOIN ap a         ON (a.id = ac.trans_id)
1141          WHERE (a.vendor_id = ?)
1142            AND (NOT ((c.link LIKE '%_tax%') OR (c.link LIKE '%_paid%')))
1143            AND (a.id IN (SELECT max(a2.id) FROM ap a2 WHERE a2.vendor_id = ?))|;
1144     my $refs = selectall_hashref_query($form, $dbh, $query, $vid, $vid);
1145
1146     my $i = 0;
1147     for $ref (@$refs) {
1148       if ($ref->{category} eq 'E') {
1149         $i++;
1150         my ($tax_id, $rate);
1151         if ($params->{initial_transdate}) {
1152           my $tax_query = qq|SELECT tk.tax_id, t.rate FROM taxkeys tk
1153                              LEFT JOIN tax t ON (tk.tax_id = t.id)
1154                              WHERE (tk.chart_id = ?) AND (startdate <= ?)
1155                              ORDER BY tk.startdate DESC
1156                              LIMIT 1|;
1157           ($tax_id, $rate) = selectrow_query($form, $dbh, $tax_query, $ref->{id}, $params->{initial_transdate});
1158           $params->{"taxchart_$i"} = "${tax_id}--${rate}";
1159         }
1160
1161         $params->{"AP_amount_$i"} = "$ref->{accno}--$tax_id";
1162       }
1163
1164       if ($ref->{category} eq 'L') {
1165         $params->{APselected} = $params->{AP_1} = $ref->{accno};
1166       }
1167     }
1168     $params->{rowcount} = $i if ($i && !$params->{type});
1169   }
1170
1171   $dbh->disconnect();
1172
1173   $main::lxdebug->leave_sub();
1174 }
1175
1176 sub retrieve_item {
1177   $main::lxdebug->enter_sub();
1178
1179   my ($self, $myconfig, $form) = @_;
1180
1181   # connect to database
1182   my $dbh = $form->dbconnect($myconfig);
1183
1184   my $i = $form->{rowcount};
1185
1186   # don't include assemblies or obsolete parts
1187   my $where = "NOT p.assembly = '1' AND NOT p.obsolete = '1'";
1188   my @values;
1189
1190   foreach my $table_column (qw(p.partnumber p.description pg.partsgroup)) {
1191     my $field = (split m{\.}, $table_column)[1];
1192     next unless $form->{"${field}_${i}"};
1193     $where .= " AND lower(${table_column}) LIKE lower(?)";
1194     push @values, '%' . $form->{"${field}_${i}"} . '%';
1195   }
1196
1197   my (%mm_by_id);
1198   if ($form->{"partnumber_$i"} && !$form->{"description_$i"}) {
1199     $where .= qq| OR (NOT p.obsolete = '1' AND p.ean = ? )|;
1200     push @values, $form->{"partnumber_$i"};
1201
1202     # also search hits in makemodels, but only cache the results by id and merge later
1203     my $mm_query = qq|
1204       SELECT parts_id, model FROM makemodel
1205       LEFT JOIN parts ON parts.id = parts_id
1206       WHERE NOT parts.obsolete AND model ILIKE ? AND (make IS NULL OR make = ?);
1207     |;
1208     my $mm_results = selectall_hashref_query($::form, $dbh, $mm_query, '%' . $form->{"partnumber_$i"} . '%', $::form->{vendor_id});
1209     my @mm_ids     = map { $_->{parts_id} } @$mm_results;
1210     push @{$mm_by_id{ $_->{parts_id} } ||= []}, $_ for @$mm_results;
1211
1212     if (@mm_ids) {
1213       $where .= qq| OR p.id IN (| . join(',', ('?') x @mm_ids) . qq|)|;
1214       push @values, @mm_ids;
1215     }
1216   }
1217
1218   # Search for part ID overrides all other criteria.
1219   if ($form->{"id_${i}"}) {
1220     $where  = qq|p.id = ?|;
1221     @values = ($form->{"id_${i}"});
1222   }
1223
1224   if ($form->{"description_$i"}) {
1225     $where .= " ORDER BY p.description";
1226   } else {
1227     $where .= " ORDER BY p.partnumber";
1228   }
1229
1230   my $transdate = "";
1231   if ($form->{type} eq "invoice") {
1232     $transdate = $form->{deliverydate} ? $dbh->quote($form->{deliverydate})
1233                : $form->{invdate} ? $dbh->quote($form->{invdate})
1234                : "current_date";
1235   } else {
1236     $transdate = $form->{transdate} ? $dbh->quote($form->{transdate}) : "current_date";
1237   }
1238
1239   my $taxzone_id = $form->{taxzone_id} * 1;
1240   $taxzone_id = SL::DB::Manager::TaxZone->get_default->id unless SL::DB::Manager::TaxZone->find_by(id => $taxzone_id);
1241
1242   my $query =
1243     qq|SELECT
1244          p.id, p.partnumber, p.description, p.lastcost AS sellprice, p.listprice,
1245          p.unit, p.assembly, p.onhand, p.formel,
1246          p.notes AS partnotes, p.notes AS longdescription, p.not_discountable,
1247          p.inventory_accno_id, p.price_factor_id,
1248          p.ean,
1249
1250          pfac.factor AS price_factor,
1251
1252          c1.accno                         AS inventory_accno,
1253          c1.new_chart_id                  AS inventory_new_chart,
1254          date($transdate) - c1.valid_from AS inventory_valid,
1255
1256          c2.accno                         AS income_accno,
1257          c2.new_chart_id                  AS income_new_chart,
1258          date($transdate) - c2.valid_from AS income_valid,
1259
1260          c3.accno                         AS expense_accno,
1261          c3.new_chart_id                  AS expense_new_chart,
1262          date($transdate) - c3.valid_from AS expense_valid,
1263
1264          pg.partsgroup
1265
1266        FROM parts p
1267        LEFT JOIN chart c1 ON
1268          ((SELECT inventory_accno_id
1269            FROM buchungsgruppen
1270            WHERE id = p.buchungsgruppen_id) = c1.id)
1271        LEFT JOIN chart c2 ON
1272          ((SELECT tc.income_accno_id
1273            FROM taxzone_charts tc
1274            WHERE tc.taxzone_id = '$taxzone_id' and tc.buchungsgruppen_id = p.buchungsgruppen_id) = c2.id)
1275        LEFT JOIN chart c3 ON
1276          ((SELECT tc.expense_accno_id
1277            FROM taxzone_charts tc
1278            WHERE tc.taxzone_id = '$taxzone_id' and tc.buchungsgruppen_id = p.buchungsgruppen_id) = c3.id)
1279        LEFT JOIN partsgroup pg ON (pg.id = p.partsgroup_id)
1280        LEFT JOIN price_factors pfac ON (pfac.id = p.price_factor_id)
1281        WHERE $where|;
1282   my $sth = prepare_execute_query($form, $dbh, $query, @values);
1283
1284   my @translation_queries = ( [ qq|SELECT tr.translation, tr.longdescription
1285                                    FROM translation tr
1286                                    WHERE tr.language_id = ? AND tr.parts_id = ?| ],
1287                               [ qq|SELECT tr.translation, tr.longdescription
1288                                    FROM translation tr
1289                                    WHERE tr.language_id IN
1290                                      (SELECT id
1291                                       FROM language
1292                                       WHERE article_code = (SELECT article_code FROM language WHERE id = ?))
1293                                      AND tr.parts_id = ?
1294                                    LIMIT 1| ] );
1295   map { push @{ $_ }, prepare_query($form, $dbh, $_->[0]) } @translation_queries;
1296
1297   $form->{item_list} = [];
1298   while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
1299
1300     if ($mm_by_id{$ref->{id}}) {
1301       $ref->{makemodels} = $mm_by_id{$ref->{id}};
1302       push @{ $ref->{matches} ||= [] }, $::locale->text('Model') . ': ' . join ', ', map { $_->{model} } @{ $mm_by_id{$ref->{id}} };
1303     }
1304
1305     if ($ref->{ean} eq $::form->{"partnumber_$i"}) {
1306       push @{ $ref->{matches} ||= [] }, $::locale->text('EAN') . ': ' . $ref->{ean};
1307     }
1308
1309     # In der Buchungsgruppe ist immer ein Bestandskonto verknuepft, auch wenn
1310     # es sich um eine Dienstleistung handelt. Bei Dienstleistungen muss das
1311     # Buchungskonto also aus dem Ergebnis rausgenommen werden.
1312     if (!$ref->{inventory_accno_id}) {
1313       map({ delete($ref->{"inventory_${_}"}); } qw(accno new_chart valid));
1314     }
1315     delete($ref->{inventory_accno_id});
1316
1317     # get tax rates and description
1318     my $accno_id = ($form->{vc} eq "customer") ? $ref->{income_accno} : $ref->{expense_accno};
1319     $query =
1320       qq|SELECT c.accno, t.taxdescription, t.rate, t.taxnumber
1321          FROM tax t
1322          LEFT JOIN chart c on (c.id = t.chart_id)
1323          WHERE t.id IN
1324            (SELECT tk.tax_id
1325             FROM taxkeys tk
1326             WHERE tk.chart_id =
1327               (SELECT id
1328                FROM chart
1329                WHERE accno = ?)
1330               AND (startdate <= $transdate)
1331             ORDER BY startdate DESC
1332             LIMIT 1)
1333          ORDER BY c.accno|;
1334     my $stw = prepare_execute_query($form, $dbh, $query, $accno_id);
1335
1336     $ref->{taxaccounts} = "";
1337     my $i = 0;
1338     while (my $ptr = $stw->fetchrow_hashref("NAME_lc")) {
1339
1340       if (($ptr->{accno} eq "") && ($ptr->{rate} == 0)) {
1341         $i++;
1342         $ptr->{accno} = $i;
1343       }
1344
1345       $ref->{taxaccounts} .= "$ptr->{accno} ";
1346
1347       if (!($form->{taxaccounts} =~ /\Q$ptr->{accno}\E/)) {
1348         $form->{"$ptr->{accno}_rate"}         = $ptr->{rate};
1349         $form->{"$ptr->{accno}_description"}  = $ptr->{taxdescription};
1350         $form->{"$ptr->{accno}_taxnumber"}    = $ptr->{taxnumber};
1351         $form->{taxaccounts}                 .= "$ptr->{accno} ";
1352       }
1353
1354       if ($form->{language_id}) {
1355         for my $spec (@translation_queries) {
1356           do_statement($form, $spec->[1], $spec->[0], conv_i($form->{language_id}), conv_i($ref->{id}));
1357           my ($translation, $longdescription) = $spec->[1]->fetchrow_array;
1358           next unless $translation;
1359           $ref->{description} = $translation;
1360           $ref->{longdescription} = $longdescription;
1361           last;
1362         }
1363       }
1364     }
1365
1366     $stw->finish();
1367     chop $ref->{taxaccounts};
1368
1369     $ref->{onhand} *= 1;
1370
1371     push @{ $form->{item_list} }, $ref;
1372
1373   }
1374
1375   $sth->finish();
1376   $_->[1]->finish for @translation_queries;
1377
1378   foreach my $item (@{ $form->{item_list} }) {
1379     my $custom_variables = CVar->get_custom_variables(module   => 'IC',
1380                                                       trans_id => $item->{id},
1381                                                       dbh      => $dbh,
1382                                                      );
1383
1384     map { $item->{"ic_cvar_" . $_->{name} } = $_->{value} } @{ $custom_variables };
1385   }
1386
1387   $dbh->disconnect();
1388
1389   $main::lxdebug->leave_sub();
1390 }
1391
1392 sub vendor_details {
1393   $main::lxdebug->enter_sub();
1394
1395   my ($self, $myconfig, $form, @wanted_vars) = @_;
1396
1397   # connect to database
1398   my $dbh = $form->dbconnect($myconfig);
1399
1400   my @values;
1401
1402   # get contact id, set it if nessessary
1403   $form->{cp_id} *= 1;
1404   my $contact = "";
1405   if ($form->{cp_id}) {
1406     $contact = "AND cp.cp_id = ?";
1407     push @values, $form->{cp_id};
1408   }
1409
1410   # get rest for the vendor
1411   # fax and phone and email as vendor*
1412   my $query =
1413     qq|SELECT ct.*, cp.*, ct.notes as vendornotes, phone as vendorphone, fax as vendorfax, email as vendoremail,
1414          cu.name AS currency
1415        FROM vendor ct
1416        LEFT JOIN contacts cp ON (ct.id = cp.cp_cv_id)
1417        LEFT JOIN currencies cu ON (ct.currency_id = cu.id)
1418        WHERE (ct.id = ?) $contact
1419        ORDER BY cp.cp_id
1420        LIMIT 1|;
1421   my $ref = selectfirst_hashref_query($form, $dbh, $query, $form->{vendor_id}, @values);
1422
1423   # remove id and taxincluded before copy back
1424   delete @$ref{qw(id taxincluded)};
1425
1426   @wanted_vars = grep({ $_ } @wanted_vars);
1427   if (scalar(@wanted_vars) > 0) {
1428     my %h_wanted_vars;
1429     map({ $h_wanted_vars{$_} = 1; } @wanted_vars);
1430     map({ delete($ref->{$_}) unless ($h_wanted_vars{$_}); } keys(%{$ref}));
1431   }
1432
1433   map { $form->{$_} = $ref->{$_} } keys %$ref;
1434
1435   my $custom_variables = CVar->get_custom_variables('dbh'      => $dbh,
1436                                                     'module'   => 'CT',
1437                                                     'trans_id' => $form->{vendor_id});
1438   map { $form->{"vc_cvar_$_->{name}"} = $_->{value} } @{ $custom_variables };
1439
1440   $form->{cp_greeting} = GenericTranslations->get('dbh'              => $dbh,
1441                                                   'translation_type' => 'greetings::' . ($form->{cp_gender} eq 'f' ? 'female' : 'male'),
1442                                                   'allow_fallback'   => 1);
1443
1444   $dbh->disconnect();
1445
1446   $main::lxdebug->leave_sub();
1447 }
1448
1449 sub item_links {
1450   $main::lxdebug->enter_sub();
1451
1452   my ($self, $myconfig, $form) = @_;
1453
1454   # connect to database
1455   my $dbh = $form->dbconnect($myconfig);
1456
1457   my $query =
1458     qq|SELECT accno, description, link
1459        FROM chart
1460        WHERE link LIKE '%IC%'
1461        ORDER BY accno|;
1462   my $sth = prepare_execute_query($query, $dbh, $query);
1463
1464   while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
1465     foreach my $key (split(/:/, $ref->{link})) {
1466       if ($key =~ /IC/) {
1467         push @{ $form->{IC_links}{$key} },
1468           { accno       => $ref->{accno},
1469             description => $ref->{description} };
1470       }
1471     }
1472   }
1473
1474   $sth->finish();
1475   $dbh->disconnect();
1476
1477   $main::lxdebug->leave_sub();
1478 }
1479
1480 sub _delete_payments {
1481   $main::lxdebug->enter_sub();
1482
1483   my ($self, $form, $dbh) = @_;
1484
1485   my @delete_acc_trans_ids;
1486
1487   # Delete old payment entries from acc_trans.
1488   my $query =
1489     qq|SELECT acc_trans_id
1490        FROM acc_trans
1491        WHERE (trans_id = ?) AND fx_transaction
1492
1493        UNION
1494
1495        SELECT at.acc_trans_id
1496        FROM acc_trans at
1497        LEFT JOIN chart c ON (at.chart_id = c.id)
1498        WHERE (trans_id = ?) AND (c.link LIKE '%AP_paid%')|;
1499   push @delete_acc_trans_ids, selectall_array_query($form, $dbh, $query, conv_i($form->{id}), conv_i($form->{id}));
1500
1501   $query =
1502     qq|SELECT at.acc_trans_id
1503        FROM acc_trans at
1504        LEFT JOIN chart c ON (at.chart_id = c.id)
1505        WHERE (trans_id = ?)
1506          AND ((c.link = 'AP') OR (c.link LIKE '%:AP') OR (c.link LIKE 'AP:%'))
1507        ORDER BY at.acc_trans_id
1508        OFFSET 1|;
1509   push @delete_acc_trans_ids, selectall_array_query($form, $dbh, $query, conv_i($form->{id}));
1510
1511   if (@delete_acc_trans_ids) {
1512     $query = qq|DELETE FROM acc_trans WHERE acc_trans_id IN (| . join(", ", @delete_acc_trans_ids) . qq|)|;
1513     do_query($form, $dbh, $query);
1514   }
1515
1516   $main::lxdebug->leave_sub();
1517 }
1518
1519 sub post_payment {
1520   $main::lxdebug->enter_sub();
1521
1522   my ($self, $myconfig, $form, $locale) = @_;
1523
1524   # connect to database, turn off autocommit
1525   my $dbh = $form->dbconnect_noauto($myconfig);
1526
1527   my (%payments, $old_form, $row, $item, $query, %keep_vars);
1528
1529   $old_form = save_form();
1530
1531   # Delete all entries in acc_trans from prior payments.
1532   if (SL::DB::Default->get->payments_changeable != 0) {
1533     $self->_delete_payments($form, $dbh);
1534   }
1535
1536   # Save the new payments the user made before cleaning up $form.
1537   map { $payments{$_} = $form->{$_} } grep m/^datepaid_\d+$|^gldate_\d+$|^acc_trans_id_\d+$|^memo_\d+$|^source_\d+$|^exchangerate_\d+$|^paid_\d+$|^AP_paid_\d+$|^paidaccounts$/, keys %{ $form };
1538
1539   # Clean up $form so that old content won't tamper the results.
1540   %keep_vars = map { $_, 1 } qw(login password id);
1541   map { delete $form->{$_} unless $keep_vars{$_} } keys %{ $form };
1542
1543   # Retrieve the invoice from the database.
1544   $self->retrieve_invoice($myconfig, $form);
1545
1546   # Set up the content of $form in the way that IR::post_invoice() expects.
1547   $form->{exchangerate} = $form->format_amount($myconfig, $form->{exchangerate});
1548
1549   for $row (1 .. scalar @{ $form->{invoice_details} }) {
1550     $item = $form->{invoice_details}->[$row - 1];
1551
1552     map { $item->{$_} = $form->format_amount($myconfig, $item->{$_}) } qw(qty sellprice);
1553
1554     map { $form->{"${_}_${row}"} = $item->{$_} } keys %{ $item };
1555   }
1556
1557   $form->{rowcount} = scalar @{ $form->{invoice_details} };
1558
1559   delete @{$form}{qw(invoice_details paidaccounts storno paid)};
1560
1561   # Restore the payment options from the user input.
1562   map { $form->{$_} = $payments{$_} } keys %payments;
1563
1564   # Get the AP accno (which is normally done by Form::create_links()).
1565   $query =
1566     qq|SELECT c.accno
1567        FROM acc_trans at
1568        LEFT JOIN chart c ON (at.chart_id = c.id)
1569        WHERE (trans_id = ?)
1570          AND ((c.link = 'AP') OR (c.link LIKE '%:AP') OR (c.link LIKE 'AP:%'))
1571        ORDER BY at.acc_trans_id
1572        LIMIT 1|;
1573
1574   ($form->{AP}) = selectfirst_array_query($form, $dbh, $query, conv_i($form->{id}));
1575
1576   # Post the new payments.
1577   $self->post_invoice($myconfig, $form, $dbh, 1);
1578
1579   restore_form($old_form);
1580
1581   my $rc = $dbh->commit();
1582   $dbh->disconnect();
1583
1584   $main::lxdebug->leave_sub();
1585
1586   return $rc;
1587 }
1588
1589 sub get_duedate {
1590   $::lxdebug->enter_sub;
1591
1592   my ($self, %params) = @_;
1593
1594   if (!$params{vendor_id} || !$params{invdate}) {
1595     $::lxdebug->leave_sub;
1596     return $params{default};
1597   }
1598
1599   my $dbh      = $::form->get_standard_dbh;
1600   my $query    = qq|SELECT ?::date + pt.terms_netto
1601                     FROM vendor v
1602                     LEFT JOIN payment_terms pt ON (pt.id = v.payment_id)
1603                     WHERE v.id = ?|;
1604
1605   my ($duedate) = selectfirst_array_query($::form, $dbh, $query, $params{invdate}, $params{vendor_id});
1606
1607   $duedate ||= $params{default};
1608
1609   $::lxdebug->leave_sub;
1610
1611   return $duedate;
1612 }
1613
1614
1615 1;