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