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