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