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