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