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