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