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