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