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