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