Einkauf/Verkauf: Lieferadressenfelder nie aus Stammdaten vorbelegen
[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   $form->{name} = $form->{vendor};
724   $form->{name} =~ s/--\Q$form->{vendor_id}\E//;
725
726   # add shipto
727   $form->add_shipto($dbh, $form->{id}, "AP");
728
729   # delete zero entries
730   do_query($form, $dbh, qq|DELETE FROM acc_trans WHERE amount = 0|);
731
732   Common::webdav_folder($form);
733
734   # Link this record to the records it was created from.
735   RecordLinks->create_links('dbh'        => $dbh,
736                             'mode'       => 'ids',
737                             'from_table' => 'oe',
738                             'from_ids'   => $form->{convert_from_oe_ids},
739                             'to_table'   => 'ap',
740                             'to_id'      => $form->{id},
741     );
742   delete $form->{convert_from_oe_ids};
743
744   my @convert_from_do_ids = map { $_ * 1 } grep { $_ } split m/\s+/, $form->{convert_from_do_ids};
745   if (scalar @convert_from_do_ids) {
746     DO->close_orders('dbh' => $dbh,
747                      'ids' => \@convert_from_do_ids);
748
749     RecordLinks->create_links('dbh'        => $dbh,
750                               'mode'       => 'ids',
751                               'from_table' => 'delivery_orders',
752                               'from_ids'   => \@convert_from_do_ids,
753                               'to_table'   => 'ap',
754                               'to_id'      => $form->{id},
755       );
756   }
757   delete $form->{convert_from_do_ids};
758
759   ARAP->close_orders_if_billed('dbh'     => $dbh,
760                                'arap_id' => $form->{id},
761                                'table'   => 'ap',);
762
763   # safety check datev export
764   if ($::instance_conf->get_datev_check_on_purchase_invoice) {
765     my $transdate = $::form->{invdate} ? DateTime->from_lxoffice($::form->{invdate}) : undef;
766     $transdate  ||= DateTime->today;
767
768     my $datev = SL::DATEV->new(
769       exporttype => DATEV_ET_BUCHUNGEN,
770       format     => DATEV_FORMAT_KNE,
771       dbh        => $dbh,
772       from       => $transdate,
773       to         => $transdate,
774       trans_id   => $form->{id},
775     );
776
777     $datev->export;
778
779     if ($datev->errors) {
780       $dbh->rollback;
781       die join "\n", $::locale->text('DATEV check returned errors:'), $datev->errors;
782     }
783   }
784
785   my $rc = 1;
786   if (!$provided_dbh) {
787     $rc = $dbh->commit();
788     $dbh->disconnect();
789   }
790
791   $main::lxdebug->leave_sub();
792
793   return $rc;
794 }
795
796 sub reverse_invoice {
797   $main::lxdebug->enter_sub();
798
799   my ($dbh, $form) = @_;
800
801   # reverse inventory items
802   my $query =
803     qq|SELECT i.parts_id, p.inventory_accno_id, p.expense_accno_id, i.qty, i.allocated, i.sellprice
804        FROM invoice i, parts p
805        WHERE (i.parts_id = p.id)
806          AND (i.trans_id = ?)|;
807   my $sth = prepare_execute_query($form, $dbh, $query, conv_i($form->{id}));
808
809   my $netamount = 0;
810
811   while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
812     $netamount += $form->round_amount($ref->{sellprice} * $ref->{qty} * -1, 2);
813
814     next unless $ref->{inventory_accno_id};
815
816     # if $ref->{allocated} > 0 than we sold that many items
817     next if ($ref->{allocated} <= 0);
818
819     # get references for sold items
820     $query =
821       qq|SELECT i.id, i.trans_id, i.allocated, a.transdate
822          FROM invoice i, ar a
823          WHERE (i.parts_id = ?)
824            AND (i.allocated < 0)
825            AND (i.trans_id = a.id)
826          ORDER BY transdate DESC|;
827       my $sth2 = prepare_execute_query($form, $dbh, $query, $ref->{parts_id});
828
829       while (my $pthref = $sth2->fetchrow_hashref("NAME_lc")) {
830         my $qty = $ref->{allocated};
831         if (($ref->{allocated} + $pthref->{allocated}) > 0) {
832           $qty = $pthref->{allocated} * -1;
833         }
834
835         my $amount = $form->round_amount($ref->{sellprice} * $qty, 2);
836
837         #adjust allocated
838         $form->update_balance($dbh, "invoice", "allocated", qq|id = $pthref->{id}|, $qty);
839
840         $form->update_balance($dbh, "acc_trans", "amount",
841                               qq|    (trans_id = $pthref->{trans_id})
842                                  AND (chart_id = $ref->{expense_accno_id})
843                                  AND (transdate = '$pthref->{transdate}')|,
844                               $amount);
845
846         $form->update_balance($dbh, "acc_trans", "amount",
847                               qq|    (trans_id = $pthref->{trans_id})
848                                  AND (chart_id = $ref->{inventory_accno_id})
849                                  AND (transdate = '$pthref->{transdate}')|,
850                               $amount * -1);
851
852         last if (($ref->{allocated} -= $qty) <= 0);
853       }
854     $sth2->finish();
855   }
856   $sth->finish();
857
858   my $id = conv_i($form->{id});
859
860   # delete acc_trans
861   $query = qq|DELETE FROM acc_trans WHERE trans_id = ?|;
862   do_query($form, $dbh, $query, $id);
863
864   # delete invoice entries
865   $query = qq|DELETE FROM invoice WHERE trans_id = ?|;
866   do_query($form, $dbh, $query, $id);
867
868   $query = qq|DELETE FROM shipto WHERE (trans_id = ?) AND (module = 'AP')|;
869   do_query($form, $dbh, $query, $id);
870
871   $main::lxdebug->leave_sub();
872 }
873
874 sub delete_invoice {
875   $main::lxdebug->enter_sub();
876
877   my ($self, $myconfig, $form) = @_;
878   my $query;
879   # connect to database
880   my $dbh = $form->dbconnect_noauto($myconfig);
881
882   &reverse_invoice($dbh, $form);
883
884   # delete zero entries
885   $query = qq|DELETE FROM acc_trans WHERE amount = 0|;
886   do_query($form, $dbh, $query);
887
888   # delete AP record
889   $query = qq|DELETE FROM ap WHERE id = ?|;
890   do_query($form, $dbh, $query, conv_i($form->{id}));
891
892   my $rc = $dbh->commit;
893   $dbh->disconnect;
894
895   $main::lxdebug->leave_sub();
896
897   return $rc;
898 }
899
900 sub retrieve_invoice {
901   $main::lxdebug->enter_sub();
902
903   my ($self, $myconfig, $form) = @_;
904
905   # connect to database
906   my $dbh = $form->dbconnect($myconfig);
907
908   my ($query, $sth, $ref, $q_invdate);
909
910   if (!$form->{id}) {
911     $q_invdate = qq|, COALESCE((SELECT transdate FROM ar WHERE id = (SELECT MAX(id) FROM ar)), current_date) AS invdate|;
912     if ($form->{vendor_id}) {
913       my $vendor_id = $dbh->quote($form->{vendor_id} * 1);
914       $q_invdate .=
915         qq|, COALESCE((SELECT transdate FROM ar WHERE id = (SELECT MAX(id) FROM ar)), current_date) +
916              COALESCE((SELECT pt.terms_netto
917                        FROM vendor v
918                        LEFT JOIN payment_terms pt ON (v.payment_id = pt.id)
919                        WHERE v.id = $vendor_id),
920                       0) AS duedate|;
921     }
922   }
923
924   # get default accounts and last invoice number
925
926   $query = qq|SELECT
927                (SELECT c.accno FROM chart c WHERE d.inventory_accno_id = c.id) AS inventory_accno,
928                (SELECT c.accno FROM chart c WHERE d.income_accno_id = c.id)    AS income_accno,
929                (SELECT c.accno FROM chart c WHERE d.expense_accno_id = c.id)   AS expense_accno,
930                (SELECT c.accno FROM chart c WHERE d.fxgain_accno_id = c.id)    AS fxgain_accno,
931                (SELECT c.accno FROM chart c WHERE d.fxloss_accno_id = c.id)    AS fxloss_accno
932                $q_invdate
933                FROM defaults d|;
934   $ref = selectfirst_hashref_query($form, $dbh, $query);
935   map { $form->{$_} = $ref->{$_} } keys %$ref;
936
937   if (!$form->{id}) {
938     $dbh->disconnect();
939     $main::lxdebug->leave_sub();
940
941     return;
942   }
943
944   # retrieve invoice
945   $query = qq|SELECT cp_id, invnumber, transdate AS invdate, duedate,
946                 orddate, quodate, globalproject_id,
947                 ordnumber, quonumber, paid, taxincluded, notes, taxzone_id, storno, gldate,
948                 intnotes, (SELECT cu.name FROM currencies cu WHERE cu.id=ap.currency_id) AS currency, direct_debit,
949                 delivery_term_id
950               FROM ap
951               WHERE id = ?|;
952   $ref = selectfirst_hashref_query($form, $dbh, $query, conv_i($form->{id}));
953   map { $form->{$_} = $ref->{$_} } keys %$ref;
954
955   $form->{exchangerate}  = $form->get_exchangerate($dbh, $form->{currency}, $form->{invdate}, "sell");
956
957   # get shipto
958   $query = qq|SELECT * FROM shipto WHERE (trans_id = ?) AND (module = 'AP')|;
959   $ref = selectfirst_hashref_query($form, $dbh, $query, conv_i($form->{id}));
960   delete $ref->{id};
961   map { $form->{$_} = $ref->{$_} } keys %$ref;
962
963   my $transdate  = $form->{invdate} ? $dbh->quote($form->{invdate}) : "current_date";
964   my $taxzone_id = $form->{taxzone_id} * 1;
965
966   $taxzone_id = 0 if ((3 < $taxzone_id) || (0 > $taxzone_id));
967
968   # retrieve individual items
969   $query =
970     qq|SELECT
971         c1.accno AS inventory_accno, c1.new_chart_id AS inventory_new_chart, date($transdate) - c1.valid_from AS inventory_valid,
972         c2.accno AS income_accno,    c2.new_chart_id AS income_new_chart,    date($transdate) - c2.valid_from AS income_valid,
973         c3.accno AS expense_accno,   c3.new_chart_id AS expense_new_chart,   date($transdate) - c3.valid_from AS expense_valid,
974
975         i.id AS invoice_id,
976         i.description, i.longdescription, i.qty, i.fxsellprice AS sellprice, i.parts_id AS id, i.unit, i.deliverydate, i.project_id, i.serialnumber,
977         i.price_factor_id, i.price_factor, i.marge_price_factor, i.discount,
978         p.partnumber, p.inventory_accno_id AS part_inventory_accno_id,  pr.projectnumber, pg.partsgroup
979
980         FROM invoice i
981         JOIN parts p ON (i.parts_id = p.id)
982         LEFT JOIN chart c1 ON ((SELECT inventory_accno_id             FROM buchungsgruppen WHERE id = p.buchungsgruppen_id) = c1.id)
983         LEFT JOIN chart c2 ON ((SELECT income_accno_id_${taxzone_id}  FROM buchungsgruppen WHERE id = p.buchungsgruppen_id) = c2.id)
984         LEFT JOIN chart c3 ON ((SELECT expense_accno_id_${taxzone_id} FROM buchungsgruppen WHERE id = p.buchungsgruppen_id) = c3.id)
985         LEFT JOIN project pr    ON (i.project_id = pr.id)
986         LEFT JOIN partsgroup pg ON (pg.id = p.partsgroup_id)
987
988         WHERE i.trans_id = ?
989
990         ORDER BY i.id|;
991   $sth = prepare_execute_query($form, $dbh, $query, conv_i($form->{id}));
992
993   while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
994     # Retrieve custom variables.
995     my $cvars = CVar->get_custom_variables(dbh        => $dbh,
996                                            module     => 'IC',
997                                            sub_module => 'invoice',
998                                            trans_id   => $ref->{invoice_id},
999                                           );
1000     map { $ref->{"ic_cvar_$_->{name}"} = $_->{value} } @{ $cvars };
1001     delete $ref->{invoice_id};
1002
1003     map({ delete($ref->{$_}); } qw(inventory_accno inventory_new_chart inventory_valid)) if !$ref->{"part_inventory_accno_id"};
1004     delete($ref->{"part_inventory_accno_id"});
1005
1006     foreach my $type (qw(inventory income expense)) {
1007       while ($ref->{"${type}_new_chart"} && ($ref->{"${type}_valid"} >=0)) {
1008         my $query = qq|SELECT accno, new_chart_id, date($transdate) - valid_from FROM chart WHERE id = ?|;
1009         @$ref{ map $type.$_, qw(_accno _new_chart _valid) } = selectrow_query($form, $dbh, $query, $ref->{"${type}_new_chart"});
1010       }
1011     }
1012
1013     # get tax rates and description
1014     my $accno_id = ($form->{vc} eq "customer") ? $ref->{income_accno} : $ref->{expense_accno};
1015     $query =
1016       qq|SELECT c.accno, t.taxdescription, t.rate, t.taxnumber FROM tax t
1017          LEFT JOIN chart c ON (c.id = t.chart_id)
1018          WHERE t.id in
1019            (SELECT tk.tax_id FROM taxkeys tk
1020             WHERE tk.chart_id = (SELECT id FROM chart WHERE accno = ?)
1021               AND (startdate <= $transdate)
1022             ORDER BY startdate DESC
1023             LIMIT 1)
1024          ORDER BY c.accno|;
1025     my $stw = prepare_execute_query($form, $dbh, $query, $accno_id);
1026     $ref->{taxaccounts} = "";
1027
1028     my $i = 0;
1029     while (my $ptr = $stw->fetchrow_hashref("NAME_lc")) {
1030       if (($ptr->{accno} eq "") && ($ptr->{rate} == 0)) {
1031         $i++;
1032         $ptr->{accno} = $i;
1033       }
1034
1035       $ref->{taxaccounts} .= "$ptr->{accno} ";
1036
1037       if (!($form->{taxaccounts} =~ /\Q$ptr->{accno}\E/)) {
1038         $form->{"$ptr->{accno}_rate"}         = $ptr->{rate};
1039         $form->{"$ptr->{accno}_description"}  = $ptr->{taxdescription};
1040         $form->{"$ptr->{accno}_taxnumber"}    = $ptr->{taxnumber};
1041         $form->{taxaccounts}                 .= "$ptr->{accno} ";
1042       }
1043
1044     }
1045
1046     chop $ref->{taxaccounts};
1047     push @{ $form->{invoice_details} }, $ref;
1048     $stw->finish();
1049   }
1050   $sth->finish();
1051
1052   Common::webdav_folder($form);
1053
1054   $dbh->disconnect();
1055
1056   $main::lxdebug->leave_sub();
1057 }
1058
1059 sub get_vendor {
1060   $main::lxdebug->enter_sub();
1061
1062   my ($self, $myconfig, $form, $params) = @_;
1063
1064   $params = $form unless defined $params && ref $params eq "HASH";
1065
1066   # connect to database
1067   my $dbh = $form->dbconnect($myconfig);
1068
1069   my $dateformat = $myconfig->{dateformat};
1070   $dateformat .= "yy" if $myconfig->{dateformat} !~ /^y/;
1071
1072   my $vid = conv_i($params->{vendor_id});
1073   my $vnr = conv_i($params->{vendornumber});
1074
1075   my $duedate =
1076     ($params->{invdate})
1077     ? "to_date(" . $dbh->quote($params->{invdate}) . ", '$dateformat')"
1078     : "current_date";
1079
1080   # get vendor
1081   my @values = ();
1082   my $where = '';
1083   if ($vid) {
1084     $where .= 'AND v.id = ?';
1085     push @values, $vid;
1086   }
1087   if ($vnr) {
1088     $where .= 'AND v.vendornumber = ?';
1089     push @values, $vnr;
1090   }
1091   my $query =
1092     qq|SELECT
1093          v.id AS vendor_id, v.name AS vendor, v.discount as vendor_discount,
1094          v.creditlimit, v.terms, v.notes AS intnotes,
1095          v.email, v.cc, v.bcc, v.language_id, v.payment_id, v.delivery_term_id,
1096          v.street, v.zipcode, v.city, v.country, v.taxzone_id, cu.name AS curr, v.direct_debit,
1097          $duedate + COALESCE(pt.terms_netto, 0) AS duedate,
1098          b.description AS business
1099        FROM vendor v
1100        LEFT JOIN business b       ON (b.id = v.business_id)
1101        LEFT JOIN payment_terms pt ON (v.payment_id = pt.id)
1102        LEFT JOIN currencies cu    ON (v.currency_id = cu.id)
1103        WHERE 1=1 $where|;
1104   my $ref = selectfirst_hashref_query($form, $dbh, $query, @values);
1105   map { $params->{$_} = $ref->{$_} } keys %$ref;
1106
1107   # use vendor currency
1108   $form->{currency} = $form->{curr};
1109
1110   $params->{creditremaining} = $params->{creditlimit};
1111
1112   $query = qq|SELECT SUM(amount - paid) FROM ap WHERE vendor_id = ?|;
1113   my ($unpaid_invoices) = selectfirst_array_query($form, $dbh, $query, $vid);
1114   $params->{creditremaining} -= $unpaid_invoices;
1115
1116   $query = qq|SELECT o.amount,
1117                 (SELECT e.sell
1118                  FROM exchangerate e
1119                  WHERE (e.currency_id = o.currency_id)
1120                    AND (e.transdate = o.transdate)) AS exch
1121               FROM oe o
1122               WHERE (o.vendor_id = ?) AND (o.quotation = '0') AND (o.closed = '0')|;
1123   my $sth = prepare_execute_query($form, $dbh, $query, $vid);
1124   while (my ($amount, $exch) = $sth->fetchrow_array()) {
1125     $exch = 1 unless $exch;
1126     $params->{creditremaining} -= $amount * $exch;
1127   }
1128   $sth->finish();
1129
1130   if (!$params->{id} && $params->{type} !~ /_(order|quotation)/) {
1131     # setup last accounts used
1132     $query =
1133       qq|SELECT c.id, c.accno, c.description, c.link, c.category
1134          FROM chart c
1135          JOIN acc_trans ac ON (ac.chart_id = c.id)
1136          JOIN ap a         ON (a.id = ac.trans_id)
1137          WHERE (a.vendor_id = ?)
1138            AND (NOT ((c.link LIKE '%_tax%') OR (c.link LIKE '%_paid%')))
1139            AND (a.id IN (SELECT max(a2.id) FROM ap a2 WHERE a2.vendor_id = ?))|;
1140     my $refs = selectall_hashref_query($form, $dbh, $query, $vid, $vid);
1141
1142     my $i = 0;
1143     for $ref (@$refs) {
1144       if ($ref->{category} eq 'E') {
1145         $i++;
1146         my ($tax_id, $rate);
1147         if ($params->{initial_transdate}) {
1148           my $tax_query = qq|SELECT tk.tax_id, t.rate FROM taxkeys tk
1149                              LEFT JOIN tax t ON (tk.tax_id = t.id)
1150                              WHERE (tk.chart_id = ?) AND (startdate <= ?)
1151                              ORDER BY tk.startdate DESC
1152                              LIMIT 1|;
1153           ($tax_id, $rate) = selectrow_query($form, $dbh, $tax_query, $ref->{id}, $params->{initial_transdate});
1154           $params->{"taxchart_$i"} = "${tax_id}--${rate}";
1155         }
1156
1157         $params->{"AP_amount_$i"} = "$ref->{accno}--$tax_id";
1158       }
1159
1160       if ($ref->{category} eq 'L') {
1161         $params->{APselected} = $params->{AP_1} = $ref->{accno};
1162       }
1163     }
1164     $params->{rowcount} = $i if ($i && !$params->{type});
1165   }
1166
1167   $dbh->disconnect();
1168
1169   $main::lxdebug->leave_sub();
1170 }
1171
1172 sub retrieve_item {
1173   $main::lxdebug->enter_sub();
1174
1175   my ($self, $myconfig, $form) = @_;
1176
1177   # connect to database
1178   my $dbh = $form->dbconnect($myconfig);
1179
1180   my $i = $form->{rowcount};
1181
1182   # don't include assemblies or obsolete parts
1183   my $where = "NOT p.assembly = '1' AND NOT p.obsolete = '1'";
1184   my @values;
1185
1186   foreach my $table_column (qw(p.partnumber p.description pg.partsgroup)) {
1187     my $field = (split m{\.}, $table_column)[1];
1188     next unless $form->{"${field}_${i}"};
1189     $where .= " AND lower(${table_column}) LIKE lower(?)";
1190     push @values, '%' . $form->{"${field}_${i}"} . '%';
1191   }
1192   #Es soll auch nach EAN gesucht werden, ohne Einschränkung durch Beschreibung
1193   if ($form->{"partnumber_$i"} && !$form->{"description_$i"}) {
1194       $where .= qq| OR (NOT p.obsolete = '1' AND p.ean = ? )|;
1195       push @values, $form->{"partnumber_$i"};
1196    }
1197
1198   # Search for part ID overrides all other criteria.
1199   if ($form->{"id_${i}"}) {
1200     $where  = qq|p.id = ?|;
1201     @values = ($form->{"id_${i}"});
1202   }
1203
1204   if ($form->{"description_$i"}) {
1205     $where .= " ORDER BY p.description";
1206   } else {
1207     $where .= " ORDER BY p.partnumber";
1208   }
1209
1210   my $transdate = "";
1211   if ($form->{type} eq "invoice") {
1212     $transdate = $form->{deliverydate} ? $dbh->quote($form->{deliverydate})
1213                : $form->{invdate} ? $dbh->quote($form->{invdate})
1214                : "current_date";
1215   } else {
1216     $transdate = $form->{transdate} ? $dbh->quote($form->{transdate}) : "current_date";
1217   }
1218
1219   my $taxzone_id = $form->{taxzone_id} * 1;
1220   $taxzone_id    = 0 if ((3 < $taxzone_id) || (0 > $taxzone_id));
1221
1222   my $query =
1223     qq|SELECT
1224          p.id, p.partnumber, p.description, p.lastcost AS sellprice, p.listprice,
1225          p.unit, p.assembly, p.onhand, p.formel,
1226          p.notes AS partnotes, p.notes AS longdescription, p.not_discountable,
1227          p.inventory_accno_id, p.price_factor_id,
1228
1229          pfac.factor AS price_factor,
1230
1231          c1.accno                         AS inventory_accno,
1232          c1.new_chart_id                  AS inventory_new_chart,
1233          date($transdate) - c1.valid_from AS inventory_valid,
1234
1235          c2.accno                         AS income_accno,
1236          c2.new_chart_id                  AS income_new_chart,
1237          date($transdate) - c2.valid_from AS income_valid,
1238
1239          c3.accno                         AS expense_accno,
1240          c3.new_chart_id                  AS expense_new_chart,
1241          date($transdate) - c3.valid_from AS expense_valid,
1242
1243          pg.partsgroup
1244
1245        FROM parts p
1246        LEFT JOIN chart c1 ON
1247          ((SELECT inventory_accno_id
1248            FROM buchungsgruppen
1249            WHERE id = p.buchungsgruppen_id) = c1.id)
1250        LEFT JOIN chart c2 ON
1251          ((SELECT income_accno_id_${taxzone_id}
1252            FROM buchungsgruppen
1253            WHERE id = p.buchungsgruppen_id) = c2.id)
1254        LEFT JOIN chart c3 ON
1255          ((SELECT expense_accno_id_${taxzone_id}
1256            FROM buchungsgruppen
1257            WHERE id = p.buchungsgruppen_id) = c3.id)
1258        LEFT JOIN partsgroup pg ON (pg.id = p.partsgroup_id)
1259        LEFT JOIN price_factors pfac ON (pfac.id = p.price_factor_id)
1260        WHERE $where|;
1261   my $sth = prepare_execute_query($form, $dbh, $query, @values);
1262
1263   my @translation_queries = ( [ qq|SELECT tr.translation, tr.longdescription
1264                                    FROM translation tr
1265                                    WHERE tr.language_id = ? AND tr.parts_id = ?| ],
1266                               [ qq|SELECT tr.translation, tr.longdescription
1267                                    FROM translation tr
1268                                    WHERE tr.language_id IN
1269                                      (SELECT id
1270                                       FROM language
1271                                       WHERE article_code = (SELECT article_code FROM language WHERE id = ?))
1272                                      AND tr.parts_id = ?
1273                                    LIMIT 1| ] );
1274   map { push @{ $_ }, prepare_query($form, $dbh, $_->[0]) } @translation_queries;
1275
1276   $form->{item_list} = [];
1277   while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
1278
1279     # In der Buchungsgruppe ist immer ein Bestandskonto verknuepft, auch wenn
1280     # es sich um eine Dienstleistung handelt. Bei Dienstleistungen muss das
1281     # Buchungskonto also aus dem Ergebnis rausgenommen werden.
1282     if (!$ref->{inventory_accno_id}) {
1283       map({ delete($ref->{"inventory_${_}"}); } qw(accno new_chart valid));
1284     }
1285     delete($ref->{inventory_accno_id});
1286
1287     # get tax rates and description
1288     my $accno_id = ($form->{vc} eq "customer") ? $ref->{income_accno} : $ref->{expense_accno};
1289     $query =
1290       qq|SELECT c.accno, t.taxdescription, t.rate, t.taxnumber
1291          FROM tax t
1292          LEFT JOIN chart c on (c.id = t.chart_id)
1293          WHERE t.id IN
1294            (SELECT tk.tax_id
1295             FROM taxkeys tk
1296             WHERE tk.chart_id =
1297               (SELECT id
1298                FROM chart
1299                WHERE accno = ?)
1300               AND (startdate <= $transdate)
1301             ORDER BY startdate DESC
1302             LIMIT 1)
1303          ORDER BY c.accno|;
1304     my $stw = prepare_execute_query($form, $dbh, $query, $accno_id);
1305
1306     $ref->{taxaccounts} = "";
1307     my $i = 0;
1308     while (my $ptr = $stw->fetchrow_hashref("NAME_lc")) {
1309
1310       if (($ptr->{accno} eq "") && ($ptr->{rate} == 0)) {
1311         $i++;
1312         $ptr->{accno} = $i;
1313       }
1314
1315       $ref->{taxaccounts} .= "$ptr->{accno} ";
1316
1317       if (!($form->{taxaccounts} =~ /\Q$ptr->{accno}\E/)) {
1318         $form->{"$ptr->{accno}_rate"}         = $ptr->{rate};
1319         $form->{"$ptr->{accno}_description"}  = $ptr->{taxdescription};
1320         $form->{"$ptr->{accno}_taxnumber"}    = $ptr->{taxnumber};
1321         $form->{taxaccounts}                 .= "$ptr->{accno} ";
1322       }
1323
1324       if ($form->{language_id}) {
1325         for my $spec (@translation_queries) {
1326           do_statement($form, $spec->[1], $spec->[0], conv_i($form->{language_id}), conv_i($ref->{id}));
1327           my ($translation, $longdescription) = $spec->[1]->fetchrow_array;
1328           next unless $translation;
1329           $ref->{description} = $translation;
1330           $ref->{longdescription} = $longdescription;
1331           last;
1332         }
1333       }
1334     }
1335
1336     $stw->finish();
1337     chop $ref->{taxaccounts};
1338
1339     $ref->{onhand} *= 1;
1340
1341     push @{ $form->{item_list} }, $ref;
1342
1343   }
1344
1345   $sth->finish();
1346   $_->[1]->finish for @translation_queries;
1347
1348   foreach my $item (@{ $form->{item_list} }) {
1349     my $custom_variables = CVar->get_custom_variables(module   => 'IC',
1350                                                       trans_id => $item->{id},
1351                                                       dbh      => $dbh,
1352                                                      );
1353
1354     map { $item->{"ic_cvar_" . $_->{name} } = $_->{value} } @{ $custom_variables };
1355   }
1356
1357   $dbh->disconnect();
1358
1359   $main::lxdebug->leave_sub();
1360 }
1361
1362 sub vendor_details {
1363   $main::lxdebug->enter_sub();
1364
1365   my ($self, $myconfig, $form, @wanted_vars) = @_;
1366
1367   # connect to database
1368   my $dbh = $form->dbconnect($myconfig);
1369
1370   my @values;
1371
1372   # get contact id, set it if nessessary
1373   $form->{cp_id} *= 1;
1374   my $contact = "";
1375   if ($form->{cp_id}) {
1376     $contact = "AND cp.cp_id = ?";
1377     push @values, $form->{cp_id};
1378   }
1379
1380   # get rest for the vendor
1381   # fax and phone and email as vendor*
1382   my $query =
1383     qq|SELECT ct.*, cp.*, ct.notes as vendornotes, phone as vendorphone, fax as vendorfax, email as vendoremail,
1384          cu.name AS currency
1385        FROM vendor ct
1386        LEFT JOIN contacts cp ON (ct.id = cp.cp_cv_id)
1387        LEFT JOIN currencies cu ON (ct.currency_id = cu.id)
1388        WHERE (ct.id = ?) $contact
1389        ORDER BY cp.cp_id
1390        LIMIT 1|;
1391   my $ref = selectfirst_hashref_query($form, $dbh, $query, $form->{vendor_id}, @values);
1392
1393   # remove id and taxincluded before copy back
1394   delete @$ref{qw(id taxincluded)};
1395
1396   @wanted_vars = grep({ $_ } @wanted_vars);
1397   if (scalar(@wanted_vars) > 0) {
1398     my %h_wanted_vars;
1399     map({ $h_wanted_vars{$_} = 1; } @wanted_vars);
1400     map({ delete($ref->{$_}) unless ($h_wanted_vars{$_}); } keys(%{$ref}));
1401   }
1402
1403   map { $form->{$_} = $ref->{$_} } keys %$ref;
1404
1405   my $custom_variables = CVar->get_custom_variables('dbh'      => $dbh,
1406                                                     'module'   => 'CT',
1407                                                     'trans_id' => $form->{vendor_id});
1408   map { $form->{"vc_cvar_$_->{name}"} = $_->{value} } @{ $custom_variables };
1409
1410   $form->{cp_greeting} = GenericTranslations->get('dbh'              => $dbh,
1411                                                   'translation_type' => 'greetings::' . ($form->{cp_gender} eq 'f' ? 'female' : 'male'),
1412                                                   'allow_fallback'   => 1);
1413
1414   $dbh->disconnect();
1415
1416   $main::lxdebug->leave_sub();
1417 }
1418
1419 sub item_links {
1420   $main::lxdebug->enter_sub();
1421
1422   my ($self, $myconfig, $form) = @_;
1423
1424   # connect to database
1425   my $dbh = $form->dbconnect($myconfig);
1426
1427   my $query =
1428     qq|SELECT accno, description, link
1429        FROM chart
1430        WHERE link LIKE '%IC%'
1431        ORDER BY accno|;
1432   my $sth = prepare_execute_query($query, $dbh, $query);
1433
1434   while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
1435     foreach my $key (split(/:/, $ref->{link})) {
1436       if ($key =~ /IC/) {
1437         push @{ $form->{IC_links}{$key} },
1438           { accno       => $ref->{accno},
1439             description => $ref->{description} };
1440       }
1441     }
1442   }
1443
1444   $sth->finish();
1445   $dbh->disconnect();
1446
1447   $main::lxdebug->leave_sub();
1448 }
1449
1450 sub _delete_payments {
1451   $main::lxdebug->enter_sub();
1452
1453   my ($self, $form, $dbh) = @_;
1454
1455   my @delete_acc_trans_ids;
1456
1457   # Delete old payment entries from acc_trans.
1458   my $query =
1459     qq|SELECT acc_trans_id
1460        FROM acc_trans
1461        WHERE (trans_id = ?) AND fx_transaction
1462
1463        UNION
1464
1465        SELECT at.acc_trans_id
1466        FROM acc_trans at
1467        LEFT JOIN chart c ON (at.chart_id = c.id)
1468        WHERE (trans_id = ?) AND (c.link LIKE '%AP_paid%')|;
1469   push @delete_acc_trans_ids, selectall_array_query($form, $dbh, $query, conv_i($form->{id}), conv_i($form->{id}));
1470
1471   $query =
1472     qq|SELECT at.acc_trans_id
1473        FROM acc_trans at
1474        LEFT JOIN chart c ON (at.chart_id = c.id)
1475        WHERE (trans_id = ?)
1476          AND ((c.link = 'AP') OR (c.link LIKE '%:AP') OR (c.link LIKE 'AP:%'))
1477        ORDER BY at.acc_trans_id
1478        OFFSET 1|;
1479   push @delete_acc_trans_ids, selectall_array_query($form, $dbh, $query, conv_i($form->{id}));
1480
1481   if (@delete_acc_trans_ids) {
1482     $query = qq|DELETE FROM acc_trans WHERE acc_trans_id IN (| . join(", ", @delete_acc_trans_ids) . qq|)|;
1483     do_query($form, $dbh, $query);
1484   }
1485
1486   $main::lxdebug->leave_sub();
1487 }
1488
1489 sub post_payment {
1490   $main::lxdebug->enter_sub();
1491
1492   my ($self, $myconfig, $form, $locale) = @_;
1493
1494   # connect to database, turn off autocommit
1495   my $dbh = $form->dbconnect_noauto($myconfig);
1496
1497   my (%payments, $old_form, $row, $item, $query, %keep_vars);
1498
1499   $old_form = save_form();
1500
1501   # Delete all entries in acc_trans from prior payments.
1502   if (SL::DB::Default->get->payments_changeable != 0) {
1503     $self->_delete_payments($form, $dbh);
1504   }
1505
1506   # Save the new payments the user made before cleaning up $form.
1507   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 };
1508
1509   # Clean up $form so that old content won't tamper the results.
1510   %keep_vars = map { $_, 1 } qw(login password id);
1511   map { delete $form->{$_} unless $keep_vars{$_} } keys %{ $form };
1512
1513   # Retrieve the invoice from the database.
1514   $self->retrieve_invoice($myconfig, $form);
1515
1516   # Set up the content of $form in the way that IR::post_invoice() expects.
1517   $form->{exchangerate} = $form->format_amount($myconfig, $form->{exchangerate});
1518
1519   for $row (1 .. scalar @{ $form->{invoice_details} }) {
1520     $item = $form->{invoice_details}->[$row - 1];
1521
1522     map { $item->{$_} = $form->format_amount($myconfig, $item->{$_}) } qw(qty sellprice);
1523
1524     map { $form->{"${_}_${row}"} = $item->{$_} } keys %{ $item };
1525   }
1526
1527   $form->{rowcount} = scalar @{ $form->{invoice_details} };
1528
1529   delete @{$form}{qw(invoice_details paidaccounts storno paid)};
1530
1531   # Restore the payment options from the user input.
1532   map { $form->{$_} = $payments{$_} } keys %payments;
1533
1534   # Get the AP accno (which is normally done by Form::create_links()).
1535   $query =
1536     qq|SELECT c.accno
1537        FROM acc_trans at
1538        LEFT JOIN chart c ON (at.chart_id = c.id)
1539        WHERE (trans_id = ?)
1540          AND ((c.link = 'AP') OR (c.link LIKE '%:AP') OR (c.link LIKE 'AP:%'))
1541        ORDER BY at.acc_trans_id
1542        LIMIT 1|;
1543
1544   ($form->{AP}) = selectfirst_array_query($form, $dbh, $query, conv_i($form->{id}));
1545
1546   # Post the new payments.
1547   $self->post_invoice($myconfig, $form, $dbh, 1);
1548
1549   restore_form($old_form);
1550
1551   my $rc = $dbh->commit();
1552   $dbh->disconnect();
1553
1554   $main::lxdebug->leave_sub();
1555
1556   return $rc;
1557 }
1558
1559 sub get_duedate {
1560   $::lxdebug->enter_sub;
1561
1562   my ($self, %params) = @_;
1563
1564   if (!$params{vendor_id} || !$params{invdate}) {
1565     $::lxdebug->leave_sub;
1566     return $params{default};
1567   }
1568
1569   my $dbh      = $::form->get_standard_dbh;
1570   my $query    = qq|SELECT ?::date + pt.terms_netto
1571                     FROM vendor v
1572                     LEFT JOIN payment_terms pt ON (pt.id = v.payment_id)
1573                     WHERE v.id = ?|;
1574
1575   my ($duedate) = selectfirst_array_query($::form, $dbh, $query, $params{invdate}, $params{vendor_id});
1576
1577   $duedate ||= $params{default};
1578
1579   $::lxdebug->leave_sub;
1580
1581   return $duedate;
1582 }
1583
1584
1585 1;