Anzahlungs-Rg.: Druckvariblen: offenen Betrag jeder Anzahlungs-Rg. und Summe
[kivitendo-erp.git] / SL / IS.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) 1998-2002
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 invoicing module
33 #
34 #======================================================================
35
36 package IS;
37
38 use List::Util qw(max sum0);
39 use List::MoreUtils qw(any);
40
41 use Carp;
42 use SL::AM;
43 use SL::ARAP;
44 use SL::CVar;
45 use SL::Common;
46 use SL::DATEV qw(:CONSTANTS);
47 use SL::DBUtils;
48 use SL::DO;
49 use SL::GenericTranslations;
50 use SL::HTML::Restrict;
51 use SL::MoreCommon;
52 use SL::IC;
53 use SL::IO;
54 use SL::TransNumber;
55 use SL::DB::Chart;
56 use SL::DB::Default;
57 use SL::DB::Draft;
58 use SL::DB::Tax;
59 use SL::DB::TaxZone;
60 use SL::TransNumber;
61 use SL::DB;
62 use SL::Presenter::Part qw(type_abbreviation classification_abbreviation);
63 use Data::Dumper;
64
65 use strict;
66 use constant PCLASS_OK             =>   0;
67 use constant PCLASS_NOTFORSALE     =>   1;
68 use constant PCLASS_NOTFORPURCHASE =>   2;
69
70 sub invoice_details {
71   $main::lxdebug->enter_sub();
72
73   # prepare invoice for printing
74
75   my ($self, $myconfig, $form, $locale) = @_;
76
77   $form->{duedate} ||= $form->{invdate};
78
79   # connect to database
80   my $dbh = $form->get_standard_dbh;
81   my $sth;
82
83   my (@project_ids);
84   $form->{TEMPLATE_ARRAYS} = {};
85
86   push(@project_ids, $form->{"globalproject_id"}) if ($form->{"globalproject_id"});
87
88   $form->get_lists('price_factors' => 'ALL_PRICE_FACTORS');
89   my %price_factors;
90
91   foreach my $pfac (@{ $form->{ALL_PRICE_FACTORS} }) {
92     $price_factors{$pfac->{id}}  = $pfac;
93     $pfac->{factor}             *= 1;
94     $pfac->{formatted_factor}    = $form->format_amount($myconfig, $pfac->{factor});
95   }
96
97   # sort items by partsgroup
98   for my $i (1 .. $form->{rowcount}) {
99 #    $partsgroup = "";
100 #    if ($form->{"partsgroup_$i"} && $form->{groupitems}) {
101 #      $partsgroup = $form->{"partsgroup_$i"};
102 #    }
103 #    push @partsgroup, [$i, $partsgroup];
104     push(@project_ids, $form->{"project_id_$i"}) if ($form->{"project_id_$i"});
105   }
106
107   my $projects = [];
108   my %projects_by_id;
109   if (@project_ids) {
110     $projects = SL::DB::Manager::Project->get_all(query => [ id => \@project_ids ]);
111     %projects_by_id = map { $_->id => $_ } @$projects;
112   }
113
114   if ($projects_by_id{$form->{"globalproject_id"}}) {
115     $form->{globalprojectnumber} = $projects_by_id{$form->{"globalproject_id"}}->projectnumber;
116     $form->{globalprojectdescription} = $projects_by_id{$form->{"globalproject_id"}}->description;
117
118     for (@{ $projects_by_id{$form->{"globalproject_id"}}->cvars_by_config }) {
119       $form->{"project_cvar_" . $_->config->name} = $_->value_as_text;
120     }
121   }
122
123   my $tax = 0;
124   my $item;
125   my $i;
126   my @partsgroup = ();
127   my $partsgroup;
128
129   # sort items by partsgroup
130   for $i (1 .. $form->{rowcount}) {
131     $partsgroup = "";
132     if ($form->{"partsgroup_$i"} && $form->{groupitems}) {
133       $partsgroup = $form->{"partsgroup_$i"};
134     }
135     push @partsgroup, [$i, $partsgroup];
136   }
137
138   my $sameitem = "";
139   my @taxaccounts;
140   my %taxaccounts;
141   my %taxbase;
142   my $taxrate;
143   my $taxamount;
144   my $taxbase;
145   my $taxdiff;
146   my $nodiscount;
147   my $yesdiscount;
148   my $nodiscount_subtotal = 0;
149   my $discount_subtotal = 0;
150   my $position = 0;
151   my $subtotal_header = 0;
152   my $subposition = 0;
153
154   $form->{discount} = [];
155
156   # get some values of parts from db on store them in extra array,
157   # so that they can be sorted in later
158   my %prepared_template_arrays = IC->prepare_parts_for_printing(myconfig => $myconfig, form => $form);
159   my @prepared_arrays          = keys %prepared_template_arrays;
160   my @separate_totals          = qw(non_separate_subtotal);
161
162   my $ic_cvar_configs = CVar->get_configs(module => 'IC');
163   my $project_cvar_configs = CVar->get_configs(module => 'Projects');
164
165   my @arrays =
166     qw(runningnumber number description longdescription qty qty_nofmt unit bin
167        deliverydate_oe ordnumber_oe donumber_do transdate_oe invnumber invdate
168        partnotes serialnumber reqdate sellprice sellprice_nofmt listprice listprice_nofmt netprice netprice_nofmt
169        discount discount_nofmt p_discount discount_sub discount_sub_nofmt nodiscount_sub nodiscount_sub_nofmt
170        linetotal linetotal_nofmt nodiscount_linetotal nodiscount_linetotal_nofmt tax_rate projectnumber projectdescription
171        price_factor price_factor_name partsgroup weight weight_nofmt lineweight lineweight_nofmt);
172
173   push @arrays, map { "ic_cvar_$_->{name}" } @{ $ic_cvar_configs };
174   push @arrays, map { "project_cvar_$_->{name}" } @{ $project_cvar_configs };
175
176   my @tax_arrays = qw(taxbase tax taxdescription taxrate taxnumber tax_id);
177
178   my @payment_arrays = qw(payment paymentaccount paymentdate paymentsource paymentmemo);
179
180   my @invoices_for_advance_payment_arrays = qw(iap_invnumber iap_transdate ifip_amount iap_taxamount);
181
182   map { $form->{TEMPLATE_ARRAYS}->{$_} = [] } (@arrays, @tax_arrays, @payment_arrays, @prepared_arrays, @invoices_for_advance_payment_arrays);
183
184   my $totalweight = 0;
185   foreach $item (sort { $a->[1] cmp $b->[1] } @partsgroup) {
186     $i = $item->[0];
187
188     if ($item->[1] ne $sameitem) {
189       push(@{ $form->{TEMPLATE_ARRAYS}->{entry_type}  }, 'partsgroup');
190       push(@{ $form->{TEMPLATE_ARRAYS}->{description} }, qq|$item->[1]|);
191       $sameitem = $item->[1];
192
193       map({ push(@{ $form->{TEMPLATE_ARRAYS}->{$_} }, "") } grep({ $_ ne "description" } (@arrays, @prepared_arrays)));
194     }
195
196     $form->{"qty_$i"} = $form->parse_amount($myconfig, $form->{"qty_$i"});
197
198     if ($form->{"id_$i"} != 0) {
199
200       # Prepare linked items for printing
201       if ( $form->{"invoice_id_$i"} ) {
202
203         require SL::DB::InvoiceItem;
204         my $invoice_item = SL::DB::Manager::InvoiceItem->find_by( id => $form->{"invoice_id_$i"} );
205         my $linkeditems  = $invoice_item->linked_records( direction => 'from', recursive => 1 );
206
207         # check for (recursively) linked sales quotation items, sales order
208         # items and sales delivery order items.
209
210         # The checks for $form->{"ordnumber_$i"} and quo and do are for the old
211         # behaviour, where this data was stored in its own database fields in
212         # the invoice items, and there were no record links for the items.
213
214         # If this information were to be fetched in retrieve_invoice, e.g. for showing
215         # this information in the second row, then these fields will already have
216         # been set and won't be calculated again. This shouldn't be done there
217         # though, as each invocation creates several database calls per item, and would
218         # make the interface very slow for many items. So currently these
219         # requests are only made when printing the record.
220
221         # When using the workflow an invoice item can only be (recursively) linked to at
222         # most one sales quotation item and at most one delivery order item.  But it may
223         # be linked back to several order items, if collective orders were involved. If
224         # that is the case we will always choose the very first order item from the
225         # original order, i.e. where it first appeared in an order.
226
227         # TODO: credit note items aren't checked for a record link to their
228         # invoice item
229
230         unless ( $form->{"ordnumber_$i"} ) {
231
232           # $form->{"ordnumber_$i"} comes from ordnumber in invoice, if an
233           # entry exists this must be from before the change from ordnumber to linked items.
234           # So we just use that value and don't check for linked items.
235           # In that case there won't be any links for quo or do items either
236
237           # sales order items are fetched and sorted by id, the lowest id is first
238           # It is assumed that the id always grows, so the item we want (the original) will have the lowest id
239           # better solution: filter the order_item that doesn't have any links from other order_items
240           #                  or maybe fetch linked_records with param save_path and order by _record_length_depth
241           my @linked_orderitems = grep { $_->isa("SL::DB::OrderItem") && $_->record->type eq 'sales_order' } @{$linkeditems};
242           if ( scalar @linked_orderitems ) {
243             @linked_orderitems = sort { $a->id <=> $b->id } @linked_orderitems;
244             my $orderitem = $linked_orderitems[0]; # 0: the original order item, -1: the last collective order item
245
246             $form->{"ordnumber_$i"}       = $orderitem->record->record_number;
247             $form->{"transdate_oe_$i"}    = $orderitem->record->transdate->to_kivitendo;
248             $form->{"cusordnumber_oe_$i"} = $orderitem->record->cusordnumber;
249           };
250
251           my @linked_quoitems = grep { $_->isa("SL::DB::OrderItem") && $_->record->type eq 'sales_quotation' } @{$linkeditems};
252           if ( scalar @linked_quoitems ) {
253             croak "an invoice item may only be linked back to 1 sales quotation item, something is wrong\n" unless scalar @linked_quoitems == 1;
254             $form->{"quonumber_$i"}     = $linked_quoitems[0]->record->record_number;
255             $form->{"transdate_quo_$i"} = $linked_quoitems[0]->record->transdate->to_kivitendo;
256           };
257
258           my @linked_deliveryorderitems = grep { $_->isa("SL::DB::DeliveryOrderItem") && $_->record->type eq 'sales_delivery_order' } @{$linkeditems};
259           if ( scalar @linked_deliveryorderitems ) {
260             croak "an invoice item may only be linked back to 1 sales delivery item, something is wrong\n" unless scalar @linked_deliveryorderitems == 1;
261             $form->{"donumber_$i"}     = $linked_deliveryorderitems[0]->record->record_number;
262             $form->{"transdate_do_$i"} = $linked_deliveryorderitems[0]->record->transdate->to_kivitendo;
263           };
264         };
265       };
266
267
268       # add number, description and qty to $form->{number},
269       if ($form->{"subtotal_$i"} && !$subtotal_header) {
270         $subtotal_header = $i;
271         $position = int($position);
272         $subposition = 0;
273         $position++;
274       } elsif ($subtotal_header) {
275         $subposition += 1;
276         $position = int($position);
277         $position = $position.".".$subposition;
278       } else {
279         $position = int($position);
280         $position++;
281       }
282
283       my $price_factor = $price_factors{$form->{"price_factor_id_$i"}} || { 'factor' => 1 };
284
285       push(@{ $form->{TEMPLATE_ARRAYS}->{$_} },                $prepared_template_arrays{$_}[$i - 1]) for @prepared_arrays;
286
287       push @{ $form->{TEMPLATE_ARRAYS}->{entry_type} },        'normal';
288       push @{ $form->{TEMPLATE_ARRAYS}->{runningnumber} },     $position;
289       push @{ $form->{TEMPLATE_ARRAYS}->{number} },            $form->{"partnumber_$i"};
290       push @{ $form->{TEMPLATE_ARRAYS}->{serialnumber} },      $form->{"serialnumber_$i"};
291       push @{ $form->{TEMPLATE_ARRAYS}->{bin} },               $form->{"bin_$i"};
292       push @{ $form->{TEMPLATE_ARRAYS}->{partnotes} },         $form->{"partnotes_$i"};
293       push @{ $form->{TEMPLATE_ARRAYS}->{description} },       $form->{"description_$i"};
294       push @{ $form->{TEMPLATE_ARRAYS}->{longdescription} },   $form->{"longdescription_$i"};
295       push @{ $form->{TEMPLATE_ARRAYS}->{qty} },               $form->format_amount($myconfig, $form->{"qty_$i"});
296       push @{ $form->{TEMPLATE_ARRAYS}->{qty_nofmt} },         $form->{"qty_$i"};
297       push @{ $form->{TEMPLATE_ARRAYS}->{unit} },              $form->{"unit_$i"};
298       push @{ $form->{TEMPLATE_ARRAYS}->{deliverydate_oe} },   $form->{"reqdate_$i"};
299       push @{ $form->{TEMPLATE_ARRAYS}->{sellprice} },         $form->{"sellprice_$i"};
300       push @{ $form->{TEMPLATE_ARRAYS}->{sellprice_nofmt} },   $form->parse_amount($myconfig, $form->{"sellprice_$i"});
301       # linked item print variables
302       push @{ $form->{TEMPLATE_ARRAYS}->{quonumber_quo} },     $form->{"quonumber_$i"};
303       push @{ $form->{TEMPLATE_ARRAYS}->{transdate_quo} },     $form->{"transdate_quo_$i"};
304       push @{ $form->{TEMPLATE_ARRAYS}->{ordnumber_oe} },      $form->{"ordnumber_$i"};
305       push @{ $form->{TEMPLATE_ARRAYS}->{transdate_oe} },      $form->{"transdate_oe_$i"};
306       push @{ $form->{TEMPLATE_ARRAYS}->{cusordnumber_oe} },   $form->{"cusordnumber_oe_$i"};
307       push @{ $form->{TEMPLATE_ARRAYS}->{donumber_do} },       $form->{"donumber_$i"};
308       push @{ $form->{TEMPLATE_ARRAYS}->{transdate_do} },      $form->{"transdate_do_$i"};
309
310       push @{ $form->{TEMPLATE_ARRAYS}->{invnumber} },         $form->{"invnumber"};
311       push @{ $form->{TEMPLATE_ARRAYS}->{invdate} },           $form->{"invdate"};
312       push @{ $form->{TEMPLATE_ARRAYS}->{price_factor} },      $price_factor->{formatted_factor};
313       push @{ $form->{TEMPLATE_ARRAYS}->{price_factor_name} }, $price_factor->{description};
314       push @{ $form->{TEMPLATE_ARRAYS}->{partsgroup} },        $form->{"partsgroup_$i"};
315       push @{ $form->{TEMPLATE_ARRAYS}->{reqdate} },           $form->{"reqdate_$i"};
316       push @{ $form->{TEMPLATE_ARRAYS}->{listprice} },         $form->format_amount($myconfig, $form->{"listprice_$i"}, 2);
317       push(@{ $form->{TEMPLATE_ARRAYS}->{listprice_nofmt} },   $form->{"listprice_$i"});
318
319       my $sellprice     = $form->parse_amount($myconfig, $form->{"sellprice_$i"});
320       my ($dec)         = ($sellprice =~ /\.(\d+)/);
321       my $decimalplaces = max 2, length($dec);
322
323       my $parsed_discount            = $form->parse_amount($myconfig, $form->{"discount_$i"});
324
325       my $linetotal_exact            = $form->{"qty_$i"} * $sellprice * (100 - $parsed_discount) / 100 / $price_factor->{factor};
326       my $linetotal                  = $form->round_amount($linetotal_exact, 2);
327
328       my $nodiscount_exact_linetotal = $form->{"qty_$i"} * $sellprice                                  / $price_factor->{factor};
329       my $nodiscount_linetotal       = $form->round_amount($nodiscount_exact_linetotal,2);
330
331       my $discount                   = $nodiscount_linetotal - $linetotal; # is always rounded because $nodiscount_linetotal and $linetotal are rounded
332
333       my $discount_round_error       = $discount + ($linetotal_exact - $nodiscount_exact_linetotal); # not used
334
335       $form->{"netprice_$i"}   = $form->round_amount($form->{"qty_$i"} ? ($linetotal / $form->{"qty_$i"}) : 0, $decimalplaces);
336
337       push @{ $form->{TEMPLATE_ARRAYS}->{netprice} },       ($form->{"netprice_$i"} != 0) ? $form->format_amount($myconfig, $form->{"netprice_$i"}, $decimalplaces) : '';
338       push @{ $form->{TEMPLATE_ARRAYS}->{netprice_nofmt} }, ($form->{"netprice_$i"} != 0) ? $form->{"netprice_$i"} : '';
339
340       $linetotal = ($linetotal != 0) ? $linetotal : '';
341
342       push @{ $form->{TEMPLATE_ARRAYS}->{discount} },       ($discount != 0) ? $form->format_amount($myconfig, $discount * -1, 2) : '';
343       push @{ $form->{TEMPLATE_ARRAYS}->{discount_nofmt} }, ($discount != 0) ? $discount * -1 : '';
344       push @{ $form->{TEMPLATE_ARRAYS}->{p_discount} },     $form->{"discount_$i"};
345
346       if ( $prepared_template_arrays{separate}[$i - 1]  ) {
347         my $pabbr = $prepared_template_arrays{separate}[$i - 1];
348         if ( ! $form->{"separate_${pabbr}_subtotal"} ) {
349             push @separate_totals , "separate_${pabbr}_subtotal";
350             $form->{"separate_${pabbr}_subtotal"} = 0;
351         }
352         $form->{"separate_${pabbr}_subtotal"} += $linetotal;
353       } else {
354         $form->{non_separate_subtotal} += $linetotal;
355       }
356
357       $form->{total}            += $linetotal;
358       $form->{nodiscount_total} += $nodiscount_linetotal;
359       $form->{discount_total}   += $discount;
360
361       if ($subtotal_header) {
362         $discount_subtotal   += $linetotal;
363         $nodiscount_subtotal += $nodiscount_linetotal;
364       }
365
366       if ($form->{"subtotal_$i"} && $subtotal_header && ($subtotal_header != $i)) {
367         push @{ $form->{TEMPLATE_ARRAYS}->{discount_sub} },         $form->format_amount($myconfig, $discount_subtotal,   2);
368         push @{ $form->{TEMPLATE_ARRAYS}->{discount_sub_nofmt} },   $discount_subtotal;
369         push @{ $form->{TEMPLATE_ARRAYS}->{nodiscount_sub} },       $form->format_amount($myconfig, $nodiscount_subtotal, 2);
370         push @{ $form->{TEMPLATE_ARRAYS}->{nodiscount_sub_nofmt} }, $nodiscount_subtotal;
371
372         $discount_subtotal   = 0;
373         $nodiscount_subtotal = 0;
374         $subtotal_header     = 0;
375
376       } else {
377         push @{ $form->{TEMPLATE_ARRAYS}->{$_} }, "" for qw(discount_sub nodiscount_sub discount_sub_nofmt nodiscount_sub_nofmt);
378       }
379
380       if (!$form->{"discount_$i"}) {
381         $nodiscount += $linetotal;
382       }
383
384       push @{ $form->{TEMPLATE_ARRAYS}->{linetotal} },                  $form->format_amount($myconfig, $linetotal, 2);
385       push @{ $form->{TEMPLATE_ARRAYS}->{linetotal_nofmt} },            $linetotal_exact;
386       push @{ $form->{TEMPLATE_ARRAYS}->{nodiscount_linetotal} },       $form->format_amount($myconfig, $nodiscount_linetotal, 2);
387       push @{ $form->{TEMPLATE_ARRAYS}->{nodiscount_linetotal_nofmt} }, $nodiscount_linetotal;
388
389       my $project = $projects_by_id{$form->{"project_id_$i"}} || SL::DB::Project->new;
390
391       push @{ $form->{TEMPLATE_ARRAYS}->{projectnumber} },              $project->projectnumber;
392       push @{ $form->{TEMPLATE_ARRAYS}->{projectdescription} },         $project->description;
393
394       my $lineweight = $form->{"qty_$i"} * $form->{"weight_$i"};
395       $totalweight += $lineweight;
396       push @{ $form->{TEMPLATE_ARRAYS}->{weight} },            $form->format_amount($myconfig, $form->{"weight_$i"}, 3);
397       push @{ $form->{TEMPLATE_ARRAYS}->{weight_nofmt} },      $form->{"weight_$i"};
398       push @{ $form->{TEMPLATE_ARRAYS}->{lineweight} },        $form->format_amount($myconfig, $lineweight, 3);
399       push @{ $form->{TEMPLATE_ARRAYS}->{lineweight_nofmt} },  $lineweight;
400
401       @taxaccounts = split(/ /, $form->{"taxaccounts_$i"});
402       $taxrate     = 0;
403       $taxdiff     = 0;
404
405       map { $taxrate += $form->{"${_}_rate"} } @taxaccounts;
406
407       if ($form->{taxincluded}) {
408
409         # calculate tax
410         $taxamount = $linetotal * $taxrate / (1 + $taxrate);
411         $taxbase = $linetotal - $taxamount;
412       } else {
413         $taxamount = $linetotal * $taxrate;
414         $taxbase   = $linetotal;
415       }
416
417       if ($form->round_amount($taxrate, 7) == 0) {
418         if ($form->{taxincluded}) {
419           foreach my $accno (@taxaccounts) {
420             $taxamount            = $form->round_amount($linetotal * $form->{"${accno}_rate"} / (1 + abs($form->{"${accno}_rate"})), 2);
421
422             $taxaccounts{$accno} += $taxamount;
423             $taxdiff             += $taxamount;
424
425             $taxbase{$accno}     += $taxbase;
426           }
427           $taxaccounts{ $taxaccounts[0] } += $taxdiff;
428         } else {
429           foreach my $accno (@taxaccounts) {
430             $taxaccounts{$accno} += $linetotal * $form->{"${accno}_rate"};
431             $taxbase{$accno}     += $taxbase;
432           }
433         }
434       } else {
435         foreach my $accno (@taxaccounts) {
436           $taxaccounts{$accno} += $taxamount * $form->{"${accno}_rate"} / $taxrate;
437           $taxbase{$accno}     += $taxbase;
438         }
439       }
440       my $tax_rate = $taxrate * 100;
441       push(@{ $form->{TEMPLATE_ARRAYS}->{tax_rate} }, qq|$tax_rate|);
442       if ($form->{"part_type_$i"} eq 'assembly') {
443         $sameitem = "";
444
445         # get parts and push them onto the stack
446         my $sortorder = "";
447         if ($form->{groupitems}) {
448           $sortorder =
449             qq|ORDER BY pg.partsgroup, a.position|;
450         } else {
451           $sortorder = qq|ORDER BY a.position|;
452         }
453
454         my $query =
455           qq|SELECT p.partnumber, p.description, p.unit, a.qty, pg.partsgroup
456              FROM assembly a
457              JOIN parts p ON (a.parts_id = p.id)
458              LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
459              WHERE (a.bom = '1') AND (a.id = ?) $sortorder|;
460         $sth = prepare_execute_query($form, $dbh, $query, conv_i($form->{"id_$i"}));
461
462         while (my $ref = $sth->fetchrow_hashref('NAME_lc')) {
463           if ($form->{groupitems} && $ref->{partsgroup} ne $sameitem) {
464             map({ push(@{ $form->{TEMPLATE_ARRAYS}->{$_} }, "") } grep({ $_ ne "description" } (@arrays, @prepared_arrays)));
465             $sameitem = ($ref->{partsgroup}) ? $ref->{partsgroup} : "--";
466             push(@{ $form->{TEMPLATE_ARRAYS}->{entry_type}  }, 'assembly-item-partsgroup');
467             push(@{ $form->{TEMPLATE_ARRAYS}->{description} }, $sameitem);
468           }
469
470           map { $form->{"a_$_"} = $ref->{$_} } qw(partnumber description);
471
472           push(@{ $form->{TEMPLATE_ARRAYS}->{entry_type}  }, 'assembly-item');
473           push(@{ $form->{TEMPLATE_ARRAYS}->{description} },
474                $form->format_amount($myconfig, $ref->{qty} * $form->{"qty_$i"}
475                  )
476                  . qq| -- $form->{"a_partnumber"}, $form->{"a_description"}|);
477           map({ push(@{ $form->{TEMPLATE_ARRAYS}->{$_} }, "") } grep({ $_ ne "description" } (@arrays, @prepared_arrays)));
478
479         }
480         $sth->finish;
481       }
482
483       CVar->get_non_editable_ic_cvars(form               => $form,
484                                       dbh                => $dbh,
485                                       row                => $i,
486                                       sub_module         => 'invoice',
487                                       may_converted_from => ['delivery_order_items', 'orderitems', 'invoice']);
488
489       push @{ $form->{TEMPLATE_ARRAYS}->{"ic_cvar_$_->{name}"} },
490         CVar->format_to_template(CVar->parse($form->{"ic_cvar_$_->{name}_$i"}, $_), $_)
491           for @{ $ic_cvar_configs };
492
493       push @{ $form->{TEMPLATE_ARRAYS}->{"project_cvar_" . $_->config->name} }, $_->value_as_text for @{ $project->cvars_by_config };
494     }
495   }
496
497   $form->{totalweight}       = $form->format_amount($myconfig, $totalweight, 3);
498   $form->{totalweight_nofmt} = $totalweight;
499   my $defaults = AM->get_defaults();
500   $form->{weightunit}        = $defaults->{weightunit};
501
502   foreach my $item (sort keys %taxaccounts) {
503     $tax += $taxamount = $form->round_amount($taxaccounts{$item}, 2);
504
505     push(@{ $form->{TEMPLATE_ARRAYS}->{taxbase} },        $form->format_amount($myconfig, $taxbase{$item}, 2));
506     push(@{ $form->{TEMPLATE_ARRAYS}->{taxbase_nofmt} },  $taxbase{$item});
507     push(@{ $form->{TEMPLATE_ARRAYS}->{tax} },            $form->format_amount($myconfig, $taxamount,      2));
508     push(@{ $form->{TEMPLATE_ARRAYS}->{tax_nofmt} },      $taxamount );
509     push(@{ $form->{TEMPLATE_ARRAYS}->{taxrate} },        $form->format_amount($myconfig, $form->{"${item}_rate"} * 100));
510     push(@{ $form->{TEMPLATE_ARRAYS}->{taxrate_nofmt} },  $form->{"${item}_rate"} * 100);
511     push(@{ $form->{TEMPLATE_ARRAYS}->{taxnumber} },      $form->{"${item}_taxnumber"});
512     push(@{ $form->{TEMPLATE_ARRAYS}->{tax_id} },         $form->{"${item}_tax_id"});
513
514     # taxnumber (= accno) is used for grouping the amounts of the various taxes and as a prefix in form
515
516     # This code used to assume that at most one tax entry can point to the same
517     # chart_id, even though chart_id does not have a unique constraint!
518
519     # This chart_id was then looked up via its accno, which is the key that is
520     # used to group the different taxes by for a record
521
522     # As we now also store the tax_id we can use that to look up the tax
523     # instead, this is only done here to get the (translated) taxdescription.
524
525     if ( $form->{"${item}_tax_id"} ) {
526       my $tax_obj = SL::DB::Manager::Tax->find_by(id => $form->{"${item}_tax_id"}) or die "Can't find tax with id " . $form->{"${item}_tax_id"};
527       my $description = $tax_obj ? $tax_obj->translated_attribute('taxdescription',  $form->{language_id}, 0) : '';
528       push(@{ $form->{TEMPLATE_ARRAYS}->{taxdescription} }, $description . q{ } . 100 * $form->{"${item}_rate"} . q{%});
529     }
530
531   }
532
533   for my $i (1 .. $form->{paidaccounts}) {
534     if ($form->{"paid_$i"}) {
535       my ($accno, $description) = split(/--/, $form->{"AR_paid_$i"});
536
537       push(@{ $form->{TEMPLATE_ARRAYS}->{payment} },        $form->{"paid_$i"});
538       push(@{ $form->{TEMPLATE_ARRAYS}->{paymentaccount} }, $description);
539       push(@{ $form->{TEMPLATE_ARRAYS}->{paymentdate} },    $form->{"datepaid_$i"});
540       push(@{ $form->{TEMPLATE_ARRAYS}->{paymentsource} },  $form->{"source_$i"});
541       push(@{ $form->{TEMPLATE_ARRAYS}->{paymentmemo} },    $form->{"memo_$i"});
542
543       $form->{paid} += $form->parse_amount($myconfig, $form->{"paid_$i"});
544     }
545   }
546   if($form->{taxincluded}) {
547     $form->{subtotal}       = $form->format_amount($myconfig, $form->{total} - $tax, 2);
548     $form->{subtotal_nofmt} = $form->{total} - $tax;
549   }
550   else {
551     $form->{subtotal}       = $form->format_amount($myconfig, $form->{total}, 2);
552     $form->{subtotal_nofmt} = $form->{total};
553   }
554
555   $form->{nodiscount_subtotal} = $form->format_amount($myconfig, $form->{nodiscount_total}, 2);
556   $form->{discount_total}      = $form->format_amount($myconfig, $form->{discount_total}, 2);
557   $form->{nodiscount}          = $form->format_amount($myconfig, $nodiscount, 2);
558   $form->{yesdiscount}         = $form->format_amount($myconfig, $form->{nodiscount_total} - $nodiscount, 2);
559
560   my $grossamount = ($form->{taxincluded}) ? $form->{total} : $form->{total} + $tax;
561   $form->{invtotal} = $form->round_amount($grossamount, 2, 1);
562   $form->{rounding} = $form->round_amount(
563     $form->{invtotal} - $form->round_amount($grossamount, 2),
564     2
565   );
566
567   $form->{rounding} = $form->format_amount($myconfig, $form->{rounding}, 2);
568   $form->{total}    = $form->format_amount($myconfig, $form->{invtotal} - $form->{paid}, 2);
569   $form->{invtotal} = $form->format_amount($myconfig, $form->{invtotal}, 2);
570   $form->{paid}     = $form->format_amount($myconfig, $form->{paid}, 2);
571
572   $form->set_payment_options($myconfig, $form->{invdate}, 'sales_invoice');
573
574   $form->{department}    = SL::DB::Manager::Department->find_by(id => $form->{department_id})->description if $form->{department_id};
575   $form->{delivery_term} = SL::DB::Manager::DeliveryTerm->find_by(id => $form->{delivery_term_id} || undef);
576   $form->{delivery_term}->description_long($form->{delivery_term}->translated_attribute('description_long', $form->{language_id})) if $form->{delivery_term} && $form->{language_id};
577
578   $form->{username} = $myconfig->{name};
579   $form->{$_} = $form->format_amount($myconfig, $form->{$_}, 2) for @separate_totals;
580
581   foreach my $invoice_for_advance_payment (@{$self->_get_invoices_for_advance_payment($form->{convert_from_ar_ids} || $form->{id})}) {
582     # Collect VAT of invoices for advance payment.
583     # Set sellprices to fxsellprices for items, because
584     # the PriceTaxCalculator sets fxsellprice from sellprice before calculating.
585     $_->sellprice($_->fxsellprice) for @{$invoice_for_advance_payment->items};
586     my %pat       = $invoice_for_advance_payment->calculate_prices_and_taxes;
587     my $taxamount = sum0 values %{ $pat{taxes_by_tax_id} };
588
589     push(@{ $form->{TEMPLATE_ARRAYS}->{"iap_$_"} },                $invoice_for_advance_payment->$_) for qw(invnumber transdate);
590     push(@{ $form->{TEMPLATE_ARRAYS}->{"iap_amount_nofmt"} },      $invoice_for_advance_payment->amount);
591     push(@{ $form->{TEMPLATE_ARRAYS}->{"iap_amount"} },            $invoice_for_advance_payment->amount_as_number);
592     push(@{ $form->{TEMPLATE_ARRAYS}->{"iap_taxamount_nofmt"} },   $taxamount);
593     push(@{ $form->{TEMPLATE_ARRAYS}->{"iap_taxamount"} },         $form->format_amount($myconfig, $taxamount, 2));
594
595     my $open_amount = $form->round_amount($invoice_for_advance_payment->open_amount, 2);
596     push(@{ $form->{TEMPLATE_ARRAYS}->{"iap_open_amount_nofmt"} }, $open_amount);
597     push(@{ $form->{TEMPLATE_ARRAYS}->{"iap_open_amount"} },       $form->format_amount($myconfig, $open_amount, 2));
598
599     $form->{iap_amount_nofmt}      += $invoice_for_advance_payment->amount;
600     $form->{iap_taxamount_nofmt}   += $taxamount;
601     $form->{iap_open_amount_nofmt} += $open_amount;
602     $form->{iap_existing}           = 1;
603   }
604   $form->{iap_amount}      = $form->format_amount($myconfig, $form->{iap_amount_nofmt},      2);
605   $form->{iap_taxamount}   = $form->format_amount($myconfig, $form->{iap_taxamount_nofmt},   2);
606   $form->{iap_open_amount} = $form->format_amount($myconfig, $form->{iap_open_amount_nofmt}, 2);
607
608   $main::lxdebug->leave_sub();
609 }
610
611 sub customer_details {
612   $main::lxdebug->enter_sub();
613
614   my ($self, $myconfig, $form, @wanted_vars) = @_;
615
616   # connect to database
617   my $dbh = $form->get_standard_dbh;
618
619   my $language_id = $form->{language_id};
620
621   # get contact id, set it if nessessary
622   $form->{cp_id} *= 1;
623
624   my @values =  (conv_i($form->{customer_id}));
625
626   my $where = "";
627   if ($form->{cp_id}) {
628     $where = qq| AND (cp.cp_id = ?) |;
629     push(@values, conv_i($form->{cp_id}));
630   }
631
632   # get rest for the customer
633   my $query =
634     qq|SELECT ct.*, cp.*, ct.notes as customernotes,
635          ct.phone AS customerphone, ct.fax AS customerfax, ct.email AS customeremail,
636          cu.name AS currency
637        FROM customer ct
638        LEFT JOIN contacts cp on ct.id = cp.cp_cv_id
639        LEFT JOIN currencies cu ON (ct.currency_id = cu.id)
640        WHERE (ct.id = ?) $where
641        ORDER BY cp.cp_id
642        LIMIT 1|;
643   my $ref = selectfirst_hashref_query($form, $dbh, $query, @values);
644   # we have no values, probably a invalid contact person. hotfix and first idea for issue #10
645   if (!$ref) {
646     my $customer = SL::DB::Manager::Customer->find_by(id => $::form->{customer_id});
647     if ($customer) {
648       $ref->{name} = $customer->name;
649       $ref->{street} = $customer->street;
650       $ref->{zipcode} = $customer->zipcode;
651       $ref->{country} = $customer->country;
652       $ref->{gln} = $customer->gln;
653     }
654     my $contact = SL::DB::Manager::Contact->find_by(cp_id => $::form->{cp_id});
655     if ($contact) {
656       $ref->{cp_name} = $contact->cp_name;
657       $ref->{cp_givenname} = $contact->cp_givenname;
658       $ref->{cp_gender} = $contact->cp_gender;
659     }
660   }
661   # remove id,notes (double of customernotes) and taxincluded before copy back
662   delete @$ref{qw(id taxincluded notes)};
663
664   @wanted_vars = grep({ $_ } @wanted_vars);
665   if (scalar(@wanted_vars) > 0) {
666     my %h_wanted_vars;
667     map({ $h_wanted_vars{$_} = 1; } @wanted_vars);
668     map({ delete($ref->{$_}) unless ($h_wanted_vars{$_}); } keys(%{$ref}));
669   }
670
671   map { $form->{$_} = $ref->{$_} } keys %$ref;
672
673   if ($form->{delivery_customer_id}) {
674     $query =
675       qq|SELECT *, notes as customernotes
676          FROM customer
677          WHERE id = ?
678          LIMIT 1|;
679     $ref = selectfirst_hashref_query($form, $dbh, $query, conv_i($form->{delivery_customer_id}));
680
681     map { $form->{"dc_$_"} = $ref->{$_} } keys %$ref;
682   }
683
684   if ($form->{delivery_vendor_id}) {
685     $query =
686       qq|SELECT *, notes as customernotes
687          FROM customer
688          WHERE id = ?
689          LIMIT 1|;
690     $ref = selectfirst_hashref_query($form, $dbh, $query, conv_i($form->{delivery_vendor_id}));
691
692     map { $form->{"dv_$_"} = $ref->{$_} } keys %$ref;
693   }
694
695   my $custom_variables = CVar->get_custom_variables('dbh'      => $dbh,
696                                                     'module'   => 'CT',
697                                                     'trans_id' => $form->{customer_id});
698   map { $form->{"vc_cvar_$_->{name}"} = $_->{value} } @{ $custom_variables };
699
700   if ($form->{cp_id}) {
701     $custom_variables = CVar->get_custom_variables(dbh      => $dbh,
702                                                    module   => 'Contacts',
703                                                    trans_id => $form->{cp_id});
704     $form->{"cp_cvar_$_->{name}"} = $_->{value} for @{ $custom_variables };
705   }
706
707   $form->{cp_greeting} = GenericTranslations->get('dbh'              => $dbh,
708                                                   'translation_type' => 'greetings::' . ($form->{cp_gender} eq 'f' ? 'female' : 'male'),
709                                                   'language_id'      => $language_id,
710                                                   'allow_fallback'   => 1);
711
712
713   $main::lxdebug->leave_sub();
714 }
715
716 sub post_invoice {
717   my ($self, $myconfig, $form, $provided_dbh, %params) = @_;
718   $main::lxdebug->enter_sub();
719
720   my $rc = SL::DB->client->with_transaction(\&_post_invoice, $self, $myconfig, $form, $provided_dbh, %params);
721
722   $::lxdebug->leave_sub;
723   return $rc;
724 }
725
726 sub _post_invoice {
727   my ($self, $myconfig, $form, $provided_dbh, %params) = @_;
728
729   my $payments_only = $params{payments_only};
730   my $dbh = $provided_dbh || SL::DB->client->dbh;
731   my $restricter = SL::HTML::Restrict->create;
732
733   my ($query, $sth, $null, $project_id, @values);
734   my $exchangerate = 0;
735
736   my $ic_cvar_configs = CVar->get_configs(module => 'IC',
737                                           dbh    => $dbh);
738
739   if (!$form->{employee_id}) {
740     $form->get_employee($dbh);
741   }
742
743   $form->{defaultcurrency} = $form->get_default_currency($myconfig);
744   my $defaultcurrency = $form->{defaultcurrency};
745
746   my $all_units = AM->retrieve_units($myconfig, $form);
747
748   my $already_booked = !!$form->{id};
749
750   if (!$payments_only) {
751     if ($form->{storno}) {
752       _delete_transfers($dbh, $form, $form->{storno_id});
753     }
754     if ($form->{id}) {
755       &reverse_invoice($dbh, $form);
756       _delete_transfers($dbh, $form, $form->{id});
757
758     } else {
759       my $trans_number   = SL::TransNumber->new(type => $form->{type}, dbh => $dbh, number => $form->{invnumber}, save => 1);
760       $form->{invnumber} = $trans_number->create_unique unless $trans_number->is_unique;
761
762       $query = qq|SELECT nextval('glid')|;
763       ($form->{"id"}) = selectrow_query($form, $dbh, $query);
764
765       $query = qq|INSERT INTO ar (id, invnumber, currency_id, taxzone_id) VALUES (?, ?, (SELECT id FROM currencies WHERE name=?), ?)|;
766       do_query($form, $dbh, $query, $form->{"id"}, $form->{"id"}, $form->{currency}, $form->{taxzone_id});
767
768       if (!$form->{invnumber}) {
769         my $trans_number   = SL::TransNumber->new(type => $form->{type}, dbh => $dbh, number => $form->{invnumber}, id => $form->{id});
770         $form->{invnumber} = $trans_number->create_unique;
771       }
772     }
773   }
774
775   my ($netamount, $invoicediff) = (0, 0);
776   my ($amount, $linetotal, $lastincomeaccno);
777
778   if ($form->{currency} eq $defaultcurrency) {
779     $form->{exchangerate} = 1;
780   } else {
781     $exchangerate = $form->check_exchangerate($myconfig, $form->{currency}, $form->{invdate}, 'buy');
782   }
783
784   $form->{exchangerate} =
785     ($exchangerate)
786     ? $exchangerate
787     : $form->parse_amount($myconfig, $form->{exchangerate});
788
789   $form->{expense_inventory} = "";
790
791   my %baseunits;
792
793   $form->get_lists('price_factors' => 'ALL_PRICE_FACTORS');
794   my %price_factors = map { $_->{id} => $_->{factor} } @{ $form->{ALL_PRICE_FACTORS} };
795   my $price_factor;
796
797   $form->{amount}      = {};
798   $form->{amount_cogs} = {};
799
800   my @processed_invoice_ids;
801
802   foreach my $i (1 .. $form->{rowcount}) {
803     if ($form->{type} eq "credit_note") {
804       $form->{"qty_$i"} = $form->parse_amount($myconfig, $form->{"qty_$i"}) * -1;
805       $form->{shipped} = 1;
806     } else {
807       $form->{"qty_$i"} = $form->parse_amount($myconfig, $form->{"qty_$i"});
808     }
809     my $basefactor;
810     my $baseqty;
811
812     $form->{"marge_percent_$i"} = $form->parse_amount($myconfig, $form->{"marge_percent_$i"}) * 1;
813     $form->{"marge_absolut_$i"} = $form->parse_amount($myconfig, $form->{"marge_absolut_$i"}) * 1;
814     $form->{"lastcost_$i"} = $form->parse_amount($myconfig, $form->{"lastcost_$i"}) * 1;
815
816     if ($form->{storno}) {
817       $form->{"qty_$i"} *= -1;
818     }
819
820     if ($form->{"id_$i"}) {
821       my $item_unit;
822       my $position = $i;
823
824       if (defined($baseunits{$form->{"id_$i"}})) {
825         $item_unit = $baseunits{$form->{"id_$i"}};
826       } else {
827         # get item baseunit
828         $query = qq|SELECT unit FROM parts WHERE id = ?|;
829         ($item_unit) = selectrow_query($form, $dbh, $query, conv_i($form->{"id_$i"}));
830         $baseunits{$form->{"id_$i"}} = $item_unit;
831       }
832
833       if (defined($all_units->{$item_unit}->{factor})
834           && ($all_units->{$item_unit}->{factor} ne '')
835           && ($all_units->{$item_unit}->{factor} != 0)) {
836         $basefactor = $all_units->{$form->{"unit_$i"}}->{factor} / $all_units->{$item_unit}->{factor};
837       } else {
838         $basefactor = 1;
839       }
840       $baseqty = $form->{"qty_$i"} * $basefactor;
841
842       my ($allocated, $taxrate) = (0, 0);
843       my $taxamount;
844
845       # add tax rates
846       map { $taxrate += $form->{"${_}_rate"} } split(/ /, $form->{"taxaccounts_$i"});
847
848       # keep entered selling price
849       my $fxsellprice =
850         $form->parse_amount($myconfig, $form->{"sellprice_$i"});
851
852       my ($dec) = ($fxsellprice =~ /\.(\d+)/);
853       $dec = length $dec;
854       my $decimalplaces = ($dec > 2) ? $dec : 2;
855
856       # undo discount formatting
857       $form->{"discount_$i"} = $form->parse_amount($myconfig, $form->{"discount_$i"}) / 100;
858
859       # deduct discount
860       $form->{"sellprice_$i"} = $fxsellprice * (1 - $form->{"discount_$i"});
861
862       # round linetotal to 2 decimal places
863       $price_factor = $price_factors{ $form->{"price_factor_id_$i"} } || 1;
864       $linetotal    = $form->round_amount($form->{"sellprice_$i"} * $form->{"qty_$i"} / $price_factor, 2);
865
866       if ($form->{taxincluded}) {
867         $taxamount = $linetotal * ($taxrate / (1 + $taxrate));
868         $form->{"sellprice_$i"} =
869           $form->{"sellprice_$i"} * (1 / (1 + $taxrate));
870       } else {
871         $taxamount = $linetotal * $taxrate;
872       }
873
874       $netamount += $linetotal;
875
876       if ($taxamount != 0) {
877         map {
878           $form->{amount}{ $form->{id} }{$_} +=
879             $taxamount * $form->{"${_}_rate"} / $taxrate
880         } split(/ /, $form->{"taxaccounts_$i"});
881       }
882
883       # add amount to income, $form->{amount}{trans_id}{accno}
884       $amount = $form->{"sellprice_$i"} * $form->{"qty_$i"} * $form->{exchangerate} / $price_factor;
885
886       $linetotal = $form->round_amount($form->{"sellprice_$i"} * $form->{"qty_$i"} / $price_factor, 2) * $form->{exchangerate};
887       $linetotal = $form->round_amount($linetotal, 2);
888
889       # this is the difference from the inventory
890       $invoicediff += ($amount - $linetotal);
891
892       $form->{amount}{ $form->{id} }{ $form->{"income_accno_$i"} } +=
893         $linetotal;
894
895       $lastincomeaccno = $form->{"income_accno_$i"};
896
897       # adjust and round sellprice
898       $form->{"sellprice_$i"} =
899         $form->round_amount($form->{"sellprice_$i"} * $form->{exchangerate},
900                             $decimalplaces);
901
902       next if $payments_only;
903
904       if ($form->{"inventory_accno_$i"} || $form->{"part_type_$i"} eq 'assembly') {
905
906         if ($form->{"part_type_$i"} eq 'assembly') {
907           # record assembly item as allocated
908           &process_assembly($dbh, $myconfig, $form, $position, $form->{"id_$i"}, $baseqty);
909
910         } else {
911           $allocated = &cogs($dbh, $myconfig, $form, $form->{"id_$i"}, $baseqty, $basefactor, $i);
912         }
913       }
914
915       # Get pricegroup_id and save it. Unfortunately the interface
916       # also uses ID "0" for signalling that none is selected, but "0"
917       # must not be stored in the database. Therefore we cannot simply
918       # use conv_i().
919       ($null, my $pricegroup_id) = split(/--/, $form->{"sellprice_pg_$i"});
920       $pricegroup_id *= 1;
921       $pricegroup_id  = undef if !$pricegroup_id;
922
923       CVar->get_non_editable_ic_cvars(form               => $form,
924                                       dbh                => $dbh,
925                                       row                => $i,
926                                       sub_module         => 'invoice',
927                                       may_converted_from => ['delivery_order_items', 'orderitems', 'invoice']);
928
929       if (!$form->{"invoice_id_$i"}) {
930         # there is no persistent id, therefore create one with all necessary constraints
931         my $q_invoice_id = qq|SELECT nextval('invoiceid')|;
932         my $h_invoice_id = prepare_query($form, $dbh, $q_invoice_id);
933         do_statement($form, $h_invoice_id, $q_invoice_id);
934         $form->{"invoice_id_$i"}  = $h_invoice_id->fetchrow_array();
935         my $q_create_invoice_id = qq|INSERT INTO invoice (id, trans_id, position, parts_id) values (?, ?, ?, ?)|;
936         do_query($form, $dbh, $q_create_invoice_id, conv_i($form->{"invoice_id_$i"}),
937                  conv_i($form->{id}), conv_i($position), conv_i($form->{"id_$i"}));
938         $h_invoice_id->finish();
939       }
940
941       # save detail record in invoice table
942       $query = <<SQL;
943         UPDATE invoice SET trans_id = ?, position = ?, parts_id = ?, description = ?, longdescription = ?, qty = ?,
944                            sellprice = ?, fxsellprice = ?, discount = ?, allocated = ?, assemblyitem = ?,
945                            unit = ?, deliverydate = ?, project_id = ?, serialnumber = ?, pricegroup_id = ?,
946                            base_qty = ?, subtotal = ?,
947                            marge_percent = ?, marge_total = ?, lastcost = ?, active_price_source = ?, active_discount_source = ?,
948                            price_factor_id = ?, price_factor = (SELECT factor FROM price_factors WHERE id = ?), marge_price_factor = ?
949         WHERE id = ?
950 SQL
951
952       @values = (conv_i($form->{id}), conv_i($position), conv_i($form->{"id_$i"}),
953                  $form->{"description_$i"}, $restricter->process($form->{"longdescription_$i"}), $form->{"qty_$i"},
954                  $form->{"sellprice_$i"}, $fxsellprice,
955                  $form->{"discount_$i"}, $allocated, 'f',
956                  $form->{"unit_$i"}, conv_date($form->{"reqdate_$i"}), conv_i($form->{"project_id_$i"}),
957                  $form->{"serialnumber_$i"}, $pricegroup_id,
958                  $baseqty, $form->{"subtotal_$i"} ? 't' : 'f',
959                  $form->{"marge_percent_$i"}, $form->{"marge_absolut_$i"},
960                  $form->{"lastcost_$i"},
961                  $form->{"active_price_source_$i"}, $form->{"active_discount_source_$i"},
962                  conv_i($form->{"price_factor_id_$i"}), conv_i($form->{"price_factor_id_$i"}),
963                  conv_i($form->{"marge_price_factor_$i"}),
964                  conv_i($form->{"invoice_id_$i"}));
965       do_query($form, $dbh, $query, @values);
966       push @processed_invoice_ids, $form->{"invoice_id_$i"};
967
968       CVar->save_custom_variables(module       => 'IC',
969                                   sub_module   => 'invoice',
970                                   trans_id     => $form->{"invoice_id_$i"},
971                                   configs      => $ic_cvar_configs,
972                                   variables    => $form,
973                                   name_prefix  => 'ic_',
974                                   name_postfix => "_$i",
975                                   dbh          => $dbh);
976     }
977     # link previous items with invoice items
978     foreach (qw(delivery_order_items orderitems invoice)) {
979       if (!$form->{useasnew} && $form->{"converted_from_${_}_id_$i"}) {
980         RecordLinks->create_links('dbh'        => $dbh,
981                                   'mode'       => 'ids',
982                                   'from_table' => $_,
983                                   'from_ids'   => $form->{"converted_from_${_}_id_$i"},
984                                   'to_table'   => 'invoice',
985                                   'to_id'      => $form->{"invoice_id_$i"},
986         );
987       }
988       delete $form->{"converted_from_${_}_id_$i"};
989     }
990   }
991
992   # total payments, don't move we need it here
993   for my $i (1 .. $form->{paidaccounts}) {
994     if ($form->{type} eq "credit_note") {
995       $form->{"paid_$i"} = $form->parse_amount($myconfig, $form->{"paid_$i"}) * -1;
996     } else {
997       $form->{"paid_$i"} = $form->parse_amount($myconfig, $form->{"paid_$i"});
998     }
999     $form->{paid} += $form->{"paid_$i"};
1000     $form->{datepaid} = $form->{"datepaid_$i"} if ($form->{"datepaid_$i"});
1001   }
1002
1003   my ($tax, $diff) = (0, 0);
1004
1005   $netamount = $form->round_amount($netamount, 2);
1006
1007   # figure out rounding errors for total amount vs netamount + taxes
1008   if ($form->{taxincluded}) {
1009
1010     $amount = $form->round_amount($netamount * $form->{exchangerate}, 2);
1011     $diff += $amount - $netamount * $form->{exchangerate};
1012     $netamount = $amount;
1013
1014     foreach my $item (split(/ /, $form->{taxaccounts})) {
1015       $amount = $form->{amount}{ $form->{id} }{$item} * $form->{exchangerate};
1016       $form->{amount}{ $form->{id} }{$item} = $form->round_amount($amount, 2);
1017       $tax += $form->{amount}{ $form->{id} }{$item};
1018       $netamount -= $form->{amount}{ $form->{id} }{$item};
1019     }
1020
1021     $invoicediff += $diff;
1022     ######## this only applies to tax included
1023     if ($lastincomeaccno) {
1024       $form->{amount}{ $form->{id} }{$lastincomeaccno} += $invoicediff;
1025     }
1026
1027   } else {
1028     $amount    = $form->round_amount($netamount * $form->{exchangerate}, 2);
1029     $diff      = $amount - $netamount * $form->{exchangerate};
1030     $netamount = $amount;
1031     foreach my $item (split(/ /, $form->{taxaccounts})) {
1032       $form->{amount}{ $form->{id} }{$item} =
1033         $form->round_amount($form->{amount}{ $form->{id} }{$item}, 2);
1034       $amount =
1035         $form->round_amount(
1036                  $form->{amount}{ $form->{id} }{$item} * $form->{exchangerate},
1037                  2);
1038       $diff +=
1039         $amount - $form->{amount}{ $form->{id} }{$item} *
1040         $form->{exchangerate};
1041       $form->{amount}{ $form->{id} }{$item} = $form->round_amount($amount, 2);
1042       $tax += $form->{amount}{ $form->{id} }{$item};
1043     }
1044   }
1045
1046   # Invoice Summary includes Rounding
1047   my $grossamount = $netamount + $tax;
1048   my $rounding = $form->round_amount(
1049     $form->round_amount($grossamount, 2, 1) - $form->round_amount($grossamount, 2),
1050     2
1051   );
1052   my $rnd_accno = $rounding == 0 ? 0
1053                 : $rounding > 0  ? $form->{rndgain_accno}
1054                 :                  $form->{rndloss_accno}
1055   ;
1056   $form->{amount}{ $form->{id} }{ $form->{AR} } = $form->round_amount($grossamount, 2, 1);
1057   $form->{paid} = $form->round_amount(
1058     $form->{paid} * $form->{exchangerate} + $diff,
1059     2
1060   );
1061
1062   # reverse AR
1063   $form->{amount}{ $form->{id} }{ $form->{AR} } *= -1;
1064
1065   # update exchangerate
1066   if (($form->{currency} ne $defaultcurrency) && !$exchangerate) {
1067     $form->update_exchangerate($dbh, $form->{currency}, $form->{invdate},
1068                                $form->{exchangerate}, 0);
1069   }
1070
1071   $project_id = conv_i($form->{"globalproject_id"});
1072   # entsprechend auch beim Bestimmen des Steuerschlüssels in Taxkey.pm berücksichtigen
1073   my $taxdate = $form->{tax_point} ||$form->{deliverydate} || $form->{invdate};
1074
1075   # Sanity checks for invoices for advance payment and final invoices
1076   my $advance_payment_clearing_chart;
1077   if (any { $_ eq $form->{type} } qw(invoice_for_advance_payment final_invoice)) {
1078     $advance_payment_clearing_chart = SL::DB::Chart->new(id => $::instance_conf->get_advance_payment_clearing_chart_id)->load;
1079     die "No Clearing Chart for Advance Payment" unless ref $advance_payment_clearing_chart eq 'SL::DB::Chart';
1080
1081     my @current_taxaccounts = (split(/ /, $form->{taxaccounts}));
1082     die 'Wrong call: Cannot post invoice for advance payment or final invoice with more than one tax' if (scalar @current_taxaccounts > 1);
1083
1084     my @trans_ids = keys %{ $form->{amount} };
1085     if (scalar @trans_ids > 1) {
1086       require Data::Dumper;
1087       die "Invalid state for advance payment more than one trans_id " . Dumper($form->{amount});
1088     }
1089   }
1090
1091   my $iap_amounts;
1092   if ($form->{type} eq 'final_invoice') {
1093     my $invoices_for_advance_payment = $self->_get_invoices_for_advance_payment($form->{convert_from_ar_ids} || $form->{id});
1094     if (scalar @$invoices_for_advance_payment > 0) {
1095       # reverse booking for invoices for advance payment
1096       foreach my $invoice_for_advance_payment (@$invoices_for_advance_payment) {
1097         # delete ?
1098         # --> is implemented below (bookings are marked in memo field)
1099         #
1100         # TODO: helper table acc_trans_advance_payment
1101         # trans_id for final invoice connects to acc_trans_id here
1102         # my $booking = SL::DB::AccTrans->new( ...)
1103         # --> helper table not nessessary because of mark in memo field
1104         #
1105         # TODO: If final_invoice change (delete storno) delete all connectin acc_trans entries, if
1106         # period is not closed
1107         # --> no problem because gldate of reverse booking is date of final invoice
1108         #     if deletion of final invoice is allowed, reverting bookings in invoices
1109         #     for advance payment are allowed, too.
1110         # $booking->id, $self->id in helper table
1111         if (!$already_booked) {
1112           $form->{amount}->{$invoice_for_advance_payment->id}->{$advance_payment_clearing_chart->accno} = -1 * $invoice_for_advance_payment->netamount;
1113           $form->{memo}  ->{$invoice_for_advance_payment->id}->{$advance_payment_clearing_chart->accno} = 'reverse booking by final invoice';
1114           # AR
1115           $form->{amount}->{$invoice_for_advance_payment->id}->{$form->{AR}} = $invoice_for_advance_payment->netamount;
1116           $form->{memo}  ->{$invoice_for_advance_payment->id}->{$form->{AR}} = 'reverse booking by final invoice';
1117         }
1118
1119         # VAT for invoices for advance payment is booked on payment of these. So do not book this VAT for final invoice.
1120         # And book the amount of the invoices for advance payment with taxkey 0 (see below).
1121         # Collect amounts and VAT of invoices for advance payment.
1122
1123         # Set sellprices to fxsellprices for items, because
1124         # the PriceTaxCalculator sets fxsellprice from sellprice before calculating.
1125         $_->sellprice($_->fxsellprice) for @{$invoice_for_advance_payment->items};
1126         my %pat = $invoice_for_advance_payment->calculate_prices_and_taxes;
1127
1128         foreach my $tax_chart_id (keys %{ $pat{taxes_by_chart_id} }) {
1129           my $tax_accno = SL::DB::Chart->load_cached($tax_chart_id)->accno;
1130           $form->{amount}{ $form->{id} }{$tax_accno}  -= $pat{taxes_by_chart_id}->{$tax_chart_id};
1131           $form->{amount}{ $form->{id} }{$form->{AR}} += $pat{taxes_by_chart_id}->{$tax_chart_id};
1132         }
1133
1134         foreach my $amount_chart_id (keys %{ $pat{amounts} }) {
1135           my $amount_accno = SL::DB::Chart->load_cached($amount_chart_id)->accno;
1136           $iap_amounts->{$amount_accno}                 += $pat{amounts}->{$amount_chart_id}->{amount};
1137           $form->{amount}{ $form->{id} }{$amount_accno} -= $pat{amounts}->{$amount_chart_id}->{amount};
1138         }
1139       }
1140     }
1141   }
1142
1143   if ($form->{type} eq 'invoice_for_advance_payment') {
1144     # get gross and move to clearing chart - delete everything else
1145     # 1. gross
1146     my $gross = $form->{amount}{ $form->{id} }{$form->{AR}};
1147     # 2. destroy
1148     undef $form->{amount}{ $form->{id} };
1149     # 3. rebuild
1150     $form->{amount}{ $form->{id} }{$form->{AR}}            = $gross;
1151     $form->{amount}{ $form->{id} }{$advance_payment_clearing_chart->accno} = $gross * -1;
1152     # 4. no cogs, hopefully not commonly used at all
1153     undef $form->{amount_cogs};
1154   }
1155
1156   foreach my $trans_id (keys %{ $form->{amount_cogs} }) {
1157     foreach my $accno (keys %{ $form->{amount_cogs}{$trans_id} }) {
1158       next unless ($form->{expense_inventory} =~ /\Q$accno\E/);
1159
1160       $form->{amount_cogs}{$trans_id}{$accno} = $form->round_amount($form->{amount_cogs}{$trans_id}{$accno}, 2);
1161
1162       if (!$payments_only && ($form->{amount_cogs}{$trans_id}{$accno} != 0)) {
1163         $query =
1164           qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate, tax_id, taxkey, project_id, chart_link)
1165                VALUES (?, (SELECT id FROM chart WHERE accno = ?), ?, ?, (SELECT id FROM tax WHERE taxkey=0), 0, ?, (SELECT link FROM chart WHERE accno = ?))|;
1166         @values = (conv_i($trans_id), $accno, $form->{amount_cogs}{$trans_id}{$accno}, conv_date($form->{invdate}), conv_i($project_id), $accno);
1167         do_query($form, $dbh, $query, @values);
1168         $form->{amount_cogs}{$trans_id}{$accno} = 0;
1169       }
1170     }
1171
1172     foreach my $accno (keys %{ $form->{amount_cogs}{$trans_id} }) {
1173       $form->{amount_cogs}{$trans_id}{$accno} = $form->round_amount($form->{amount_cogs}{$trans_id}{$accno}, 2);
1174
1175       if (!$payments_only && ($form->{amount_cogs}{$trans_id}{$accno} != 0)) {
1176         $query =
1177           qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate, tax_id, taxkey, project_id, chart_link)
1178                VALUES (?, (SELECT id FROM chart WHERE accno = ?), ?, ?, (SELECT id FROM tax WHERE taxkey=0), 0, ?, (SELECT link FROM chart WHERE accno = ?))|;
1179         @values = (conv_i($trans_id), $accno, $form->{amount_cogs}{$trans_id}{$accno}, conv_date($form->{invdate}), conv_i($project_id), $accno);
1180         do_query($form, $dbh, $query, @values);
1181       }
1182     }
1183   }
1184
1185   foreach my $trans_id (keys %{ $form->{amount} }) {
1186     foreach my $accno (keys %{ $form->{amount}{$trans_id} }) {
1187       next unless ($form->{expense_inventory} =~ /\Q$accno\E/);
1188
1189       $form->{amount}{$trans_id}{$accno} = $form->round_amount($form->{amount}{$trans_id}{$accno}, 2);
1190
1191       if (!$payments_only && ($form->{amount}{$trans_id}{$accno} != 0)) {
1192         $query =
1193           qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate, tax_id, taxkey, project_id, chart_link, memo)
1194              VALUES (?, (SELECT id FROM chart WHERE accno = ?), ?, ?,
1195                      (SELECT tax_id
1196                       FROM taxkeys
1197                       WHERE chart_id= (SELECT id
1198                                        FROM chart
1199                                        WHERE accno = ?)
1200                       AND startdate <= ?
1201                       ORDER BY startdate DESC LIMIT 1),
1202                      (SELECT taxkey_id
1203                       FROM taxkeys
1204                       WHERE chart_id= (SELECT id
1205                                        FROM chart
1206                                        WHERE accno = ?)
1207                       AND startdate <= ?
1208                       ORDER BY startdate DESC LIMIT 1),
1209                      ?,
1210                      (SELECT link FROM chart WHERE accno = ?),
1211                      ?)|;
1212         @values = (conv_i($trans_id), $accno, $form->{amount}{$trans_id}{$accno}, conv_date($form->{invdate}), $accno, conv_date($taxdate), $accno, conv_date($taxdate), conv_i($project_id), $accno, $form->{memo}{$trans_id}{$accno});
1213         do_query($form, $dbh, $query, @values);
1214         $form->{amount}{$trans_id}{$accno} = 0;
1215       }
1216     }
1217
1218     foreach my $accno (keys %{ $form->{amount}{$trans_id} }) {
1219       $form->{amount}{$trans_id}{$accno} = $form->round_amount($form->{amount}{$trans_id}{$accno}, 2);
1220
1221       if (!$payments_only && ($form->{amount}{$trans_id}{$accno} != 0)) {
1222         $query =
1223           qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate, tax_id, taxkey, project_id, chart_link, memo)
1224              VALUES (?, (SELECT id FROM chart WHERE accno = ?), ?, ?,
1225                      (SELECT tax_id
1226                       FROM taxkeys
1227                       WHERE chart_id= (SELECT id
1228                                        FROM chart
1229                                        WHERE accno = ?)
1230                       AND startdate <= ?
1231                       ORDER BY startdate DESC LIMIT 1),
1232                      (SELECT taxkey_id
1233                       FROM taxkeys
1234                       WHERE chart_id= (SELECT id
1235                                        FROM chart
1236                                        WHERE accno = ?)
1237                       AND startdate <= ?
1238                       ORDER BY startdate DESC LIMIT 1),
1239                      ?,
1240                      (SELECT link FROM chart WHERE accno = ?),
1241                      ?)|;
1242         @values = (conv_i($trans_id), $accno, $form->{amount}{$trans_id}{$accno}, conv_date($form->{invdate}), $accno, conv_date($taxdate), $accno, conv_date($taxdate), conv_i($project_id), $accno,$form->{memo}{$trans_id}{$accno});
1243         do_query($form, $dbh, $query, @values);
1244       }
1245     }
1246     if (!$payments_only && ($rnd_accno != 0)) {
1247       $query =
1248         qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate, tax_id, taxkey, project_id, chart_link)
1249              VALUES (?, (SELECT id FROM chart WHERE accno = ?), ?, ?, (SELECT id FROM tax WHERE taxkey=0), 0, ?, (SELECT link FROM chart WHERE accno = ?))|;
1250       @values = (conv_i($trans_id), $rnd_accno, $rounding, conv_date($form->{invdate}), conv_i($project_id), $rnd_accno);
1251       do_query($form, $dbh, $query, @values);
1252       $rnd_accno = 0;
1253     }
1254   }
1255
1256   # Book the amount of the invoices for advance payment with taxkey 0 (see below).
1257   if ($form->{type} eq 'final_invoice' && $iap_amounts) {
1258     foreach my $accno (keys %$iap_amounts) {
1259       $query =
1260         qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate, tax_id, taxkey, project_id, chart_link)
1261         VALUES (?, (SELECT id FROM chart WHERE accno = ?), ?, ?, (SELECT id FROM tax WHERE taxkey=0), 0, ?, (SELECT link FROM chart WHERE accno = ?))|;
1262       @values = (conv_i($form->{id}), $accno, $iap_amounts->{$accno}, conv_date($form->{invdate}), conv_i($project_id), $accno);
1263       do_query($form, $dbh, $query, @values);
1264     }
1265   }
1266
1267   # deduct payment differences from diff
1268   for my $i (1 .. $form->{paidaccounts}) {
1269     if ($form->{"paid_$i"} != 0) {
1270       $amount =
1271         $form->round_amount($form->{"paid_$i"} * $form->{exchangerate}, 2);
1272       $diff -= $amount - $form->{"paid_$i"} * $form->{exchangerate};
1273     }
1274   }
1275
1276   my %already_cleared = %{ $params{already_cleared} // {} };
1277
1278   # record payments and offsetting AR
1279   if (!$form->{storno}) {
1280     for my $i (1 .. $form->{paidaccounts}) {
1281
1282       if ($form->{"acc_trans_id_$i"}
1283           && $payments_only
1284           && (SL::DB::Default->get->payments_changeable == 0)) {
1285         next;
1286       }
1287
1288       next if ($form->{"paid_$i"} == 0);
1289
1290       my ($accno) = split(/--/, $form->{"AR_paid_$i"});
1291       $form->{"datepaid_$i"} = $form->{invdate}
1292       unless ($form->{"datepaid_$i"});
1293       $form->{datepaid} = $form->{"datepaid_$i"};
1294
1295       $exchangerate = 0;
1296
1297       if ($form->{currency} eq $defaultcurrency) {
1298         $form->{"exchangerate_$i"} = 1;
1299       } else {
1300         $exchangerate              = $form->check_exchangerate($myconfig, $form->{currency}, $form->{"datepaid_$i"}, 'buy');
1301         $form->{"exchangerate_$i"} = $exchangerate || $form->parse_amount($myconfig, $form->{"exchangerate_$i"});
1302       }
1303
1304       # record AR
1305       $amount = $form->round_amount($form->{"paid_$i"} * $form->{exchangerate} + $diff, 2);
1306
1307       my $new_cleared = !$form->{"acc_trans_id_$i"}                                                       ? 'f'
1308                       : !$already_cleared{$form->{"acc_trans_id_$i"}}                                     ? 'f'
1309                       : $already_cleared{$form->{"acc_trans_id_$i"}}->{amount} != $form->{"paid_$i"} * -1 ? 'f'
1310                       : $already_cleared{$form->{"acc_trans_id_$i"}}->{accno}  != $accno                  ? 'f'
1311                       : $already_cleared{$form->{"acc_trans_id_$i"}}->{cleared}                           ? 't'
1312                       :                                                                                     'f';
1313
1314       if ($form->{amount}{ $form->{id} }{ $form->{AR} } != 0) {
1315         $query =
1316         qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate, tax_id, taxkey, project_id, cleared, chart_link)
1317            VALUES (?, (SELECT id FROM chart WHERE accno = ?), ?, ?,
1318                    (SELECT tax_id
1319                     FROM taxkeys
1320                     WHERE chart_id= (SELECT id
1321                                      FROM chart
1322                                      WHERE accno = ?)
1323                     AND startdate <= ?
1324                     ORDER BY startdate DESC LIMIT 1),
1325                    (SELECT taxkey_id
1326                     FROM taxkeys
1327                     WHERE chart_id= (SELECT id
1328                                      FROM chart
1329                                      WHERE accno = ?)
1330                     AND startdate <= ?
1331                     ORDER BY startdate DESC LIMIT 1),
1332                    ?, ?,
1333                    (SELECT link FROM chart WHERE accno = ?))|;
1334         @values = (conv_i($form->{"id"}), $form->{AR}, $amount, $form->{"datepaid_$i"}, $form->{AR}, conv_date($taxdate), $form->{AR}, conv_date($taxdate), $project_id, $new_cleared, $form->{AR});
1335         do_query($form, $dbh, $query, @values);
1336       }
1337
1338       # record payment
1339       $form->{"paid_$i"} *= -1;
1340       my $gldate = (conv_date($form->{"gldate_$i"}))? conv_date($form->{"gldate_$i"}) : conv_date($form->current_date($myconfig));
1341
1342       $query =
1343       qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate, gldate, source, memo, tax_id, taxkey, project_id, cleared, chart_link)
1344          VALUES (?, (SELECT id FROM chart WHERE accno = ?), ?, ?, ?, ?, ?,
1345                  (SELECT tax_id
1346                   FROM taxkeys
1347                   WHERE chart_id= (SELECT id
1348                                    FROM chart
1349                                    WHERE accno = ?)
1350                   AND startdate <= ?
1351                   ORDER BY startdate DESC LIMIT 1),
1352                  (SELECT taxkey_id
1353                   FROM taxkeys
1354                   WHERE chart_id= (SELECT id
1355                                    FROM chart
1356                                    WHERE accno = ?)
1357                   AND startdate <= ?
1358                   ORDER BY startdate DESC LIMIT 1),
1359                  ?, ?,
1360                  (SELECT link FROM chart WHERE accno = ?))|;
1361       @values = (conv_i($form->{"id"}), $accno, $form->{"paid_$i"}, $form->{"datepaid_$i"},
1362                  $gldate, $form->{"source_$i"}, $form->{"memo_$i"}, $accno, conv_date($taxdate), $accno, conv_date($taxdate), $project_id, $new_cleared, $accno);
1363       do_query($form, $dbh, $query, @values);
1364
1365       # exchangerate difference
1366       $form->{fx}{$accno}{ $form->{"datepaid_$i"} } +=
1367         $form->{"paid_$i"} * ($form->{"exchangerate_$i"} - 1) + $diff;
1368
1369       # gain/loss
1370       $amount =
1371         $form->{"paid_$i"} * $form->{exchangerate} - $form->{"paid_$i"} *
1372         $form->{"exchangerate_$i"};
1373       if ($amount > 0) {
1374         $form->{fx}{ $form->{fxgain_accno} }{ $form->{"datepaid_$i"} } += $amount;
1375       } else {
1376         $form->{fx}{ $form->{fxloss_accno} }{ $form->{"datepaid_$i"} } += $amount;
1377       }
1378
1379       $diff = 0;
1380
1381       # update exchange rate
1382       if (($form->{currency} ne $defaultcurrency) && !$exchangerate) {
1383         $form->update_exchangerate($dbh, $form->{currency},
1384                                    $form->{"datepaid_$i"},
1385                                    $form->{"exchangerate_$i"}, 0);
1386       }
1387     }
1388
1389   } else {                      # if (!$form->{storno})
1390     $form->{marge_total} *= -1;
1391   }
1392
1393   IO->set_datepaid(table => 'ar', id => $form->{id}, dbh => $dbh);
1394
1395   # record exchange rate differences and gains/losses
1396   foreach my $accno (keys %{ $form->{fx} }) {
1397     foreach my $transdate (keys %{ $form->{fx}{$accno} }) {
1398       $form->{fx}{$accno}{$transdate} = $form->round_amount($form->{fx}{$accno}{$transdate}, 2);
1399       if ( $form->{fx}{$accno}{$transdate} != 0 ) {
1400
1401         $query =
1402           qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate, cleared, fx_transaction, tax_id, taxkey, project_id, chart_link)
1403              VALUES (?, (SELECT id FROM chart WHERE accno = ?), ?, ?, '0', '1',
1404                  (SELECT tax_id
1405                   FROM taxkeys
1406                   WHERE chart_id= (SELECT id
1407                                    FROM chart
1408                                    WHERE accno = ?)
1409                   AND startdate <= ?
1410                   ORDER BY startdate DESC LIMIT 1),
1411                  (SELECT taxkey_id
1412                   FROM taxkeys
1413                   WHERE chart_id= (SELECT id
1414                                    FROM chart
1415                                    WHERE accno = ?)
1416                   AND startdate <= ?
1417                   ORDER BY startdate DESC LIMIT 1),
1418                  ?,
1419                  (SELECT link FROM chart WHERE accno = ?))|;
1420         @values = (conv_i($form->{"id"}), $accno, $form->{fx}{$accno}{$transdate}, conv_date($transdate), $accno, conv_date($taxdate), $accno, conv_date($taxdate), conv_i($project_id), $accno);
1421         do_query($form, $dbh, $query, @values);
1422       }
1423     }
1424   }
1425
1426   if ($payments_only) {
1427     $query = qq|UPDATE ar SET paid = ? WHERE id = ?|;
1428     do_query($form, $dbh, $query,  $form->{paid}, conv_i($form->{id}));
1429
1430     $form->new_lastmtime('ar');
1431
1432     return;
1433   }
1434
1435   $amount = $form->round_amount( $netamount + $tax, 2, 1);
1436
1437   # save AR record
1438   #erweiterung fuer lieferscheinnummer (donumber) 12.02.09 jb
1439
1440   $query = qq|UPDATE ar set
1441                 invnumber   = ?, ordnumber     = ?, quonumber     = ?, cusordnumber  = ?,
1442                 transdate   = ?, orddate       = ?, quodate       = ?, tax_point     = ?, customer_id   = ?,
1443                 amount      = ?, netamount     = ?, paid          = ?,
1444                 duedate     = ?, deliverydate  = ?, invoice       = ?, shippingpoint = ?,
1445                 shipvia     = ?,                    notes         = ?, intnotes      = ?,
1446                 currency_id = (SELECT id FROM currencies WHERE name = ?),
1447                 department_id = ?, payment_id    = ?, taxincluded   = ?,
1448                 type        = ?, language_id   = ?, taxzone_id    = ?, shipto_id     = ?, billing_address_id = ?,
1449                 employee_id = ?, salesman_id   = ?, storno_id     = ?, storno        = ?,
1450                 cp_id       = ?, marge_total   = ?, marge_percent = ?,
1451                 globalproject_id               = ?, delivery_customer_id             = ?,
1452                 transaction_description        = ?, delivery_vendor_id               = ?,
1453                 donumber    = ?, invnumber_for_credit_note = ?,        direct_debit  = ?,
1454                 delivery_term_id = ?
1455               WHERE id = ?|;
1456   @values = (          $form->{"invnumber"},           $form->{"ordnumber"},             $form->{"quonumber"},          $form->{"cusordnumber"},
1457              conv_date($form->{"invdate"}),  conv_date($form->{"orddate"}),    conv_date($form->{"quodate"}), conv_date($form->{tax_point}), conv_i($form->{"customer_id"}),
1458                        $amount,                        $netamount,                       $form->{"paid"},
1459              conv_date($form->{"duedate"}),  conv_date($form->{"deliverydate"}),    '1',                                $form->{"shippingpoint"},
1460                        $form->{"shipvia"},                                $restricter->process($form->{"notes"}),       $form->{"intnotes"},
1461                        $form->{"currency"},     conv_i($form->{"department_id"}), conv_i($form->{"payment_id"}),        $form->{"taxincluded"} ? 't' : 'f',
1462                        $form->{"type"},         conv_i($form->{"language_id"}),   conv_i($form->{"taxzone_id"}), conv_i($form->{"shipto_id"}), conv_i($form->{billing_address_id}),
1463                 conv_i($form->{"employee_id"}), conv_i($form->{"salesman_id"}),   conv_i($form->{storno_id}),           $form->{"storno"} ? 't' : 'f',
1464                 conv_i($form->{"cp_id"}),            1 * $form->{marge_total} ,      1 * $form->{marge_percent},
1465                 conv_i($form->{"globalproject_id"}),                              conv_i($form->{"delivery_customer_id"}),
1466                        $form->{transaction_description},                          conv_i($form->{"delivery_vendor_id"}),
1467                        $form->{"donumber"}, $form->{"invnumber_for_credit_note"},        $form->{direct_debit} ? 't' : 'f',
1468                 conv_i($form->{delivery_term_id}),
1469                 conv_i($form->{"id"}));
1470   do_query($form, $dbh, $query, @values);
1471
1472
1473   if ($form->{storno}) {
1474     $query =
1475       qq!UPDATE ar SET
1476            paid = amount,
1477            storno = 't',
1478            intnotes = ? || intnotes
1479          WHERE id = ?!;
1480     do_query($form, $dbh, $query, "Rechnung storniert am $form->{invdate} ", conv_i($form->{"storno_id"}));
1481     do_query($form, $dbh, qq|UPDATE ar SET paid = amount WHERE id = ?|, conv_i($form->{"id"}));
1482   }
1483
1484   # maybe we are in a larger transaction and the current
1485   # object is not yet persistent in the db, therefore we
1486   # need the current dbh to get the not yet committed mtime
1487   $form->new_lastmtime('ar', $provided_dbh);
1488
1489   # add shipto
1490   if (!$form->{shipto_id}) {
1491     $form->add_shipto($dbh, $form->{id}, "AR");
1492   }
1493
1494   # save printed, emailed and queued
1495   $form->save_status($dbh);
1496
1497   Common::webdav_folder($form);
1498
1499   if ($form->{convert_from_ar_ids}) {
1500     RecordLinks->create_links('dbh'        => $dbh,
1501                               'mode'       => 'ids',
1502                               'from_table' => 'ar',
1503                               'from_ids'   => $form->{convert_from_ar_ids},
1504                               'to_table'   => 'ar',
1505                               'to_id'      => $form->{id},
1506     );
1507     delete $form->{convert_from_ar_ids};
1508   }
1509
1510   # Link this record to the records it was created from.
1511   if ($form->{convert_from_oe_ids}) {
1512     RecordLinks->create_links('dbh'        => $dbh,
1513                               'mode'       => 'ids',
1514                               'from_table' => 'oe',
1515                               'from_ids'   => $form->{convert_from_oe_ids},
1516                               'to_table'   => 'ar',
1517                               'to_id'      => $form->{id},
1518       );
1519     delete $form->{convert_from_oe_ids};
1520   }
1521
1522   my @convert_from_do_ids = map { $_ * 1 } grep { $_ } split m/\s+/, $form->{convert_from_do_ids};
1523
1524   if (scalar @convert_from_do_ids) {
1525     DO->close_orders('dbh' => $dbh,
1526                      'ids' => \@convert_from_do_ids);
1527
1528     RecordLinks->create_links('dbh'        => $dbh,
1529                               'mode'       => 'ids',
1530                               'from_table' => 'delivery_orders',
1531                               'from_ids'   => \@convert_from_do_ids,
1532                               'to_table'   => 'ar',
1533                               'to_id'      => $form->{id},
1534       );
1535   }
1536   delete $form->{convert_from_do_ids};
1537
1538   ARAP->close_orders_if_billed('dbh'     => $dbh,
1539                                'arap_id' => $form->{id},
1540                                'table'   => 'ar',);
1541
1542   # search for orphaned invoice items
1543   $query  = sprintf 'SELECT id FROM invoice WHERE trans_id = ? AND NOT id IN (%s)', join ', ', ("?") x scalar @processed_invoice_ids;
1544   @values = (conv_i($form->{id}), map { conv_i($_) } @processed_invoice_ids);
1545   my @orphaned_ids = map { $_->{id} } selectall_hashref_query($form, $dbh, $query, @values);
1546   if (scalar @orphaned_ids) {
1547     # clean up invoice items
1548     $query  = sprintf 'DELETE FROM invoice WHERE id IN (%s)', join ', ', ("?") x scalar @orphaned_ids;
1549     do_query($form, $dbh, $query, @orphaned_ids);
1550   }
1551
1552   if ($form->{draft_id}) {
1553     SL::DB::Manager::Draft->delete_all(where => [ id => delete($form->{draft_id}) ]);
1554   }
1555
1556   # safety check datev export
1557   if ($::instance_conf->get_datev_check_on_sales_invoice) {
1558
1559     my $datev = SL::DATEV->new(
1560       dbh        => $dbh,
1561       trans_id   => $form->{id},
1562     );
1563
1564     $datev->generate_datev_data;
1565
1566     if ($datev->errors) {
1567       die join "\n", $::locale->text('DATEV check returned errors:'), $datev->errors;
1568     }
1569   }
1570
1571   # update shop status
1572   my $invoice = SL::DB::Invoice->new( id => $form->{id} )->load;
1573   my @linked_shop_orders = $invoice->linked_records(
1574     from      => 'ShopOrder',
1575     via       => ['DeliveryOrder','Order',],
1576   );
1577     #do update
1578     my $shop_order = $linked_shop_orders[0][0];
1579   if ( $shop_order ) {
1580     require SL::Shop;
1581     my $shop_config = SL::DB::Manager::Shop->get_first( query => [ id => $shop_order->shop_id ] );
1582     my $shop = SL::Shop->new( config => $shop_config );
1583     $shop->connector->set_orderstatus($shop_order->shop_trans_id, "completed");
1584   }
1585
1586   return 1;
1587 }
1588
1589 sub _get_invoices_for_advance_payment {
1590   my ($self, $id) = @_;
1591
1592   return [] if !$id;
1593
1594   my $invoice_obj      = SL::DB::Invoice->new(id => $id*1)->load;
1595   my $links            = $invoice_obj->linked_records(direction => 'from', from => ['Invoice'], recursive => 1);
1596   my @related_invoices = grep {'SL::DB::Invoice' eq ref $_ && "invoice_for_advance_payment" eq $_->type} @$links;
1597
1598   push @related_invoices, $invoice_obj if "invoice_for_advance_payment" eq $invoice_obj->type;
1599
1600   return \@related_invoices;
1601 }
1602
1603
1604 sub transfer_out {
1605   $::lxdebug->enter_sub;
1606
1607   my ($self, $form, $dbh) = @_;
1608
1609   my (@errors, @transfers);
1610
1611   # do nothing, if transfer default is not requested at all
1612   if (!$::instance_conf->get_transfer_default) {
1613     $::lxdebug->leave_sub;
1614     return \@errors;
1615   }
1616
1617   require SL::WH;
1618
1619   foreach my $i (1 .. $form->{rowcount}) {
1620     next if !$form->{"id_$i"};
1621
1622     my ($err, $qty, $wh_id, $bin_id, $chargenumber);
1623
1624     if ($::instance_conf->get_sales_serial_eq_charge && $form->{"serialnumber_$i"}) {
1625       my @serials = split(" ", $form->{"serialnumber_$i"});
1626       if (scalar @serials != $form->{"qty_$i"}) {
1627         push @errors, $::locale->text("Cannot transfer #1 qty with #2 serial number(s)", $form->{"qty_$i"}, scalar @serials);
1628         last;
1629       }
1630       foreach my $serial (@serials) {
1631         ($qty, $wh_id, $bin_id, $chargenumber) = WH->get_wh_and_bin_for_charge(chargenumber => $serial);
1632         if (!$qty) {
1633           push @errors, $::locale->text("Not enough in stock for the serial number #1", $serial);
1634           last;
1635         }
1636         push @transfers, {
1637             'parts_id'         => $form->{"id_$i"},
1638             'qty'              => 1,
1639             'unit'             => $form->{"unit_$i"},
1640             'transfer_type'    => 'shipped',
1641             'src_warehouse_id' => $wh_id,
1642             'src_bin_id'       => $bin_id,
1643             'chargenumber'     => $chargenumber,
1644             'project_id'       => $form->{"project_id_$i"},
1645             'invoice_id'       => $form->{"invoice_id_$i"},
1646             'comment'          => $::locale->text("Default transfer invoice with charge number"),
1647         };
1648       }
1649       $err = []; # error handling uses @errors direct
1650     } else {
1651       ($err, $wh_id, $bin_id)    = _determine_wh_and_bin($dbh, $::instance_conf,
1652                                                          $form->{"id_$i"},
1653                                                          $form->{"qty_$i"},
1654                                                          $form->{"unit_$i"});
1655       if (!@{ $err } && $wh_id && $bin_id) {
1656         push @transfers, {
1657           'parts_id'         => $form->{"id_$i"},
1658           'qty'              => $form->{"qty_$i"},
1659           'unit'             => $form->{"unit_$i"},
1660           'transfer_type'    => 'shipped',
1661           'src_warehouse_id' => $wh_id,
1662           'src_bin_id'       => $bin_id,
1663           'project_id'       => $form->{"project_id_$i"},
1664           'invoice_id'       => $form->{"invoice_id_$i"},
1665           'comment'          => $::locale->text("Default transfer invoice"),
1666         };
1667       }
1668     }
1669     push @errors, @{ $err };
1670   } # end form rowcount
1671
1672   if (!@errors) {
1673     WH->transfer(@transfers);
1674   }
1675
1676   $::lxdebug->leave_sub;
1677   return \@errors;
1678 }
1679
1680 sub _determine_wh_and_bin {
1681   $::lxdebug->enter_sub(2);
1682
1683   my ($dbh, $conf, $part_id, $qty, $unit) = @_;
1684   my @errors;
1685
1686   my $part = SL::DB::Part->new(id => $part_id)->load;
1687
1688   # ignore service if they are not configured to be transfered
1689   if ($part->is_service && !$conf->get_transfer_default_services) {
1690     $::lxdebug->leave_sub(2);
1691     return (\@errors);
1692   }
1693
1694   # test negative qty
1695   if ($qty < 0) {
1696     push @errors, $::locale->text("Cannot transfer negative quantities.");
1697     return (\@errors);
1698   }
1699
1700   # get/test default bin
1701   my ($default_wh_id, $default_bin_id);
1702   if ($conf->get_transfer_default_use_master_default_bin) {
1703     $default_wh_id  = $conf->get_warehouse_id if $conf->get_warehouse_id;
1704     $default_bin_id = $conf->get_bin_id       if $conf->get_bin_id;
1705   }
1706   my $wh_id  = $part->warehouse_id || $default_wh_id;
1707   my $bin_id = $part->bin_id       || $default_bin_id;
1708
1709   # check qty and bin
1710   if ($bin_id) {
1711     my ($max_qty, $error) = WH->get_max_qty_parts_bin(dbh      => $dbh,
1712                                                       parts_id => $part->id,
1713                                                       bin_id   => $bin_id);
1714     if ($error == 1) {
1715       push @errors, $::locale->text('Part "#1" has chargenumber or best before date set. So it cannot be transfered automatically.',
1716                                     $part->description);
1717     }
1718     my $form_unit_obj = SL::DB::Unit->new(name => $unit)->load;
1719     my $part_unit_qty = $form_unit_obj->convert_to($qty, $part->unit_obj);
1720     my $diff_qty      = $max_qty - $part_unit_qty;
1721     if (!@errors && $diff_qty < 0) {
1722       push @errors, $::locale->text('For part "#1" there are missing #2 #3 in the default warehouse/bin "#4/#5".',
1723                                     $part->description,
1724                                     $::form->format_amount(\%::myconfig, -1*$diff_qty),
1725                                     $part->unit_obj->name,
1726                                     SL::DB::Warehouse->new(id => $wh_id)->load->description,
1727                                     SL::DB::Bin->new(      id => $bin_id)->load->description);
1728     }
1729   } else {
1730     push @errors, $::locale->text('For part "#1" there is no default warehouse and bin defined.',
1731                                   $part->description);
1732   }
1733
1734   # transfer to special "ignore onhand" bin if requested and default bin does not work
1735   if (@errors && $conf->get_transfer_default_ignore_onhand && $conf->get_bin_id_ignore_onhand) {
1736     $wh_id  = $conf->get_warehouse_id_ignore_onhand;
1737     $bin_id = $conf->get_bin_id_ignore_onhand;
1738     if ($wh_id && $bin_id) {
1739       @errors = ();
1740     } else {
1741       push @errors, $::locale->text('For part "#1" there is no default warehouse and bin for ignoring onhand defined.',
1742                                     $part->description);
1743     }
1744   }
1745
1746   $::lxdebug->leave_sub(2);
1747   return (\@errors, $wh_id, $bin_id);
1748 }
1749
1750 sub _delete_transfers {
1751   $::lxdebug->enter_sub;
1752
1753   my ($dbh, $form, $id) = @_;
1754
1755   my $query = qq|DELETE FROM inventory WHERE invoice_id
1756                   IN (SELECT id FROM invoice WHERE trans_id = ?)|;
1757
1758   do_query($form, $dbh, $query, $id);
1759
1760   $::lxdebug->leave_sub;
1761 }
1762
1763 sub _delete_payments {
1764   $main::lxdebug->enter_sub();
1765
1766   my ($self, $form, $dbh) = @_;
1767
1768   my @delete_acc_trans_ids;
1769
1770   # Delete old payment entries from acc_trans.
1771   my $query =
1772     qq|SELECT acc_trans_id
1773        FROM acc_trans
1774        WHERE (trans_id = ?) AND fx_transaction
1775
1776        UNION
1777
1778        SELECT at.acc_trans_id
1779        FROM acc_trans at
1780        LEFT JOIN chart c ON (at.chart_id = c.id)
1781        WHERE (trans_id = ?) AND (c.link LIKE '%AR_paid%')|;
1782   push @delete_acc_trans_ids, selectall_array_query($form, $dbh, $query, conv_i($form->{id}), conv_i($form->{id}));
1783
1784   $query =
1785     qq|SELECT at.acc_trans_id
1786        FROM acc_trans at
1787        LEFT JOIN chart c ON (at.chart_id = c.id)
1788        WHERE (trans_id = ?)
1789          AND ((c.link = 'AR') OR (c.link LIKE '%:AR') OR (c.link LIKE 'AR:%'))
1790        ORDER BY at.acc_trans_id
1791        OFFSET 1|;
1792   push @delete_acc_trans_ids, selectall_array_query($form, $dbh, $query, conv_i($form->{id}));
1793
1794   if (@delete_acc_trans_ids) {
1795     $query = qq|DELETE FROM acc_trans WHERE acc_trans_id IN (| . join(", ", @delete_acc_trans_ids) . qq|)|;
1796     do_query($form, $dbh, $query);
1797   }
1798
1799   $main::lxdebug->leave_sub();
1800 }
1801
1802 sub post_payment {
1803   my ($self, $myconfig, $form, $locale) = @_;
1804   $main::lxdebug->enter_sub();
1805
1806   my $rc = SL::DB->client->with_transaction(\&_post_payment, $self, $myconfig, $form, $locale);
1807
1808   $::lxdebug->leave_sub;
1809   return $rc;
1810 }
1811
1812 sub _post_payment {
1813   my ($self, $myconfig, $form, $locale) = @_;
1814
1815   my $dbh = SL::DB->client->dbh;
1816
1817   my (%payments, $old_form, $row, $item, $query, %keep_vars);
1818
1819   $old_form = save_form();
1820
1821   $query = <<SQL;
1822     SELECT at.acc_trans_id, at.amount, at.cleared, c.accno
1823     FROM acc_trans at
1824     LEFT JOIN chart c ON (at.chart_id = c.id)
1825     WHERE (at.trans_id = ?)
1826 SQL
1827
1828   my %already_cleared = selectall_as_map($form, $dbh, $query, 'acc_trans_id', [ qw(amount cleared accno) ], $form->{id});
1829
1830   # Delete all entries in acc_trans from prior payments.
1831   if (SL::DB::Default->get->payments_changeable != 0) {
1832     $self->_delete_payments($form, $dbh);
1833   }
1834
1835   # Save the new payments the user made before cleaning up $form.
1836   map { $payments{$_} = $form->{$_} } grep m/^datepaid_\d+$|^gldate_\d+$|^acc_trans_id_\d+$|^memo_\d+$|^source_\d+$|^exchangerate_\d+$|^paid_\d+$|^AR_paid_\d+$|^paidaccounts$/, keys %{ $form };
1837
1838   # Clean up $form so that old content won't tamper the results.
1839   %keep_vars = map { $_, 1 } qw(login password id);
1840   map { delete $form->{$_} unless $keep_vars{$_} } keys %{ $form };
1841
1842   # Retrieve the invoice from the database.
1843   $self->retrieve_invoice($myconfig, $form);
1844
1845   # Set up the content of $form in the way that IS::post_invoice() expects.
1846   $form->{exchangerate} = $form->format_amount($myconfig, $form->{exchangerate});
1847
1848   for $row (1 .. scalar @{ $form->{invoice_details} }) {
1849     $item = $form->{invoice_details}->[$row - 1];
1850
1851     map { $item->{$_} = $form->format_amount($myconfig, $item->{$_}) } qw(qty sellprice discount);
1852
1853     map { $form->{"${_}_${row}"} = $item->{$_} } keys %{ $item };
1854   }
1855
1856   $form->{rowcount} = scalar @{ $form->{invoice_details} };
1857
1858   delete @{$form}{qw(invoice_details paidaccounts storno paid)};
1859
1860   # Restore the payment options from the user input.
1861   map { $form->{$_} = $payments{$_} } keys %payments;
1862
1863   # Get the AR accno (which is normally done by Form::create_links()).
1864   $query =
1865     qq|SELECT c.accno
1866        FROM acc_trans at
1867        LEFT JOIN chart c ON (at.chart_id = c.id)
1868        WHERE (trans_id = ?)
1869          AND ((c.link = 'AR') OR (c.link LIKE '%:AR') OR (c.link LIKE 'AR:%'))
1870        ORDER BY at.acc_trans_id
1871        LIMIT 1|;
1872
1873   ($form->{AR}) = selectfirst_array_query($form, $dbh, $query, conv_i($form->{id}));
1874
1875   # Post the new payments.
1876   $self->post_invoice($myconfig, $form, $dbh, payments_only => 1, already_cleared => \%already_cleared);
1877
1878   restore_form($old_form);
1879
1880   return 1;
1881 }
1882
1883 sub process_assembly {
1884   $main::lxdebug->enter_sub();
1885
1886   my ($dbh, $myconfig, $form, $position, $id, $totalqty) = @_;
1887
1888   my $query =
1889     qq|SELECT a.parts_id, a.qty, p.part_type, p.partnumber, p.description, p.unit
1890        FROM assembly a
1891        JOIN parts p ON (a.parts_id = p.id)
1892        WHERE (a.id = ?)|;
1893   my $sth = prepare_execute_query($form, $dbh, $query, conv_i($id));
1894
1895   while (my $ref = $sth->fetchrow_hashref('NAME_lc')) {
1896
1897     my $allocated = 0;
1898
1899     $ref->{inventory_accno_id} *= 1;
1900     $ref->{expense_accno_id}   *= 1;
1901
1902     # multiply by number of assemblies
1903     $ref->{qty} *= $totalqty;
1904
1905     if ($ref->{assembly}) {
1906       &process_assembly($dbh, $myconfig, $form, $position, $ref->{parts_id}, $ref->{qty});
1907       next;
1908     } else {
1909       if ($ref->{inventory_accno_id}) {
1910         $allocated = &cogs($dbh, $myconfig, $form, $ref->{parts_id}, $ref->{qty});
1911       }
1912     }
1913
1914     # save detail record for individual assembly item in invoice table
1915     $query =
1916       qq|INSERT INTO invoice (trans_id, position, description, parts_id, qty, sellprice, fxsellprice, allocated, assemblyitem, unit)
1917          VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)|;
1918     my @values = (conv_i($form->{id}), conv_i($position), $ref->{description},
1919                   conv_i($ref->{parts_id}), $ref->{qty}, 0, 0, $allocated, 't', $ref->{unit});
1920     do_query($form, $dbh, $query, @values);
1921
1922   }
1923
1924   $sth->finish;
1925
1926   $main::lxdebug->leave_sub();
1927 }
1928
1929 sub cogs {
1930   $main::lxdebug->enter_sub();
1931
1932   # adjust allocated in table invoice according to FIFO princicple
1933   # for a certain part with part_id $id
1934
1935   my ($dbh, $myconfig, $form, $id, $totalqty, $basefactor, $row) = @_;
1936
1937   $basefactor ||= 1;
1938
1939   $form->{taxzone_id} *=1;
1940   my $transdate  = $form->{invdate} ? $dbh->quote($form->{invdate}) : "current_date";
1941   my $taxzone_id = $form->{"taxzone_id"} * 1;
1942   my $query =
1943     qq|SELECT i.id, i.trans_id, i.base_qty, i.allocated, i.sellprice, i.price_factor,
1944          c1.accno AS inventory_accno, c1.new_chart_id AS inventory_new_chart, date($transdate) - c1.valid_from AS inventory_valid,
1945          c2.accno AS    income_accno, c2.new_chart_id AS    income_new_chart, date($transdate) - c2.valid_from AS    income_valid,
1946          c3.accno AS   expense_accno, c3.new_chart_id AS   expense_new_chart, date($transdate) - c3.valid_from AS   expense_valid
1947        FROM invoice i, parts p
1948        LEFT JOIN chart c1 ON ((SELECT inventory_accno_id FROM buchungsgruppen WHERE id = p.buchungsgruppen_id) = c1.id)
1949        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)
1950        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)
1951        WHERE (i.parts_id = p.id)
1952          AND (i.parts_id = ?)
1953          AND ((i.base_qty + i.allocated) < 0)
1954        ORDER BY trans_id|;
1955   my $sth = prepare_execute_query($form, $dbh, $query, conv_i($id));
1956
1957   my $allocated = 0;
1958   my $qty;
1959
1960 # all invoice entries of an example part:
1961
1962 # id | trans_id | base_qty | allocated | sellprice | inventory_accno | income_accno | expense_accno
1963 # ---+----------+----------+-----------+-----------+-----------------+--------------+---------------
1964 #  4 |        4 |       -5 |         5 |  20.00000 | 1140            | 4400         | 5400     bought 5 for 20
1965 #  5 |        5 |        4 |        -4 |  50.00000 | 1140            | 4400         | 5400     sold   4 for 50
1966 #  6 |        6 |        1 |        -1 |  50.00000 | 1140            | 4400         | 5400     sold   1 for 50
1967 #  7 |        7 |       -5 |         1 |  20.00000 | 1140            | 4400         | 5400     bought 5 for 20
1968 #  8 |        8 |        1 |        -1 |  50.00000 | 1140            | 4400         | 5400     sold   1 for 50
1969
1970 # AND ((i.base_qty + i.allocated) < 0) filters out all but line with id=7, elsewhere i.base_qty + i.allocated has already reached 0
1971 # and all parts have been allocated
1972
1973 # so transaction 8 only sees transaction 7 with unallocated parts and adjusts allocated for that transaction, before allocated was 0
1974 #  7 |        7 |       -5 |         1 |  20.00000 | 1140            | 4400         | 5400     bought 5 for 20
1975
1976 # in this example there are still 4 unsold articles
1977
1978
1979   # search all invoice entries for the part in question, adjusting "allocated"
1980   # until the total number of sold parts has been reached
1981
1982   # ORDER BY trans_id ensures FIFO
1983
1984
1985   while (my $ref = $sth->fetchrow_hashref('NAME_lc')) {
1986     if (($qty = (($ref->{base_qty} * -1) - $ref->{allocated})) > $totalqty) {
1987       $qty = $totalqty;
1988     }
1989
1990     # update allocated in invoice
1991     $form->update_balance($dbh, "invoice", "allocated", qq|id = $ref->{id}|, $qty);
1992
1993     # total expenses and inventory
1994     # sellprice is the cost of the item
1995     my $linetotal = $form->round_amount(($ref->{sellprice} * $qty) / ( ($ref->{price_factor} || 1) * ( $basefactor || 1 )), 2);
1996
1997     if ( $::instance_conf->get_inventory_system eq 'perpetual' ) {
1998       # Bestandsmethode: when selling parts, deduct their purchase value from the inventory account
1999       $ref->{expense_accno} = ($form->{"expense_accno_$row"}) ? $form->{"expense_accno_$row"} : $ref->{expense_accno};
2000       # add to expense
2001       $form->{amount_cogs}{ $form->{id} }{ $ref->{expense_accno} } += -$linetotal;
2002       $form->{expense_inventory} .= " " . $ref->{expense_accno};
2003       $ref->{inventory_accno} = ($form->{"inventory_accno_$row"}) ? $form->{"inventory_accno_$row"} : $ref->{inventory_accno};
2004       # deduct inventory
2005       $form->{amount_cogs}{ $form->{id} }{ $ref->{inventory_accno} } -= -$linetotal;
2006       $form->{expense_inventory} .= " " . $ref->{inventory_accno};
2007     }
2008
2009     # add allocated
2010     $allocated -= $qty;
2011
2012     last if (($totalqty -= $qty) <= 0);
2013   }
2014
2015   $sth->finish;
2016
2017   $main::lxdebug->leave_sub();
2018
2019   return $allocated;
2020 }
2021
2022 sub reverse_invoice {
2023   $main::lxdebug->enter_sub();
2024
2025   my ($dbh, $form) = @_;
2026
2027   # reverse inventory items
2028   my $query =
2029     qq|SELECT i.id, i.parts_id, i.qty, i.assemblyitem, p.part_type
2030        FROM invoice i
2031        JOIN parts p ON (i.parts_id = p.id)
2032        WHERE i.trans_id = ?|;
2033   my $sth = prepare_execute_query($form, $dbh, $query, conv_i($form->{"id"}));
2034
2035   while (my $ref = $sth->fetchrow_hashref('NAME_lc')) {
2036
2037     if ($ref->{inventory_accno_id}) {
2038       # de-allocated purchases
2039       $query =
2040         qq|SELECT i.id, i.trans_id, i.allocated
2041            FROM invoice i
2042            WHERE (i.parts_id = ?) AND (i.allocated > 0)
2043            ORDER BY i.trans_id DESC|;
2044       my $sth2 = prepare_execute_query($form, $dbh, $query, conv_i($ref->{"parts_id"}));
2045
2046       while (my $inhref = $sth2->fetchrow_hashref('NAME_lc')) {
2047         my $qty = $ref->{qty};
2048         if (($ref->{qty} - $inhref->{allocated}) > 0) {
2049           $qty = $inhref->{allocated};
2050         }
2051
2052         # update invoice
2053         $form->update_balance($dbh, "invoice", "allocated", qq|id = $inhref->{id}|, $qty * -1);
2054
2055         last if (($ref->{qty} -= $qty) <= 0);
2056       }
2057       $sth2->finish;
2058     }
2059   }
2060
2061   $sth->finish;
2062
2063   # delete acc_trans
2064   my @values = (conv_i($form->{id}));
2065   do_query($form, $dbh, qq|DELETE FROM acc_trans WHERE trans_id = ?|, @values);
2066
2067   $query = qq|DELETE FROM custom_variables
2068               WHERE (config_id IN (SELECT id        FROM custom_variable_configs WHERE (module = 'ShipTo')))
2069                 AND (trans_id  IN (SELECT shipto_id FROM shipto                  WHERE (module = 'AR') AND (trans_id = ?)))|;
2070   do_query($form, $dbh, $query, @values);
2071   do_query($form, $dbh, qq|DELETE FROM shipto WHERE (trans_id = ?) AND (module = 'AR')|, @values);
2072
2073   $main::lxdebug->leave_sub();
2074 }
2075
2076 sub delete_invoice {
2077   my ($self, $myconfig, $form) = @_;
2078   $main::lxdebug->enter_sub();
2079
2080   my $rc = SL::DB->client->with_transaction(\&_delete_invoice, $self, $myconfig, $form);
2081
2082   $::lxdebug->leave_sub;
2083   return $rc;
2084 }
2085
2086 sub _delete_invoice {
2087   my ($self, $myconfig, $form) = @_;
2088
2089   my $dbh = SL::DB->client->dbh;
2090
2091   &reverse_invoice($dbh, $form);
2092   _delete_transfers($dbh, $form, $form->{id});
2093
2094   my @values = (conv_i($form->{id}));
2095
2096   # Falls wir ein Storno haben, müssen zwei Felder in der stornierten Rechnung wieder
2097   # zurückgesetzt werden. Vgl:
2098   #  id | storno | storno_id |  paid   |  amount
2099   #----+--------+-----------+---------+-----------
2100   # 18 | f      |           | 0.00000 | 119.00000
2101   # ZU:
2102   # 18 | t      |           |  119.00000 |  119.00000
2103   #
2104   if($form->{storno}){
2105     # storno_id auslesen und korrigieren
2106     my ($invoice_id) = selectfirst_array_query($form, $dbh, qq|SELECT storno_id FROM ar WHERE id = ?|,@values);
2107     do_query($form, $dbh, qq|UPDATE ar SET storno = 'f', paid = 0 WHERE id = ?|, $invoice_id);
2108   }
2109
2110   # if we delete a final invoice, the reverse bookings for the clearing account in the invoice for advance payment
2111   # must be deleted as well
2112   my $invoices_for_advance_payment = $self->_get_invoices_for_advance_payment($form->{convert_from_ar_ids} || $form->{id});
2113
2114   # Todo: allow only if invoice for advance payment is not paid.
2115   # die if any { $_->paid } for @$invoices_for_advance_payment;
2116   my @trans_ids_to_consider        = map { $_->id } @$invoices_for_advance_payment;
2117   if (scalar @trans_ids_to_consider) {
2118     my $query = sprintf 'DELETE FROM acc_trans WHERE memo LIKE ? AND trans_id IN (%s)', join ', ', ("?") x scalar @trans_ids_to_consider;
2119     do_query($form, $dbh, $query, 'reverse booking by final invoice', @trans_ids_to_consider);
2120   }
2121
2122   # delete spool files
2123   my @spoolfiles = selectall_array_query($form, $dbh, qq|SELECT spoolfile FROM status WHERE trans_id = ?|, @values);
2124
2125   my @queries = (
2126     qq|DELETE FROM status WHERE trans_id = ?|,
2127     qq|DELETE FROM periodic_invoices WHERE ar_id = ?|,
2128     qq|DELETE FROM invoice WHERE trans_id = ?|,
2129     qq|DELETE FROM ar WHERE id = ?|,
2130   );
2131
2132   map { do_query($form, $dbh, $_, @values) } @queries;
2133
2134   my $spool = $::lx_office_conf{paths}->{spool};
2135   map { unlink "$spool/$_" if -f "$spool/$_"; } @spoolfiles;
2136
2137   return 1;
2138 }
2139
2140 sub retrieve_invoice {
2141   my ($self, $myconfig, $form) = @_;
2142   $main::lxdebug->enter_sub();
2143
2144   my $rc = SL::DB->client->with_transaction(\&_retrieve_invoice, $self, $myconfig, $form);
2145
2146   $::lxdebug->leave_sub;
2147   return $rc;
2148 }
2149
2150 sub _retrieve_invoice {
2151   my ($self, $myconfig, $form) = @_;
2152
2153   my $dbh = SL::DB->client->dbh;
2154
2155   my ($sth, $ref, $query);
2156
2157   my $query_transdate = !$form->{id} ? ", current_date AS invdate" : '';
2158
2159   $query =
2160     qq|SELECT
2161          (SELECT c.accno FROM chart c WHERE d.inventory_accno_id = c.id) AS inventory_accno,
2162          (SELECT c.accno FROM chart c WHERE d.income_accno_id = c.id)    AS income_accno,
2163          (SELECT c.accno FROM chart c WHERE d.expense_accno_id = c.id)   AS expense_accno,
2164          (SELECT c.accno FROM chart c WHERE d.fxgain_accno_id = c.id)    AS fxgain_accno,
2165          (SELECT c.accno FROM chart c WHERE d.fxloss_accno_id = c.id)    AS fxloss_accno,
2166          (SELECT c.accno FROM chart c WHERE d.rndgain_accno_id = c.id)   AS rndgain_accno,
2167          (SELECT c.accno FROM chart c WHERE d.rndloss_accno_id = c.id)   AS rndloss_accno
2168          ${query_transdate}
2169        FROM defaults d|;
2170
2171   $ref = selectfirst_hashref_query($form, $dbh, $query);
2172   map { $form->{$_} = $ref->{$_} } keys %{ $ref };
2173
2174   if ($form->{id}) {
2175     my $id = conv_i($form->{id});
2176
2177     # retrieve invoice
2178     #erweiterung um das entsprechende feld lieferscheinnummer (a.donumber) in der html-maske anzuzeigen 12.02.2009 jb
2179
2180     $query =
2181       qq|SELECT
2182            a.invnumber, a.ordnumber, a.quonumber, a.cusordnumber,
2183            a.orddate, a.quodate, a.globalproject_id,
2184            a.transdate AS invdate, a.deliverydate, a.tax_point, a.paid, a.storno, a.storno_id, a.gldate,
2185            a.shippingpoint, a.shipvia, a.notes, a.intnotes, a.taxzone_id,
2186            a.duedate, a.taxincluded, (SELECT cu.name FROM currencies cu WHERE cu.id=a.currency_id) AS currency, a.shipto_id, a.cp_id,
2187            a.billing_address_id,
2188            a.employee_id, a.salesman_id, a.payment_id,
2189            a.mtime, a.itime,
2190            a.language_id, a.delivery_customer_id, a.delivery_vendor_id, a.type,
2191            a.transaction_description, a.donumber, a.invnumber_for_credit_note,
2192            a.marge_total, a.marge_percent, a.direct_debit, a.delivery_term_id,
2193            dc.dunning_description,
2194            e.name AS employee
2195          FROM ar a
2196          LEFT JOIN employee e ON (e.id = a.employee_id)
2197          LEFT JOIN dunning_config dc ON (a.dunning_config_id = dc.id)
2198          WHERE a.id = ?|;
2199     $ref = selectfirst_hashref_query($form, $dbh, $query, $id);
2200     map { $form->{$_} = $ref->{$_} } keys %{ $ref };
2201     $form->{mtime} = $form->{itime} if !$form->{mtime};
2202     $form->{lastmtime} = $form->{mtime};
2203
2204     $form->{exchangerate} = $form->get_exchangerate($dbh, $form->{currency}, $form->{invdate}, "buy");
2205
2206     foreach my $vc (qw(customer vendor)) {
2207       next if !$form->{"delivery_${vc}_id"};
2208       ($form->{"delivery_${vc}_string"}) = selectrow_query($form, $dbh, qq|SELECT name FROM customer WHERE id = ?|, $id);
2209     }
2210
2211     # get shipto
2212     $query = qq|SELECT * FROM shipto WHERE (trans_id = ?) AND (module = 'AR')|;
2213     $ref = selectfirst_hashref_query($form, $dbh, $query, $id);
2214     $form->{$_} = $ref->{$_} for grep { m{^shipto(?!_id$)} } keys %$ref;
2215
2216     # get printed, emailed
2217     $query = qq|SELECT printed, emailed, spoolfile, formname FROM status WHERE trans_id = ?|;
2218     $sth = prepare_execute_query($form, $dbh, $query, $id);
2219
2220     while ($ref = $sth->fetchrow_hashref('NAME_lc')) {
2221       $form->{printed} .= "$ref->{formname} " if $ref->{printed};
2222       $form->{emailed} .= "$ref->{formname} " if $ref->{emailed};
2223       $form->{queued} .= "$ref->{formname} $ref->{spoolfile} " if $ref->{spoolfile};
2224     }
2225     $sth->finish;
2226     map { $form->{$_} =~ s/ +$//g } qw(printed emailed queued);
2227
2228     my $transdate = $form->{tax_point}    ? $dbh->quote($form->{tax_point})
2229                   : $form->{deliverydate} ? $dbh->quote($form->{deliverydate})
2230                   : $form->{invdate}      ? $dbh->quote($form->{invdate})
2231                   :                         "current_date";
2232
2233
2234     my $taxzone_id = $form->{taxzone_id} *= 1;
2235     $taxzone_id = SL::DB::Manager::TaxZone->get_default->id unless SL::DB::Manager::TaxZone->find_by(id => $taxzone_id);
2236
2237     # retrieve individual items
2238     $query =
2239       qq|SELECT
2240            c1.accno AS inventory_accno, c1.new_chart_id AS inventory_new_chart, date($transdate) - c1.valid_from AS inventory_valid,
2241            c2.accno AS income_accno,    c2.new_chart_id AS income_new_chart,    date($transdate) - c2.valid_from as income_valid,
2242            c3.accno AS expense_accno,   c3.new_chart_id AS expense_new_chart,   date($transdate) - c3.valid_from AS expense_valid,
2243
2244            i.id AS invoice_id,
2245            i.description, i.longdescription, i.qty, i.fxsellprice AS sellprice, i.discount, i.parts_id AS id, i.unit, i.deliverydate AS reqdate,
2246            i.project_id, i.serialnumber, i.pricegroup_id, i.ordnumber, i.donumber, i.transdate, i.cusordnumber, i.subtotal, i.lastcost,
2247            i.price_factor_id, i.price_factor, i.marge_price_factor, i.active_price_source, i.active_discount_source,
2248            p.partnumber, p.part_type, p.notes AS partnotes, p.formel, p.listprice,
2249            p.classification_id,
2250            pr.projectnumber, pg.partsgroup, prg.pricegroup
2251
2252          FROM invoice i
2253          LEFT JOIN parts p ON (i.parts_id = p.id)
2254          LEFT JOIN project pr ON (i.project_id = pr.id)
2255          LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
2256          LEFT JOIN pricegroup prg ON (i.pricegroup_id = prg.id)
2257
2258          LEFT JOIN chart c1 ON ((SELECT inventory_accno_id             FROM buchungsgruppen WHERE id = p.buchungsgruppen_id) = c1.id)
2259          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)
2260          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)
2261
2262          WHERE (i.trans_id = ?) AND NOT (i.assemblyitem = '1') ORDER BY i.position|;
2263
2264     $sth = prepare_execute_query($form, $dbh, $query, $id);
2265
2266     while (my $ref = $sth->fetchrow_hashref('NAME_lc')) {
2267       # Retrieve custom variables.
2268       my $cvars = CVar->get_custom_variables(dbh        => $dbh,
2269                                              module     => 'IC',
2270                                              sub_module => 'invoice',
2271                                              trans_id   => $ref->{invoice_id},
2272                                             );
2273       map { $ref->{"ic_cvar_$_->{name}"} = $_->{value} } @{ $cvars };
2274
2275       map({ delete($ref->{$_}); } qw(inventory_accno inventory_new_chart inventory_valid)) if !$ref->{"part_inventory_accno_id"};
2276       delete($ref->{"part_inventory_accno_id"});
2277
2278       foreach my $type (qw(inventory income expense)) {
2279         while ($ref->{"${type}_new_chart"} && ($ref->{"${type}_valid"} >=0)) {
2280           my $query = qq|SELECT accno, new_chart_id, date($transdate) - valid_from FROM chart WHERE id = ?|;
2281           @$ref{ map $type.$_, qw(_accno _new_chart _valid) } = selectrow_query($form, $dbh, $query, $ref->{"${type}_new_chart"});
2282         }
2283       }
2284
2285       # get tax rates and description
2286       my $accno_id = ($form->{vc} eq "customer") ? $ref->{income_accno} : $ref->{expense_accno};
2287       $query =
2288         qq|SELECT c.accno, t.taxdescription, t.rate, t.id as tax_id, c.accno as taxnumber
2289            FROM tax t
2290            LEFT JOIN chart c ON (c.id = t.chart_id)
2291            WHERE t.id IN
2292              (SELECT tk.tax_id FROM taxkeys tk
2293               WHERE tk.chart_id = (SELECT id FROM chart WHERE accno = ?)
2294                 AND startdate <= date($transdate)
2295               ORDER BY startdate DESC LIMIT 1)
2296            ORDER BY c.accno|;
2297       my $stw = prepare_execute_query($form, $dbh, $query, $accno_id);
2298       $ref->{taxaccounts} = "";
2299       my $i=0;
2300       while (my $ptr = $stw->fetchrow_hashref('NAME_lc')) {
2301
2302         if (($ptr->{accno} eq "") && ($ptr->{rate} == 0)) {
2303           $i++;
2304           $ptr->{accno} = $i;
2305         }
2306         $ref->{taxaccounts} .= "$ptr->{accno} ";
2307
2308         if (!($form->{taxaccounts} =~ /\Q$ptr->{accno}\E/)) {
2309           $form->{"$ptr->{accno}_rate"}        = $ptr->{rate};
2310           $form->{"$ptr->{accno}_description"} = $ptr->{taxdescription};
2311           $form->{"$ptr->{accno}_taxnumber"}   = $ptr->{taxnumber}; # don't use this anymore
2312           $form->{"$ptr->{accno}_tax_id"}      = $ptr->{tax_id};
2313           $form->{taxaccounts} .= "$ptr->{accno} ";
2314         }
2315
2316       }
2317
2318       $ref->{qty} *= -1 if $form->{type} eq "credit_note";
2319
2320       chop $ref->{taxaccounts};
2321       push @{ $form->{invoice_details} }, $ref;
2322       $stw->finish;
2323     }
2324     $sth->finish;
2325
2326     # Fetch shipping address.
2327     $query = qq|SELECT s.* FROM shipto s WHERE s.trans_id = ? AND s.module = 'AR'|;
2328     $ref   = selectfirst_hashref_query($form, $dbh, $query, $form->{id});
2329
2330     $form->{$_} = $ref->{$_} for grep { $_ ne 'id' } keys %$ref;
2331
2332     if ($form->{shipto_id}) {
2333       my $cvars = CVar->get_custom_variables(
2334         dbh      => $dbh,
2335         module   => 'ShipTo',
2336         trans_id => $form->{shipto_id},
2337       );
2338       $form->{"shiptocvar_$_->{name}"} = $_->{value} for @{ $cvars };
2339     }
2340
2341     Common::webdav_folder($form);
2342   }
2343
2344   return 1;
2345 }
2346
2347 sub get_customer {
2348   $main::lxdebug->enter_sub();
2349
2350   my ($self, $myconfig, $form) = @_;
2351
2352   # connect to database
2353   my $dbh = $form->get_standard_dbh;
2354
2355   my $dateformat = $myconfig->{dateformat};
2356   $dateformat .= "yy" if $myconfig->{dateformat} !~ /^y/;
2357
2358   my (@values, $ref, $query);
2359
2360   my $cid = conv_i($form->{customer_id});
2361   my $payment_id;
2362
2363   # get customer
2364   my $where = '';
2365   if ($cid) {
2366     $where .= 'AND c.id = ?';
2367     push @values, $cid;
2368   }
2369   $query =
2370     qq|SELECT
2371          c.id AS customer_id, c.name AS customer, c.discount as customer_discount, c.creditlimit,
2372          c.email, c.cc, c.bcc, c.language_id, c.payment_id, c.delivery_term_id,
2373          c.street, c.zipcode, c.city, c.country,
2374          c.notes AS intnotes, c.pricegroup_id as customer_pricegroup_id, c.taxzone_id, c.salesman_id, cu.name AS curr,
2375          c.taxincluded_checked, c.direct_debit,
2376          (SELECT aba.id
2377           FROM additional_billing_addresses aba
2378           WHERE aba.default_address
2379           LIMIT 1) AS default_billing_address_id,
2380          b.discount AS tradediscount, b.description AS business
2381        FROM customer c
2382        LEFT JOIN business b ON (b.id = c.business_id)
2383        LEFT JOIN currencies cu ON (c.currency_id=cu.id)
2384        WHERE 1 = 1 $where|;
2385   $ref = selectfirst_hashref_query($form, $dbh, $query, @values);
2386
2387   delete $ref->{salesman_id} if !$ref->{salesman_id};
2388   delete $ref->{payment_id}  if !$ref->{payment_id};
2389
2390   map { $form->{$_} = $ref->{$_} } keys %$ref;
2391
2392   if ($form->{payment_id}) {
2393     my $reference_date = $form->{invdate} ? DateTime->from_kivitendo($form->{invdate}) : undef;
2394     $form->{duedate}   = SL::DB::PaymentTerm->new(id => $form->{payment_id})->load->calc_date(reference_date => $reference_date)->to_kivitendo;
2395   } else {
2396     $form->{duedate}   = DateTime->today_local->to_kivitendo;
2397   }
2398
2399   # use customer currency
2400   $form->{currency} = $form->{curr};
2401
2402   $query =
2403     qq|SELECT sum(amount - paid) AS dunning_amount
2404        FROM ar
2405        WHERE (paid < amount)
2406          AND (customer_id = ?)
2407          AND (dunning_config_id IS NOT NULL)|;
2408   $ref = selectfirst_hashref_query($form, $dbh, $query, $cid);
2409   map { $form->{$_} = $ref->{$_} } keys %$ref;
2410
2411   $query =
2412     qq|SELECT dnn.dunning_description AS max_dunning_level
2413        FROM dunning_config dnn
2414        WHERE id IN (SELECT dunning_config_id
2415                     FROM ar
2416                     WHERE (paid < amount) AND (customer_id = ?) AND (dunning_config_id IS NOT NULL))
2417        ORDER BY dunning_level DESC LIMIT 1|;
2418   $ref = selectfirst_hashref_query($form, $dbh, $query, $cid);
2419   map { $form->{$_} = $ref->{$_} } keys %$ref;
2420
2421   $form->{creditremaining} = $form->{creditlimit};
2422   $query = qq|SELECT SUM(amount - paid) FROM ar WHERE customer_id = ?|;
2423   my ($value) = selectrow_query($form, $dbh, $query, $cid);
2424   $form->{creditremaining} -= $value;
2425
2426   $query =
2427     qq|SELECT o.amount,
2428          (SELECT e.buy FROM exchangerate e
2429           WHERE e.currency_id = o.currency_id
2430             AND e.transdate = o.transdate)
2431        FROM oe o
2432        WHERE o.customer_id = ?
2433          AND o.quotation = '0'
2434          AND o.closed = '0'|;
2435   my $sth = prepare_execute_query($form, $dbh, $query, $cid);
2436
2437   while (my ($amount, $exch) = $sth->fetchrow_array) {
2438     $exch = 1 unless $exch;
2439     $form->{creditremaining} -= $amount * $exch;
2440   }
2441   $sth->finish;
2442
2443   $main::lxdebug->leave_sub();
2444 }
2445
2446 sub retrieve_item {
2447   $main::lxdebug->enter_sub();
2448
2449   my ($self, $myconfig, $form) = @_;
2450
2451   # connect to database
2452   my $dbh = $form->get_standard_dbh;
2453
2454   my $i = $form->{rowcount};
2455
2456   my $where = qq|NOT p.obsolete = '1'|;
2457   my @values;
2458
2459   foreach my $column (qw(p.partnumber p.description pgpartsgroup )) {
2460     my ($table, $field) = split m/\./, $column;
2461     next if !$form->{"${field}_${i}"};
2462     $where .= qq| AND lower(${column}) ILIKE ?|;
2463     push @values, like($form->{"${field}_${i}"});
2464   }
2465
2466   my (%mm_by_id);
2467   if ($form->{"partnumber_$i"} && !$form->{"description_$i"}) {
2468     $where .= qq| OR (NOT p.obsolete = '1' AND p.ean = ? )|;
2469     push @values, $form->{"partnumber_$i"};
2470
2471     # also search hits in makemodels, but only cache the results by id and merge later
2472     my $mm_query = qq|
2473       SELECT parts_id, model FROM makemodel LEFT JOIN parts ON parts.id = parts_id WHERE NOT parts.obsolete AND model ILIKE ?;
2474     |;
2475     my $mm_results = selectall_hashref_query($::form, $dbh, $mm_query, like($form->{"partnumber_$i"}));
2476     my @mm_ids     = map { $_->{parts_id} } @$mm_results;
2477     push @{$mm_by_id{ $_->{parts_id} } ||= []}, $_ for @$mm_results;
2478
2479     if (@mm_ids) {
2480       $where .= qq| OR p.id IN (| . join(',', ('?') x @mm_ids) . qq|)|;
2481       push @values, @mm_ids;
2482     }
2483   }
2484
2485   # Search for part ID overrides all other criteria.
2486   if ($form->{"id_${i}"}) {
2487     $where  = qq|p.id = ?|;
2488     @values = ($form->{"id_${i}"});
2489   }
2490
2491   if ($form->{"description_$i"}) {
2492     $where .= qq| ORDER BY p.description|;
2493   } else {
2494     $where .= qq| ORDER BY p.partnumber|;
2495   }
2496
2497   my $transdate;
2498   if ($form->{type} eq "invoice") {
2499     $transdate =
2500       $form->{deliverydate} ? $dbh->quote($form->{deliverydate}) :
2501       $form->{invdate}      ? $dbh->quote($form->{invdate}) :
2502                               "current_date";
2503   } else {
2504     $transdate =
2505       $form->{transdate}    ? $dbh->quote($form->{transdate}) :
2506                               "current_date";
2507   }
2508
2509   my $taxzone_id = $form->{taxzone_id} * 1;
2510   $taxzone_id = 0 if (0 > $taxzone_id) || (3 < $taxzone_id);
2511
2512   my $query =
2513     qq|SELECT
2514          p.id, p.partnumber, p.description, p.sellprice,
2515          p.listprice, p.part_type, p.lastcost,
2516          p.ean, p.notes,
2517          p.classification_id,
2518
2519          c1.accno AS inventory_accno,
2520          c1.new_chart_id AS inventory_new_chart,
2521          date($transdate) - c1.valid_from AS inventory_valid,
2522
2523          c2.accno AS income_accno,
2524          c2.new_chart_id AS income_new_chart,
2525          date($transdate)  - c2.valid_from AS income_valid,
2526
2527          c3.accno AS expense_accno,
2528          c3.new_chart_id AS expense_new_chart,
2529          date($transdate) - c3.valid_from AS expense_valid,
2530
2531          p.unit, p.part_type, p.onhand,
2532          p.notes AS partnotes, p.notes AS longdescription,
2533          p.not_discountable, p.formel, p.payment_id AS part_payment_id,
2534          p.price_factor_id, p.weight,
2535
2536          pfac.factor AS price_factor,
2537          pt.used_for_sale AS used_for_sale,
2538          pg.partsgroup
2539
2540        FROM parts p
2541        LEFT JOIN chart c1 ON
2542          ((SELECT inventory_accno_id
2543            FROM buchungsgruppen
2544            WHERE id = p.buchungsgruppen_id) = c1.id)
2545        LEFT JOIN chart c2 ON
2546          ((SELECT tc.income_accno_id
2547            FROM taxzone_charts tc
2548            WHERE tc.buchungsgruppen_id = p.buchungsgruppen_id and tc.taxzone_id = ${taxzone_id}) = c2.id)
2549        LEFT JOIN chart c3 ON
2550          ((SELECT tc.expense_accno_id
2551            FROM taxzone_charts tc
2552            WHERE tc.buchungsgruppen_id = p.buchungsgruppen_id and tc.taxzone_id = ${taxzone_id}) = c3.id)
2553        LEFT JOIN partsgroup pg ON (pg.id = p.partsgroup_id)
2554        LEFT JOIN part_classifications pt ON (pt.id = p.classification_id)
2555        LEFT JOIN price_factors pfac ON (pfac.id = p.price_factor_id)
2556        WHERE $where|;
2557   my $sth = prepare_execute_query($form, $dbh, $query, @values);
2558
2559   my @translation_queries = ( [ qq|SELECT tr.translation, tr.longdescription
2560                                    FROM translation tr
2561                                    WHERE tr.language_id = ? AND tr.parts_id = ?| ],
2562                               [ qq|SELECT tr.translation, tr.longdescription
2563                                    FROM translation tr
2564                                    WHERE tr.language_id IN
2565                                      (SELECT id
2566                                       FROM language
2567                                       WHERE article_code = (SELECT article_code FROM language WHERE id = ?))
2568                                      AND tr.parts_id = ?
2569                                    LIMIT 1| ] );
2570   map { push @{ $_ }, prepare_query($form, $dbh, $_->[0]) } @translation_queries;
2571
2572   my $has_wrong_pclass = PCLASS_OK;
2573   while (my $ref = $sth->fetchrow_hashref('NAME_lc')) {
2574
2575     if ($mm_by_id{$ref->{id}}) {
2576       $ref->{makemodels} = $mm_by_id{$ref->{id}};
2577       push @{ $ref->{matches} ||= [] }, $::locale->text('Model') . ': ' . join ', ', map { $_->{model} } @{ $mm_by_id{$ref->{id}} };
2578     }
2579
2580     if (($::form->{"partnumber_$i"} ne '') && ($ref->{ean} eq $::form->{"partnumber_$i"})) {
2581       push @{ $ref->{matches} ||= [] }, $::locale->text('EAN') . ': ' . $ref->{ean};
2582     }
2583
2584     $ref->{type_and_classific} = type_abbreviation($ref->{part_type}) .
2585                                  classification_abbreviation($ref->{classification_id});
2586     if (! $ref->{used_for_sale} ) {
2587       $has_wrong_pclass = PCLASS_NOTFORSALE ;
2588       next;
2589     }
2590     # In der Buchungsgruppe ist immer ein Bestandskonto verknuepft, auch wenn
2591     # es sich um eine Dienstleistung handelt. Bei Dienstleistungen muss das
2592     # Buchungskonto also aus dem Ergebnis rausgenommen werden.
2593     if (!$ref->{inventory_accno_id}) {
2594       map({ delete($ref->{"inventory_${_}"}); } qw(accno new_chart valid));
2595     }
2596     delete($ref->{inventory_accno_id});
2597
2598     foreach my $type (qw(inventory income expense)) {
2599       while ($ref->{"${type}_new_chart"} && ($ref->{"${type}_valid"} >=0)) {
2600         my $query =
2601           qq|SELECT accno, new_chart_id, date($transdate) - valid_from
2602              FROM chart
2603              WHERE id = ?|;
2604         ($ref->{"${type}_accno"},
2605          $ref->{"${type}_new_chart"},
2606          $ref->{"${type}_valid"})
2607           = selectrow_query($form, $dbh, $query, $ref->{"${type}_new_chart"});
2608       }
2609     }
2610
2611     if ($form->{payment_id} eq "") {
2612       $form->{payment_id} = $form->{part_payment_id};
2613     }
2614
2615     # get tax rates and description
2616     my $accno_id = ($form->{vc} eq "customer") ? $ref->{income_accno} : $ref->{expense_accno};
2617     $query =
2618       qq|SELECT c.accno, t.taxdescription, t.id as tax_id, t.rate, c.accno as taxnumber
2619          FROM tax t
2620          LEFT JOIN chart c ON (c.id = t.chart_id)
2621          WHERE t.id in
2622            (SELECT tk.tax_id
2623             FROM taxkeys tk
2624             WHERE tk.chart_id = (SELECT id from chart WHERE accno = ?)
2625               AND startdate <= ?
2626             ORDER BY startdate DESC
2627             LIMIT 1)
2628          ORDER BY c.accno|;
2629     @values = ($accno_id, $transdate eq "current_date" ? "now" : $transdate);
2630     my $stw = $dbh->prepare($query);
2631     $stw->execute(@values) || $form->dberror($query);
2632
2633     $ref->{taxaccounts} = "";
2634     my $i = 0;
2635     while (my $ptr = $stw->fetchrow_hashref('NAME_lc')) {
2636
2637       if (($ptr->{accno} eq "") && ($ptr->{rate} == 0)) {
2638         $i++;
2639         $ptr->{accno} = $i;
2640       }
2641       $ref->{taxaccounts} .= "$ptr->{accno} ";
2642
2643       if (!($form->{taxaccounts} =~ /\Q$ptr->{accno}\E/)) {
2644         $form->{"$ptr->{accno}_rate"}        = $ptr->{rate};
2645         $form->{"$ptr->{accno}_description"} = $ptr->{taxdescription};
2646         $form->{"$ptr->{accno}_taxnumber"}   = $ptr->{taxnumber};
2647         $form->{"$ptr->{accno}_tax_id"}      = $ptr->{tax_id};
2648         $form->{taxaccounts} .= "$ptr->{accno} ";
2649       }
2650
2651     }
2652
2653     $stw->finish;
2654     chop $ref->{taxaccounts};
2655
2656     if ($form->{language_id}) {
2657       for my $spec (@translation_queries) {
2658         do_statement($form, $spec->[1], $spec->[0], conv_i($form->{language_id}), conv_i($ref->{id}));
2659         my ($translation, $longdescription) = $spec->[1]->fetchrow_array;
2660         next unless $translation;
2661         $ref->{description} = $translation;
2662         $ref->{longdescription} = $longdescription;
2663         last;
2664       }
2665     }
2666
2667     $ref->{onhand} *= 1;
2668     push @{ $form->{item_list} }, $ref;
2669   }
2670   $sth->finish;
2671   $_->[1]->finish for @translation_queries;
2672
2673   $form->{is_wrong_pclass} = $has_wrong_pclass;
2674   $form->{NOTFORSALE}      = PCLASS_NOTFORSALE;
2675   $form->{NOTFORPURCHASE}  = PCLASS_NOTFORPURCHASE;
2676   foreach my $item (@{ $form->{item_list} }) {
2677     my $custom_variables = CVar->get_custom_variables(module   => 'IC',
2678                                                       trans_id => $item->{id},
2679                                                       dbh      => $dbh,
2680                                                      );
2681     $form->{is_wrong_pclass} = PCLASS_OK; # one correct type
2682     map { $item->{"ic_cvar_" . $_->{name} } = $_->{value} } @{ $custom_variables };
2683   }
2684   $main::lxdebug->leave_sub();
2685 }
2686
2687 sub has_storno {
2688   $main::lxdebug->enter_sub();
2689
2690   my ($self, $myconfig, $form, $table) = @_;
2691
2692   $main::lxdebug->leave_sub() and return 0 unless ($form->{id});
2693
2694   # make sure there's no funny stuff in $table
2695   # ToDO: die when this happens and throw an error
2696   $main::lxdebug->leave_sub() and return 0 if ($table =~ /\W/);
2697
2698   my $dbh = $form->get_standard_dbh;
2699
2700   my $query = qq|SELECT storno FROM $table WHERE storno_id = ?|;
2701   my ($result) = selectrow_query($form, $dbh, $query, $form->{id});
2702
2703   $main::lxdebug->leave_sub();
2704
2705   return $result;
2706 }
2707
2708 sub is_storno {
2709   $main::lxdebug->enter_sub();
2710
2711   my ($self, $myconfig, $form, $table, $id) = @_;
2712
2713   $main::lxdebug->leave_sub() and return 0 unless ($id);
2714
2715   # make sure there's no funny stuff in $table
2716   # ToDO: die when this happens and throw an error
2717   $main::lxdebug->leave_sub() and return 0 if ($table =~ /\W/);
2718
2719   my $dbh = $form->get_standard_dbh;
2720
2721   my $query = qq|SELECT storno FROM $table WHERE id = ?|;
2722   my ($result) = selectrow_query($form, $dbh, $query, $id);
2723
2724   $main::lxdebug->leave_sub();
2725
2726   return $result;
2727 }
2728
2729 sub get_standard_accno_current_assets {
2730   $main::lxdebug->enter_sub();
2731
2732   my ($self, $myconfig, $form) = @_;
2733
2734   my $dbh = $form->get_standard_dbh;
2735
2736   my $query = qq| SELECT accno FROM chart WHERE id = (SELECT ar_paid_accno_id FROM defaults)|;
2737   my ($result) = selectrow_query($form, $dbh, $query);
2738
2739   $main::lxdebug->leave_sub();
2740
2741   return $result;
2742 }
2743
2744 1;