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