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