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