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