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