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