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