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