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