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