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