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