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