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