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