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