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