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