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