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