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