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