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