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