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