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