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