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