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