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