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