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