Anzeige und Auswahl von Projektnummern bei Einkaufs- und Verkaufsbelegen nur noch...
[kivitendo-erp.git] / SL / OE.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) 1999-2003
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 # Order entry module
32 # Quotation
33 #======================================================================
34
35 package OE;
36
37 use SL::AM;
38 use SL::Common;
39 use SL::DBUtils;
40
41 sub transactions {
42   $main::lxdebug->enter_sub();
43
44   my ($self, $myconfig, $form) = @_;
45
46   # connect to database
47   my $dbh = $form->dbconnect($myconfig);
48
49   my $query;
50   my $ordnumber = 'ordnumber';
51   my $quotation = '0';
52   my ($null, $department_id) = split /--/, $form->{department};
53
54   my $department = " AND o.department_id = $department_id" if $department_id;
55
56   my $rate = ($form->{vc} eq 'customer') ? 'buy' : 'sell';
57
58   if ($form->{type} =~ /_quotation$/) {
59     $quotation = '1';
60     $ordnumber = 'quonumber';
61   }
62
63   my $number = $form->like(lc $form->{$ordnumber});
64   my $name   = $form->like(lc $form->{ $form->{vc} });
65
66   my $query = qq|SELECT o.id, o.ordnumber, o.transdate, o.reqdate,
67                  o.amount, ct.name, o.netamount, o.$form->{vc}_id,
68                  ex.$rate AS exchangerate,
69                  o.closed, o.delivered, o.quonumber, o.shippingpoint, o.shipvia,
70                  e.name AS employee
71                  FROM oe o
72                  JOIN $form->{vc} ct ON (o.$form->{vc}_id = ct.id)
73                  LEFT JOIN employee e ON (o.employee_id = e.id)
74                  LEFT JOIN exchangerate ex ON (ex.curr = o.curr
75                                                AND ex.transdate = o.transdate)
76                  WHERE o.quotation = '$quotation'
77                  $department|;
78
79   if ($form->{"$form->{vc}_id"}) {
80     $query .= qq| AND o.$form->{vc}_id = $form->{"$form->{vc}_id"}|;
81   } else {
82     if ($form->{ $form->{vc} }) {
83       $query .= " AND lower(ct.name) LIKE '$name'";
84     }
85   }
86   if (!$form->{open} && !$form->{closed}) {
87     $query .= " AND o.id = 0";
88   } elsif (!($form->{open} && $form->{closed})) {
89     $query .= ($form->{open}) ? " AND o.closed = '0'" : " AND o.closed = '1'";
90   }
91
92   if (($form->{"notdelivered"} || $form->{"delivered"}) &&
93       ($form->{"notdelivered"} ne $form->{"delivered"})) {
94     $query .= $form->{"delivered"} ?
95       " AND o.delivered " : " AND NOT o.delivered";
96   }
97
98   my $sortorder = join ', ',
99     ("o.id", $form->sort_columns(transdate, $ordnumber, name));
100   $sortorder = $form->{sort} if $form->{sort};
101
102   $query .= " AND lower($ordnumber) LIKE '$number'" if $form->{$ordnumber};
103   $query .= " AND o.transdate >= '$form->{transdatefrom}'"
104     if $form->{transdatefrom};
105   $query .= " AND o.transdate <= '$form->{transdateto}'"
106     if $form->{transdateto};
107   $query .= " ORDER by $sortorder";
108
109   my $sth = $dbh->prepare($query);
110   $sth->execute || $form->dberror($query);
111
112   my %id = ();
113   while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
114     $ref->{exchangerate} = 1 unless $ref->{exchangerate};
115     push @{ $form->{OE} }, $ref if $ref->{id} != $id{ $ref->{id} };
116     $id{ $ref->{id} } = $ref->{id};
117   }
118
119   $sth->finish;
120   $dbh->disconnect;
121
122   $main::lxdebug->leave_sub();
123 }
124
125 sub save {
126   $main::lxdebug->enter_sub();
127
128   my ($self, $myconfig, $form) = @_;
129
130   # connect to database, turn off autocommit
131   my $dbh = $form->dbconnect_noauto($myconfig);
132
133   my ($query, $sth, $null);
134   my $exchangerate = 0;
135
136   my $service_units = AM->retrieve_units($myconfig,$form,"service");
137   my $part_units = AM->retrieve_units($myconfig,$form,"dimension");
138   $form->{service_units} =$service_units;
139   $form->{part_units} =$part_units;
140
141   ($null, $form->{employee_id}) = split /--/, $form->{employee};
142   unless ($form->{employee_id}) {
143     $form->get_employee($dbh);
144   }
145
146   $form->{payment_id} *= 1;
147   $form->{language_id} *= 1;
148   $form->{shipto_id} *= 1;
149   $form->{delivery_customer_id} *= 1;
150   $form->{delivery_vendor_id} *= 1;
151
152   my $ml = ($form->{type} eq 'sales_order') ? 1 : -1;
153
154   if ($form->{id}) {
155
156     &adj_onhand($dbh, $form, $ml) if $form->{type} =~ /_order$/;
157
158     $query = qq|DELETE FROM orderitems
159                 WHERE trans_id = $form->{id}|;
160     $dbh->do($query) || $form->dberror($query);
161
162     $query = qq|DELETE FROM shipto
163                 WHERE trans_id = $form->{id} AND module = 'OE'|;
164     $dbh->do($query) || $form->dberror($query);
165
166   } else {
167
168     my $uid = rand() . time;
169
170     $uid .= $form->{login};
171
172     $uid = substr($uid, 2, 75);
173
174     $query = qq|INSERT INTO oe (ordnumber, employee_id)
175                 VALUES ('$uid', $form->{employee_id})|;
176     $dbh->do($query) || $form->dberror($query);
177
178     $query = qq|SELECT o.id FROM oe o
179                 WHERE o.ordnumber = '$uid'|;
180     $sth = $dbh->prepare($query);
181     $sth->execute || $form->dberror($query);
182
183     ($form->{id}) = $sth->fetchrow_array;
184     $sth->finish;
185   }
186
187   map { $form->{$_} =~ s/\'/\'\'/g }
188     qw(ordnumber quonumber shippingpoint shipvia notes intnotes message);
189
190   my $amount;
191   my $linetotal;
192   my $discount;
193   my $project_id;
194   my $reqdate;
195   my $taxrate;
196   my $taxamount;
197   my $fxsellprice;
198   my %taxbase;
199   my @taxaccounts;
200   my %taxaccounts;
201   my $netamount = 0;
202
203   for my $i (1 .. $form->{rowcount}) {
204
205     map {
206       $form->{"${_}_$i"} =
207         $form->parse_amount($myconfig, $form->{"${_}_$i"})
208     } qw(qty ship);
209
210     if ($form->{"id_$i"}) {
211
212       # get item baseunit
213       $query = qq|SELECT p.unit
214                   FROM parts p
215                   WHERE p.id = $form->{"id_$i"}|;
216       $sth = $dbh->prepare($query);
217       $sth->execute || $form->dberror($query);
218
219       my ($item_unit) = $sth->fetchrow_array();
220       $sth->finish;
221
222       if ($form->{"inventory_accno_$i"}) {
223         if (defined($part_units->{$item_unit}->{factor}) && $part_units->{$item_unit}->{factor} ne '' && $part_units->{$item_unit}->{factor} ne '0') {
224           $basefactor = $part_units->{$form->{"unit_$i"}}->{factor} / $part_units->{$item_unit}->{factor};
225         } else {
226           $basefactor = 1;
227         }
228         $baseqty = $form->{"qty_$i"} * $basefactor;
229       } else {
230         if (defined($service_units->{$item_unit}->{factor}) && $service_units->{$item_unit}->{factor} ne '' && $service_units->{$item_unit}->{factor} ne '0') {
231           $basefactor = $service_units->{$form->{"unit_$i"}}->{factor} / $service_units->{$item_unit}->{factor};
232         } else {
233           $basefactor = 1;
234         }
235         $baseqty = $form->{"qty_$i"} * $basefactor;
236       }
237
238       map { $form->{"${_}_$i"} =~ s/\'/\'\'/g }
239         qw(partnumber description unit);
240
241       # set values to 0 if nothing entered
242       $form->{"discount_$i"} =
243         $form->parse_amount($myconfig, $form->{"discount_$i"}) / 100;
244
245       $form->{"sellprice_$i"} =
246         $form->parse_amount($myconfig, $form->{"sellprice_$i"});
247       $fxsellprice = $form->{"sellprice_$i"};
248
249       my ($dec) = ($form->{"sellprice_$i"} =~ /\.(\d+)/);
250       $dec = length $dec;
251       my $decimalplaces = ($dec > 2) ? $dec : 2;
252
253       $discount =
254         $form->round_amount($form->{"sellprice_$i"} * $form->{"discount_$i"},
255                             $decimalplaces);
256       $form->{"sellprice_$i"} =
257         $form->round_amount($form->{"sellprice_$i"} - $discount,
258                             $decimalplaces);
259
260       $form->{"inventory_accno_$i"} *= 1;
261       $form->{"expense_accno_$i"}   *= 1;
262
263       $linetotal =
264         $form->round_amount($form->{"sellprice_$i"} * $form->{"qty_$i"}, 2);
265
266       @taxaccounts = split / /, $form->{"taxaccounts_$i"};
267       $taxrate     = 0;
268       $taxdiff     = 0;
269
270       map { $taxrate += $form->{"${_}_rate"} } @taxaccounts;
271
272       if ($form->{taxincluded}) {
273         $taxamount = $linetotal * $taxrate / (1 + $taxrate);
274         $taxbase   = $linetotal - $taxamount;
275
276         # we are not keeping a natural price, do not round
277         $form->{"sellprice_$i"} =
278           $form->{"sellprice_$i"} * (1 / (1 + $taxrate));
279       } else {
280         $taxamount = $linetotal * $taxrate;
281         $taxbase   = $linetotal;
282       }
283
284       if ($form->round_amount($taxrate, 7) == 0) {
285         if ($form->{taxincluded}) {
286           foreach $item (@taxaccounts) {
287             $taxamount =
288               $form->round_amount($linetotal * $form->{"${item}_rate"} /
289                                     (1 + abs($form->{"${item}_rate"})),
290                                   2);
291
292             $taxaccounts{$item} += $taxamount;
293             $taxdiff            += $taxamount;
294
295             $taxbase{$item} += $taxbase;
296           }
297           $taxaccounts{ $taxaccounts[0] } += $taxdiff;
298         } else {
299           foreach $item (@taxaccounts) {
300             $taxaccounts{$item} += $linetotal * $form->{"${item}_rate"};
301             $taxbase{$item}     += $taxbase;
302           }
303         }
304       } else {
305         foreach $item (@taxaccounts) {
306           $taxaccounts{$item} +=
307             $taxamount * $form->{"${item}_rate"} / $taxrate;
308           $taxbase{$item} += $taxbase;
309         }
310       }
311
312       $netamount += $form->{"sellprice_$i"} * $form->{"qty_$i"};
313
314       $reqdate =
315         ($form->{"reqdate_$i"}) ? qq|'$form->{"reqdate_$i"}'| : "NULL";
316
317       # get pricegroup_id and save ist
318       ($null, my $pricegroup_id) = split /--/, $form->{"sellprice_pg_$i"};
319       $pricegroup_id *= 1;
320       $subtotal = $form->{"subtotal_$i"} * 1;
321
322       # save detail record in orderitems table
323       $query = qq|INSERT INTO orderitems (|;
324       $query .= "id, " if $form->{"orderitems_id_$i"};
325       $query .= qq|trans_id, parts_id, description, longdescription, qty, base_qty, sellprice, discount,
326                    unit, reqdate, project_id, serialnumber, ship, pricegroup_id,
327                    ordnumber, transdate, cusordnumber, subtotal)
328                    VALUES (|;
329       $query .= qq|$form->{"orderitems_id_$i"},|
330         if $form->{"orderitems_id_$i"};
331       $query .= qq|$form->{id}, $form->{"id_$i"},
332                    '$form->{"description_$i"}', '$form->{"longdescription_$i"}', $form->{"qty_$i"}, $baseqty,
333                    $fxsellprice, $form->{"discount_$i"},
334                    '$form->{"unit_$i"}', $reqdate, | . conv_i($form->{"project_id_$i"}, 'NULL') . qq|,
335                    '$form->{"serialnumber_$i"}', $form->{"ship_$i"}, '$pricegroup_id',
336                    '$form->{"ordnumber_$i"}', '$form->{"transdate_$i"}', '$form->{"cusordnumber_$i"}', '$subtotal')|;
337       $dbh->do($query) || $form->dberror($query);
338
339       $form->{"sellprice_$i"} = $fxsellprice;
340       $form->{"discount_$i"} *= 100;
341     }
342   }
343
344   # set values which could be empty
345   map { $form->{$_} *= 1 }
346     qw(vendor_id customer_id taxincluded closed quotation);
347
348   $reqdate = ($form->{reqdate}) ? qq|'$form->{reqdate}'| : "NULL";
349
350   # add up the tax
351   my $tax = 0;
352   map { $tax += $form->round_amount($taxaccounts{$_}, 2) } keys %taxaccounts;
353
354   $amount = $form->round_amount($netamount + $tax, 2);
355   $netamount = $form->round_amount($netamount, 2);
356
357   if ($form->{currency} eq $form->{defaultcurrency}) {
358     $form->{exchangerate} = 1;
359   } else {
360     $exchangerate =
361       $form->check_exchangerate($myconfig,
362                                 $form->{currency},
363                                 $form->{transdate},
364                                 ($form->{vc} eq 'customer') ? 'buy' : 'sell');
365   }
366
367   $form->{exchangerate} =
368     ($exchangerate)
369     ? $exchangerate
370     : $form->parse_amount($myconfig, $form->{exchangerate});
371
372   my $quotation;
373
374   # fill in subject if there is none
375   if ($form->{type} =~ /_order$/) {
376     $quotation = '0';
377     $form->{subject} = qq|$form->{label} $form->{ordnumber}|
378       unless $form->{subject};
379   } else {
380     $quotation = '1';
381     $form->{subject} = qq|$form->{label} $form->{quonumber}|
382       unless $form->{subject};
383   }
384
385   # if there is a message stuff it into the intnotes
386   my $cc  = "Cc: $form->{cc}\\r\n"   if $form->{cc};
387   my $bcc = "Bcc: $form->{bcc}\\r\n" if $form->{bcc};
388   my $now = scalar localtime;
389   $form->{intnotes} .= qq|\r
390 \r| if $form->{intnotes};
391
392   $form->{intnotes} .= qq|[email]\r
393 Date: $now
394 To: $form->{email}\r
395 $cc${bcc}Subject: $form->{subject}\r
396 \r
397 Message: $form->{message}\r| if $form->{message};
398
399   ($null, $form->{department_id}) = split(/--/, $form->{department});
400   $form->{department_id} *= 1;
401   $form->{payment_id} *= 1;
402   $form->{language_id} *= 1;
403   $form->{taxzone_id} *= 1;
404   $form->{proforma} *= 1;
405
406
407
408   # save OE record
409   $query = qq|UPDATE oe set
410               ordnumber = '$form->{ordnumber}',
411               quonumber = '$form->{quonumber}',
412               cusordnumber = '$form->{cusordnumber}',
413               transdate = '$form->{transdate}',
414               vendor_id = $form->{vendor_id},
415               customer_id = $form->{customer_id},
416               amount = $amount,
417               netamount = $netamount,
418               reqdate = $reqdate,
419               taxincluded = '$form->{taxincluded}',
420               shippingpoint = '$form->{shippingpoint}',
421               shipvia = '$form->{shipvia}',
422               notes = '$form->{notes}',
423               intnotes = '$form->{intnotes}',
424               curr = '$form->{currency}',
425               closed = '$form->{closed}',
426               delivered = '| . ($form->{delivered} ? "t" : "f") . qq|',
427               proforma = '$form->{proforma}',
428               quotation = '$quotation',
429               department_id = $form->{department_id},
430               language_id = $form->{language_id},
431               taxzone_id = $form->{taxzone_id},
432               shipto_id = $form->{shipto_id},
433               payment_id = $form->{payment_id},
434               delivery_vendor_id = $form->{delivery_vendor_id},
435               delivery_customer_id = $form->{delivery_customer_id},
436               globalproject_id = | . conv_i($form->{"globalproject_id"}, 'NULL') . qq|,
437               employee_id = $form->{employee_id},
438               cp_id = | . conv_i($form->{cp_id}, 'NULL') . qq|
439               WHERE id = $form->{id}|;
440   $dbh->do($query) || $form->dberror($query);
441
442   $form->{ordtotal} = $amount;
443
444   # add shipto
445   $form->{name} = $form->{ $form->{vc} };
446   $form->{name} =~ s/--$form->{"$form->{vc}_id"}//;
447
448   if (!$form->{shipto_id}) {
449     $form->add_shipto($dbh, $form->{id}, "OE");
450   }
451
452   # save printed, emailed, queued
453   $form->save_status($dbh);
454
455   if (($form->{currency} ne $form->{defaultcurrency}) && !$exchangerate) {
456     if ($form->{vc} eq 'customer') {
457       $form->update_exchangerate($dbh, $form->{currency}, $form->{transdate},
458                                  $form->{exchangerate}, 0);
459     }
460     if ($form->{vc} eq 'vendor') {
461       $form->update_exchangerate($dbh, $form->{currency}, $form->{transdate},
462                                  0, $form->{exchangerate});
463     }
464   }
465
466   if ($form->{type} =~ /_order$/) {
467
468     # adjust onhand
469     &adj_onhand($dbh, $form, $ml * -1);
470   }
471
472   my $rc = $dbh->commit;
473   $dbh->disconnect;
474
475   Common::webdav_folder($form) if ($main::webdav);
476
477   $main::lxdebug->leave_sub();
478
479   return $rc;
480 }
481
482 # this function closes multiple orders given in $form->{ordnumber_#}.
483 # use this for multiple orders that don't have to be saved back
484 # single orders should use OE::save instead.
485 sub close_orders {
486   $main::lxdebug->enter_sub();
487
488   my ($self, $myconfig, $form) = @_;
489
490   # get ids from $form
491   map { push @ids, $form->{"ordnumber_$_"} if $form->{"ordnumber_$_"} }
492     (1 .. $form->{rowcount});
493
494   my $dbh = $form->dbconnect($myconfig);
495   $query = qq|UPDATE oe SET
496               closed = TRUE
497               WHERE ordnumber IN (|
498     . join(', ', map { $dbh->quote($_) } @ids) . qq|)|;
499   $dbh->do($query) || $form->dberror($query);
500   $dbh->disconnect;
501
502   $main::lxdebug->leave_sub();
503 }
504
505 sub close_order {
506   $main::lxdebug->enter_sub();
507
508   my ($self, $myconfig, $form) = @_;
509
510   $main::lxdebug->leave_sub() unless ($form->{"id"});
511
512   my $dbh = $form->dbconnect($myconfig);
513   do_query($form, $dbh, qq|UPDATE oe SET closed = TRUE where id = ?|,
514            $form->{"id"});
515   $dbh->disconnect;
516
517   $main::lxdebug->leave_sub();
518 }
519
520 sub delete {
521   $main::lxdebug->enter_sub();
522
523   my ($self, $myconfig, $form, $spool) = @_;
524
525   # connect to database
526   my $dbh = $form->dbconnect_noauto($myconfig);
527
528   # delete spool files
529   my $query = qq|SELECT s.spoolfile FROM status s
530                  WHERE s.trans_id = $form->{id}|;
531   $sth = $dbh->prepare($query);
532   $sth->execute || $self->dberror($query);
533
534   my $spoolfile;
535   my @spoolfiles = ();
536
537   while (($spoolfile) = $sth->fetchrow_array) {
538     push @spoolfiles, $spoolfile;
539   }
540   $sth->finish;
541
542   $query = qq|SELECT o.parts_id, o.ship FROM orderitems o
543               WHERE o.trans_id = $form->{id}|;
544   $sth = $dbh->prepare($query);
545   $sth->execute || $self->dberror($query);
546
547   while (my ($id, $ship) = $sth->fetchrow_array) {
548     $form->update_balance($dbh, "parts", "onhand", qq|id = $id|, $ship * -1);
549   }
550   $sth->finish;
551
552   # delete inventory
553   $query = qq|DELETE FROM inventory
554               WHERE oe_id = $form->{id}|;
555   $dbh->do($query) || $form->dberror($query);
556
557   # delete status entries
558   $query = qq|DELETE FROM status
559               WHERE trans_id = $form->{id}|;
560   $dbh->do($query) || $form->dberror($query);
561
562   # delete OE record
563   $query = qq|DELETE FROM oe
564               WHERE id = $form->{id}|;
565   $dbh->do($query) || $form->dberror($query);
566
567   # delete individual entries
568   $query = qq|DELETE FROM orderitems
569               WHERE trans_id = $form->{id}|;
570   $dbh->do($query) || $form->dberror($query);
571
572   $query = qq|DELETE FROM shipto
573               WHERE trans_id = $form->{id} AND module = 'OE'|;
574   $dbh->do($query) || $form->dberror($query);
575
576   my $rc = $dbh->commit;
577   $dbh->disconnect;
578
579   if ($rc) {
580     foreach $spoolfile (@spoolfiles) {
581       unlink "$spool/$spoolfile" if $spoolfile;
582     }
583   }
584
585   $main::lxdebug->leave_sub();
586
587   return $rc;
588 }
589
590 sub retrieve {
591   $main::lxdebug->enter_sub();
592
593   my ($self, $myconfig, $form) = @_;
594
595   # connect to database
596   my $dbh = $form->dbconnect_noauto($myconfig);
597
598   my $query, @ids;
599
600   # translate the ids (given by id_# and trans_id_#) into one array of ids, so we can join them later
601   map {
602     push @ids, $form->{"trans_id_$_"}
603       if ($form->{"id_$_"} and $form->{"trans_id_$_"})
604   } (1 .. $form->{"rowcount"});
605
606   # if called in multi id mode, and still only got one id, switch back to single id
607   if ($form->{"rowcount"} and $#ids == 0) {
608     $form->{"id"} = $ids[0];
609     undef @ids;
610   }
611
612   if ($form->{id}) {
613
614     # get default accounts and last order number
615     $query = qq|SELECT (SELECT c.accno FROM chart c
616                         WHERE d.inventory_accno_id = c.id) AS inventory_accno,
617                        (SELECT c.accno FROM chart c
618                         WHERE d.income_accno_id = c.id) AS income_accno,
619                        (SELECT c.accno FROM chart c
620                         WHERE d.expense_accno_id = c.id) AS expense_accno,
621                        (SELECT c.accno FROM chart c
622                         WHERE d.fxgain_accno_id = c.id) AS fxgain_accno,
623                        (SELECT c.accno FROM chart c
624                         WHERE d.fxloss_accno_id = c.id) AS fxloss_accno,
625                 d.curr AS currencies
626                 FROM defaults d|;
627   } else {
628     $query = qq|SELECT (SELECT c.accno FROM chart c
629                         WHERE d.inventory_accno_id = c.id) AS inventory_accno,
630                        (SELECT c.accno FROM chart c
631                         WHERE d.income_accno_id = c.id) AS income_accno,
632                        (SELECT c.accno FROM chart c
633                         WHERE d.expense_accno_id = c.id) AS expense_accno,
634                        (SELECT c.accno FROM chart c
635                         WHERE d.fxgain_accno_id = c.id) AS fxgain_accno,
636                        (SELECT c.accno FROM chart c
637                         WHERE d.fxloss_accno_id = c.id) AS fxloss_accno,
638                 d.curr AS currencies,
639                 current_date AS transdate, current_date AS reqdate
640                 FROM defaults d|;
641   }
642   my $sth = $dbh->prepare($query);
643   $sth->execute || $form->dberror($query);
644
645   my $ref = $sth->fetchrow_hashref(NAME_lc);
646   map { $form->{$_} = $ref->{$_} } keys %$ref;
647   $sth->finish;
648
649   ($form->{currency}) = split /:/, $form->{currencies};
650
651   # set reqdate if this is an invoice->order conversion. If someone knows a better check to ensure
652   # we come from invoices, feel free.
653   $form->{reqdate} = $form->{deliverydate}
654     if (    $form->{deliverydate}
655         and $form->{callback} =~ /action=ar_transactions/);
656
657   if ($form->{id} or @ids) {
658
659     # retrieve order for single id
660     # NOTE: this query is intended to fetch all information only ONCE.
661     # so if any of these infos is important (or even different) for any item,
662     # it will be killed out and then has to be fetched from the item scope query further down
663     $query = qq|SELECT o.cp_id, o.ordnumber, o.transdate, o.reqdate,
664                 o.taxincluded, o.shippingpoint, o.shipvia, o.notes, o.intnotes,
665                 o.curr AS currency, e.name AS employee, o.employee_id,
666                 o.$form->{vc}_id, cv.name AS $form->{vc}, o.amount AS invtotal,
667                 o.closed, o.reqdate, o.quonumber, o.department_id, o.cusordnumber,
668                 d.description AS department, o.payment_id, o.language_id, o.taxzone_id,
669                 o.delivery_customer_id, o.delivery_vendor_id, o.proforma, o.shipto_id,
670                 o.globalproject_id,
671                 o.delivered
672                 FROM oe o
673                 JOIN $form->{vc} cv ON (o.$form->{vc}_id = cv.id)
674                 LEFT JOIN employee e ON (o.employee_id = e.id)
675                 LEFT JOIN department d ON (o.department_id = d.id)
676                 |
677       . ($form->{id}
678          ? qq|WHERE o.id = $form->{id}|
679          : qq|WHERE o.id IN (| . join(', ', @ids) . qq|)|);
680
681     #$main::lxdebug->message(0, $query);
682
683     $sth = $dbh->prepare($query);
684     $sth->execute || $form->dberror($query);
685
686     $ref = $sth->fetchrow_hashref(NAME_lc);
687     map { $form->{$_} = $ref->{$_} } keys %$ref;
688
689
690
691     # set all entries for multiple ids blank that yield different information
692     while ($ref = $sth->fetchrow_hashref(NAME_lc)) {
693       map { $form->{$_} = '' if ($ref->{$_} ne $form->{$_}) } keys %$ref;
694     }
695
696     # if not given, fill transdate with current_date
697     $form->{transdate} = $form->current_date($myconfig)
698       unless $form->{transdate};
699
700     $sth->finish;
701
702     if ($form->{delivery_customer_id}) {
703       $query = qq|SELECT name FROM customer WHERE id=$form->{delivery_customer_id}|;
704       $sth = $dbh->prepare($query);
705       $sth->execute || $form->dberror($query);
706       ($form->{delivery_customer_string}) = $sth->fetchrow_array();
707       $sth->finish;
708     }
709
710     if ($form->{delivery_vendor_id}) {
711       $query = qq|SELECT name FROM customer WHERE id=$form->{delivery_vendor_id}|;
712       $sth = $dbh->prepare($query);
713       $sth->execute || $form->dberror($query);
714       ($form->{delivery_vendor_string}) = $sth->fetchrow_array();
715       $sth->finish;
716     }
717
718     # shipto and pinted/mailed/queued status makes only sense for single id retrieve
719     if (!@ids) {
720       $query = qq|SELECT s.* FROM shipto s
721                   WHERE s.trans_id = $form->{id} AND s.module = 'OE'|;
722       $sth = $dbh->prepare($query);
723       $sth->execute || $form->dberror($query);
724
725       $ref = $sth->fetchrow_hashref(NAME_lc);
726       delete($ref->{id});
727       map { $form->{$_} = $ref->{$_} } keys %$ref;
728       $sth->finish;
729
730       # get printed, emailed and queued
731       $query = qq|SELECT s.printed, s.emailed, s.spoolfile, s.formname
732                   FROM status s
733                   WHERE s.trans_id = $form->{id}|;
734       $sth = $dbh->prepare($query);
735       $sth->execute || $form->dberror($query);
736
737       while ($ref = $sth->fetchrow_hashref(NAME_lc)) {
738         $form->{printed} .= "$ref->{formname} " if $ref->{printed};
739         $form->{emailed} .= "$ref->{formname} " if $ref->{emailed};
740         $form->{queued} .= "$ref->{formname} $ref->{spoolfile} "
741           if $ref->{spoolfile};
742       }
743       $sth->finish;
744       map { $form->{$_} =~ s/ +$//g } qw(printed emailed queued);
745     }    # if !@ids
746
747     my %oid = ('Pg'     => 'oid',
748                'Oracle' => 'rowid');
749
750     my $transdate =
751       $form->{transdate} ? $dbh->quote($form->{transdate}) : "current_date";
752
753     if(!$form->{taxzone_id}) {
754       $form->{taxzone_id} = 0;
755     }
756     # retrieve individual items
757     # this query looks up all information about the items
758     # stuff different from the whole will not be overwritten, but saved with a suffix.
759     $query = qq|SELECT o.id AS orderitems_id,
760                 c1.accno AS inventory_accno, c1.new_chart_id AS inventory_new_chart, date($transdate) - c1.valid_from as inventory_valid,
761                 c2.accno AS income_accno, c2.new_chart_id AS income_new_chart, date($transdate)  - c2.valid_from as income_valid,
762                 c3.accno AS expense_accno, c3.new_chart_id AS expense_new_chart, date($transdate) - c3.valid_from as expense_valid,
763                 oe.ordnumber AS ordnumber_oe, oe.transdate AS transdate_oe, oe.cusordnumber AS cusordnumber_oe, 
764                 p.partnumber, p.assembly, o.description, o.qty,
765                 o.sellprice, o.parts_id AS id, o.unit, o.discount, p.bin, p.notes AS partnotes, p.inventory_accno_id AS part_inventory_accno_id,
766                 o.reqdate, o.project_id, o.serialnumber, o.ship,
767                 o.ordnumber, o.transdate, o.cusordnumber, o.subtotal, o.longdescription,
768                 pr.projectnumber, p.formel,
769                 pg.partsgroup, o.pricegroup_id, (SELECT pricegroup FROM pricegroup WHERE id=o.pricegroup_id) as pricegroup
770                 FROM orderitems o
771                 JOIN parts p ON (o.parts_id = p.id)
772                 JOIN oe ON (o.trans_id = oe.id)
773                 LEFT JOIN chart c1 ON ((select inventory_accno_id from buchungsgruppen where id=p.buchungsgruppen_id) = c1.id)
774                 LEFT JOIN chart c2 ON ((select income_accno_id_$form->{taxzone_id} from buchungsgruppen where id=p.buchungsgruppen_id) = c2.id)
775                 LEFT JOIN chart c3 ON ((select expense_accno_id_$form->{taxzone_id} from buchungsgruppen where id=p.buchungsgruppen_id) = c3.id)
776                 LEFT JOIN project pr ON (o.project_id = pr.id)
777                 LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
778                 |
779       . ($form->{id}
780          ? qq|WHERE o.trans_id = $form->{id}|
781          : qq|WHERE o.trans_id IN (| . join(", ", @ids) . qq|)|)
782       . qq|
783                 ORDER BY o.$oid{$myconfig->{dbdriver}}|;
784
785     $sth = $dbh->prepare($query);
786     $sth->execute || $form->dberror($query);
787
788     while ($ref = $sth->fetchrow_hashref(NAME_lc)) {
789       if (!$ref->{"part_inventory_accno_id"}) {
790         map({ delete($ref->{$_}); } qw(inventory_accno inventory_new_chart inventory_valid));
791       }
792       delete($ref->{"part_inventory_accno_id"});
793
794       # in collective order, copy global ordnumber, transdate, cusordnumber into item scope
795       #   unless already present there
796       # remove _oe entries afterwards
797       map { $ref->{$_} = $ref->{"${_}_oe"} if ($ref->{$_} eq '') }
798         qw|ordnumber transdate cusordnumber|
799         if (@ids);
800       map { delete $ref->{$_} } qw|ordnumber_oe transdate_oe cusordnumber_oe|;
801
802
803
804     while ($ref->{inventory_new_chart} && ($ref->{inventory_valid} >=0)) {
805       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}|;
806       my $stw = $dbh->prepare($query);
807       $stw->execute || $form->dberror($query);
808       ($ref->{inventory_accno}, $ref->{inventory_new_chart}, $ref->{inventory_valid}) = $stw->fetchrow_array;
809       $stw->finish;
810     }
811
812     while ($ref->{income_new_chart} && ($ref->{income_valid} >=0)) {
813       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}|;
814       my $stw = $dbh->prepare($query);
815       $stw->execute || $form->dberror($query);
816       ($ref->{income_accno}, $ref->{income_new_chart}, $ref->{income_valid}) = $stw->fetchrow_array;
817       $stw->finish;
818     }
819
820     while ($ref->{expense_new_chart} && ($ref->{expense_valid} >=0)) {
821       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}|;
822       my $stw = $dbh->prepare($query);
823       $stw->execute || $form->dberror($query);
824       ($ref->{expense_accno}, $ref->{expense_new_chart}, $ref->{expense_valid}) = $stw->fetchrow_array;
825       $stw->finish;
826     }
827
828       # delete orderitems_id in collective orders, so that they get cloned no matter what
829       delete $ref->{orderitems_id} if (@ids);
830
831       # get tax rates and description
832       $accno_id =
833         ($form->{vc} eq "customer") ? $ref->{income_accno} : $ref->{expense_accno};
834       $query = qq|SELECT c.accno, t.taxdescription, t.rate, t.taxnumber
835               FROM tax t LEFT JOIN chart c on (c.id=t.chart_id)
836               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)
837               ORDER BY c.accno|;
838       $stw = $dbh->prepare($query);
839       $stw->execute || $form->dberror($query);
840       $ref->{taxaccounts} = "";
841       my $i = 0;
842       while ($ptr = $stw->fetchrow_hashref(NAME_lc)) {
843
844         #    if ($customertax{$ref->{accno}}) {
845         if (($ptr->{accno} eq "") && ($ptr->{rate} == 0)) {
846           $i++;
847           $ptr->{accno} = $i;
848         }
849         $ref->{taxaccounts} .= "$ptr->{accno} ";
850         if (!($form->{taxaccounts} =~ /$ptr->{accno}/)) {
851           $form->{"$ptr->{accno}_rate"}        = $ptr->{rate};
852           $form->{"$ptr->{accno}_description"} = $ptr->{taxdescription};
853           $form->{"$ptr->{accno}_taxnumber"}   = $ptr->{taxnumber};
854           $form->{taxaccounts} .= "$ptr->{accno} ";
855         }
856
857       }
858
859       chop $ref->{taxaccounts};
860       push @{ $form->{form_details} }, $ref;
861       $stw->finish;
862     }
863     $sth->finish;
864
865   } else {
866
867     # get last name used
868     $form->lastname_used($dbh, $myconfig, $form->{vc})
869       unless $form->{"$form->{vc}_id"};
870
871   }
872
873   $form->{exchangerate} =
874     $form->get_exchangerate($dbh, $form->{currency}, $form->{transdate},
875                             ($form->{vc} eq 'customer') ? "buy" : "sell");
876
877   Common::webdav_folder($form) if ($main::webdav);
878
879   # get tax zones
880   $query = qq|SELECT id, description
881               FROM tax_zones|;
882   $sth = $dbh->prepare($query);
883   $sth->execute || $form->dberror($query);
884
885
886   while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
887     push @{ $form->{TAXZONE} }, $ref;
888   }
889   $sth->finish;
890
891
892   my $rc = $dbh->commit;
893   $dbh->disconnect;
894
895   $main::lxdebug->leave_sub();
896
897   return $rc;
898 }
899
900 sub order_details {
901   $main::lxdebug->enter_sub();
902
903   my ($self, $myconfig, $form) = @_;
904
905   # connect to database
906   my $dbh = $form->dbconnect($myconfig);
907   my $query;
908   my $sth;
909   my $nodiscount;
910   my $yesdiscount;
911   my $nodiscount_subtotal = 0;
912   my $discount_subtotal = 0;
913   my $item;
914   my $i;
915   my @partsgroup = ();
916   my $partsgroup;
917   my $position = 0;
918   my $subtotal_header = 0;
919   my $subposition = 0;
920
921   my %oid = ('Pg'     => 'oid',
922              'Oracle' => 'rowid');
923
924   # sort items by partsgroup
925   for $i (1 .. $form->{rowcount}) {
926     $partsgroup = "";
927     if ($form->{"partsgroup_$i"} && $form->{groupitems}) {
928       $partsgroup = $form->{"partsgroup_$i"};
929     }
930     push @partsgroup, [$i, $partsgroup];
931   }
932
933   my $sameitem = "";
934   foreach $item (sort { $a->[1] cmp $b->[1] } @partsgroup) {
935     $i = $item->[0];
936
937     if ($item->[1] ne $sameitem) {
938       push(@{ $form->{description} }, qq|$item->[1]|);
939       $sameitem = $item->[1];
940
941       map { push(@{ $form->{$_} }, "") }
942         qw(runningnumber number qty ship unit bin partnotes
943            serialnumber reqdate sellprice listprice netprice
944            discount p_discount linetotal);
945     }
946
947     $form->{"qty_$i"} = $form->parse_amount($myconfig, $form->{"qty_$i"});
948
949     if ($form->{"id_$i"} != 0) {
950
951       # add number, description and qty to $form->{number}, ....
952
953       if ($form->{"subtotal_$i"} && !$subtotal_header) {
954         $subtotal_header = $i;
955         $position = int($position);
956         $subposition = 0;
957         $position++;
958       } elsif ($subtotal_header) {
959         $subposition += 1;
960         $position = int($position);
961         $position = $position.".".$subposition;
962       } else {
963         $position = int($position);
964         $position++;
965       }
966
967       push(@{ $form->{runningnumber} }, $i);
968       push(@{ $form->{number} },        qq|$form->{"partnumber_$i"}|);
969       push(@{ $form->{description} },   qq|$form->{"description_$i"}|);
970       push(@{ $form->{longdescription} },   qq|$form->{"longdescription_$i"}|);
971       push(@{ $form->{qty} },
972            $form->format_amount($myconfig, $form->{"qty_$i"}));
973       push(@{ $form->{ship} },
974            $form->format_amount($myconfig, $form->{"ship_$i"}));
975       push(@{ $form->{unit} },         qq|$form->{"unit_$i"}|);
976       push(@{ $form->{bin} },          qq|$form->{"bin_$i"}|);
977       push(@{ $form->{"partnotes"} },  qq|$form->{"partnotes_$i"}|);
978       push(@{ $form->{serialnumber} }, qq|$form->{"serialnumber_$i"}|);
979       push(@{ $form->{reqdate} },      qq|$form->{"reqdate_$i"}|);
980
981       push(@{ $form->{sellprice} }, $form->{"sellprice_$i"});
982
983       push(@{ $form->{listprice} }, $form->{"listprice_$i"});
984
985       my $sellprice = $form->parse_amount($myconfig, $form->{"sellprice_$i"});
986       my ($dec) = ($sellprice =~ /\.(\d+)/);
987       $dec = length $dec;
988       my $decimalplaces = ($dec > 2) ? $dec : 2;
989
990       my $i_discount =
991         $form->round_amount(
992                             $sellprice * $form->parse_amount($myconfig,
993                                                  $form->{"discount_$i"}) / 100,
994                             $decimalplaces);
995
996       my $discount =
997         $form->round_amount($form->{"qty_$i"} * $i_discount, $decimalplaces);
998
999       # keep a netprice as well, (sellprice - discount)
1000       #$form->{"netprice_$i"} = $sellprice - $discount;
1001       $form->{"netprice_$i"} = $sellprice - $i_discount;
1002       my $nodiscount_linetotal =
1003         $form->round_amount($form->{"qty_$i"} * $sellprice, 2);
1004       my $linetotal =
1005         $form->round_amount($form->{"qty_$i"} * $form->{"netprice_$i"}, 2);
1006
1007       push(@{ $form->{netprice} },
1008            ($form->{"netprice_$i"} != 0)
1009            ? $form->format_amount(
1010                                  $myconfig, $form->{"netprice_$i"},
1011                                  $decimalplaces
1012              )
1013            : " ");
1014
1015       $discount =
1016         ($discount != 0)
1017         ? $form->format_amount($myconfig, $discount * -1, $decimalplaces)
1018         : " ";
1019       $linetotal = ($linetotal != 0) ? $linetotal : " ";
1020
1021       push(@{ $form->{discount} },   $discount);
1022       push(@{ $form->{p_discount} }, $form->{"discount_$i"});
1023
1024       $form->{ordtotal} += $linetotal;
1025      $discount_subtotal += $linetotal;
1026       $form->{nodiscount_total} += $nodiscount_linetotal;
1027       $nodiscount_subtotal += $nodiscount_linetotal;
1028       $form->{discount_total} += $form->parse_amount($myconfig, $discount);
1029
1030       if ($form->{"subtotal_$i"} && $subtotal_header && ($subtotal_header != $i)) {
1031         $discount_subtotal = $form->format_amount($myconfig, $discount_subtotal, 2);
1032         push(@{ $form->{discount_sub} },  $discount_subtotal);
1033         $nodiscount_subtotal = $form->format_amount($myconfig, $nodiscount_subtotal, 2);
1034         push(@{ $form->{nodiscount_sub} }, $nodiscount_subtotal);
1035         $discount_subtotal = 0;
1036         $nodiscount_subtotal = 0;
1037         $subtotal_header = 0;
1038       } else {
1039         push(@{ $form->{discount_sub} }, "");
1040         push(@{ $form->{nodiscount_sub} }, "");
1041       }
1042
1043       if ($linetotal == $netto_linetotal) {
1044         $nodiscount += $linetotal;
1045       }
1046       push(@{ $form->{linetotal} },
1047            $form->format_amount($myconfig, $linetotal, 2));
1048       push(@{ $form->{nodiscount_linetotal} },
1049            $form->format_amount($myconfig, $nodiscount_linetotal, 2));
1050
1051       my ($taxamount, $taxbase);
1052       my $taxrate = 0;
1053
1054       map { $taxrate += $form->{"${_}_rate"} } split / /,
1055         $form->{"taxaccounts_$i"};
1056
1057       if ($form->{taxincluded}) {
1058
1059         # calculate tax
1060         $taxamount = $linetotal * $taxrate / (1 + $taxrate);
1061         $taxbase = $linetotal / (1 + $taxrate);
1062       } else {
1063         $taxamount = $linetotal * $taxrate;
1064         $taxbase   = $linetotal;
1065       }
1066
1067       if ($taxamount != 0) {
1068         foreach my $item (split / /, $form->{"taxaccounts_$i"}) {
1069           $taxaccounts{$item} +=
1070             $taxamount * $form->{"${item}_rate"} / $taxrate;
1071           $taxbase{$item} += $taxbase;
1072         }
1073       }
1074
1075       $tax_rate = $taxrate * 100;
1076       push(@{ $form->{tax_rate} }, qq|$tax_rate|);
1077
1078       if ($form->{"assembly_$i"}) {
1079         $sameitem = "";
1080
1081         # get parts and push them onto the stack
1082         my $sortorder = "";
1083         if ($form->{groupitems}) {
1084           $sortorder =
1085             qq|ORDER BY pg.partsgroup, a.$oid{$myconfig->{dbdriver}}|;
1086         } else {
1087           $sortorder = qq|ORDER BY a.$oid{$myconfig->{dbdriver}}|;
1088         }
1089
1090         $query = qq|SELECT p.partnumber, p.description, p.unit, a.qty,
1091                     pg.partsgroup
1092                     FROM assembly a
1093                     JOIN parts p ON (a.parts_id = p.id)
1094                     LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
1095                     WHERE a.bom = '1'
1096                     AND a.id = '$form->{"id_$i"}'
1097                     $sortorder|;
1098         $sth = $dbh->prepare($query);
1099         $sth->execute || $form->dberror($query);
1100
1101         while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
1102           if ($form->{groupitems} && $ref->{partsgroup} ne $sameitem) {
1103             map { push(@{ $form->{$_} }, "") }
1104               qw(runningnumber ship bin serialnumber number unit bin qty 
1105                  reqdate sellprice listprice netprice discount p_discount
1106                  linetotal nodiscount_linetotal);
1107             $sameitem = ($ref->{partsgroup}) ? $ref->{partsgroup} : "--";
1108             push(@{ $form->{description} }, $sameitem);
1109           }
1110
1111           push(@{ $form->{description} },
1112                $form->format_amount($myconfig, $ref->{qty} * $form->{"qty_$i"}
1113                  )
1114                  . qq|, $ref->{partnumber}, $ref->{description}|);
1115
1116           map { push(@{ $form->{$_} }, "") }
1117             qw(number unit qty runningnumber ship bin serialnumber reqdate 
1118                sellprice listprice netprice discount p_discount linetotal 
1119                nodiscount_linetotal);
1120
1121         }
1122         $sth->finish;
1123       }
1124
1125     }
1126   }
1127
1128   my $tax = 0;
1129   foreach $item (sort keys %taxaccounts) {
1130       push(@{ $form->{taxbase} },
1131            $form->format_amount($myconfig, $taxbase{$item}, 2));
1132
1133       $tax += $taxamount = $form->round_amount($taxaccounts{$item}, 2);
1134
1135       push(@{ $form->{tax} }, $form->format_amount($myconfig, $taxamount, 2));
1136       push(@{ $form->{taxdescription} }, $form->{"${item}_description"});
1137       push(@{ $form->{taxrate} },
1138            $form->format_amount($myconfig, $form->{"${item}_rate"} * 100));
1139       push(@{ $form->{taxnumber} }, $form->{"${item}_taxnumber"});
1140   }
1141   $form->{subtotal} = $form->format_amount($myconfig, $form->{total}, 2);
1142   $yesdiscount = $form->{nodiscount_total} - $nodiscount;
1143   $form->{nodiscount_subtotal} = $form->format_amount($myconfig, $form->{nodiscount_total}, 2);
1144   $form->{discount_total} = $form->format_amount($myconfig, $form->{discount_total}, 2);
1145   $form->{nodiscount} = $form->format_amount($myconfig, $nodiscount, 2);
1146   $form->{yesdiscount} = $form->format_amount($myconfig, $yesdiscount, 2);
1147
1148   $form->{subtotal} = $form->format_amount($myconfig, $form->{ordtotal}, 2);
1149   $form->{ordtotal} =
1150     ($form->{taxincluded}) ? $form->{ordtotal} : $form->{ordtotal} + $tax;
1151
1152   # format amounts
1153   $form->{quototal} = $form->{ordtotal} =
1154     $form->format_amount($myconfig, $form->{ordtotal}, 2);
1155
1156   if ($form->{type} =~ /_quotation/) {
1157     $form->set_payment_options($myconfig, $form->{quodate});
1158   } else {
1159     $form->set_payment_options($myconfig, $form->{orddate});
1160   }
1161
1162   # myconfig variables
1163   map { $form->{$_} = $myconfig->{$_} }
1164     (qw(company address tel fax signature businessnumber));
1165   $form->{username} = $myconfig->{name};
1166
1167   $dbh->disconnect;
1168
1169   $main::lxdebug->leave_sub();
1170 }
1171
1172 sub project_description {
1173   $main::lxdebug->enter_sub();
1174
1175   my ($self, $dbh, $id) = @_;
1176
1177   my $query = qq|SELECT p.description
1178                  FROM project p
1179                  WHERE p.id = $id|;
1180   my $sth = $dbh->prepare($query);
1181   $sth->execute || $form->dberror($query);
1182
1183   ($_) = $sth->fetchrow_array;
1184
1185   $sth->finish;
1186
1187   $main::lxdebug->leave_sub();
1188
1189   return $_;
1190 }
1191
1192 sub adj_onhand {
1193   $main::lxdebug->enter_sub();
1194
1195   my ($dbh, $form, $ml) = @_;
1196
1197   my $service_units = $form->{service_units};
1198   my $part_units = $form->{part_units};
1199
1200   my $query = qq|SELECT oi.parts_id, oi.ship, oi.unit, p.inventory_accno_id, p.assembly
1201                  FROM orderitems oi
1202                  JOIN parts p ON (p.id = oi.parts_id)
1203                  WHERE oi.trans_id = $form->{id}|;
1204   my $sth = $dbh->prepare($query);
1205   $sth->execute || $form->dberror($query);
1206
1207   $query = qq|SELECT sum(p.inventory_accno_id)
1208               FROM parts p
1209               JOIN assembly a ON (a.parts_id = p.id)
1210               WHERE a.id = ?|;
1211   my $ath = $dbh->prepare($query) || $form->dberror($query);
1212
1213   my $ispa;
1214
1215   while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
1216   #print(STDERR "Bin in Schleife $ref->{inventory_accno_id}\n");
1217
1218     if ($ref->{inventory_accno_id} || $ref->{assembly}) {
1219
1220       # do not update if assembly consists of all services
1221       if ($ref->{assembly}) {
1222         $ath->execute($ref->{parts_id}) || $form->dberror($query);
1223
1224         ($ispa) = $sth->fetchrow_array;
1225         $ath->finish;
1226
1227         next unless $ispa;
1228
1229       }
1230
1231       # get item baseunit
1232       $query = qq|SELECT p.unit
1233                   FROM parts p
1234                   WHERE p.id = $ref->{parts_id}|;
1235       my $stw = $dbh->prepare($query);
1236       $stw->execute || $form->dberror($query);
1237
1238       my ($item_unit) = $stw->fetchrow_array();
1239       $stw->finish;
1240
1241       if ($ref->{inventory_accno_id}) {        
1242         if (defined($part_units->{$item_unit}->{factor}) && $part_units->{$item_unit}->{factor} ne '' && $part_units->{$item_unit}->{factor} ne '0') {
1243           $basefactor = $part_units->{$ref->{unit}}->{factor} / $part_units->{$item_unit}->{factor};
1244         } else {
1245           $basefactor = 1;
1246         }
1247         $baseqty = $ref->{ship} * $basefactor;
1248       } else {
1249         if (defined($service_units->{$item_unit}->{factor}) && $service_units->{$item_unit}->{factor} ne '' && $service_units->{$item_unit}->{factor} ne '0') {
1250           $basefactor = $service_units->{$ref->{unit}}->{factor} / $part_units->{$item_unit}->{factor};
1251         } else {
1252           $basefactor = 1;
1253         }
1254         $baseqty = $ref->{ship} * $basefactor;
1255       }  
1256       #print(STDERR "$baseqty Basismenge\n");
1257
1258       # adjust onhand in parts table
1259       $form->update_balance($dbh, "parts", "onhand",
1260                             qq|id = $ref->{parts_id}|,
1261                             $baseqty * $ml);
1262     }
1263   }
1264
1265   $sth->finish;
1266
1267   $main::lxdebug->leave_sub();
1268 }
1269
1270 1;
1271