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