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