Einkaufs- und Verkaufsrechnungen: Beim Erstellen der Einträge in acc_trans keine...
[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 Data::Dumper;
38 use SL::AM;
39 use SL::Common;
40 use SL::DBUtils;
41
42 sub invoice_details {
43   $main::lxdebug->enter_sub();
44
45   my ($self, $myconfig, $form, $locale) = @_;
46
47   $form->{duedate} = $form->{invdate} unless ($form->{duedate});
48
49   # connect to database
50   my $dbh = $form->dbconnect($myconfig);
51
52   my $query = qq|SELECT date '$form->{duedate}' - date '$form->{invdate}'
53                  AS terms
54                  FROM defaults|;
55   my $sth = $dbh->prepare($query);
56   $sth->execute || $form->dberror($query);
57
58   ($form->{terms}) = $sth->fetchrow_array;
59   $sth->finish;
60
61   my (@project_ids, %projectnumbers);
62
63   push(@project_ids, $form->{"globalproject_id"}) if ($form->{"globalproject_id"});
64
65   # sort items by partsgroup
66   for $i (1 .. $form->{rowcount}) {
67     $partsgroup = "";
68     if ($form->{"partsgroup_$i"} && $form->{groupitems}) {
69       $partsgroup = $form->{"partsgroup_$i"};
70     }
71     push @partsgroup, [$i, $partsgroup];
72     push(@project_ids, $form->{"project_id_$i"}) if ($form->{"project_id_$i"});
73   }
74
75   if (@project_ids) {
76     $query = "SELECT id, projectnumber FROM project WHERE id IN (" .
77       join(", ", map({ "?" } @project_ids)) . ")";
78     $sth = $dbh->prepare($query);
79     $sth->execute(@project_ids) ||
80       $form->dberror($query . " (" . join(", ", @project_ids) . ")");
81     while (my $ref = $sth->fetchrow_hashref()) {
82       $projectnumbers{$ref->{id}} = $ref->{projectnumber};
83     }
84     $sth->finish();
85   }
86
87   $form->{"globalprojectnumber"} =
88     $projectnumbers{$form->{"globalproject_id"}};
89
90   my $tax = 0;
91   my $item;
92   my $i;
93   my @partsgroup = ();
94   my $partsgroup;
95   my %oid = ('Pg'     => 'oid',
96              'Oracle' => 'rowid');
97
98   # sort items by partsgroup
99   for $i (1 .. $form->{rowcount}) {
100     $partsgroup = "";
101     if ($form->{"partsgroup_$i"} && $form->{groupitems}) {
102       $partsgroup = $form->{"partsgroup_$i"};
103     }
104     push @partsgroup, [$i, $partsgroup];
105   }
106
107   my $sameitem = "";
108   my @taxaccounts;
109   my %taxaccounts;
110   my %taxbase;
111   my $taxrate;
112   my $taxamount;
113   my $taxbase;
114   my $taxdiff;
115   my $nodiscount;
116   my $yesdiscount;
117   my $nodiscount_subtotal = 0;
118   my $discount_subtotal = 0;
119   my $position = 0;
120   my $subtotal_header = 0;
121   my $subposition = 0;
122
123   my @arrays =
124     qw(runningnumber number description longdescription qty ship unit bin
125        deliverydate_oe ordnumber_oe transdate_oe licensenumber validuntil
126        partnotes serialnumber reqdate sellprice listprice netprice
127        discount p_discount discount_sub nodiscount_sub
128        linetotal  nodiscount_linetotal tax_rate projectnumber);
129
130   my @tax_arrays =
131     qw(taxbase tax taxdescription taxrate taxnumber);
132
133   foreach $item (sort { $a->[1] cmp $b->[1] } @partsgroup) {
134     $i = $item->[0];
135
136     if ($item->[1] ne $sameitem) {
137       push(@{ $form->{description} }, qq|$item->[1]|);
138       $sameitem = $item->[1];
139
140       map({ push(@{ $form->{$_} }, "") } grep({ $_ ne "description" } @arrays));
141     }
142
143     $form->{"qty_$i"} = $form->parse_amount($myconfig, $form->{"qty_$i"});
144
145     if ($form->{"id_$i"} != 0) {
146
147       # add number, description and qty to $form->{number},
148       if ($form->{"subtotal_$i"} && !$subtotal_header) {
149         $subtotal_header = $i;
150         $position = int($position);
151         $subposition = 0;
152         $position++;
153       } elsif ($subtotal_header) {
154         $subposition += 1;
155         $position = int($position);
156         $position = $position.".".$subposition;
157       } else {
158         $position = int($position);
159         $position++;
160       }
161       push(@{ $form->{runningnumber} }, $position);
162       push(@{ $form->{number} },        qq|$form->{"partnumber_$i"}|);
163       push(@{ $form->{serialnumber} },  qq|$form->{"serialnumber_$i"}|);
164       push(@{ $form->{bin} },           qq|$form->{"bin_$i"}|);
165       push(@{ $form->{"partnotes"} },   qq|$form->{"partnotes_$i"}|);
166       push(@{ $form->{description} },   qq|$form->{"description_$i"}|);
167       push(@{ $form->{longdescription} },   qq|$form->{"longdescription_$i"}|);
168       push(@{ $form->{qty} },
169            $form->format_amount($myconfig, $form->{"qty_$i"}));
170       push(@{ $form->{unit} },            qq|$form->{"unit_$i"}|);
171       push(@{ $form->{deliverydate_oe} }, qq|$form->{"deliverydate_$i"}|);
172
173       push(@{ $form->{sellprice} },    $form->{"sellprice_$i"});
174       push(@{ $form->{ordnumber_oe} }, qq|$form->{"ordnumber_$i"}|);
175       push(@{ $form->{transdate_oe} }, qq|$form->{"transdate_$i"}|);
176       push(@{ $form->{invnumber} }, qq|$form->{"invnumber"}|);
177       push(@{ $form->{invdate} }, qq|$form->{"invdate"}|);
178
179       if ($form->{lizenzen}) {
180         if ($form->{"licensenumber_$i"}) {
181           $query =
182             qq|SELECT l.licensenumber, l.validuntil FROM license l WHERE l.id = $form->{"licensenumber_$i"}|;
183           $sth = $dbh->prepare($query);
184           $sth->execute || $form->dberror($query);
185
186           ($licensenumber, $validuntil) = $sth->fetchrow_array;
187           push(@{ $form->{licensenumber} }, $licensenumber);
188           push(@{ $form->{validuntil} },
189                $locale->date($myconfig, $validuntil, 0));
190           $sth->finish;
191         } else {
192           push(@{ $form->{licensenumber} }, "");
193           push(@{ $form->{validuntil} },    "");
194         }
195       }
196
197       # listprice
198       push(@{ $form->{listprice} }, $form->{"listprice_$i"});
199
200       my $sellprice = $form->parse_amount($myconfig, $form->{"sellprice_$i"});
201       my ($dec) = ($sellprice =~ /\.(\d+)/);
202       $dec = length $dec;
203       my $decimalplaces = ($dec > 2) ? $dec : 2;
204
205       my $i_discount =
206         $form->round_amount(
207                             $sellprice * $form->parse_amount($myconfig,
208                                                  $form->{"discount_$i"}) / 100,
209                             $decimalplaces);
210
211       my $discount =
212         $form->round_amount($form->{"qty_$i"} * $i_discount, $decimalplaces);
213
214       # keep a netprice as well, (sellprice - discount)
215       $form->{"netprice_$i"} = $sellprice - $i_discount;
216
217       push(@{ $form->{netprice} },
218            ($form->{"netprice_$i"} != 0)
219            ? $form->format_amount(
220                                  $myconfig, $form->{"netprice_$i"},
221                                  $decimalplaces
222              )
223            : " ");
224
225       my $linetotal =
226         $form->round_amount($form->{"qty_$i"} * $form->{"netprice_$i"}, 2);
227
228       my $nodiscount_linetotal =
229         $form->round_amount($form->{"qty_$i"} * $sellprice, 2);
230
231       $discount =
232         ($discount != 0)
233         ? $form->format_amount($myconfig, $discount * -1, $decimalplaces)
234         : " ";
235       $linetotal = ($linetotal != 0) ? $linetotal : " ";
236
237       push(@{ $form->{discount} },   $discount);
238       push(@{ $form->{p_discount} }, $form->{"discount_$i"});
239       if (($form->{"discount_$i"} ne "") && ($form->{"discount_$i"} != 0)) {
240         $form->{discount_p} = $form->{"discount_$i"};
241       }
242       $form->{total} += $linetotal;
243       $discount_subtotal += $linetotal;
244       $form->{nodiscount_total} += $nodiscount_linetotal;
245       $nodiscount_subtotal += $nodiscount_linetotal;
246       $form->{discount_total} += $form->parse_amount($myconfig, $discount);
247
248       if ($form->{"subtotal_$i"} && $subtotal_header && ($subtotal_header != $i)) {
249         $discount_subtotal = $form->format_amount($myconfig, $discount_subtotal, 2);
250         push(@{ $form->{discount_sub} },  $discount_subtotal);
251         $nodiscount_subtotal = $form->format_amount($myconfig, $nodiscount_subtotal, 2);
252         push(@{ $form->{nodiscount_sub} }, $nodiscount_subtotal);
253         $discount_subtotal = 0;
254         $nodiscount_subtotal = 0;
255         $subtotal_header = 0;
256       } else {
257         push(@{ $form->{discount_sub} }, "");
258         push(@{ $form->{nodiscount_sub} }, "");
259       }
260
261       if ($linetotal == $netto_linetotal) {
262         $nodiscount += $linetotal;
263       }
264
265       push(@{ $form->{linetotal} },
266            $form->format_amount($myconfig, $linetotal, 2));
267       push(@{ $form->{nodiscount_linetotal} },
268            $form->format_amount($myconfig, $nodiscount_linetotal, 2));
269
270       push(@{ $form->{projectnumber} }, $projectnumbers{$form->{"project_id_$i"}});
271
272       @taxaccounts = split / /, $form->{"taxaccounts_$i"};
273       $taxrate     = 0;
274       $taxdiff     = 0;
275
276       map { $taxrate += $form->{"${_}_rate"} } @taxaccounts;
277
278       if ($form->{taxincluded}) {
279
280         # calculate tax
281         $taxamount = $linetotal * $taxrate / (1 + $taxrate);
282         $taxbase = $linetotal - $taxamount;
283       } else {
284         $taxamount = $linetotal * $taxrate;
285         $taxbase   = $linetotal;
286       }
287
288       if ($form->round_amount($taxrate, 7) == 0) {
289         if ($form->{taxincluded}) {
290           foreach $item (@taxaccounts) {
291             $taxamount =
292               $form->round_amount($linetotal * $form->{"${item}_rate"} /
293                                     (1 + abs($form->{"${item}_rate"})),
294                                   2);
295
296             $taxaccounts{$item} += $taxamount;
297             $taxdiff            += $taxamount;
298
299             $taxbase{$item} += $taxbase;
300           }
301           $taxaccounts{ $taxaccounts[0] } += $taxdiff;
302         } else {
303           foreach $item (@taxaccounts) {
304             $taxaccounts{$item} += $linetotal * $form->{"${item}_rate"};
305             $taxbase{$item}     += $taxbase;
306           }
307         }
308       } else {
309         foreach $item (@taxaccounts) {
310           $taxaccounts{$item} +=
311             $taxamount * $form->{"${item}_rate"} / $taxrate;
312           $taxbase{$item} += $taxbase;
313         }
314       }
315       $tax_rate = $taxrate * 100;
316       push(@{ $form->{tax_rate} }, qq|$tax_rate|);
317       if ($form->{"assembly_$i"}) {
318         $sameitem = "";
319
320         # get parts and push them onto the stack
321         my $sortorder = "";
322         if ($form->{groupitems}) {
323           $sortorder =
324             qq|ORDER BY pg.partsgroup, a.$oid{$myconfig->{dbdriver}}|;
325         } else {
326           $sortorder = qq|ORDER BY a.$oid{$myconfig->{dbdriver}}|;
327         }
328
329         $query = qq|SELECT p.partnumber, p.description, p.unit, a.qty,
330                     pg.partsgroup
331                     FROM assembly a
332                     JOIN parts p ON (a.parts_id = p.id)
333                     LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
334                     WHERE a.bom = '1'
335                     AND a.id = '$form->{"id_$i"}'
336                     $sortorder|;
337         $sth = $dbh->prepare($query);
338         $sth->execute || $form->dberror($query);
339
340         while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
341           if ($form->{groupitems} && $ref->{partsgroup} ne $sameitem) {
342             map({ push(@{ $form->{$_} }, "") } grep({ $_ ne "description" } @arrays));
343             $sameitem = ($ref->{partsgroup}) ? $ref->{partsgroup} : "--";
344             push(@{ $form->{description} }, $sameitem);
345           }
346
347           map { $form->{"a_$_"} = $ref->{$_} } qw(partnumber description);
348
349           push(@{ $form->{description} },
350                $form->format_amount($myconfig, $ref->{qty} * $form->{"qty_$i"}
351                  )
352                  . qq| -- $form->{"a_partnumber"}, $form->{"a_description"}|);
353           map({ push(@{ $form->{$_} }, "") } grep({ $_ ne "description" } @arrays));
354
355         }
356         $sth->finish;
357       }
358     }
359   }
360
361   foreach my $item (sort keys %taxaccounts) {
362     push(@{ $form->{taxbase} },
363           $form->format_amount($myconfig, $taxbase{$item}, 2));
364
365     $tax += $taxamount = $form->round_amount($taxaccounts{$item}, 2);
366
367     push(@{ $form->{tax} }, $form->format_amount($myconfig, $taxamount, 2));
368     push(@{ $form->{taxdescription} }, $form->{"${item}_description"}  . q{ } . 100 * $form->{"${item}_rate"} . q{%});
369     push(@{ $form->{taxrate} },
370           $form->format_amount($myconfig, $form->{"${item}_rate"} * 100));
371     push(@{ $form->{taxnumber} }, $form->{"${item}_taxnumber"});
372   }
373
374   for my $i (1 .. $form->{paidaccounts}) {
375     if ($form->{"paid_$i"}) {
376       push(@{ $form->{payment} }, $form->{"paid_$i"});
377       my ($accno, $description) = split /--/, $form->{"AR_paid_$i"};
378       push(@{ $form->{paymentaccount} }, $description);
379       push(@{ $form->{paymentdate} },    $form->{"datepaid_$i"});
380       push(@{ $form->{paymentsource} },  $form->{"source_$i"});
381
382       $form->{paid} += $form->parse_amount($myconfig, $form->{"paid_$i"});
383     }
384   }
385
386   $form->{subtotal} = $form->format_amount($myconfig, $form->{total}, 2);
387   $yesdiscount = $form->{nodiscount_total} - $nodiscount;
388   $form->{nodiscount_subtotal} = $form->format_amount($myconfig, $form->{nodiscount_total}, 2);
389   $form->{discount_total} = $form->format_amount($myconfig, $form->{discount_total}, 2);
390   $form->{nodiscount} = $form->format_amount($myconfig, $nodiscount, 2);
391   $form->{yesdiscount} = $form->format_amount($myconfig, $yesdiscount, 2);
392
393   $form->{invtotal} =
394     ($form->{taxincluded}) ? $form->{total} : $form->{total} + $tax;
395   $form->{total} =
396     $form->format_amount($myconfig, $form->{invtotal} - $form->{paid}, 2);
397
398   $form->{invtotal} = $form->format_amount($myconfig, $form->{invtotal}, 2);
399   $form->{paid} = $form->format_amount($myconfig, $form->{paid}, 2);
400   $form->set_payment_options($myconfig, $form->{invdate});
401
402   $form->{username} = $myconfig->{name};
403
404   $dbh->disconnect;
405
406   $main::lxdebug->leave_sub();
407 }
408
409 sub project_description {
410   $main::lxdebug->enter_sub();
411
412   my ($self, $dbh, $id) = @_;
413
414   my $query = qq|SELECT p.description
415                  FROM project p
416                  WHERE p.id = $id|;
417   my $sth = $dbh->prepare($query);
418   $sth->execute || $form->dberror($query);
419
420   ($_) = $sth->fetchrow_array;
421
422   $sth->finish;
423
424   $main::lxdebug->leave_sub();
425
426   return $_;
427 }
428
429 sub customer_details {
430   $main::lxdebug->enter_sub();
431
432   my ($self, $myconfig, $form, @wanted_vars) = @_;
433
434   # connect to database
435   my $dbh = $form->dbconnect($myconfig);
436
437   # get contact id, set it if nessessary
438   $form->{cp_id} *= 1;
439
440   $contact = "";
441   if ($form->{cp_id}) {
442     $contact = "and cp.cp_id = $form->{cp_id}";
443   }
444
445   # get rest for the customer
446   my $query = qq|SELECT ct.*, cp.*, ct.notes as customernotes, ct.phone AS customerphone, ct.fax AS customerfax, ct.email AS customeremail
447                  FROM customer ct
448                  LEFT JOIN contacts cp on ct.id = cp.cp_cv_id
449                  WHERE ct.id = $form->{customer_id} $contact order by cp.cp_id limit 1|;
450   my $sth = $dbh->prepare($query);
451   $sth->execute || $form->dberror($query);
452
453   $ref = $sth->fetchrow_hashref(NAME_lc);
454
455   # remove id and taxincluded before copy back
456   delete @$ref{qw(id taxincluded)};
457
458   @wanted_vars = grep({ $_ } @wanted_vars);
459   if (scalar(@wanted_vars) > 0) {
460     my %h_wanted_vars;
461     map({ $h_wanted_vars{$_} = 1; } @wanted_vars);
462     map({ delete($ref->{$_}) unless ($h_wanted_vars{$_}); } keys(%{$ref}));
463   }
464
465   map { $form->{$_} = $ref->{$_} } keys %$ref;
466   $sth->finish;
467
468   if ($form->{delivery_customer_id}) {
469     my $query = qq|SELECT ct.*, ct.notes as customernotes
470                  FROM customer ct
471                  WHERE ct.id = $form->{delivery_customer_id} limit 1|;
472     my $sth = $dbh->prepare($query);
473     $sth->execute || $form->dberror($query);
474
475     $ref = $sth->fetchrow_hashref(NAME_lc);
476
477     $sth->finish;
478     map { $form->{"dc_$_"} = $ref->{$_} } keys %$ref;
479   }
480
481   if ($form->{delivery_vendor_id}) {
482     my $query = qq|SELECT ct.*, ct.notes as customernotes
483                  FROM customer ct
484                  WHERE ct.id = $form->{delivery_vendor_id} limit 1|;
485     my $sth = $dbh->prepare($query);
486     $sth->execute || $form->dberror($query);
487
488     $ref = $sth->fetchrow_hashref(NAME_lc);
489
490     $sth->finish;
491     map { $form->{"dv_$_"} = $ref->{$_} } keys %$ref;
492   }
493   $dbh->disconnect;
494
495   $main::lxdebug->leave_sub();
496 }
497
498 sub post_invoice {
499   $main::lxdebug->enter_sub();
500
501   my ($self, $myconfig, $form) = @_;
502
503   # connect to database, turn off autocommit
504   my $dbh = $form->dbconnect_noauto($myconfig);
505
506   my ($query, $sth, $null, $project_id, $deliverydate);
507   my $exchangerate = 0;
508
509   ($null, $form->{employee_id}) = split /--/, $form->{employee};
510   unless ($form->{employee_id}) {
511     $form->get_employee($dbh);
512   }
513
514   $form->{payment_id} *= 1;
515   $form->{language_id} *= 1;
516   $form->{taxzone_id} *= 1;
517   $form->{delivery_customer_id} *= 1;
518   $form->{delivery_vendor_id} *= 1;
519   $form->{storno} *= 1;
520   $form->{shipto_id} *= 1;
521
522
523   ($null, $form->{department_id}) = split(/--/, $form->{department});
524   $form->{department_id} *= 1;
525
526   my $service_units = AM->retrieve_units($myconfig,$form,"service");
527   my $part_units = AM->retrieve_units($myconfig,$form,"dimension");
528
529
530
531   if ($form->{id}) {
532
533     &reverse_invoice($dbh, $form);
534
535   } else {
536     my $uid = rand() . time;
537
538     $uid .= $form->{login};
539
540     $uid = substr($uid, 2, 75);
541
542     $query = qq|INSERT INTO ar (invnumber, employee_id)
543                 VALUES ('$uid', $form->{employee_id})|;
544     $dbh->do($query) || $form->dberror($query);
545
546     $query = qq|SELECT a.id FROM ar a
547                 WHERE a.invnumber = '$uid'|;
548     $sth = $dbh->prepare($query);
549     $sth->execute || $form->dberror($query);
550
551     ($form->{id}) = $sth->fetchrow_array;
552     $sth->finish;
553
554     if (!$form->{invnumber}) {
555       $form->{invnumber} =
556         $form->update_defaults($myconfig, $form->{type} eq "credit_note" ?
557                                "cnnumber" : "invnumber", $dbh);
558     }
559   }
560
561   map { $form->{$_} =~ s/\'/\'\'/g }
562     (qw(invnumber shippingpoint shipvia notes intnotes message));
563
564   my ($netamount, $invoicediff) = (0, 0);
565   my ($amount, $linetotal, $lastincomeaccno);
566
567   if ($form->{currency} eq $form->{defaultcurrency}) {
568     $form->{exchangerate} = 1;
569   } else {
570     $exchangerate =
571       $form->check_exchangerate($myconfig, $form->{currency},
572                                 $form->{transdate}, 'buy');
573   }
574
575   $form->{exchangerate} =
576     ($exchangerate)
577     ? $exchangerate
578     : $form->parse_amount($myconfig, $form->{exchangerate});
579
580   $form->{expense_inventory} = "";
581
582   foreach my $i (1 .. $form->{rowcount}) {
583     if ($form->{type} eq "credit_note") {
584       $form->{"qty_$i"} = $form->parse_amount($myconfig, $form->{"qty_$i"}) * -1;
585       $form->{shipped} = 1;   
586     } else {
587       $form->{"qty_$i"} = $form->parse_amount($myconfig, $form->{"qty_$i"});
588     }
589     my $basefactor;
590     my $basqty;
591
592     if ($form->{storno}) {
593       $form->{"qty_$i"} *= -1;
594     }
595
596     if ($form->{"id_$i"}) {
597
598       # get item baseunit
599       $query = qq|SELECT p.unit
600                   FROM parts p
601                   WHERE p.id = $form->{"id_$i"}|;
602       $sth = $dbh->prepare($query);
603       $sth->execute || $form->dberror($query);
604
605       my ($item_unit) = $sth->fetchrow_array();
606       $sth->finish;
607
608       if ($form->{"inventory_accno_$i"}) {
609         if (defined($part_units->{$item_unit}->{factor}) && $part_units->{$item_unit}->{factor} ne '' && $part_units->{$item_unit}->{factor} ne '0') {
610           $basefactor = $part_units->{$form->{"unit_$i"}}->{factor} / $part_units->{$item_unit}->{factor};
611         } else {
612           $basefactor = 1;
613         }
614         $baseqty = $form->{"qty_$i"} * $basefactor;
615       } else {
616         if (defined($service_units->{$item_unit}->{factor}) && $service_units->{$item_unit}->{factor} ne '' && $service_units->{$item_unit}->{factor} ne '0') {
617           $basefactor = $service_units->{$form->{"unit_$i"}}->{factor} / $service_units->{$item_unit}->{factor};
618         } else {
619           $basefactor = 1;
620         }
621         $baseqty = $form->{"qty_$i"} * $basefactor;
622       }
623
624       map { $form->{"${_}_$i"} =~ s/\'/\'\'/g }
625         (qw(partnumber description unit));
626
627       # undo discount formatting
628       $form->{"discount_$i"} =
629         $form->parse_amount($myconfig, $form->{"discount_$i"}) / 100;
630
631       my ($allocated, $taxrate) = (0, 0);
632       my $taxamount;
633
634       # keep entered selling price
635       my $fxsellprice =
636         $form->parse_amount($myconfig, $form->{"sellprice_$i"});
637
638       my ($dec) = ($fxsellprice =~ /\.(\d+)/);
639       $dec = length $dec;
640       my $decimalplaces = ($dec > 2) ? $dec : 2;
641
642       # deduct discount
643       my $discount =
644         $form->round_amount($fxsellprice * $form->{"discount_$i"},
645                             $decimalplaces);
646       $form->{"sellprice_$i"} = $fxsellprice - $discount;
647
648       # add tax rates
649       map { $taxrate += $form->{"${_}_rate"} } split / /,
650         $form->{"taxaccounts_$i"};
651
652       # round linetotal to 2 decimal places
653       $linetotal =
654         $form->round_amount($form->{"sellprice_$i"} * $form->{"qty_$i"}, 2);
655
656       if ($form->{taxincluded}) {
657         $taxamount = $linetotal * ($taxrate / (1 + $taxrate));
658         $form->{"sellprice_$i"} =
659           $form->{"sellprice_$i"} * (1 / (1 + $taxrate));
660       } else {
661         $taxamount = $linetotal * $taxrate;
662       }
663
664       $netamount += $linetotal;
665
666       if ($taxamount != 0) {
667         map {
668           $form->{amount}{ $form->{id} }{$_} +=
669             $taxamount * $form->{"${_}_rate"} / $taxrate
670         } split / /, $form->{"taxaccounts_$i"};
671       }
672
673       # add amount to income, $form->{amount}{trans_id}{accno}
674       $amount =
675         $form->{"sellprice_$i"} * $form->{"qty_$i"} * $form->{exchangerate};
676
677       $linetotal =
678         $form->round_amount($form->{"sellprice_$i"} * $form->{"qty_$i"}, 2) *
679         $form->{exchangerate};
680       $linetotal = $form->round_amount($linetotal, 2);
681
682       # this is the difference from the inventory
683       $invoicediff += ($amount - $linetotal);
684
685       $form->{amount}{ $form->{id} }{ $form->{"income_accno_$i"} } +=
686         $linetotal;
687
688       $lastincomeaccno = $form->{"income_accno_$i"};
689
690       # adjust and round sellprice
691       $form->{"sellprice_$i"} =
692         $form->round_amount($form->{"sellprice_$i"} * $form->{exchangerate},
693                             $decimalplaces);
694
695       if ($form->{"inventory_accno_$i"} || $form->{"assembly_$i"}) {
696
697         # adjust parts onhand quantity
698
699         if ($form->{"assembly_$i"}) {
700
701           # do not update if assembly consists of all services
702           $query = qq|SELECT sum(p.inventory_accno_id)
703                       FROM parts p
704                       JOIN assembly a ON (a.parts_id = p.id)
705                       WHERE a.id = $form->{"id_$i"}|;
706           $sth = $dbh->prepare($query);
707           $sth->execute || $form->dberror($query);
708
709           if ($sth->fetchrow_array) {
710             $form->update_balance($dbh, "parts", "onhand",
711                                   qq|id = $form->{"id_$i"}|,
712                                   $baseqty * -1)
713               unless $form->{shipped};
714           }
715           $sth->finish;
716
717           # record assembly item as allocated
718           &process_assembly($dbh, $form, $form->{"id_$i"}, $baseqty);
719         } else {
720           $form->update_balance($dbh, "parts", "onhand",
721                                 qq|id = $form->{"id_$i"}|,
722                                 $baseqty * -1)
723             unless $form->{shipped};
724
725           $allocated = &cogs($dbh, $form, $form->{"id_$i"}, $baseqty, $basefactor, $i);
726         }
727       }
728
729       $deliverydate =
730         ($form->{"deliverydate_$i"})
731         ? qq|'$form->{"deliverydate_$i"}'|
732         : "NULL";
733
734       # get pricegroup_id and save it
735       ($null, my $pricegroup_id) = split /--/, $form->{"sellprice_pg_$i"};
736       $pricegroup_id *= 1;
737       my $subtotal = $form->{"subtotal_$i"} * 1;
738
739       # save detail record in invoice table
740       $query = qq|INSERT INTO invoice (trans_id, parts_id, description,longdescription, qty,
741                   sellprice, fxsellprice, discount, allocated, assemblyitem,
742                   unit, deliverydate, project_id, serialnumber, pricegroup_id,
743                   ordnumber, transdate, cusordnumber, base_qty, subtotal)
744                   VALUES ($form->{id}, $form->{"id_$i"},
745                   '$form->{"description_$i"}', '$form->{"longdescription_$i"}', $form->{"qty_$i"},
746                   $form->{"sellprice_$i"}, $fxsellprice,
747                   $form->{"discount_$i"}, $allocated, 'f',
748                   '$form->{"unit_$i"}', $deliverydate, | . conv_i($form->{"project_id_$i"}, 'NULL') . qq|,
749                   '$form->{"serialnumber_$i"}', '$pricegroup_id',
750                   '$form->{"ordnumber_$i"}', '$form->{"transdate_$i"}', '$form->{"cusordnumber_$i"}', $baseqty, '$subtotal')|;
751       $dbh->do($query) || $form->dberror($query);
752
753       if ($form->{lizenzen}) {
754         if ($form->{"licensenumber_$i"}) {
755           $query =
756             qq|SELECT i.id FROM invoice i WHERE i.trans_id=$form->{id} ORDER BY i.oid DESC LIMIT 1|;
757           $sth = $dbh->prepare($query);
758           $sth->execute || $form->dberror($query);
759
760           ($invoice_row_id) = $sth->fetchrow_array;
761           $sth->finish;
762
763           $query =
764             qq|INSERT INTO licenseinvoice (trans_id, license_id) VALUES ($invoice_row_id, $form->{"licensenumber_$i"})|;
765           $dbh->do($query) || $form->dberror($query);
766         }
767       }
768
769     }
770   }
771
772   $form->{datepaid} = $form->{invdate};
773
774   # total payments, don't move we need it here
775   for my $i (1 .. $form->{paidaccounts}) {
776     if ($form->{type} eq "credit_note") {
777       $form->{"paid_$i"} = $form->parse_amount($myconfig, $form->{"paid_$i"}) * -1;
778     } else {
779       $form->{"paid_$i"} = $form->parse_amount($myconfig, $form->{"paid_$i"});
780     }
781     $form->{paid} += $form->{"paid_$i"};
782     $form->{datepaid} = $form->{"datepaid_$i"} if ($form->{"datepaid_$i"});
783   }
784
785   my ($tax, $diff) = (0, 0);
786
787   $netamount = $form->round_amount($netamount, 2);
788
789   # figure out rounding errors for total amount vs netamount + taxes
790   if ($form->{taxincluded}) {
791
792     $amount = $form->round_amount($netamount * $form->{exchangerate}, 2);
793     $diff += $amount - $netamount * $form->{exchangerate};
794     $netamount = $amount;
795
796     foreach my $item (split / /, $form->{taxaccounts}) {
797       $amount = $form->{amount}{ $form->{id} }{$item} * $form->{exchangerate};
798       $form->{amount}{ $form->{id} }{$item} = $form->round_amount($amount, 2);
799       $tax += $form->{amount}{ $form->{id} }{$item};
800       $netamount -= $form->{amount}{ $form->{id} }{$item};
801     }
802
803     $invoicediff += $diff;
804     ######## this only applies to tax included
805     if ($lastincomeaccno) {
806       $form->{amount}{ $form->{id} }{$lastincomeaccno} += $invoicediff;
807     }
808
809   } else {
810     $amount    = $form->round_amount($netamount * $form->{exchangerate}, 2);
811     $diff      = $amount - $netamount * $form->{exchangerate};
812     $netamount = $amount;
813     foreach my $item (split / /, $form->{taxaccounts}) {
814       $form->{amount}{ $form->{id} }{$item} =
815         $form->round_amount($form->{amount}{ $form->{id} }{$item}, 2);
816       $amount =
817         $form->round_amount(
818                  $form->{amount}{ $form->{id} }{$item} * $form->{exchangerate},
819                  2);
820       $diff +=
821         $amount - $form->{amount}{ $form->{id} }{$item} *
822         $form->{exchangerate};
823       $form->{amount}{ $form->{id} }{$item} = $form->round_amount($amount, 2);
824       $tax += $form->{amount}{ $form->{id} }{$item};
825     }
826   }
827
828   $form->{amount}{ $form->{id} }{ $form->{AR} } = $netamount + $tax;
829   $form->{paid} =
830     $form->round_amount($form->{paid} * $form->{exchangerate} + $diff, 2);
831
832   # reverse AR
833   $form->{amount}{ $form->{id} }{ $form->{AR} } *= -1;
834
835   # update exchangerate
836   if (($form->{currency} ne $form->{defaultcurrency}) && !$exchangerate) {
837     $form->update_exchangerate($dbh, $form->{currency}, $form->{invdate},
838                                $form->{exchangerate}, 0);
839   }
840
841   $project_id = conv_i($form->{"globalproject_id"});
842
843   foreach my $trans_id (keys %{ $form->{amount} }) {
844     foreach my $accno (keys %{ $form->{amount}{$trans_id} }) {
845       next unless ($form->{expense_inventory} =~ /$accno/);
846       if (
847           ($form->{amount}{$trans_id}{$accno} =
848            $form->round_amount($form->{amount}{$trans_id}{$accno}, 2)
849           ) != 0
850         ) {
851         $query = qq|INSERT INTO acc_trans (trans_id, chart_id, amount,
852                     transdate, taxkey, project_id)
853                     VALUES ($trans_id, (SELECT c.id FROM chart c
854                                         WHERE c.accno = '$accno'),
855                     $form->{amount}{$trans_id}{$accno}, '$form->{invdate}',
856                     (SELECT taxkey_id  FROM chart WHERE accno = '$accno'), ?)|;
857         do_query($form, $dbh, $query, $project_id);
858         $form->{amount}{$trans_id}{$accno} = 0;
859       }
860     }
861
862     foreach my $accno (keys %{ $form->{amount}{$trans_id} }) {
863       if (
864           ($form->{amount}{$trans_id}{$accno} =
865            $form->round_amount($form->{amount}{$trans_id}{$accno}, 2)
866           ) != 0
867         ) {
868         $query = qq|INSERT INTO acc_trans (trans_id, chart_id, amount,
869                     transdate, taxkey, project_id)
870                     VALUES ($trans_id, (SELECT id FROM chart
871                                         WHERE accno = '$accno'),
872                     $form->{amount}{$trans_id}{$accno}, '$form->{invdate}',
873                     (SELECT taxkey_id  FROM chart WHERE accno = '$accno'), ?)|;
874         do_query($form, $dbh, $query, $project_id);
875       }
876     }
877   }
878
879   # deduct payment differences from diff
880   for my $i (1 .. $form->{paidaccounts}) {
881     if ($form->{"paid_$i"} != 0) {
882       $amount =
883         $form->round_amount($form->{"paid_$i"} * $form->{exchangerate}, 2);
884       $diff -= $amount - $form->{"paid_$i"} * $form->{exchangerate};
885     }
886   }
887
888   # force AR entry if 0
889   #  $form->{amount}{$form->{id}}{$form->{AR}} = 1 if ($form->{amount}{$form->{id}}{$form->{AR}} == 0);
890
891   # record payments and offsetting AR
892   if (!$form->{storno}) {
893     for my $i (1 .. $form->{paidaccounts}) {
894   
895       if ($form->{"paid_$i"} != 0) {
896         my ($accno) = split /--/, $form->{"AR_paid_$i"};
897         $form->{"datepaid_$i"} = $form->{invdate}
898           unless ($form->{"datepaid_$i"});
899         $form->{datepaid} = $form->{"datepaid_$i"};
900   
901         $exchangerate = 0;
902   
903         if ($form->{currency} eq $form->{defaultcurrency}) {
904           $form->{"exchangerate_$i"} = 1;
905         } else {
906           $exchangerate =
907             $form->check_exchangerate($myconfig, $form->{currency},
908                                       $form->{"datepaid_$i"}, 'buy');
909   
910           $form->{"exchangerate_$i"} =
911             ($exchangerate)
912             ? $exchangerate
913             : $form->parse_amount($myconfig, $form->{"exchangerate_$i"});
914         }
915   
916         # record AR
917         $amount =
918           $form->round_amount($form->{"paid_$i"} * $form->{exchangerate} + $diff,
919                               2);
920   
921         if ($form->{amount}{ $form->{id} }{ $form->{AR} } != 0) {
922           $query = qq|INSERT INTO acc_trans (trans_id, chart_id, amount,
923                       transdate, taxkey, project_id)
924                       VALUES ($form->{id}, (SELECT c.id FROM chart c
925                                           WHERE c.accno = ?),
926                       $amount, '$form->{"datepaid_$i"}',
927                       (SELECT taxkey_id FROM chart WHERE accno = ?), ?)|;
928           do_query($form, $dbh, $query, $form->{AR}, $form->{AR}, $project_id);
929         }
930   
931         # record payment
932         $form->{"paid_$i"} *= -1;
933   
934         $query = qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate,
935                     source, memo, taxkey, project_id)
936                     VALUES ($form->{id}, (SELECT c.id FROM chart c
937                                         WHERE c.accno = ?),
938                     $form->{"paid_$i"}, '$form->{"datepaid_$i"}',
939                     '$form->{"source_$i"}', '$form->{"memo_$i"}',
940                     (SELECT taxkey_id FROM chart WHERE accno = ?), ?)|;
941         do_query($form, $dbh, $query, $accno, $accno, $project_id);
942   
943         # exchangerate difference
944         $form->{fx}{$accno}{ $form->{"datepaid_$i"} } +=
945           $form->{"paid_$i"} * ($form->{"exchangerate_$i"} - 1) + $diff;
946   
947         # gain/loss
948         $amount =
949           $form->{"paid_$i"} * $form->{exchangerate} - $form->{"paid_$i"} *
950           $form->{"exchangerate_$i"};
951         if ($amount > 0) {
952           $form->{fx}{ $form->{fxgain_accno} }{ $form->{"datepaid_$i"} } +=
953             $amount;
954         } else {
955           $form->{fx}{ $form->{fxloss_accno} }{ $form->{"datepaid_$i"} } +=
956             $amount;
957         }
958   
959         $diff = 0;
960   
961         # update exchange rate
962         if (($form->{currency} ne $form->{defaultcurrency}) && !$exchangerate) {
963           $form->update_exchangerate($dbh, $form->{currency},
964                                     $form->{"datepaid_$i"},
965                                     $form->{"exchangerate_$i"}, 0);
966         }
967       }
968     }
969   }
970
971   # record exchange rate differences and gains/losses
972   foreach my $accno (keys %{ $form->{fx} }) {
973     foreach my $transdate (keys %{ $form->{fx}{$accno} }) {
974       if (
975           ($form->{fx}{$accno}{$transdate} =
976            $form->round_amount($form->{fx}{$accno}{$transdate}, 2)
977           ) != 0
978         ) {
979
980         $query = qq|INSERT INTO acc_trans (trans_id, chart_id, amount,
981                     transdate, cleared, fx_transaction, taxkey, project_id)
982                     VALUES ($form->{id},
983                            (SELECT c.id FROM chart c
984                             WHERE c.accno = ?),
985                     $form->{fx}{$accno}{$transdate}, '$transdate', '0', '1',
986                     (SELECT taxkey_id FROM chart WHERE accno = ?), ?)|;
987         do_query($form, $dbh, $query, $accno, $accno, $project_id);
988       }
989     }
990   }
991
992   $amount = $netamount + $tax;
993
994   # set values which could be empty to 0
995   $form->{terms}       *= 1;
996   $form->{taxincluded} *= 1;
997   my $datepaid = ($form->{paid})    ? qq|'$form->{datepaid}'| : "NULL";
998   my $duedate  = ($form->{duedate}) ? qq|'$form->{duedate}'|  : "NULL";
999   my $deliverydate =
1000     ($form->{deliverydate}) ? qq|'$form->{deliverydate}'| : "NULL";
1001
1002   # fill in subject if there is none
1003   $form->{subject} = qq|$form->{label} $form->{invnumber}|
1004     unless $form->{subject};
1005
1006   # if there is a message stuff it into the intnotes
1007   my $cc  = "Cc: $form->{cc}\\r\n"   if $form->{cc};
1008   my $bcc = "Bcc: $form->{bcc}\\r\n" if $form->{bcc};
1009   my $now = scalar localtime;
1010   $form->{intnotes} .= qq|\r
1011 \r| if $form->{intnotes};
1012
1013   $form->{intnotes} .= qq|[email]\r
1014 Date: $now
1015 To: $form->{email}\r
1016 $cc${bcc}Subject: $form->{subject}\r
1017 \r
1018 Message: $form->{message}\r| if $form->{message};
1019
1020   # save AR record
1021   $query = qq|UPDATE ar set
1022               invnumber = '$form->{invnumber}',
1023               ordnumber = '$form->{ordnumber}',
1024               quonumber = '$form->{quonumber}',
1025               cusordnumber = '$form->{cusordnumber}',
1026               transdate = '$form->{invdate}',
1027               orddate = | . conv_dateq($form->{orddate}) . qq|,
1028               quodate = | . conv_dateq($form->{quodate}) . qq|,
1029               customer_id = $form->{customer_id},
1030               amount = $amount,
1031               netamount = $netamount,
1032               paid = $form->{paid},
1033               datepaid = $datepaid,
1034               duedate = $duedate,
1035               deliverydate = $deliverydate,
1036               invoice = '1',
1037               shippingpoint = '$form->{shippingpoint}',
1038               shipvia = '$form->{shipvia}',
1039               terms = $form->{terms},
1040               notes = '$form->{notes}',
1041               intnotes = '$form->{intnotes}',
1042               taxincluded = '$form->{taxincluded}',
1043               curr = '$form->{currency}',
1044               department_id = $form->{department_id},
1045               payment_id = $form->{payment_id},
1046               type = '$form->{type}',
1047               language_id = $form->{language_id},
1048               taxzone_id = $form->{taxzone_id},
1049               shipto_id = $form->{shipto_id},
1050               delivery_customer_id = $form->{delivery_customer_id},
1051               delivery_vendor_id = $form->{delivery_vendor_id},
1052               employee_id = $form->{employee_id},
1053               storno = '$form->{storno}',
1054               globalproject_id = | . conv_i($form->{"globalproject_id"}, 'NULL') . qq|,
1055               cp_id = | . conv_i($form->{"cp_id"}, 'NULL') . qq|
1056               WHERE id = $form->{id}
1057              |;
1058   $dbh->do($query) || $form->dberror($query);
1059
1060   if ($form->{storno}) {
1061     $query = qq| update ar set paid=paid+amount where id=$form->{storno_id}|;
1062     $dbh->do($query) || $form->dberror($query);
1063     $query = qq| update ar set storno='$form->{storno}' where id=$form->{storno_id}|;
1064     $dbh->do($query) || $form->dberror($query);
1065     $query = qq§ update ar set intnotes='Rechnung storniert am $form->{invdate} ' || intnotes where id=$form->{storno_id}§;
1066     $dbh->do($query) || $form->dberror($query);
1067
1068     $query = qq| update ar set paid=amount where id=$form->{id}|;
1069     $dbh->do($query) || $form->dberror($query);
1070   }
1071
1072   $form->{pago_total} = $amount;
1073
1074   # add shipto
1075   $form->{name} = $form->{customer};
1076   $form->{name} =~ s/--$form->{customer_id}//;
1077
1078   if (!$form->{shipto_id}) {
1079     $form->add_shipto($dbh, $form->{id}, "AR");
1080   }
1081
1082   # save printed, emailed and queued
1083   $form->save_status($dbh);
1084
1085   Common::webdav_folder($form) if ($main::webdav);
1086
1087   my $rc = $dbh->commit;
1088   $dbh->disconnect;
1089
1090   $main::lxdebug->leave_sub();
1091
1092   return $rc;
1093 }
1094
1095 sub post_payment {
1096   $main::lxdebug->enter_sub() and my ($self, $myconfig, $form, $locale) = @_;
1097
1098   # connect to database, turn off autocommit
1099   my $dbh = $form->dbconnect_noauto($myconfig);
1100
1101   $form->{datepaid} = $form->{invdate};
1102
1103   # total payments, don't move we need it here
1104   for my $i (1 .. $form->{paidaccounts}) {
1105     $form->{"paid_$i"}  = $form->parse_amount($myconfig, $form->{"paid_$i"});
1106     $form->{"paid_$i"} *= -1                                 if ($form->{type} eq "credit_note");
1107     $form->{"paid"}    += $form->{"paid_$i"};
1108     $form->{"datepaid"} = $form->{"datepaid_$i"}             if ($form->{"datepaid_$i"});
1109   }
1110
1111   $form->{exchangerate} = $form->get_exchangerate($dbh, $form->{currency}, $form->{invdate}, "buy");
1112
1113   # record payments and offsetting AR
1114   for my $i (1 .. $form->{paidaccounts}) {
1115     if ($form->{"paid_$i"}) {
1116
1117       my ($accno) = split /--/, $form->{"AR_paid_$i"};
1118       $form->{"datepaid_$i"} = $form->{invdate} unless ($form->{"datepaid_$i"});
1119       $form->{datepaid} = $form->{"datepaid_$i"};
1120
1121       $exchangerate = 0;
1122       if (($form->{currency} eq $form->{defaultcurrency}) || ($form->{defaultcurrency} eq "")) {
1123         $form->{"exchangerate_$i"} = 1;
1124       } else {
1125         $exchangerate = $form->check_exchangerate($myconfig, $form->{currency}, $form->{"datepaid_$i"}, 'buy');
1126         $form->{"exchangerate_$i"} = ($exchangerate) ? $exchangerate : $form->parse_amount($myconfig, $form->{"exchangerate_$i"});
1127       }
1128
1129       # record AR
1130       $amount = $form->round_amount($form->{"paid_$i"} * $form->{"exchangerate"}, 2);
1131
1132       $query = qq|DELETE FROM acc_trans WHERE trans_id = ? AND chart_id = (SELECT c.id FROM chart c WHERE c.accno = ?) AND amount = ? AND transdate = ?|;
1133       do_query($form, $dbh, $query, $form->{id}, $form->{AR}, $amount, $form->{"datepaid_$i"});
1134       $query = qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate, project_id, taxkey) 
1135                   VALUES (?, (SELECT id FROM chart WHERE accno = ?), ?, ?, ?, (SELECT taxkey_id FROM chart WHERE accno = ?))|;
1136       do_query($form, $dbh, $query, $form->{id}, $form->{AR}, $amount, $form->{"datepaid_$i"}, conv_i($form->{"globalproject_id"}), $accno);
1137
1138       # record payment
1139       $form->{"paid_$i"} *= -1;
1140
1141       $query = qq|DELETE FROM acc_trans WHERE trans_id = ? AND chart_id = (SELECT c.id FROM chart c WHERE c.accno = ?) AND amount = ? AND transdate = ? AND source = ? AND memo = ?|;
1142       do_query($form, $dbh, $query, $form->{id}, $accno, $form->{"paid_$i"}, $form->{"datepaid_$i"}, $form->{"source_$i"}, $form->{"memo_$i"});
1143       $query = qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate, source, memo, project_id, taxkey) 
1144                   VALUES (?, (SELECT c.id FROM chart c WHERE c.accno = ?), ?, ?, ?, ?, ?, (SELECT taxkey_id FROM chart WHERE accno = ?))|;
1145       do_query($form, $dbh, $query, $form->{id}, $accno, $form->{"paid_$i"}, $form->{"datepaid_$i"}, $form->{"source_$i"}, $form->{"memo_$i"}, 
1146                conv_i($form->{"globalproject_id"}), $accno);
1147
1148       # gain/loss
1149       $amount = $form->{"paid_$i"} * $form->{exchangerate} - $form->{"paid_$i"} * $form->{"exchangerate_$i"};
1150       $form->{fx}{ $form->{($amount > 0 ? 'fxgain_accno' : 'fxloss_accno')} }{ $form->{"datepaid_$i"} } += $amount;
1151
1152       $diff = 0;
1153
1154       # update exchange rate
1155       if (($form->{currency} ne $form->{defaultcurrency}) && !$exchangerate) {
1156         $form->update_exchangerate($dbh, $form->{currency}, $form->{"datepaid_$i"}, $form->{"exchangerate_$i"}, 0);
1157       }
1158
1159     }
1160   }
1161
1162   # record exchange rate differences and gains/losses
1163   foreach my $accno (keys %{ $form->{fx} }) {
1164     foreach my $transdate (keys %{ $form->{fx}{$accno} }) {
1165
1166       if ($form->{fx}{$accno}{$transdate} = $form->round_amount($form->{fx}{$accno}{$transdate}, 2)) { # '=' is no typo, it's an assignment
1167         $query = qq|DELETE FROM acc_trans WHERE trans_id = ? AND chart_id = (SELECT c.id FROM chart c WHERE c.accno = ?) 
1168                                                 AND amount = ? AND transdate = ? AND cleared = ? AND fx_transaction = ?|;
1169         do_query($form, $dbh, $query, $form->{id}, $accno, $form->{fx}{$accno}{$transdate}, $transdate, 0, 1);
1170         $query = qq|INSERT INTO acc_trans (trans_id, chart_id, amount, transdate, cleared, fx_transaction, project_id, taxkey)
1171                                    VALUES (?, (SELECT c.id FROM chart c WHERE c.accno = ?), ?, ?, ?, ?, ?, (SELECT taxkey_id FROM chart WHERE accno = ?))|;
1172         do_query($form, $dbh, $query, $form->{id}, $accno, $form->{fx}{$accno}{$transdate}, $transdate, 0, 1, conv_i($form->{"globalproject_id"}), $accno);
1173       }
1174
1175     }
1176   }
1177
1178   # save AR record
1179   delete $form->{datepaid} unless $form->{paid};
1180
1181   my $query = qq|UPDATE ar set paid = ?, datepaid = ? WHERE id = ?|;
1182   do_query($form, $dbh, $query, $form->{paid}, $form->{datepaid}, $form->{id});
1183
1184   my $rc = $dbh->commit;
1185   $dbh->disconnect;
1186
1187   $main::lxdebug->leave_sub() and return $rc;
1188 }
1189
1190 sub process_assembly {
1191   $main::lxdebug->enter_sub();
1192
1193   my ($dbh, $form, $id, $totalqty) = @_;
1194
1195   my $query = qq|SELECT a.parts_id, a.qty, p.assembly,
1196                  p.partnumber, p.description, p.unit,
1197                  p.inventory_accno_id, p.income_accno_id,
1198                  p.expense_accno_id
1199                  FROM assembly a
1200                  JOIN parts p ON (a.parts_id = p.id)
1201                  WHERE a.id = $id|;
1202   my $sth = $dbh->prepare($query);
1203   $sth->execute || $form->dberror($query);
1204
1205   while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
1206
1207     my $allocated = 0;
1208
1209     $ref->{inventory_accno_id} *= 1;
1210     $ref->{expense_accno_id}   *= 1;
1211
1212     map { $ref->{$_} =~ s/\'/\'\'/g } (qw(partnumber description unit));
1213
1214     # multiply by number of assemblies
1215     $ref->{qty} *= $totalqty;
1216
1217     if ($ref->{assembly}) {
1218       &process_assembly($dbh, $form, $ref->{parts_id}, $ref->{qty});
1219       next;
1220     } else {
1221       if ($ref->{inventory_accno_id}) {
1222         $allocated = &cogs($dbh, $form, $ref->{parts_id}, $ref->{qty});
1223       }
1224     }
1225
1226     # save detail record for individual assembly item in invoice table
1227     $query = qq|INSERT INTO invoice (trans_id, description, parts_id, qty,
1228                 sellprice, fxsellprice, allocated, assemblyitem, unit)
1229                 VALUES
1230                 ($form->{id}, '$ref->{description}',
1231                 $ref->{parts_id}, $ref->{qty}, 0, 0, $allocated, 't',
1232                 '$ref->{unit}')|;
1233     $dbh->do($query) || $form->dberror($query);
1234
1235   }
1236
1237   $sth->finish;
1238
1239   $main::lxdebug->leave_sub();
1240 }
1241
1242 sub cogs {
1243   $main::lxdebug->enter_sub();
1244
1245   my ($dbh, $form, $id, $totalqty, $basefactor, $row) = @_;
1246   $form->{taxzone_id} *=1;
1247   my $transdate = ($form->{invdate}) ? "'$form->{invdate}'" : "current_date";
1248   my $query = qq|SELECT i.id, i.trans_id, i.base_qty, i.allocated, i.sellprice,
1249                         c1.accno AS inventory_accno, c1.new_chart_id AS inventory_new_chart, date($transdate) - c1.valid_from as inventory_valid,
1250                         c2.accno AS income_accno, c2.new_chart_id AS income_new_chart, date($transdate)  - c2.valid_from as income_valid,
1251                         c3.accno AS expense_accno, c3.new_chart_id AS expense_new_chart, date($transdate) - c3.valid_from as expense_valid
1252                   FROM invoice i, parts p
1253                   LEFT JOIN chart c1 ON ((select inventory_accno_id from buchungsgruppen where id=p.buchungsgruppen_id) = c1.id)
1254                   LEFT JOIN chart c2 ON ((select income_accno_id_$form->{taxzone_id} from buchungsgruppen where id=p.buchungsgruppen_id) = c2.id)
1255                   LEFT JOIN chart c3 ON ((select expense_accno_id_$form->{taxzone_id} from buchungsgruppen where id=p.buchungsgruppen_id) = c3.id)
1256                   WHERE i.parts_id = p.id
1257                   AND i.parts_id = $id
1258                   AND (i.base_qty + i.allocated) < 0
1259                   ORDER BY trans_id|;
1260   my $sth = $dbh->prepare($query);
1261   $sth->execute || $form->dberror($query);
1262
1263   my $allocated = 0;
1264   my $qty;
1265
1266   while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
1267     if (($qty = (($ref->{base_qty} * -1) - $ref->{allocated})) > $totalqty) {
1268       $qty = $totalqty;
1269     }
1270
1271     $form->update_balance($dbh, "invoice", "allocated", qq|id = $ref->{id}|,
1272                           $qty);
1273
1274     # total expenses and inventory
1275     # sellprice is the cost of the item
1276     $linetotal = $form->round_amount(($ref->{sellprice} * $qty) / $basefactor, 2);
1277
1278     if (!$main::eur) {
1279       $ref->{expense_accno} = ($form->{"expense_accno_$row"}) ? $form->{"expense_accno_$row"} : $ref->{expense_accno};
1280       # add to expense
1281       $form->{amount}{ $form->{id} }{ $ref->{expense_accno} } += -$linetotal;
1282       $form->{expense_inventory} .= " " . $ref->{expense_accno};
1283       $ref->{inventory_accno} = ($form->{"inventory_accno_$row"}) ? $form->{"inventory_accno_$row"} : $ref->{inventory_accno};
1284       # deduct inventory
1285       $form->{amount}{ $form->{id} }{ $ref->{inventory_accno} } -= -$linetotal;
1286       $form->{expense_inventory} .= " " . $ref->{inventory_accno};
1287     }
1288
1289     # add allocated
1290     $allocated += -$qty;
1291
1292     last if (($totalqty -= $qty) <= 0);
1293   }
1294
1295   $sth->finish;
1296
1297   $main::lxdebug->leave_sub();
1298
1299   return $allocated;
1300 }
1301
1302 sub reverse_invoice {
1303   $main::lxdebug->enter_sub();
1304
1305   my ($dbh, $form) = @_;
1306
1307   # reverse inventory items
1308   my $query = qq|SELECT i.id, i.parts_id, i.qty, i.assemblyitem, p.assembly,
1309                  p.inventory_accno_id
1310                  FROM invoice i
1311                  JOIN parts p ON (i.parts_id = p.id)
1312                  WHERE i.trans_id = $form->{id}|;
1313   my $sth = $dbh->prepare($query);
1314   $sth->execute || $form->dberror($query);
1315
1316   while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
1317
1318     if ($ref->{inventory_accno_id} || $ref->{assembly}) {
1319
1320       # if the invoice item is not an assemblyitem adjust parts onhand
1321       if (!$ref->{assemblyitem}) {
1322
1323         # adjust onhand in parts table
1324         $form->update_balance($dbh, "parts", "onhand",
1325                               qq|id = $ref->{parts_id}|,
1326                               $ref->{qty});
1327       }
1328
1329       # loop if it is an assembly
1330       next if ($ref->{assembly});
1331
1332       # de-allocated purchases
1333       $query = qq|SELECT i.id, i.trans_id, i.allocated
1334                   FROM invoice i
1335                   WHERE i.parts_id = $ref->{parts_id}
1336                   AND i.allocated > 0
1337                   ORDER BY i.trans_id DESC|;
1338       my $sth = $dbh->prepare($query);
1339       $sth->execute || $form->dberror($query);
1340
1341       while (my $inhref = $sth->fetchrow_hashref(NAME_lc)) {
1342         $qty = $ref->{qty};
1343         if (($ref->{qty} - $inhref->{allocated}) > 0) {
1344           $qty = $inhref->{allocated};
1345         }
1346
1347         # update invoice
1348         $form->update_balance($dbh, "invoice", "allocated",
1349                               qq|id = $inhref->{id}|,
1350                               $qty * -1);
1351
1352         last if (($ref->{qty} -= $qty) <= 0);
1353       }
1354       $sth->finish;
1355     }
1356   }
1357
1358   $sth->finish;
1359
1360   # delete acc_trans
1361   $query = qq|DELETE FROM acc_trans
1362               WHERE trans_id = $form->{id}|;
1363   $dbh->do($query) || $form->dberror($query);
1364
1365   # delete invoice entries
1366   $query = qq|DELETE FROM invoice
1367               WHERE trans_id = $form->{id}|;
1368   $dbh->do($query) || $form->dberror($query);
1369
1370   if ($form->{lizenzen}) {
1371     $query = qq|DELETE FROM licenseinvoice
1372               WHERE trans_id in (SELECT id FROM invoice WHERE trans_id = $form->{id})|;
1373     $dbh->do($query) || $form->dberror($query);
1374   }
1375
1376   $query = qq|DELETE FROM shipto
1377               WHERE trans_id = $form->{id} AND module = 'AR'|;
1378   $dbh->do($query) || $form->dberror($query);
1379
1380   $main::lxdebug->leave_sub();
1381 }
1382
1383 sub delete_invoice {
1384   $main::lxdebug->enter_sub();
1385
1386   my ($self, $myconfig, $form, $spool) = @_;
1387
1388   # connect to database
1389   my $dbh = $form->dbconnect_noauto($myconfig);
1390
1391   &reverse_invoice($dbh, $form);
1392
1393   # delete AR record
1394   my $query = qq|DELETE FROM ar
1395                  WHERE id = $form->{id}|;
1396   $dbh->do($query) || $form->dberror($query);
1397
1398   # delete spool files
1399   $query = qq|SELECT s.spoolfile FROM status s
1400               WHERE s.trans_id = $form->{id}|;
1401   my $sth = $dbh->prepare($query);
1402   $sth->execute || $self->dberror($query);
1403
1404   my $spoolfile;
1405   my @spoolfiles = ();
1406
1407   while (($spoolfile) = $sth->fetchrow_array) {
1408     push @spoolfiles, $spoolfile;
1409   }
1410   $sth->finish;
1411
1412   # delete status entries
1413   $query = qq|DELETE FROM status
1414               WHERE trans_id = $form->{id}|;
1415   $dbh->do($query) || $form->dberror($query);
1416
1417   my $rc = $dbh->commit;
1418   $dbh->disconnect;
1419
1420   if ($rc) {
1421     foreach $spoolfile (@spoolfiles) {
1422       unlink "$spool/$spoolfile" if $spoolfile;
1423     }
1424   }
1425
1426   $main::lxdebug->leave_sub();
1427
1428   return $rc;
1429 }
1430
1431 sub retrieve_invoice {
1432   $main::lxdebug->enter_sub();
1433
1434   my ($self, $myconfig, $form) = @_;
1435
1436   # connect to database
1437   my $dbh = $form->dbconnect_noauto($myconfig);
1438
1439   my $query;
1440
1441   if ($form->{id}) {
1442
1443     # get default accounts and last invoice number
1444     $query = qq|SELECT (SELECT c.accno FROM chart c
1445                         WHERE d.inventory_accno_id = c.id) AS inventory_accno,
1446                        (SELECT c.accno FROM chart c
1447                         WHERE d.income_accno_id = c.id) AS income_accno,
1448                        (SELECT c.accno FROM chart c
1449                         WHERE d.expense_accno_id = c.id) AS expense_accno,
1450                        (SELECT c.accno FROM chart c
1451                         WHERE d.fxgain_accno_id = c.id) AS fxgain_accno,
1452                        (SELECT c.accno FROM chart c
1453                         WHERE d.fxloss_accno_id = c.id) AS fxloss_accno,
1454                 d.curr AS currencies
1455                 FROM defaults d|;
1456   } else {
1457     $query = qq|SELECT (SELECT c.accno FROM chart c
1458                         WHERE d.inventory_accno_id = c.id) AS inventory_accno,
1459                        (SELECT c.accno FROM chart c
1460                         WHERE d.income_accno_id = c.id) AS income_accno,
1461                        (SELECT c.accno FROM chart c
1462                         WHERE d.expense_accno_id = c.id) AS expense_accno,
1463                        (SELECT c.accno FROM chart c
1464                         WHERE d.fxgain_accno_id = c.id) AS fxgain_accno,
1465                        (SELECT c.accno FROM chart c
1466                         WHERE d.fxloss_accno_id = c.id) AS fxloss_accno,
1467                 d.curr AS currencies, current_date AS invdate
1468                 FROM defaults d|;
1469   }
1470   my $sth = $dbh->prepare($query);
1471   $sth->execute || $form->dberror($query);
1472
1473   my $ref = $sth->fetchrow_hashref(NAME_lc);
1474   map { $form->{$_} = $ref->{$_} } keys %$ref;
1475   $sth->finish;
1476
1477   if ($form->{id}) {
1478
1479     # retrieve invoice
1480     $query = qq|SELECT a.invnumber, a.ordnumber, a.quonumber, a.cusordnumber,
1481                 a.orddate, a.quodate, a.globalproject_id,
1482                 a.transdate AS invdate, a.deliverydate, a.paid, a.storno, a.gldate,
1483                 a.shippingpoint, a.shipvia, a.terms, a.notes, a.intnotes, a.taxzone_id,
1484                 a.duedate, a.taxincluded, a.curr AS currency, a.shipto_id, a.cp_id,
1485                 a.employee_id, e.name AS employee, a.payment_id, a.language_id, a.delivery_customer_id, a.delivery_vendor_id, a.type
1486                 FROM ar a
1487                 LEFT JOIN employee e ON (e.id = a.employee_id)
1488                 WHERE a.id = $form->{id}|;
1489     $sth = $dbh->prepare($query);
1490     $sth->execute || $form->dberror($query);
1491
1492     $ref = $sth->fetchrow_hashref(NAME_lc);
1493     map { $form->{$_} = $ref->{$_} } keys %$ref;
1494     $sth->finish;
1495
1496     $form->{exchangerate} =
1497       $form->get_exchangerate($dbh, $form->{currency}, $form->{invdate},
1498                               "buy");
1499     # get shipto
1500     $query = qq|SELECT s.* FROM shipto s
1501                 WHERE s.trans_id = $form->{id} AND s.module = 'AR'|;
1502     $sth = $dbh->prepare($query);
1503     $sth->execute || $form->dberror($query);
1504
1505     $ref = $sth->fetchrow_hashref(NAME_lc);
1506     delete($ref->{id});
1507     map { $form->{$_} = $ref->{$_} } keys %$ref;
1508     $sth->finish;
1509
1510    if ($form->{delivery_customer_id}) {
1511       $query = qq|SELECT name FROM customer WHERE id=$form->{delivery_customer_id}|;
1512       $sth = $dbh->prepare($query);
1513       $sth->execute || $form->dberror($query);
1514       ($form->{delivery_customer_string}) = $sth->fetchrow_array();
1515       $sth->finish;
1516     }
1517
1518     if ($form->{delivery_vendor_id}) {
1519       $query = qq|SELECT name FROM customer WHERE id=$form->{delivery_vendor_id}|;
1520       $sth = $dbh->prepare($query);
1521       $sth->execute || $form->dberror($query);
1522       ($form->{delivery_vendor_string}) = $sth->fetchrow_array();
1523       $sth->finish;
1524     }
1525
1526     # get printed, emailed
1527     $query = qq|SELECT s.printed, s.emailed, s.spoolfile, s.formname
1528                 FROM status s
1529                 WHERE s.trans_id = $form->{id}|;
1530     $sth = $dbh->prepare($query);
1531     $sth->execute || $form->dberror($query);
1532
1533     while ($ref = $sth->fetchrow_hashref(NAME_lc)) {
1534       $form->{printed} .= "$ref->{formname} " if $ref->{printed};
1535       $form->{emailed} .= "$ref->{formname} " if $ref->{emailed};
1536       $form->{queued} .= "$ref->{formname} $ref->{spoolfile} "
1537         if $ref->{spoolfile};
1538     }
1539     $sth->finish;
1540     map { $form->{$_} =~ s/ +$//g } qw(printed emailed queued);
1541
1542     my $transdate =
1543       $form->{deliverydate} ? $dbh->quote($form->{deliverydate}) :
1544       $form->{invdate} ? $dbh->quote($form->{invdate}) :
1545       "current_date";
1546
1547     if (!$form->{taxzone_id}) {
1548       $form->{taxzone_id} = 0;
1549     }
1550     # retrieve individual items
1551     $query = qq|SELECT  
1552                 c1.accno AS inventory_accno, c1.new_chart_id AS inventory_new_chart, date($transdate) - c1.valid_from as inventory_valid,
1553                 c2.accno AS income_accno, c2.new_chart_id AS income_new_chart, date($transdate)  - c2.valid_from as income_valid,
1554                 c3.accno AS expense_accno, c3.new_chart_id AS expense_new_chart, date($transdate) - c3.valid_from as expense_valid,
1555                 i.description, i.longdescription, i.qty, i.fxsellprice AS sellprice,
1556                 i.discount, i.parts_id AS id, i.unit, i.deliverydate,
1557                 i.project_id, pr.projectnumber, i.serialnumber,
1558                 p.partnumber, p.assembly, p.bin, p.notes AS partnotes, p.inventory_accno_id AS part_inventory_accno_id, i.id AS invoice_pos,
1559                 pg.partsgroup, i.pricegroup_id, (SELECT pricegroup FROM pricegroup WHERE id=i.pricegroup_id) as pricegroup,
1560                 i.ordnumber, i.transdate, i.cusordnumber, p.formel, i.subtotal
1561                 FROM invoice i
1562                 JOIN parts p ON (i.parts_id = p.id)
1563                 LEFT JOIN project pr ON (i.project_id = pr.id)
1564                 LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
1565                 LEFT JOIN chart c1 ON ((select inventory_accno_id from buchungsgruppen where id=p.buchungsgruppen_id) = c1.id)
1566                 LEFT JOIN chart c2 ON ((select income_accno_id_$form->{taxzone_id} from buchungsgruppen where id=p.buchungsgruppen_id) = c2.id)
1567                 LEFT JOIN chart c3 ON ((select expense_accno_id_$form->{taxzone_id} from buchungsgruppen where id=p.buchungsgruppen_id) = c3.id)
1568                 WHERE i.trans_id = $form->{id}
1569                 AND NOT i.assemblyitem = '1'
1570                 ORDER BY i.id|;
1571     $sth = $dbh->prepare($query);
1572
1573     $sth->execute || $form->dberror($query);
1574     while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
1575       if (!$ref->{"part_inventory_accno_id"}) {
1576         map({ delete($ref->{$_}); } qw(inventory_accno inventory_new_chart inventory_valid));
1577       }
1578       delete($ref->{"part_inventory_accno_id"});
1579
1580     while ($ref->{inventory_new_chart} && ($ref->{inventory_valid} >=0)) {
1581       my $query = qq| SELECT accno AS inventory_accno, new_chart_id AS inventory_new_chart, date($transdate) - valid_from AS inventory_valid FROM chart WHERE id = $ref->{inventory_new_chart}|;
1582       my $stw = $dbh->prepare($query);
1583       $stw->execute || $form->dberror($query);
1584       ($ref->{inventory_accno}, $ref->{inventory_new_chart}, $ref->{inventory_valid}) = $stw->fetchrow_array;
1585       $stw->finish;
1586     }
1587
1588     while ($ref->{income_new_chart} && ($ref->{income_valid} >=0)) {
1589       my $query = qq| SELECT accno AS income_accno, new_chart_id AS income_new_chart, date($transdate) - valid_from AS income_valid FROM chart WHERE id = $ref->{income_new_chart}|;
1590       my $stw = $dbh->prepare($query);
1591       $stw->execute || $form->dberror($query);
1592       ($ref->{income_accno}, $ref->{income_new_chart}, $ref->{income_valid}) = $stw->fetchrow_array;
1593       $stw->finish;
1594     }
1595
1596     while ($ref->{expense_new_chart} && ($ref->{expense_valid} >=0)) {
1597       my $query = qq| SELECT accno AS expense_accno, new_chart_id AS expense_new_chart, date($transdate) - valid_from AS expense_valid FROM chart WHERE id = $ref->{expense_new_chart}|;
1598       my $stw = $dbh->prepare($query);
1599       $stw->execute || $form->dberror($query);
1600       ($ref->{expense_accno}, $ref->{expense_new_chart}, $ref->{expense_valid}) = $stw->fetchrow_array;
1601       $stw->finish;
1602     }
1603
1604       # get tax rates and description
1605       $accno_id =
1606         ($form->{vc} eq "customer") ? $ref->{income_accno} : $ref->{expense_accno};
1607     $query = qq|SELECT c.accno, t.taxdescription, t.rate, t.taxnumber
1608               FROM tax t LEFT JOIN chart c on (c.id=t.chart_id)
1609               WHERE t.id in (SELECT tk.tax_id from taxkeys tk where tk.chart_id = (SELECT id from chart WHERE accno='$accno_id') AND startdate<=$transdate ORDER BY startdate desc LIMIT 1)
1610               ORDER BY c.accno|;
1611       $stw = $dbh->prepare($query);
1612       $stw->execute || $form->dberror($query);
1613       $ref->{taxaccounts} = "";
1614       my $i=0;
1615       while ($ptr = $stw->fetchrow_hashref(NAME_lc)) {
1616
1617         #    if ($customertax{$ref->{accno}}) {
1618         if (($ptr->{accno} eq "") && ($ptr->{rate} == 0)) {
1619           $i++;
1620           $ptr->{accno} = $i;
1621         }
1622         $ref->{taxaccounts} .= "$ptr->{accno} ";
1623
1624         if (!($form->{taxaccounts} =~ /$ptr->{accno}/)) {
1625           $form->{"$ptr->{accno}_rate"}        = $ptr->{rate};
1626           $form->{"$ptr->{accno}_description"} = $ptr->{taxdescription};
1627           $form->{"$ptr->{accno}_taxnumber"}   = $ptr->{taxnumber};
1628           $form->{taxaccounts} .= "$ptr->{accno} ";
1629         }
1630
1631       }
1632
1633       if ($form->{lizenzen}) {
1634         $query = qq|SELECT l.licensenumber, l.id AS licenseid
1635                  FROM license l, licenseinvoice li
1636                  WHERE l.id = li.license_id AND li.trans_id = $ref->{invoice_pos}|;
1637         $stg = $dbh->prepare($query);
1638         $stg->execute || $form->dberror($query);
1639         ($licensenumber, $licenseid) = $stg->fetchrow_array();
1640         $ref->{lizenzen} =
1641           "<option value=\"$licenseid\">$licensenumber</option>";
1642         $stg->finish();
1643       }
1644       if ($form->{type} eq "credit_note") {
1645         $ref->{qty} *= -1;
1646       }
1647
1648       chop $ref->{taxaccounts};
1649       push @{ $form->{invoice_details} }, $ref;
1650       $stw->finish;
1651     }
1652     $sth->finish;
1653
1654     Common::webdav_folder($form) if ($main::webdav);
1655   }
1656
1657   my $rc = $dbh->commit;
1658   $dbh->disconnect;
1659
1660   $main::lxdebug->leave_sub();
1661
1662   return $rc;
1663 }
1664
1665 sub get_customer {
1666   $main::lxdebug->enter_sub();
1667
1668   my ($self, $myconfig, $form) = @_;
1669
1670   # connect to database
1671   my $dbh = $form->dbconnect($myconfig);
1672
1673   my $dateformat = $myconfig->{dateformat};
1674   $dateformat .= "yy" if $myconfig->{dateformat} !~ /^y/;
1675
1676   my $duedate =
1677     ($form->{invdate})
1678     ? "to_date('$form->{invdate}', '$dateformat')"
1679     : "current_date";
1680
1681   $form->{customer_id} *= 1;
1682
1683   # get customer
1684   my $query = qq|SELECT c.name AS customer, c.discount, c.creditlimit, c.terms,
1685                  c.email, c.cc, c.bcc, c.language_id, c.payment_id AS customer_payment_id,
1686                  c.street, c.zipcode, c.city, c.country,
1687                  $duedate + COALESCE(pt.terms_netto, 0) AS duedate, c.notes AS intnotes,
1688                  b.discount AS tradediscount, b.description AS business, c.klass as customer_klass, c.taxzone_id
1689                  FROM customer c
1690                  LEFT JOIN business b ON (b.id = c.business_id)
1691                  LEFT JOIN payment_terms pt ON c.payment_id = pt.id
1692                  WHERE c.id = $form->{customer_id}|;
1693   my $sth = $dbh->prepare($query);
1694   $sth->execute || $form->dberror($query);
1695
1696   $ref = $sth->fetchrow_hashref(NAME_lc);
1697
1698   map { $form->{$_} = $ref->{$_} } keys %$ref;
1699   $sth->finish;
1700
1701   my $query = qq|SELECT sum(a.amount-a.paid) AS dunning_amount FROM ar a WHERE a.paid < a.amount AND a.customer_id=$form->{customer_id} AND a.dunning_id IS NOT NULL|;
1702   my $sth = $dbh->prepare($query);
1703
1704   $sth->execute || $form->dberror($query);
1705   
1706   $ref = $sth->fetchrow_hashref(NAME_lc);
1707
1708   map { $form->{$_} = $ref->{$_} } keys %$ref;
1709   $sth->finish;
1710
1711   #print(STDERR "DUNNING AMOUTN $form->{dunning_amount}\n");
1712
1713   my $query = qq|SELECT dnn.dunning_description AS max_dunning_level FROM dunning_config dnn WHERE id in (select dunning_id from ar WHERE paid < amount AND customer_id=$form->{customer_id} AND dunning_id IS NOT NULL) ORDER BY dunning_level DESC LIMIT 1|;
1714   my $sth = $dbh->prepare($query);
1715
1716   $sth->execute || $form->dberror($query);
1717
1718   $ref = $sth->fetchrow_hashref(NAME_lc);
1719
1720   map { $form->{$_} = $ref->{$_} } keys %$ref;
1721   $sth->finish;
1722   #print(STDERR "LEVEL $form->{max_dunning_level}\n");
1723
1724
1725   #check whether payment_terms are better than old payment_terms
1726   if (($form->{payment_id} ne "") && ($form->{customer_payment_id} ne "")) {
1727     my $query = qq|select (select ranking from payment_terms WHERE id = $form->{payment_id}), (select ranking from payment_terms WHERE id = $form->{customer_payment_id})|;
1728     my $stw = $dbh->prepare($query);
1729     $stw->execute || $form->dberror($query);
1730     ($old_ranking, $new_ranking) = $stw->fetchrow_array;
1731     $stw->finish;
1732     if ($new_ranking > $old_ranking) {
1733       $form->{payment_id} =$form->{customer_payment_id};
1734     }
1735   }
1736   if ($form->{payment_id} eq "") {
1737     $form->{payment_id} =$form->{customer_payment_id};
1738   }
1739
1740   $form->{creditremaining} = $form->{creditlimit};
1741   $query = qq|SELECT SUM(a.amount - a.paid)
1742               FROM ar a
1743               WHERE a.customer_id = $form->{customer_id}|;
1744   $sth = $dbh->prepare($query);
1745   $sth->execute || $form->dberror($query);
1746
1747   ($form->{creditremaining}) -= $sth->fetchrow_array;
1748
1749   $sth->finish;
1750
1751   $query = qq|SELECT o.amount,
1752                 (SELECT e.buy FROM exchangerate e
1753                  WHERE e.curr = o.curr
1754                  AND e.transdate = o.transdate)
1755               FROM oe o
1756               WHERE o.customer_id = $form->{customer_id}
1757               AND o.quotation = '0'
1758               AND o.closed = '0'|;
1759   $sth = $dbh->prepare($query);
1760   $sth->execute || $form->dberror($query);
1761
1762   while (my ($amount, $exch) = $sth->fetchrow_array) {
1763     $exch = 1 unless $exch;
1764     $form->{creditremaining} -= $amount * $exch;
1765   }
1766   $sth->finish;
1767
1768   # get shipto if we did not converted an order or invoice
1769   if (!$form->{shipto}) {
1770     map { delete $form->{$_} }
1771       qw(shiptoname shiptodepartment_1 shiptodepartment_2 shiptostreet shiptozipcode shiptocity shiptocountry shiptocontact shiptophone shiptofax shiptoemail);
1772
1773     $query = qq|SELECT s.* FROM shipto s
1774                 WHERE s.trans_id = $form->{customer_id} AND s.module = 'CT'|;
1775     $sth = $dbh->prepare($query);
1776     $sth->execute || $form->dberror($query);
1777
1778     $ref = $sth->fetchrow_hashref(NAME_lc);
1779     undef($ref->{id});
1780     map { $form->{$_} = $ref->{$_} } keys %$ref;
1781     $sth->finish;
1782   }
1783
1784   # get taxes we charge for this customer
1785   $query = qq|SELECT c.accno
1786               FROM chart c
1787               JOIN customertax ct ON (ct.chart_id = c.id)
1788               WHERE ct.customer_id = $form->{customer_id}|;
1789   $sth = $dbh->prepare($query);
1790   $sth->execute || $form->dberror($query);
1791
1792   my $customertax = ();
1793   while ($ref = $sth->fetchrow_hashref(NAME_lc)) {
1794     $customertax{ $ref->{accno} } = 1;
1795   }
1796   $sth->finish;
1797
1798   # setup last accounts used for this customer
1799   if (!$form->{id} && $form->{type} !~ /_(order|quotation)/) {
1800     $query = qq|SELECT c.id, c.accno, c.description, c.link, c.category
1801                 FROM chart c
1802                 JOIN acc_trans ac ON (ac.chart_id = c.id)
1803                 JOIN ar a ON (a.id = ac.trans_id)
1804                 WHERE a.customer_id = $form->{customer_id}
1805                 AND NOT (c.link LIKE '%_tax%' OR c.link LIKE '%_paid%')
1806                 AND a.id IN (SELECT max(a2.id) FROM ar a2
1807                              WHERE a2.customer_id = $form->{customer_id})|;
1808     $sth = $dbh->prepare($query);
1809     $sth->execute || $form->dberror($query);
1810
1811     my $i = 0;
1812     while ($ref = $sth->fetchrow_hashref(NAME_lc)) {
1813       if ($ref->{category} eq 'I') {
1814         $i++;
1815         $form->{"AR_amount_$i"} = "$ref->{accno}--$ref->{description}";
1816
1817         if ($form->{initial_transdate}) {
1818           my $tax_query =
1819             qq|SELECT tk.tax_id, t.rate FROM taxkeys tk | .
1820             qq|LEFT JOIN tax t ON tk.tax_id = t.id | .
1821             qq|WHERE tk.chart_id = ? AND startdate <= ? | .
1822             qq|ORDER BY tk.startdate DESC LIMIT 1|;
1823           my ($tax_id, $rate) =
1824             selectrow_query($form, $dbh, $tax_query, $ref->{id},
1825                             $form->{initial_transdate});
1826           $form->{"taxchart_$i"} = "${tax_id}--${rate}";
1827         }
1828       }
1829       if ($ref->{category} eq 'A') {
1830         $form->{ARselected} = $form->{AR_1} = $ref->{accno};
1831       }
1832     }
1833     $sth->finish;
1834     $form->{rowcount} = $i if ($i && !$form->{type});
1835   }
1836
1837   $dbh->disconnect;
1838
1839   $main::lxdebug->leave_sub();
1840 }
1841
1842 sub retrieve_item {
1843   $main::lxdebug->enter_sub();
1844
1845   my ($self, $myconfig, $form) = @_;
1846
1847   # connect to database
1848   my $dbh = $form->dbconnect($myconfig);
1849
1850   my $i = $form->{rowcount};
1851
1852   my $where = "NOT p.obsolete = '1'";
1853
1854   if ($form->{"partnumber_$i"}) {
1855     my $partnumber = $form->like(lc $form->{"partnumber_$i"});
1856     $where .= " AND lower(p.partnumber) LIKE '$partnumber'";
1857   }
1858   if ($form->{"description_$i"}) {
1859     my $description = $form->like(lc $form->{"description_$i"});
1860     $where .= " AND lower(p.description) LIKE '$description'";
1861   }
1862
1863   if ($form->{"partsgroup_$i"}) {
1864     my $partsgroup = $form->like(lc $form->{"partsgroup_$i"});
1865     $where .= " AND lower(pg.partsgroup) LIKE '$partsgroup'";
1866   }
1867
1868   if ($form->{"description_$i"}) {
1869     $where .= " ORDER BY p.description";
1870   } else {
1871     $where .= " ORDER BY p.partnumber";
1872   }
1873
1874   my $transdate;
1875   if ($form->{type} eq "invoice") {
1876     $transdate =
1877       $form->{deliverydate} ? $dbh->quote($form->{deliverydate}) :
1878       $form->{invdate} ? $dbh->quote($form->{invdate}) :
1879       "current_date";
1880   } else {
1881     $transdate =
1882       $form->{transdate} ? $dbh->quote($form->{transdate}) :
1883       "current_date";
1884   }
1885
1886   my $query = qq|SELECT p.id, p.partnumber, p.description, p.sellprice,
1887                         p.listprice, p.inventory_accno_id,
1888                         c1.accno AS inventory_accno, c1.new_chart_id AS inventory_new_chart, date($transdate) - c1.valid_from as inventory_valid,
1889                         c2.accno AS income_accno, c2.new_chart_id AS income_new_chart, date($transdate)  - c2.valid_from as income_valid,
1890                         c3.accno AS expense_accno, c3.new_chart_id AS expense_new_chart, date($transdate) - c3.valid_from as expense_valid,
1891                  p.unit, p.assembly, p.bin, p.onhand, p.notes AS partnotes, p.notes AS longdescription, p.not_discountable,
1892                  pg.partsgroup, p.formel, p.payment_id AS part_payment_id
1893                  FROM parts p
1894                  LEFT JOIN chart c1 ON ((select inventory_accno_id from buchungsgruppen where id=p.buchungsgruppen_id) = c1.id)
1895                  LEFT JOIN chart c2 ON ((select income_accno_id_$form->{taxzone_id} from buchungsgruppen where id=p.buchungsgruppen_id) = c2.id)
1896                  LEFT JOIN chart c3 ON ((select expense_accno_id_$form->{taxzone_id} from buchungsgruppen where id=p.buchungsgruppen_id) = c3.id)
1897                  LEFT JOIN partsgroup pg ON (pg.id = p.partsgroup_id)
1898                  WHERE $where|;
1899   my $sth = $dbh->prepare($query);
1900   $sth->execute || $form->dberror($query);
1901
1902   while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
1903
1904     # In der Buchungsgruppe ist immer ein Bestandskonto verknuepft, auch wenn
1905     # es sich um eine Dienstleistung handelt. Bei Dienstleistungen muss das
1906     # Buchungskonto also aus dem Ergebnis rausgenommen werden.
1907     if (!$ref->{inventory_accno_id}) {
1908       map({ delete($ref->{"inventory_${_}"}); } qw(accno new_chart valid));
1909     }
1910     delete($ref->{inventory_accno_id});
1911
1912     #set expense_accno=inventory_accno if they are different => bilanz
1913
1914
1915     while ($ref->{inventory_new_chart} && ($ref->{inventory_valid} >=0)) {
1916       my $query = qq| SELECT accno AS inventory_accno, new_chart_id AS inventory_new_chart, date($transdate) - valid_from AS inventory_valid FROM chart WHERE id = $ref->{inventory_new_chart}|;
1917       my $stw = $dbh->prepare($query);
1918       $stw->execute || $form->dberror($query);
1919       ($ref->{inventory_accno}, $ref->{inventory_new_chart}, $ref->{inventory_valid}) = $stw->fetchrow_array;
1920       $stw->finish;
1921     }
1922
1923     while ($ref->{income_new_chart} && ($ref->{income_valid} >=0)) {
1924       my $query = qq| SELECT accno AS income_accno, new_chart_id AS income_new_chart, date($transdate) - valid_from AS income_valid FROM chart WHERE id = $ref->{income_new_chart}|;
1925       my $stw = $dbh->prepare($query);
1926       $stw->execute || $form->dberror($query);
1927       ($ref->{income_accno}, $ref->{income_new_chart}, $ref->{income_valid}) = $stw->fetchrow_array;
1928       $stw->finish;
1929     }
1930
1931     while ($ref->{expense_new_chart} && ($ref->{expense_valid} >=0)) {
1932       my $query = qq| SELECT accno AS expense_accno, new_chart_id AS expense_new_chart, date($transdate) - valid_from AS expense_valid FROM chart WHERE id = $ref->{expense_new_chart}|;
1933       my $stw = $dbh->prepare($query);
1934       $stw->execute || $form->dberror($query);
1935       ($ref->{expense_accno}, $ref->{expense_new_chart}, $ref->{expense_valid}) = $stw->fetchrow_array;
1936       $stw->finish;
1937     }
1938
1939     #check whether payment_terms are better than old payment_terms
1940     if (($form->{payment_id} ne "") && ($ref->{part_payment_id} ne "")) {
1941       my $query = qq|select (select ranking from payment_terms WHERE id = $form->{payment_id}), (select ranking from payment_terms WHERE id = $ref->{part_payment_id})|;
1942       my $stw = $dbh->prepare($query);
1943       $stw->execute || $form->dberror($query);
1944       ($old_ranking, $new_ranking) = $stw->fetchrow_array;
1945       $stw->finish;
1946       if ($new_ranking <= $old_ranking) {
1947         $ref->{part_payment_id} = "";
1948       }
1949     }
1950
1951     # get tax rates and description
1952     $accno_id =
1953       ($form->{vc} eq "customer") ? $ref->{income_accno} : $ref->{expense_accno};
1954     $query = qq|SELECT c.accno, t.taxdescription, t.rate, t.taxnumber
1955               FROM tax t LEFT JOIN chart c on (c.id=t.chart_id)
1956               WHERE t.id in (SELECT tk.tax_id from taxkeys tk where tk.chart_id = (SELECT id from chart WHERE accno='$accno_id') AND startdate<=$transdate ORDER BY startdate desc LIMIT 1)
1957               ORDER BY c.accno|;
1958     $stw = $dbh->prepare($query);
1959     $stw->execute || $form->dberror($query);
1960
1961     $ref->{taxaccounts} = "";
1962     my $i = 0;
1963     while ($ptr = $stw->fetchrow_hashref(NAME_lc)) {
1964
1965       #    if ($customertax{$ref->{accno}}) {
1966       if (($ptr->{accno} eq "") && ($ptr->{rate} == 0)) {
1967         $i++;
1968         $ptr->{accno} = $i;
1969       }
1970       $ref->{taxaccounts} .= "$ptr->{accno} ";
1971
1972       if (!($form->{taxaccounts} =~ /$ptr->{accno}/)) {
1973         $form->{"$ptr->{accno}_rate"}        = $ptr->{rate};
1974         $form->{"$ptr->{accno}_description"} = $ptr->{taxdescription};
1975         $form->{"$ptr->{accno}_taxnumber"}   = $ptr->{taxnumber};
1976         $form->{taxaccounts} .= "$ptr->{accno} ";
1977       }
1978
1979     }
1980
1981     $stw->finish;
1982     chop $ref->{taxaccounts};
1983     if ($form->{language_id}) {
1984       $query = qq|SELECT tr.translation, tr.longdescription
1985                 FROM translation tr
1986                 WHERE tr.language_id=$form->{language_id} AND tr.parts_id=$ref->{id}|;
1987       $stw = $dbh->prepare($query);
1988       $stw->execute || $form->dberror($query);
1989       my ($translation, $longdescription) = $stw->fetchrow_array();
1990       if ($translation ne "") {
1991         $ref->{description} = $translation;
1992         $ref->{longdescription} = $longdescription;
1993
1994       } else {
1995         $query = qq|SELECT tr.translation, tr.longdescription
1996                 FROM translation tr
1997                 WHERE tr.language_id in (select id from language where article_code=(select article_code from language where id = $form->{language_id})) AND tr.parts_id=$ref->{id} LIMIT 1|;
1998         $stg = $dbh->prepare($query);
1999         $stg->execute || $form->dberror($query);
2000         my ($translation) = $stg->fetchrow_array();
2001         if ($translation ne "") {
2002           $ref->{description} = $translation;
2003           $ref->{longdescription} = $longdescription;
2004         }
2005         $stg->finish;
2006       }
2007       $stw->finish;
2008     }
2009
2010     push @{ $form->{item_list} }, $ref;
2011
2012     if ($form->{lizenzen}) {
2013       if ($ref->{inventory_accno} > 0) {
2014         $query =
2015           qq| SELECT l.* FROM license l WHERE l.parts_id = $ref->{id} AND NOT l.id IN (SELECT li.license_id FROM licenseinvoice li)|;
2016         $stw = $dbh->prepare($query);
2017         $stw->execute || $form->dberror($query);
2018         while ($ptr = $stw->fetchrow_hashref(NAME_lc)) {
2019           push @{ $form->{LIZENZEN}{ $ref->{id} } }, $ptr;
2020         }
2021         $stw->finish;
2022       }
2023     }
2024   }
2025   $sth->finish;
2026   $dbh->disconnect;
2027
2028   $main::lxdebug->leave_sub();
2029 }
2030
2031 ##########################
2032 # get pricegroups from database
2033 # build up selected pricegroup
2034 # if an exchange rate - change price
2035 # for each part
2036 #
2037 sub get_pricegroups_for_parts {
2038
2039   $main::lxdebug->enter_sub();
2040
2041   my ($self, $myconfig, $form) = @_;
2042
2043   my $dbh = $form->dbconnect($myconfig);
2044
2045   $form->{"PRICES"} = {};
2046
2047   my $i  = 1;
2048   my $id = 0;
2049   my $dimension_units = AM->retrieve_units($myconfig, $form, "dimension");
2050   my $service_units = AM->retrieve_units($myconfig, $form, "service");
2051   my $all_units = AM->retrieve_units($myconfig, $form);
2052   while (($form->{"id_$i"}) or ($form->{"new_id_$i"})) {
2053     $form->{"PRICES"}{$i} = [];
2054
2055     $id = $form->{"id_$i"};
2056
2057     if (!($form->{"id_$i"}) and $form->{"new_id_$i"}) {
2058
2059       $id = $form->{"new_id_$i"};
2060     }
2061
2062     ($price, $selectedpricegroup_id) = split /--/,
2063       $form->{"sellprice_pg_$i"};
2064
2065     $pricegroup_old = $form->{"pricegroup_old_$i"};
2066     $form->{"new_pricegroup_$i"} = $selectedpricegroup_id;
2067     $form->{"old_pricegroup_$i"} = $pricegroup_old;
2068     $price_new = $form->{"price_new_$i"};
2069
2070     $price_old = $form->{"price_old_$i"};
2071     $query =
2072       qq|SELECT pricegroup_id, (SELECT p.sellprice from parts p where p.id = $id) as default_sellprice,(SELECT pg.pricegroup FROM pricegroup pg WHERE id=pricegroup_id) AS pricegroup, price, '' AS selected FROM prices WHERE parts_id = $id UNION SELECT 0 as pricegroup_id,(SELECT sellprice FROM parts WHERE id=$id) as default_sellprice,'' as pricegroup, (SELECT DISTINCT sellprice from parts where id=$id) as price, 'selected' AS selected from prices ORDER BY pricegroup|;
2073
2074     $pkq = $dbh->prepare($query);
2075     $pkq->execute || $form->dberror($query);
2076     if (!$form->{"unit_old_$i"}) {
2077       # Neue Ware aus der Datenbank. In diesem Fall ist unit_$i die
2078       # Einheit, wie sie in den Stammdaten hinterlegt wurde.
2079       # Es sollte also angenommen werden, dass diese ausgewaehlt war.
2080       $form->{"unit_old_$i"} = $form->{"unit_$i"};
2081     }
2082  
2083     # Die zuletzt ausgewaehlte mit der aktuell ausgewaehlten Einheit
2084     # vergleichen und bei Unterschied den Preis entsprechend umrechnen.
2085     $form->{"selected_unit_$i"} = $form->{"unit_$i"} unless ($form->{"selected_unit_$i"});
2086
2087     my $check_units = $form->{"inventory_accno_$i"} ? $dimension_units : $service_units;
2088     if (!$check_units->{$form->{"selected_unit_$i"}} ||
2089         ($check_units->{$form->{"selected_unit_$i"}}->{"base_unit"} ne
2090          $all_units->{$form->{"unit_old_$i"}}->{"base_unit"})) {
2091       # Die ausgewaehlte Einheit ist fuer diesen Artikel nicht gueltig
2092       # (z.B. Dimensionseinheit war ausgewaehlt, es handelt sich aber
2093       # um eine Dienstleistung). Dann keinerlei Umrechnung vornehmen.
2094       $form->{"unit_old_$i"} = $form->{"selected_unit_$i"} = $form->{"unit_$i"};
2095     }
2096     my $basefactor = 1;
2097     
2098     if ($form->{"unit_old_$i"} ne $form->{"selected_unit_$i"}) {
2099       if (defined($all_units->{$form->{"unit_old_$i"}}->{"factor"}) &&
2100           $all_units->{$form->{"unit_old_$i"}}->{"factor"}) {
2101         $basefactor = $all_units->{$form->{"selected_unit_$i"}}->{"factor"} /
2102           $all_units->{$form->{"unit_old_$i"}}->{"factor"};
2103       }
2104     }
2105     if (!$form->{"basefactor_$i"}) {
2106       $form->{"basefactor_$i"} = 1;
2107     }
2108     while ($pkr = $pkq->fetchrow_hashref(NAME_lc)) {
2109
2110       #       push @{ $form->{PRICES}{$id} }, $pkr;
2111       #push @{ $form->{PRICES}{$i} }, $pkr;
2112       $pkr->{id}       = $id;
2113       $pkr->{selected} = '';
2114
2115       # if there is an exchange rate change price
2116       if (($form->{exchangerate} * 1) != 0) {
2117
2118         $pkr->{price} /= $form->{exchangerate};
2119       }
2120
2121       $pkr->{price} *= $form->{"basefactor_$i"};
2122       
2123       $pkr->{price} *= $basefactor;
2124  
2125       $pkr->{price} = $form->format_amount($myconfig, $pkr->{price}, 5);
2126
2127       if ($selectedpricegroup_id eq undef) {
2128         if ($pkr->{pricegroup_id} eq $form->{customer_klass}) {
2129
2130           $pkr->{selected}  = ' selected';
2131
2132           # no customer pricesgroup set
2133           if ($pkr->{price} == $pkr->{default_sellprice}) {
2134
2135             $pkr->{price} = $form->{"sellprice_$i"};
2136
2137           } else {
2138
2139             $form->{"sellprice_$i"} = $pkr->{price};
2140           }
2141
2142         } else {
2143           if ($pkr->{price} == $pkr->{default_sellprice}) {
2144
2145             $pkr->{price}    = $form->{"sellprice_$i"};
2146             $pkr->{selected} = ' selected';
2147           }
2148         }
2149       }
2150
2151       if ($selectedpricegroup_id or $selectedpricegroup_id == 0) {
2152         if ($selectedpricegroup_id ne $pricegroup_old) {
2153           if ($pkr->{pricegroup_id} eq $selectedpricegroup_id) {
2154             $pkr->{selected}  = ' selected';
2155           }
2156         } else {
2157           if (($price_new != $form->{"sellprice_$i"}) and ($price_new ne 0)) {
2158             if ($pkr->{pricegroup_id} == 0) {
2159               $pkr->{price}     = $form->{"sellprice_$i"};
2160               $pkr->{selected}  = ' selected';
2161             }
2162           } else {
2163             if ($pkr->{pricegroup_id} eq $selectedpricegroup_id) {
2164               $pkr->{selected}  = ' selected';
2165               if (    ($pkr->{pricegroup_id} == 0)
2166                   and ($pkr->{price} == $form->{"sellprice_$i"})) {
2167
2168                 # $pkr->{price}                         = $form->{"sellprice_$i"};
2169               } else {
2170                 $pkr->{price} = $form->{"sellprice_$i"};
2171               }
2172             }
2173           }
2174         }
2175       }
2176       push @{ $form->{PRICES}{$i} }, $pkr;
2177
2178     }
2179     $form->{"basefactor_$i"} *= $basefactor;
2180
2181     $i++;
2182
2183     $pkq->finish;
2184   }
2185
2186   $dbh->disconnect;
2187
2188   $main::lxdebug->leave_sub();
2189 }
2190
2191 sub has_storno {
2192   $main::lxdebug->enter_sub();
2193
2194   my ($self, $myconfig, $form, $table) = @_;
2195
2196   $main::lxdebug->leave_sub() and return 0 unless ($form->{id});
2197
2198   # make sure there's no funny stuff in $table
2199   # ToDO: die when this happens and throw an error
2200   $main::lxdebug->leave_sub() and return 0 if ($table =~ /\W/);
2201
2202   my $dbh = $form->dbconnect($myconfig);
2203
2204   my $query = qq|SELECT storno FROM $table WHERE id = ?|;
2205   my ($result) = selectrow_query($form, $dbh, $query, $form->{id});
2206
2207   $dbh->disconnect();
2208
2209   $main::lxdebug->leave_sub();
2210
2211   return $result;
2212 }
2213
2214 1;
2215