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