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