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