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