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