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