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