Bei boolean-Spalten lieber 't' und 'f' als 1 und 0 übergeben, weil wohl einige DBD...
[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;
393
394   # fill in subject if there is none
395   if ($form->{type} =~ /_order$/) {
396     $quotation = 't';
397     $form->{subject} = qq|$form->{label} $form->{ordnumber}|
398       unless $form->{subject};
399   } else {
400     $quotation = 'f';
401     $form->{subject} = qq|$form->{label} $form->{quonumber}|
402       unless $form->{subject};
403   }
404
405   # if there is a message stuff it into the intnotes
406   my $cc  = "Cc: $form->{cc}\\r\n"   if $form->{cc};
407   my $bcc = "Bcc: $form->{bcc}\\r\n" if $form->{bcc};
408   my $now = scalar localtime;
409   $form->{intnotes} .= qq|\r
410 \r| if $form->{intnotes};
411
412   $form->{intnotes} .= qq|[email]\r
413 Date: $now
414 To: $form->{email}\r
415 $cc${bcc}Subject: $form->{subject}\r
416 \r
417 Message: $form->{message}\r| if $form->{message};
418
419   ($null, $form->{department_id}) = split(/--/, $form->{department});
420
421   # save OE record
422   $query =
423     qq|UPDATE oe SET
424          ordnumber = ?, quonumber = ?, cusordnumber = ?, transdate = ?, vendor_id = ?,
425          customer_id = ?, amount = ?, netamount = ?, reqdate = ?, taxincluded = ?,
426          shippingpoint = ?, shipvia = ?, notes = ?, intnotes = ?, curr = ?, closed = ?,
427          delivered = ?, proforma = ?, quotation = ?, department_id = ?, language_id = ?,
428          taxzone_id = ?, shipto_id = ?, payment_id = ?, delivery_vendor_id = ?, delivery_customer_id = ?,
429          globalproject_id = ?, employee_id = ?, salesman_id = ?, cp_id = ?, transaction_description = ?, marge_total = ?, marge_percent = ?
430        WHERE id = ?|;
431
432   @values = ($form->{ordnumber}, $form->{quonumber},
433              $form->{cusordnumber}, conv_date($form->{transdate}),
434              conv_i($form->{vendor_id}), conv_i($form->{customer_id}),
435              $amount, $netamount, conv_date($reqdate),
436              $form->{taxincluded} ? 't' : 'f', $form->{shippingpoint},
437              $form->{shipvia}, $form->{notes}, $form->{intnotes},
438              substr($form->{currency}, 0, 3), $form->{closed} ? 't' : 'f',
439              $form->{delivered} ? "t" : "f", $form->{proforma} ? 't' : 'f',
440              $quotation, conv_i($form->{department_id}),
441              conv_i($form->{language_id}), conv_i($form->{taxzone_id}),
442              conv_i($form->{shipto_id}), conv_i($form->{payment_id}),
443              conv_i($form->{delivery_vendor_id}),
444              conv_i($form->{delivery_customer_id}),
445              conv_i($form->{globalproject_id}), conv_i($form->{employee_id}),
446              conv_i($form->{salesman_id}), conv_i($form->{cp_id}),
447              $form->{transaction_description},
448              $form->{marge_total} * 1, $form->{marge_percent} * 1,
449              conv_i($form->{id}));
450   do_query($form, $dbh, $query, @values);
451
452   $form->{ordtotal} = $amount;
453
454   # add shipto
455   $form->{name} = $form->{ $form->{vc} };
456   $form->{name} =~ s/--$form->{"$form->{vc}_id"}//;
457
458   if (!$form->{shipto_id}) {
459     $form->add_shipto($dbh, $form->{id}, "OE");
460   }
461
462   # save printed, emailed, queued
463   $form->save_status($dbh);
464
465   if (($form->{currency} ne $form->{defaultcurrency}) && !$exchangerate) {
466     if ($form->{vc} eq 'customer') {
467       $form->update_exchangerate($dbh, $form->{currency}, $form->{transdate},
468                                  $form->{exchangerate}, 0);
469     }
470     if ($form->{vc} eq 'vendor') {
471       $form->update_exchangerate($dbh, $form->{currency}, $form->{transdate},
472                                  0, $form->{exchangerate});
473     }
474   }
475
476   if ($form->{type} =~ /_order$/) {
477
478     # adjust onhand
479     &adj_onhand($dbh, $form, $ml * -1);
480   }
481
482   my $rc = $dbh->commit;
483   $dbh->disconnect;
484
485   $form->{saved_xyznumber} = $form->{$form->{type} =~ /_quotation$/ ?
486                                        "quonumber" : "ordnumber"};
487
488   Common::webdav_folder($form) if ($main::webdav);
489
490   $main::lxdebug->leave_sub();
491
492   return $rc;
493 }
494
495 # this function closes multiple orders given in $form->{ordnumber_#}.
496 # use this for multiple orders that don't have to be saved back
497 # single orders should use OE::save instead.
498 sub close_orders {
499   $main::lxdebug->enter_sub();
500
501   my ($self, $myconfig, $form) = @_;
502
503   # get ids from $form
504   map { push @ids, $form->{"ordnumber_$_"} if $form->{"ordnumber_$_"} }
505     (1 .. $form->{rowcount});
506
507   my $dbh = $form->dbconnect($myconfig);
508   $query = qq|UPDATE oe SET | .
509            qq|closed = TRUE | .
510            qq|WHERE ordnumber IN (|
511     . join(', ', map { $dbh->quote($_) } @ids) . qq|)|;
512   $dbh->do($query) || $form->dberror($query);
513   $dbh->disconnect;
514
515   $main::lxdebug->leave_sub();
516 }
517
518 sub close_order {
519   $main::lxdebug->enter_sub();
520
521   my ($self, $myconfig, $form) = @_;
522
523   $main::lxdebug->leave_sub() unless ($form->{"id"});
524
525   my $dbh = $form->dbconnect($myconfig);
526   do_query($form, $dbh, qq|UPDATE oe SET closed = TRUE where id = ?|,
527            $form->{"id"});
528   $dbh->disconnect;
529
530   $main::lxdebug->leave_sub();
531 }
532
533 sub delete {
534   $main::lxdebug->enter_sub();
535
536   my ($self, $myconfig, $form, $spool) = @_;
537
538   # connect to database
539   my $dbh = $form->dbconnect_noauto($myconfig);
540
541   # delete spool files
542   my $query = qq|SELECT s.spoolfile FROM status s | .
543               qq|WHERE s.trans_id = ?|;
544   my @values = (conv_i($form->{id}));
545   $sth = $dbh->prepare($query);
546   $sth->execute(@values) || $self->dberror($query);
547
548   my $spoolfile;
549   my @spoolfiles = ();
550
551   while (($spoolfile) = $sth->fetchrow_array) {
552     push @spoolfiles, $spoolfile;
553   }
554   $sth->finish;
555
556   $query = qq|SELECT o.parts_id, o.ship FROM orderitems o | .
557            qq|WHERE o.trans_id = ?|;
558   @values = (conv_i($form->{id}));
559   $sth = $dbh->prepare($query);
560   $sth->execute(@values) || $self->dberror($query);
561
562   while (my ($id, $ship) = $sth->fetchrow_array) {
563     $form->update_balance($dbh, "parts", "onhand", qq|id = $id|, $ship * -1);
564   }
565   $sth->finish;
566
567   # delete-values
568   @values = (conv_i($form->{id}));
569
570   # delete inventory
571   $query = qq|DELETE FROM inventory | .
572            qq|WHERE oe_id = ?|;
573   do_query($form, $dbh, $query, @values);
574
575   # delete status entries
576   $query = qq|DELETE FROM status | .
577            qq|WHERE trans_id = ?|;
578   do_query($form, $dbh, $query, @values);
579
580   # delete OE record
581   $query = qq|DELETE FROM oe | .
582            qq|WHERE id = ?|;
583   do_query($form, $dbh, $query, @values);
584
585   # delete individual entries
586   $query = qq|DELETE FROM orderitems | .
587            qq|WHERE trans_id = ?|;
588   do_query($form, $dbh, $query, @values);
589
590   $query = qq|DELETE FROM shipto | .
591            qq|WHERE trans_id = ? AND module = 'OE'|;
592   do_query($form, $dbh, $query, @values);
593
594   my $rc = $dbh->commit;
595   $dbh->disconnect;
596
597   if ($rc) {
598     foreach $spoolfile (@spoolfiles) {
599       unlink "$spool/$spoolfile" if $spoolfile;
600     }
601   }
602
603   $main::lxdebug->leave_sub();
604
605   return $rc;
606 }
607
608 sub retrieve {
609   $main::lxdebug->enter_sub();
610
611   my ($self, $myconfig, $form) = @_;
612
613   # connect to database
614   my $dbh = $form->dbconnect_noauto($myconfig);
615
616   my ($query, @values, @ids);
617
618   # translate the ids (given by id_# and trans_id_#) into one array of ids, so we can join them later
619   map {
620     push @ids, $form->{"trans_id_$_"}
621       if ($form->{"multi_id_$_"} and $form->{"trans_id_$_"})
622   } (1 .. $form->{"rowcount"});
623
624   # if called in multi id mode, and still only got one id, switch back to single id
625   if ($form->{"rowcount"} and $#ids == 0) {
626     $form->{"id"} = $ids[0];
627     undef @ids;
628   }
629
630   if ($form->{id}) {
631
632     # get default accounts and last order number
633     $query =
634       qq|SELECT (SELECT c.accno FROM chart c | .
635       qq|        WHERE d.inventory_accno_id = c.id) AS inventory_accno, | .
636       qq|       (SELECT c.accno FROM chart c | .
637       qq|        WHERE d.income_accno_id = c.id) AS income_accno, | .
638       qq|       (SELECT c.accno FROM chart c | .
639       qq|        WHERE d.expense_accno_id = c.id) AS expense_accno, | .
640       qq|       (SELECT c.accno FROM chart c | .
641       qq|        WHERE d.fxgain_accno_id = c.id) AS fxgain_accno, | .
642       qq|       (SELECT c.accno FROM chart c | .
643       qq|        WHERE d.fxloss_accno_id = c.id) AS fxloss_accno, | .
644       qq|d.curr AS currencies | .
645       qq|FROM defaults d|;
646   } else {
647     $query =
648       qq|SELECT (SELECT c.accno FROM chart c | .
649       qq|        WHERE d.inventory_accno_id = c.id) AS inventory_accno, | .
650       qq|       (SELECT c.accno FROM chart c | .
651       qq|        WHERE d.income_accno_id = c.id) AS income_accno, | .
652       qq|       (SELECT c.accno FROM chart c | .
653       qq|        WHERE d.expense_accno_id = c.id) AS expense_accno, | .
654       qq|       (SELECT c.accno FROM chart c | .
655       qq|        WHERE d.fxgain_accno_id = c.id) AS fxgain_accno, | .
656       qq|       (SELECT c.accno FROM chart c | .
657       qq|        WHERE d.fxloss_accno_id = c.id) AS fxloss_accno, | .
658       qq|d.curr AS currencies, | .
659       qq|current_date AS transdate, current_date AS reqdate | .
660       qq|FROM defaults d|;
661   }
662   my $sth = $dbh->prepare($query);
663   $sth->execute || $form->dberror($query);
664
665   my $ref = $sth->fetchrow_hashref(NAME_lc);
666   map { $form->{$_} = $ref->{$_} } keys %$ref;
667   $sth->finish;
668
669   ($form->{currency}) = split(/:/, $form->{currencies});
670
671   # set reqdate if this is an invoice->order conversion. If someone knows a better check to ensure
672   # we come from invoices, feel free.
673   $form->{reqdate} = $form->{deliverydate}
674     if (    $form->{deliverydate}
675         and $form->{callback} =~ /action=ar_transactions/);
676
677   my $vc = $form->{vc} eq "customer" ? "customer" : "vendor";
678
679   if ($form->{id} or @ids) {
680
681     # retrieve order for single id
682     # NOTE: this query is intended to fetch all information only ONCE.
683     # so if any of these infos is important (or even different) for any item,
684     # it will be killed out and then has to be fetched from the item scope query further down
685     $query =
686       qq|SELECT o.cp_id, o.ordnumber, o.transdate, o.reqdate, | .
687       qq|  o.taxincluded, o.shippingpoint, o.shipvia, o.notes, o.intnotes, | .
688       qq|  o.curr AS currency, e.name AS employee, o.employee_id, o.salesman_id, | .
689       qq|  o.${vc}_id, cv.name AS ${vc}, o.amount AS invtotal, | .
690       qq|  o.closed, o.reqdate, o.quonumber, o.department_id, o.cusordnumber, | .
691       qq|  d.description AS department, o.payment_id, o.language_id, o.taxzone_id, | .
692       qq|  o.delivery_customer_id, o.delivery_vendor_id, o.proforma, o.shipto_id, | .
693       qq|  o.globalproject_id, o.delivered, o.transaction_description | .
694       qq|FROM oe o | .
695       qq|JOIN ${vc} cv ON (o.${vc}_id = cv.id) | .
696       qq|LEFT JOIN employee e ON (o.employee_id = e.id) | .
697       qq|LEFT JOIN department d ON (o.department_id = d.id) | .
698                   ($form->{id} ? qq|WHERE o.id = ?| :
699        qq|WHERE o.id IN (| . join(', ', map("? ", @ids)) . qq|)|);
700     @values = $form->{id} ? ($form->{id}) : @ids;
701     $sth = prepare_execute_query($form, $dbh, $query, @values);
702
703     $ref = $sth->fetchrow_hashref(NAME_lc);
704     map { $form->{$_} = $ref->{$_} } keys %$ref;
705
706     $form->{saved_xyznumber} = $form->{$form->{type} =~ /_quotation$/ ?
707                                          "quonumber" : "ordnumber"};
708
709     # set all entries for multiple ids blank that yield different information
710     while ($ref = $sth->fetchrow_hashref(NAME_lc)) {
711       map { $form->{$_} = '' if ($ref->{$_} ne $form->{$_}) } keys %$ref;
712     }
713
714     # if not given, fill transdate with current_date
715     $form->{transdate} = $form->current_date($myconfig)
716       unless $form->{transdate};
717
718     $sth->finish;
719
720     if ($form->{delivery_customer_id}) {
721       $query = qq|SELECT name FROM customer WHERE id = ?|;
722       ($form->{delivery_customer_string}) =
723         selectrow_query($form, $dbh, $query, $form->{delivery_customer_id});
724     }
725
726     if ($form->{delivery_vendor_id}) {
727       $query = qq|SELECT name FROM customer WHERE id = ?|;
728       ($form->{delivery_vendor_string}) =
729         selectrow_query($form, $dbh, $query, $form->{delivery_vendor_id});
730     }
731
732     # shipto and pinted/mailed/queued status makes only sense for single id retrieve
733     if (!@ids) {
734       $query = qq|SELECT s.* FROM shipto s | .
735                qq|WHERE s.trans_id = ? AND s.module = 'OE'|;
736       $sth = prepare_execute_query($form, $dbh, $query, $form->{id});
737
738       $ref = $sth->fetchrow_hashref(NAME_lc);
739       delete($ref->{id});
740       map { $form->{$_} = $ref->{$_} } keys %$ref;
741       $sth->finish;
742
743       # get printed, emailed and queued
744       $query = qq|SELECT s.printed, s.emailed, s.spoolfile, s.formname | .
745                qq|FROM status s | .
746                qq|WHERE s.trans_id = ?|;
747       $sth = prepare_execute_query($form, $dbh, $query, $form->{id});
748
749       while ($ref = $sth->fetchrow_hashref(NAME_lc)) {
750         $form->{printed} .= "$ref->{formname} " if $ref->{printed};
751         $form->{emailed} .= "$ref->{formname} " if $ref->{emailed};
752         $form->{queued} .= "$ref->{formname} $ref->{spoolfile} "
753           if $ref->{spoolfile};
754       }
755       $sth->finish;
756       map { $form->{$_} =~ s/ +$//g } qw(printed emailed queued);
757     }    # if !@ids
758
759     my %oid = ('Pg'     => 'oid',
760                'Oracle' => 'rowid');
761
762     my $transdate =
763       $form->{transdate} ? $dbh->quote($form->{transdate}) : "current_date";
764
765     $form->{taxzone_id} = 0 unless ($form->{taxzone_id});
766
767     # retrieve individual items
768     # this query looks up all information about the items
769     # stuff different from the whole will not be overwritten, but saved with a suffix.
770     $query =
771       qq|SELECT o.id AS orderitems_id, | .
772       qq|  c1.accno AS inventory_accno, c1.new_chart_id AS inventory_new_chart, date($transdate) - c1.valid_from as inventory_valid, | .
773       qq|  c2.accno AS income_accno, c2.new_chart_id AS income_new_chart, date($transdate)  - c2.valid_from as income_valid, | .
774       qq|  c3.accno AS expense_accno, c3.new_chart_id AS expense_new_chart, date($transdate) - c3.valid_from as expense_valid, | .
775       qq|  oe.ordnumber AS ordnumber_oe, oe.transdate AS transdate_oe, oe.cusordnumber AS cusordnumber_oe,  | .
776       qq|  p.partnumber, p.assembly, o.description, o.qty, | .
777       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, | .
778       qq|  o.reqdate, o.project_id, o.serialnumber, o.ship, o.lastcost, | .
779       qq|  o.ordnumber, o.transdate, o.cusordnumber, o.subtotal, o.longdescription, | .
780       qq|  pr.projectnumber, p.formel, | .
781       qq|  pg.partsgroup, o.pricegroup_id, (SELECT pricegroup FROM pricegroup WHERE id=o.pricegroup_id) as pricegroup | .
782       qq|FROM orderitems o | .
783       qq|JOIN parts p ON (o.parts_id = p.id) | .
784       qq|JOIN oe ON (o.trans_id = oe.id) | .
785       qq|LEFT JOIN chart c1 ON ((SELECT inventory_accno_id FROM buchungsgruppen WHERE id=p.buchungsgruppen_id) = c1.id) | .
786       qq|LEFT JOIN chart c2 ON ((SELECT income_accno_id_$form->{taxzone_id} FROM buchungsgruppen WHERE id=p.buchungsgruppen_id) = c2.id) | .
787       qq|LEFT JOIN chart c3 ON ((SELECT expense_accno_id_$form->{taxzone_id} FROM buchungsgruppen WHERE id=p.buchungsgruppen_id) = c3.id) | .
788       qq|LEFT JOIN project pr ON (o.project_id = pr.id) | .
789       qq|LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id) | .
790       ($form->{id} ? qq|WHERE o.trans_id = ?| :
791        qq|WHERE o.trans_id IN (| . join(", ", map("?", @ids)) . qq|)|) .
792       qq|ORDER BY o.$oid{$myconfig->{dbdriver}}|;
793
794     @ids = $form->{id} ? ($form->{id}) : @ids;
795     $sth = prepare_execute_query($form, $dbh, $query, @values);
796
797     while ($ref = $sth->fetchrow_hashref(NAME_lc)) {
798       if (!$ref->{"part_inventory_accno_id"}) {
799         map({ delete($ref->{$_}); } qw(inventory_accno inventory_new_chart inventory_valid));
800       }
801       delete($ref->{"part_inventory_accno_id"});
802
803       # in collective order, copy global ordnumber, transdate, cusordnumber into item scope
804       #   unless already present there
805       # remove _oe entries afterwards
806       map { $ref->{$_} = $ref->{"${_}_oe"} if ($ref->{$_} eq '') }
807         qw|ordnumber transdate cusordnumber|
808         if (@ids);
809       map { delete $ref->{$_} } qw|ordnumber_oe transdate_oe cusordnumber_oe|;
810
811
812
813       while ($ref->{inventory_new_chart} && ($ref->{inventory_valid} >= 0)) {
814         my $query =
815           qq|SELECT accno AS inventory_accno, | .
816           qq|  new_chart_id AS inventory_new_chart, | .
817           qq|  date($transdate) - valid_from AS inventory_valid | .
818           qq|FROM chart WHERE id = $ref->{inventory_new_chart}|;
819         ($ref->{inventory_accno}, $ref->{inventory_new_chart},
820          $ref->{inventory_valid}) = selectrow_query($form, $dbh, $query);
821       }
822
823       while ($ref->{income_new_chart} && ($ref->{income_valid} >= 0)) {
824         my $query =
825           qq|SELECT accno AS income_accno, | .
826           qq|  new_chart_id AS income_new_chart, | .
827           qq|  date($transdate) - valid_from AS income_valid | .
828           qq|FROM chart WHERE id = $ref->{income_new_chart}|;
829         ($ref->{income_accno}, $ref->{income_new_chart},
830          $ref->{income_valid}) = selectrow_query($form, $dbh, $query);
831       }
832
833       while ($ref->{expense_new_chart} && ($ref->{expense_valid} >= 0)) {
834         my $query =
835           qq|SELECT accno AS expense_accno, | .
836           qq|  new_chart_id AS expense_new_chart, | .
837           qq|  date($transdate) - valid_from AS expense_valid | .
838           qq|FROM chart WHERE id = $ref->{expense_new_chart}|;
839         ($ref->{expense_accno}, $ref->{expense_new_chart},
840          $ref->{expense_valid}) = selectrow_query($form, $dbh, $query);
841       }
842
843       # delete orderitems_id in collective orders, so that they get cloned no matter what
844       delete $ref->{orderitems_id} if (@ids);
845
846       # get tax rates and description
847       $accno_id =
848         ($form->{vc} eq "customer") ? $ref->{income_accno} : $ref->{expense_accno};
849       $query =
850         qq|SELECT c.accno, t.taxdescription, t.rate, t.taxnumber | .
851         qq|FROM tax t LEFT JOIN chart c on (c.id = t.chart_id) | .
852         qq|WHERE t.id IN (SELECT tk.tax_id FROM taxkeys tk | .
853         qq|               WHERE tk.chart_id = (SELECT id FROM chart WHERE accno = ?) | .
854         qq|                 AND startdate <= $transdate ORDER BY startdate DESC LIMIT 1) | .
855         qq|ORDER BY c.accno|;
856       $stw = prepare_execute_query($form, $dbh, $query, $accno_id);
857       $ref->{taxaccounts} = "";
858       my $i = 0;
859       while ($ptr = $stw->fetchrow_hashref(NAME_lc)) {
860         if (($ptr->{accno} eq "") && ($ptr->{rate} == 0)) {
861           $i++;
862           $ptr->{accno} = $i;
863         }
864         $ref->{taxaccounts} .= "$ptr->{accno} ";
865         if (!($form->{taxaccounts} =~ /$ptr->{accno}/)) {
866           $form->{"$ptr->{accno}_rate"}        = $ptr->{rate};
867           $form->{"$ptr->{accno}_description"} = $ptr->{taxdescription};
868           $form->{"$ptr->{accno}_taxnumber"}   = $ptr->{taxnumber};
869           $form->{taxaccounts} .= "$ptr->{accno} ";
870         }
871
872       }
873
874       chop $ref->{taxaccounts};
875       push @{ $form->{form_details} }, $ref;
876       $stw->finish;
877     }
878     $sth->finish;
879
880   } else {
881
882     # get last name used
883     $form->lastname_used($dbh, $myconfig, $form->{vc})
884       unless $form->{"$form->{vc}_id"};
885
886   }
887
888   $form->{exchangerate} =
889     $form->get_exchangerate($dbh, $form->{currency}, $form->{transdate},
890                             ($form->{vc} eq 'customer') ? "buy" : "sell");
891
892   Common::webdav_folder($form) if ($main::webdav);
893
894   my $rc = $dbh->commit;
895   $dbh->disconnect;
896
897   $main::lxdebug->leave_sub();
898
899   return $rc;
900 }
901
902 sub order_details {
903   $main::lxdebug->enter_sub();
904
905   my ($self, $myconfig, $form) = @_;
906
907   # connect to database
908   my $dbh = $form->dbconnect($myconfig);
909   my $query;
910   my @values = ();
911   my $sth;
912   my $nodiscount;
913   my $yesdiscount;
914   my $nodiscount_subtotal = 0;
915   my $discount_subtotal = 0;
916   my $item;
917   my $i;
918   my @partsgroup = ();
919   my $partsgroup;
920   my $position = 0;
921   my $subtotal_header = 0;
922   my $subposition = 0;
923
924   my %oid = ('Pg'     => 'oid',
925              'Oracle' => 'rowid');
926
927   my (@project_ids, %projectnumbers);
928
929   push(@project_ids, $form->{"globalproject_id"}) if ($form->{"globalproject_id"});
930
931   # sort items by partsgroup
932   for $i (1 .. $form->{rowcount}) {
933     $partsgroup = "";
934     if ($form->{"partsgroup_$i"} && $form->{groupitems}) {
935       $partsgroup = $form->{"partsgroup_$i"};
936     }
937     push @partsgroup, [$i, $partsgroup];
938     push(@project_ids, $form->{"project_id_$i"}) if ($form->{"project_id_$i"});
939   }
940
941   if (@project_ids) {
942     $query = "SELECT id, projectnumber FROM project WHERE id IN (" .
943       join(", ", map("?", @project_ids)) . ")";
944     $sth = prepare_execute_query($form, $dbh, $query, @project_ids);
945     while (my $ref = $sth->fetchrow_hashref()) {
946       $projectnumbers{$ref->{id}} = $ref->{projectnumber};
947     }
948     $sth->finish();
949   }
950
951   $form->{"globalprojectnumber"} =
952     $projectnumbers{$form->{"globalproject_id"}};
953
954   my @arrays =
955     qw(runningnumber number description longdescription qty ship unit bin
956        partnotes serialnumber reqdate sellprice listprice netprice
957        discount p_discount discount_sub nodiscount_sub
958        linetotal  nodiscount_linetotal tax_rate projectnumber);
959
960   my $sameitem = "";
961   foreach $item (sort { $a->[1] cmp $b->[1] } @partsgroup) {
962     $i = $item->[0];
963
964     if ($item->[1] ne $sameitem) {
965       push(@{ $form->{description} }, qq|$item->[1]|);
966       $sameitem = $item->[1];
967
968       map({ push(@{ $form->{$_} }, "") } grep({ $_ ne "description" } @arrays));
969     }
970
971     $form->{"qty_$i"} = $form->parse_amount($myconfig, $form->{"qty_$i"});
972
973     if ($form->{"id_$i"} != 0) {
974
975       # add number, description and qty to $form->{number}, ....
976
977       if ($form->{"subtotal_$i"} && !$subtotal_header) {
978         $subtotal_header = $i;
979         $position = int($position);
980         $subposition = 0;
981         $position++;
982       } elsif ($subtotal_header) {
983         $subposition += 1;
984         $position = int($position);
985         $position = $position.".".$subposition;
986       } else {
987         $position = int($position);
988         $position++;
989       }
990
991       push(@{ $form->{runningnumber} }, $i);
992       push(@{ $form->{number} },        qq|$form->{"partnumber_$i"}|);
993       push(@{ $form->{description} },   qq|$form->{"description_$i"}|);
994       push(@{ $form->{longdescription} },   qq|$form->{"longdescription_$i"}|);
995       push(@{ $form->{qty} },
996            $form->format_amount($myconfig, $form->{"qty_$i"}));
997       push(@{ $form->{ship} },
998            $form->format_amount($myconfig, $form->{"ship_$i"}));
999       push(@{ $form->{unit} },         qq|$form->{"unit_$i"}|);
1000       push(@{ $form->{bin} },          qq|$form->{"bin_$i"}|);
1001       push(@{ $form->{"partnotes"} },  qq|$form->{"partnotes_$i"}|);
1002       push(@{ $form->{serialnumber} }, qq|$form->{"serialnumber_$i"}|);
1003       push(@{ $form->{reqdate} },      qq|$form->{"reqdate_$i"}|);
1004
1005       push(@{ $form->{sellprice} }, $form->{"sellprice_$i"});
1006
1007       push(@{ $form->{listprice} }, $form->{"listprice_$i"});
1008
1009       my $sellprice = $form->parse_amount($myconfig, $form->{"sellprice_$i"});
1010       my ($dec) = ($sellprice =~ /\.(\d+)/);
1011       $dec = length $dec;
1012       my $decimalplaces = ($dec > 2) ? $dec : 2;
1013
1014       my $i_discount =
1015         $form->round_amount(
1016                             $sellprice * $form->parse_amount($myconfig,
1017                                                  $form->{"discount_$i"}) / 100,
1018                             $decimalplaces);
1019
1020       my $discount =
1021         $form->round_amount($form->{"qty_$i"} * $i_discount, $decimalplaces);
1022
1023       # keep a netprice as well, (sellprice - discount)
1024       #$form->{"netprice_$i"} = $sellprice - $discount;
1025       $form->{"netprice_$i"} = $sellprice - $i_discount;
1026       my $nodiscount_linetotal =
1027         $form->round_amount($form->{"qty_$i"} * $sellprice, 2);
1028       my $linetotal =
1029         $form->round_amount($form->{"qty_$i"} * $form->{"netprice_$i"}, 2);
1030
1031       push(@{ $form->{netprice} },
1032            ($form->{"netprice_$i"} != 0)
1033            ? $form->format_amount(
1034                                  $myconfig, $form->{"netprice_$i"},
1035                                  $decimalplaces
1036              )
1037            : " ");
1038
1039       $discount =
1040         ($discount != 0)
1041         ? $form->format_amount($myconfig, $discount * -1, $decimalplaces)
1042         : " ";
1043       $linetotal = ($linetotal != 0) ? $linetotal : " ";
1044
1045       push(@{ $form->{discount} },   $discount);
1046       push(@{ $form->{p_discount} }, $form->{"discount_$i"});
1047
1048       $form->{ordtotal} += $linetotal;
1049       $discount_subtotal += $linetotal;
1050       $form->{nodiscount_total} += $nodiscount_linetotal;
1051       $nodiscount_subtotal += $nodiscount_linetotal;
1052       $form->{discount_total} += $form->parse_amount($myconfig, $discount);
1053
1054       if ($form->{"subtotal_$i"} && $subtotal_header && ($subtotal_header != $i)) {
1055         $discount_subtotal = $form->format_amount($myconfig, $discount_subtotal, 2);
1056         push(@{ $form->{discount_sub} },  $discount_subtotal);
1057         $nodiscount_subtotal = $form->format_amount($myconfig, $nodiscount_subtotal, 2);
1058         push(@{ $form->{nodiscount_sub} }, $nodiscount_subtotal);
1059         $discount_subtotal = 0;
1060         $nodiscount_subtotal = 0;
1061         $subtotal_header = 0;
1062       } else {
1063         push(@{ $form->{discount_sub} }, "");
1064         push(@{ $form->{nodiscount_sub} }, "");
1065       }
1066
1067       if ($linetotal == $netto_linetotal) {
1068         $nodiscount += $linetotal;
1069       }
1070       push(@{ $form->{linetotal} },
1071            $form->format_amount($myconfig, $linetotal, 2));
1072       push(@{ $form->{nodiscount_linetotal} },
1073            $form->format_amount($myconfig, $nodiscount_linetotal, 2));
1074
1075       push(@{ $form->{projectnumber} }, $projectnumbers{$form->{"project_id_$i"}});
1076
1077       my ($taxamount, $taxbase);
1078       my $taxrate = 0;
1079
1080       map { $taxrate += $form->{"${_}_rate"} } split(/ /, $form->{"taxaccounts_$i"});
1081
1082       if ($form->{taxincluded}) {
1083
1084         # calculate tax
1085         $taxamount = $linetotal * $taxrate / (1 + $taxrate);
1086         $taxbase = $linetotal / (1 + $taxrate);
1087       } else {
1088         $taxamount = $linetotal * $taxrate;
1089         $taxbase   = $linetotal;
1090       }
1091
1092       if ($taxamount != 0) {
1093         foreach my $item (split / /, $form->{"taxaccounts_$i"}) {
1094           $taxaccounts{$item} +=
1095             $taxamount * $form->{"${item}_rate"} / $taxrate;
1096           $taxbase{$item} += $taxbase;
1097         }
1098       }
1099
1100       $tax_rate = $taxrate * 100;
1101       push(@{ $form->{tax_rate} }, qq|$tax_rate|);
1102
1103       if ($form->{"assembly_$i"}) {
1104         $sameitem = "";
1105
1106         # get parts and push them onto the stack
1107         my $sortorder = "";
1108         if ($form->{groupitems}) {
1109           $sortorder =
1110             qq|ORDER BY pg.partsgroup, a.$oid{$myconfig->{dbdriver}}|;
1111         } else {
1112           $sortorder = qq|ORDER BY a.$oid{$myconfig->{dbdriver}}|;
1113         }
1114
1115         $query = qq|SELECT p.partnumber, p.description, p.unit, a.qty, | .
1116                        qq|pg.partsgroup | .
1117                        qq|FROM assembly a | .
1118                              qq|  JOIN parts p ON (a.parts_id = p.id) | .
1119                              qq|    LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id) | .
1120                              qq|    WHERE a.bom = '1' | .
1121                              qq|    AND a.id = ? | . $sortorder;
1122                     @values = ($form->{"id_$i"});
1123         $sth = $dbh->prepare($query);
1124         $sth->execute(@values) || $form->dberror($query);
1125
1126         while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
1127           if ($form->{groupitems} && $ref->{partsgroup} ne $sameitem) {
1128             map({ push(@{ $form->{$_} }, "") }
1129                 grep({ $_ ne "description" } @arrays));
1130             $sameitem = ($ref->{partsgroup}) ? $ref->{partsgroup} : "--";
1131             push(@{ $form->{description} }, $sameitem);
1132           }
1133
1134           push(@{ $form->{description} },
1135                $form->format_amount($myconfig, $ref->{qty} * $form->{"qty_$i"}
1136                  )
1137                  . qq|, $ref->{partnumber}, $ref->{description}|);
1138
1139           map({ push(@{ $form->{$_} }, "") }
1140               grep({ $_ ne "description" } @arrays));
1141         }
1142         $sth->finish;
1143       }
1144
1145     }
1146   }
1147
1148   my $tax = 0;
1149   foreach $item (sort keys %taxaccounts) {
1150     push(@{ $form->{taxbase} },
1151          $form->format_amount($myconfig, $taxbase{$item}, 2));
1152
1153     $tax += $taxamount = $form->round_amount($taxaccounts{$item}, 2);
1154
1155     push(@{ $form->{tax} }, $form->format_amount($myconfig, $taxamount, 2));
1156     push(@{ $form->{taxdescription} }, $form->{"${item}_description"}  . q{ } . 100 * $form->{"${item}_rate"} . q{%});
1157     push(@{ $form->{taxrate} },
1158          $form->format_amount($myconfig, $form->{"${item}_rate"} * 100));
1159     push(@{ $form->{taxnumber} }, $form->{"${item}_taxnumber"});
1160   }
1161   $yesdiscount = $form->{nodiscount_total} - $nodiscount;
1162   $form->{nodiscount_subtotal} = $form->format_amount($myconfig, $form->{nodiscount_total}, 2);
1163   $form->{discount_total} = $form->format_amount($myconfig, $form->{discount_total}, 2);
1164   $form->{nodiscount} = $form->format_amount($myconfig, $nodiscount, 2);
1165   $form->{yesdiscount} = $form->format_amount($myconfig, $yesdiscount, 2);
1166
1167   if($form->{taxincluded}) {
1168     $form->{subtotal} = $form->format_amount($myconfig, $form->{ordtotal} - $tax, 2);
1169   }
1170   else {
1171     $form->{subtotal} = $form->format_amount($myconfig, $form->{ordtotal}, 2);
1172   }
1173   $form->{ordtotal} =
1174     ($form->{taxincluded}) ? $form->{ordtotal} : $form->{ordtotal} + $tax;
1175
1176   # format amounts
1177   $form->{quototal} = $form->{ordtotal} =
1178     $form->format_amount($myconfig, $form->{ordtotal}, 2);
1179
1180   if ($form->{type} =~ /_quotation/) {
1181     $form->set_payment_options($myconfig, $form->{quodate});
1182   } else {
1183     $form->set_payment_options($myconfig, $form->{orddate});
1184   }
1185
1186   $form->{username} = $myconfig->{name};
1187
1188   $dbh->disconnect;
1189
1190   $main::lxdebug->leave_sub();
1191 }
1192
1193 sub project_description {
1194   $main::lxdebug->enter_sub();
1195
1196   my ($self, $dbh, $id) = @_;
1197
1198   my $query = qq|SELECT description FROM project WHERE id = ?|;
1199   my ($value) = selectrow_query($form, $dbh, $query, $id);
1200
1201   $main::lxdebug->leave_sub();
1202
1203   return $value;
1204 }
1205
1206 sub adj_onhand {
1207   $main::lxdebug->enter_sub();
1208
1209   my ($dbh, $form, $ml) = @_;
1210
1211   my $all_units = $form->{all_units};
1212
1213   my $query =
1214     qq|SELECT oi.parts_id, oi.ship, oi.unit, p.inventory_accno_id, p.assembly | .
1215     qq|   FROM orderitems oi | .
1216     qq|   JOIN parts p ON (p.id = oi.parts_id) | .
1217     qq|   WHERE oi.trans_id = ?|;
1218   my @values = ($form->{id});
1219   my $sth = $dbh->prepare($query);
1220   $sth->execute(@values) || $form->dberror($query);
1221
1222   $query =
1223     qq|SELECT sum(p.inventory_accno_id) | .
1224     qq|FROM parts p | .
1225     qq|JOIN assembly a ON (a.parts_id = p.id) | .
1226     qq|WHERE a.id = ?|;
1227   my $ath = $dbh->prepare($query) || $form->dberror($query);
1228
1229   my $ispa;
1230
1231   while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
1232     if ($ref->{inventory_accno_id} || $ref->{assembly}) {
1233
1234       # do not update if assembly consists of all services
1235       if ($ref->{assembly}) {
1236         $ath->execute($ref->{parts_id}) || $form->dberror($query);
1237
1238         ($ispa) = $sth->fetchrow_array;
1239         $ath->finish;
1240
1241         next unless $ispa;
1242
1243       }
1244
1245       # get item baseunit
1246       $query = qq|SELECT unit FROM parts WHERE id = ?|;
1247       my ($item_unit) = selectrow_query($form, $dbh, $query, $ref->{parts_id});
1248
1249       my $basefactor = 1;
1250       if (defined($all_units->{$item_unit}->{factor}) &&
1251           (($all_units->{$item_unit}->{factor} * 1) != 0)) {
1252         $basefactor = $all_units->{$ref->{unit}}->{factor} /
1253           $all_units->{$item_unit}->{factor};
1254       }
1255       my $baseqty = $ref->{ship} * $basefactor;
1256
1257       # adjust onhand in parts table
1258       $form->update_balance($dbh, "parts", "onhand",
1259                             qq|id = $ref->{parts_id}|,
1260                             $baseqty * $ml);
1261     }
1262   }
1263
1264   $sth->finish;
1265
1266   $main::lxdebug->leave_sub();
1267 }
1268
1269 1;