Bei Auftragsbestätigungen und Lieferantenaufträgen ein Feld "Geliefert" eingeführt...
[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   for my $i (1 .. $form->{rowcount}) {
536
537     map {
538       $form->{"${_}_$i"} =
539         $form->parse_amount($myconfig, $form->{"${_}_$i"})
540     } qw(qty ship);
541     if ($delete_oe_id) {
542       $form->{"orderitems_id_$i"} = "";
543     }
544
545     if ($form->{"qty_$i"}) {
546
547       # set values to 0 if nothing entered
548       $form->{"discount_$i"} =
549         $form->parse_amount($myconfig, $form->{"discount_$i"});
550
551       $form->{"sellprice_$i"} =
552         $form->parse_amount($myconfig, $form->{"sellprice_$i"});
553     }
554   }
555
556   # get ids from $form
557   map { push @ids, $form->{"ordnumber_$_"} if $form->{"ordnumber_$_"} }
558     (1 .. $form->{rowcount});
559
560   my $dbh = $form->dbconnect($myconfig);
561   $query = qq|UPDATE oe SET
562               closed = TRUE
563               WHERE ordnumber IN (|
564     . join(', ', map { $dbh->quote($_) } @ids) . qq|)|;
565   $dbh->do($query) || $form->dberror($query);
566   $dbh->disconnect;
567
568   $main::lxdebug->leave_sub();
569 }
570
571 sub close_order {
572   $main::lxdebug->enter_sub();
573
574   my ($self, $myconfig, $form) = @_;
575
576   $main::lxdebug->leave_sub() unless ($form->{"id"});
577
578   my $dbh = $form->dbconnect($myconfig);
579   do_query($form, $dbh, qq|UPDATE oe SET closed = TRUE where id = ?|,
580            $form->{"id"});
581   $dbh->disconnect;
582
583   $main::lxdebug->leave_sub();
584 }
585
586 sub delete {
587   $main::lxdebug->enter_sub();
588
589   my ($self, $myconfig, $form, $spool) = @_;
590
591   # connect to database
592   my $dbh = $form->dbconnect_noauto($myconfig);
593
594   # delete spool files
595   my $query = qq|SELECT s.spoolfile FROM status s
596                  WHERE s.trans_id = $form->{id}|;
597   $sth = $dbh->prepare($query);
598   $sth->execute || $self->dberror($query);
599
600   my $spoolfile;
601   my @spoolfiles = ();
602
603   while (($spoolfile) = $sth->fetchrow_array) {
604     push @spoolfiles, $spoolfile;
605   }
606   $sth->finish;
607
608   $query = qq|SELECT o.parts_id, o.ship FROM orderitems o
609               WHERE o.trans_id = $form->{id}|;
610   $sth = $dbh->prepare($query);
611   $sth->execute || $self->dberror($query);
612
613   while (my ($id, $ship) = $sth->fetchrow_array) {
614     $form->update_balance($dbh, "parts", "onhand", qq|id = $id|, $ship * -1);
615   }
616   $sth->finish;
617
618   # delete inventory
619   $query = qq|DELETE FROM inventory
620               WHERE oe_id = $form->{id}|;
621   $dbh->do($query) || $form->dberror($query);
622
623   # delete status entries
624   $query = qq|DELETE FROM status
625               WHERE trans_id = $form->{id}|;
626   $dbh->do($query) || $form->dberror($query);
627
628   # delete OE record
629   $query = qq|DELETE FROM oe
630               WHERE id = $form->{id}|;
631   $dbh->do($query) || $form->dberror($query);
632
633   # delete individual entries
634   $query = qq|DELETE FROM orderitems
635               WHERE trans_id = $form->{id}|;
636   $dbh->do($query) || $form->dberror($query);
637
638   $query = qq|DELETE FROM shipto
639               WHERE trans_id = $form->{id} AND module = 'OE'|;
640   $dbh->do($query) || $form->dberror($query);
641
642   my $rc = $dbh->commit;
643   $dbh->disconnect;
644
645   if ($rc) {
646     foreach $spoolfile (@spoolfiles) {
647       unlink "$spool/$spoolfile" if $spoolfile;
648     }
649   }
650
651   $main::lxdebug->leave_sub();
652
653   return $rc;
654 }
655
656 sub retrieve {
657   $main::lxdebug->enter_sub();
658
659   my ($self, $myconfig, $form) = @_;
660
661   # connect to database
662   my $dbh = $form->dbconnect_noauto($myconfig);
663
664   my $query, @ids;
665
666   # translate the ids (given by id_# and trans_id_#) into one array of ids, so we can join them later
667   map {
668     push @ids, $form->{"trans_id_$_"}
669       if ($form->{"id_$_"} and $form->{"trans_id_$_"})
670   } (1 .. $form->{"rowcount"});
671
672   # if called in multi id mode, and still only got one id, switch back to single id
673   if ($form->{"rowcount"} and $#ids == 0) {
674     $form->{"id"} = $ids[0];
675     undef @ids;
676   }
677
678   if ($form->{id}) {
679
680     # get default accounts and last order number
681     $query = qq|SELECT (SELECT c.accno FROM chart c
682                         WHERE d.inventory_accno_id = c.id) AS inventory_accno,
683                        (SELECT c.accno FROM chart c
684                         WHERE d.income_accno_id = c.id) AS income_accno,
685                        (SELECT c.accno FROM chart c
686                         WHERE d.expense_accno_id = c.id) AS expense_accno,
687                        (SELECT c.accno FROM chart c
688                         WHERE d.fxgain_accno_id = c.id) AS fxgain_accno,
689                        (SELECT c.accno FROM chart c
690                         WHERE d.fxloss_accno_id = c.id) AS fxloss_accno,
691                 d.curr AS currencies
692                 FROM defaults d|;
693   } else {
694     $query = qq|SELECT (SELECT c.accno FROM chart c
695                         WHERE d.inventory_accno_id = c.id) AS inventory_accno,
696                        (SELECT c.accno FROM chart c
697                         WHERE d.income_accno_id = c.id) AS income_accno,
698                        (SELECT c.accno FROM chart c
699                         WHERE d.expense_accno_id = c.id) AS expense_accno,
700                        (SELECT c.accno FROM chart c
701                         WHERE d.fxgain_accno_id = c.id) AS fxgain_accno,
702                        (SELECT c.accno FROM chart c
703                         WHERE d.fxloss_accno_id = c.id) AS fxloss_accno,
704                 d.curr AS currencies,
705                 current_date AS transdate, current_date AS reqdate
706                 FROM defaults d|;
707   }
708   my $sth = $dbh->prepare($query);
709   $sth->execute || $form->dberror($query);
710
711   my $ref = $sth->fetchrow_hashref(NAME_lc);
712   map { $form->{$_} = $ref->{$_} } keys %$ref;
713   $sth->finish;
714
715   ($form->{currency}) = split /:/, $form->{currencies};
716
717   # set reqdate if this is an invoice->order conversion. If someone knows a better check to ensure
718   # we come from invoices, feel free.
719   $form->{reqdate} = $form->{deliverydate}
720     if (    $form->{deliverydate}
721         and $form->{callback} =~ /action=ar_transactions/);
722
723   if ($form->{id} or @ids) {
724
725     # retrieve order for single id
726     # NOTE: this query is intended to fetch all information only ONCE.
727     # so if any of these infos is important (or even different) for any item,
728     # it will be killed out and then has to be fetched from the item scope query further down
729     $query = qq|SELECT o.cp_id, o.ordnumber, o.transdate, o.reqdate,
730                 o.taxincluded, o.shippingpoint, o.shipvia, o.notes, o.intnotes,
731                 o.curr AS currency, e.name AS employee, o.employee_id,
732                 o.$form->{vc}_id, cv.name AS $form->{vc}, o.amount AS invtotal,
733                 o.closed, o.reqdate, o.quonumber, o.department_id, o.cusordnumber,
734                 d.description AS department, o.payment_id, o.language_id, o.taxzone_id,
735                 o.delivery_customer_id, o.delivery_vendor_id, o.proforma, o.shipto_id,
736                 o.delivered
737                 FROM oe o
738                 JOIN $form->{vc} cv ON (o.$form->{vc}_id = cv.id)
739                 LEFT JOIN employee e ON (o.employee_id = e.id)
740                 LEFT JOIN department d ON (o.department_id = d.id)
741                 |
742       . ($form->{id}
743          ? qq|WHERE o.id = $form->{id}|
744          : qq|WHERE o.id IN (| . join(', ', @ids) . qq|)|);
745
746     #$main::lxdebug->message(0, $query);
747
748     $sth = $dbh->prepare($query);
749     $sth->execute || $form->dberror($query);
750
751     $ref = $sth->fetchrow_hashref(NAME_lc);
752     map { $form->{$_} = $ref->{$_} } keys %$ref;
753
754
755
756     # set all entries for multiple ids blank that yield different information
757     while ($ref = $sth->fetchrow_hashref(NAME_lc)) {
758       map { $form->{$_} = '' if ($ref->{$_} ne $form->{$_}) } keys %$ref;
759     }
760
761     # if not given, fill transdate with current_date
762     $form->{transdate} = $form->current_date($myconfig)
763       unless $form->{transdate};
764
765     $sth->finish;
766
767     if ($form->{delivery_customer_id}) {
768       $query = qq|SELECT name FROM customer WHERE id=$form->{delivery_customer_id}|;
769       $sth = $dbh->prepare($query);
770       $sth->execute || $form->dberror($query);
771       ($form->{delivery_customer_string}) = $sth->fetchrow_array();
772       $sth->finish;
773     }
774
775     if ($form->{delivery_vendor_id}) {
776       $query = qq|SELECT name FROM customer WHERE id=$form->{delivery_vendor_id}|;
777       $sth = $dbh->prepare($query);
778       $sth->execute || $form->dberror($query);
779       ($form->{delivery_vendor_string}) = $sth->fetchrow_array();
780       $sth->finish;
781     }
782
783     # shipto and pinted/mailed/queued status makes only sense for single id retrieve
784     if (!@ids) {
785       $query = qq|SELECT s.* FROM shipto s
786                   WHERE s.trans_id = $form->{id} AND s.module = 'OE'|;
787       $sth = $dbh->prepare($query);
788       $sth->execute || $form->dberror($query);
789
790       $ref = $sth->fetchrow_hashref(NAME_lc);
791       delete($ref->{id});
792       map { $form->{$_} = $ref->{$_} } keys %$ref;
793       $sth->finish;
794
795       # get printed, emailed and queued
796       $query = qq|SELECT s.printed, s.emailed, s.spoolfile, s.formname
797                   FROM status s
798                   WHERE s.trans_id = $form->{id}|;
799       $sth = $dbh->prepare($query);
800       $sth->execute || $form->dberror($query);
801
802       while ($ref = $sth->fetchrow_hashref(NAME_lc)) {
803         $form->{printed} .= "$ref->{formname} " if $ref->{printed};
804         $form->{emailed} .= "$ref->{formname} " if $ref->{emailed};
805         $form->{queued} .= "$ref->{formname} $ref->{spoolfile} "
806           if $ref->{spoolfile};
807       }
808       $sth->finish;
809       map { $form->{$_} =~ s/ +$//g } qw(printed emailed queued);
810     }    # if !@ids
811
812     my %oid = ('Pg'     => 'oid',
813                'Oracle' => 'rowid');
814
815     my $transdate =
816       $form->{transdate} ? $dbh->quote($form->{transdate}) : "current_date";
817
818     if(!$form->{taxzone_id}) {
819       $form->{taxzone_id} = 0;
820     }
821     # retrieve individual items
822     # this query looks up all information about the items
823     # stuff different from the whole will not be overwritten, but saved with a suffix.
824     $query = qq|SELECT o.id AS orderitems_id,
825                 c1.accno AS inventory_accno, c1.new_chart_id AS inventory_new_chart, date($transdate) - c1.valid_from as inventory_valid,
826                 c2.accno AS income_accno, c2.new_chart_id AS income_new_chart, date($transdate)  - c2.valid_from as income_valid,
827                 c3.accno AS expense_accno, c3.new_chart_id AS expense_new_chart, date($transdate) - c3.valid_from as expense_valid,
828                 oe.ordnumber AS ordnumber_oe, oe.transdate AS transdate_oe, oe.cusordnumber AS cusordnumber_oe, 
829                 p.partnumber, p.assembly, o.description, o.qty,
830                 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,
831                 o.reqdate, o.project_id, o.serialnumber, o.ship,
832                 o.ordnumber, o.transdate, o.cusordnumber, o.subtotal, o.longdescription,
833                 pr.projectnumber, p.formel,
834                 pg.partsgroup, o.pricegroup_id, (SELECT pricegroup FROM pricegroup WHERE id=o.pricegroup_id) as pricegroup
835                 FROM orderitems o
836                 JOIN parts p ON (o.parts_id = p.id)
837                 JOIN oe ON (o.trans_id = oe.id)
838                 LEFT JOIN chart c1 ON ((select inventory_accno_id from buchungsgruppen where id=p.buchungsgruppen_id) = c1.id)
839                 LEFT JOIN chart c2 ON ((select income_accno_id_$form->{taxzone_id} from buchungsgruppen where id=p.buchungsgruppen_id) = c2.id)
840                 LEFT JOIN chart c3 ON ((select expense_accno_id_$form->{taxzone_id} from buchungsgruppen where id=p.buchungsgruppen_id) = c3.id)
841                 LEFT JOIN project pr ON (o.project_id = pr.id)
842                 LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
843                 |
844       . ($form->{id}
845          ? qq|WHERE o.trans_id = $form->{id}|
846          : qq|WHERE o.trans_id IN (| . join(", ", @ids) . qq|)|)
847       . qq|
848                 ORDER BY o.$oid{$myconfig->{dbdriver}}|;
849
850     $sth = $dbh->prepare($query);
851     $sth->execute || $form->dberror($query);
852
853     while ($ref = $sth->fetchrow_hashref(NAME_lc)) {
854       if (!$ref->{"part_inventory_accno_id"}) {
855         map({ delete($ref->{$_}); } qw(inventory_accno inventory_new_chart inventory_valid));
856       }
857       delete($ref->{"part_inventory_accno_id"});
858
859       # in collective order, copy global ordnumber, transdate, cusordnumber into item scope
860       #   unless already present there
861       # remove _oe entries afterwards
862       map { $ref->{$_} = $ref->{"${_}_oe"} if ($ref->{$_} eq '') }
863         qw|ordnumber transdate cusordnumber|
864         if (@ids);
865       map { delete $ref->{$_} } qw|ordnumber_oe transdate_oe cusordnumber_oe|;
866
867
868
869     while ($ref->{inventory_new_chart} && ($ref->{inventory_valid} >=0)) {
870       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}|;
871       my $stw = $dbh->prepare($query);
872       $stw->execute || $form->dberror($query);
873       ($ref->{inventory_accno}, $ref->{inventory_new_chart}, $ref->{inventory_valid}) = $stw->fetchrow_array;
874       $stw->finish;
875     }
876
877     while ($ref->{income_new_chart} && ($ref->{income_valid} >=0)) {
878       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}|;
879       my $stw = $dbh->prepare($query);
880       $stw->execute || $form->dberror($query);
881       ($ref->{income_accno}, $ref->{income_new_chart}, $ref->{income_valid}) = $stw->fetchrow_array;
882       $stw->finish;
883     }
884
885     while ($ref->{expense_new_chart} && ($ref->{expense_valid} >=0)) {
886       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}|;
887       my $stw = $dbh->prepare($query);
888       $stw->execute || $form->dberror($query);
889       ($ref->{expense_accno}, $ref->{expense_new_chart}, $ref->{expense_valid}) = $stw->fetchrow_array;
890       $stw->finish;
891     }
892
893       # delete orderitems_id in collective orders, so that they get cloned no matter what
894       delete $ref->{orderitems_id} if (@ids);
895
896       # get tax rates and description
897       $accno_id =
898         ($form->{vc} eq "customer") ? $ref->{income_accno} : $ref->{expense_accno};
899       $query = qq|SELECT c.accno, t.taxdescription, t.rate, t.taxnumber
900               FROM tax t LEFT JOIN chart c on (c.id=t.chart_id)
901               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)
902               ORDER BY c.accno|;
903       $stw = $dbh->prepare($query);
904       $stw->execute || $form->dberror($query);
905       $ref->{taxaccounts} = "";
906       my $i = 0;
907       while ($ptr = $stw->fetchrow_hashref(NAME_lc)) {
908
909         #    if ($customertax{$ref->{accno}}) {
910         if (($ptr->{accno} eq "") && ($ptr->{rate} == 0)) {
911           $i++;
912           $ptr->{accno} = $i;
913         }
914         $ref->{taxaccounts} .= "$ptr->{accno} ";
915         if (!($form->{taxaccounts} =~ /$ptr->{accno}/)) {
916           $form->{"$ptr->{accno}_rate"}        = $ptr->{rate};
917           $form->{"$ptr->{accno}_description"} = $ptr->{taxdescription};
918           $form->{"$ptr->{accno}_taxnumber"}   = $ptr->{taxnumber};
919           $form->{taxaccounts} .= "$ptr->{accno} ";
920         }
921
922       }
923
924       chop $ref->{taxaccounts};
925       push @{ $form->{form_details} }, $ref;
926       $stw->finish;
927     }
928     $sth->finish;
929
930   } else {
931
932     # get last name used
933     $form->lastname_used($dbh, $myconfig, $form->{vc})
934       unless $form->{"$form->{vc}_id"};
935
936   }
937
938   $form->{exchangerate} =
939     $form->get_exchangerate($dbh, $form->{currency}, $form->{transdate},
940                             ($form->{vc} eq 'customer') ? "buy" : "sell");
941
942   if ($form->{webdav}) {
943     &webdav_folder($myconfig, $form);
944   }
945
946   # get tax zones
947   $query = qq|SELECT id, description
948               FROM tax_zones|;
949   $sth = $dbh->prepare($query);
950   $sth->execute || $form->dberror($query);
951
952
953   while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
954     push @{ $form->{TAXZONE} }, $ref;
955   }
956   $sth->finish;
957
958
959   my $rc = $dbh->commit;
960   $dbh->disconnect;
961
962   $main::lxdebug->leave_sub();
963
964   return $rc;
965 }
966
967 sub order_details {
968   $main::lxdebug->enter_sub();
969
970   my ($self, $myconfig, $form) = @_;
971
972   # connect to database
973   my $dbh = $form->dbconnect($myconfig);
974   my $query;
975   my $sth;
976   my $nodiscount;
977   my $yesdiscount;
978   my $nodiscount_subtotal = 0;
979   my $discount_subtotal = 0;
980   my $item;
981   my $i;
982   my @partsgroup = ();
983   my $partsgroup;
984   my $position = 0;
985   my $subtotal_header = 0;
986   my $subposition = 0;
987
988   my %oid = ('Pg'     => 'oid',
989              'Oracle' => 'rowid');
990
991   # sort items by partsgroup
992   for $i (1 .. $form->{rowcount}) {
993     $partsgroup = "";
994     if ($form->{"partsgroup_$i"} && $form->{groupitems}) {
995       $partsgroup = $form->{"partsgroup_$i"};
996     }
997     push @partsgroup, [$i, $partsgroup];
998   }
999
1000   # if there is a warehouse limit picking
1001   if ($form->{warehouse_id} && $form->{formname} =~ /(pick|packing)_list/) {
1002
1003     # run query to check for inventory
1004     $query = qq|SELECT sum(i.qty) AS qty
1005                 FROM inventory i
1006                 WHERE i.parts_id = ?
1007                 AND i.warehouse_id = ?|;
1008     $sth = $dbh->prepare($query) || $form->dberror($query);
1009
1010     for $i (1 .. $form->{rowcount}) {
1011       $sth->execute($form->{"id_$i"}, $form->{warehouse_id}) || $form->dberror;
1012
1013       ($qty) = $sth->fetchrow_array;
1014       $sth->finish;
1015
1016       $form->{"qty_$i"} = 0 if $qty == 0;
1017
1018       if ($form->parse_amount($myconfig, $form->{"ship_$i"}) > $qty) {
1019         $form->{"ship_$i"} = $form->format_amount($myconfig, $qty);
1020       }
1021     }
1022   }
1023
1024   my $sameitem = "";
1025   foreach $item (sort { $a->[1] cmp $b->[1] } @partsgroup) {
1026     $i = $item->[0];
1027
1028     if ($item->[1] ne $sameitem) {
1029       push(@{ $form->{description} }, qq|$item->[1]|);
1030       $sameitem = $item->[1];
1031
1032       map { push(@{ $form->{$_} }, "") }
1033         qw(runningnumber number qty ship unit bin partnotes
1034            serialnumber reqdate sellprice listprice netprice
1035            discount p_discount linetotal);
1036     }
1037
1038     $form->{"qty_$i"} = $form->parse_amount($myconfig, $form->{"qty_$i"});
1039
1040     if ($form->{"id_$i"} != 0) {
1041
1042       # add number, description and qty to $form->{number}, ....
1043
1044       if ($form->{"subtotal_$i"} && !$subtotal_header) {
1045         $subtotal_header = $i;
1046         $position = int($position);
1047         $subposition = 0;
1048         $position++;
1049       } elsif ($subtotal_header) {
1050         $subposition += 1;
1051         $position = int($position);
1052         $position = $position.".".$subposition;
1053       } else {
1054         $position = int($position);
1055         $position++;
1056       }
1057
1058       push(@{ $form->{runningnumber} }, $i);
1059       push(@{ $form->{number} },        qq|$form->{"partnumber_$i"}|);
1060       push(@{ $form->{description} },   qq|$form->{"description_$i"}|);
1061       push(@{ $form->{longdescription} },   qq|$form->{"longdescription_$i"}|);
1062       push(@{ $form->{qty} },
1063            $form->format_amount($myconfig, $form->{"qty_$i"}));
1064       push(@{ $form->{ship} },
1065            $form->format_amount($myconfig, $form->{"ship_$i"}));
1066       push(@{ $form->{unit} },         qq|$form->{"unit_$i"}|);
1067       push(@{ $form->{bin} },          qq|$form->{"bin_$i"}|);
1068       push(@{ $form->{"partnotes"} },  qq|$form->{"partnotes_$i"}|);
1069       push(@{ $form->{serialnumber} }, qq|$form->{"serialnumber_$i"}|);
1070       push(@{ $form->{reqdate} },      qq|$form->{"reqdate_$i"}|);
1071
1072       push(@{ $form->{sellprice} }, $form->{"sellprice_$i"});
1073
1074       push(@{ $form->{listprice} }, $form->{"listprice_$i"});
1075
1076       my $sellprice = $form->parse_amount($myconfig, $form->{"sellprice_$i"});
1077       my ($dec) = ($sellprice =~ /\.(\d+)/);
1078       $dec = length $dec;
1079       my $decimalplaces = ($dec > 2) ? $dec : 2;
1080
1081       my $i_discount =
1082         $form->round_amount(
1083                             $sellprice * $form->parse_amount($myconfig,
1084                                                  $form->{"discount_$i"}) / 100,
1085                             $decimalplaces);
1086
1087       my $discount =
1088         $form->round_amount($form->{"qty_$i"} * $i_discount, $decimalplaces);
1089
1090       # keep a netprice as well, (sellprice - discount)
1091       #$form->{"netprice_$i"} = $sellprice - $discount;
1092       $form->{"netprice_$i"} = $sellprice - $i_discount;
1093       my $nodiscount_linetotal =
1094         $form->round_amount($form->{"qty_$i"} * $sellprice, 2);
1095       my $linetotal =
1096         $form->round_amount($form->{"qty_$i"} * $form->{"netprice_$i"}, 2);
1097
1098       push(@{ $form->{netprice} },
1099            ($form->{"netprice_$i"} != 0)
1100            ? $form->format_amount(
1101                                  $myconfig, $form->{"netprice_$i"},
1102                                  $decimalplaces
1103              )
1104            : " ");
1105
1106       $discount =
1107         ($discount != 0)
1108         ? $form->format_amount($myconfig, $discount * -1, $decimalplaces)
1109         : " ";
1110       $linetotal = ($linetotal != 0) ? $linetotal : " ";
1111
1112       push(@{ $form->{discount} },   $discount);
1113       push(@{ $form->{p_discount} }, $form->{"discount_$i"});
1114
1115       $form->{ordtotal} += $linetotal;
1116      $discount_subtotal += $linetotal;
1117       $form->{nodiscount_total} += $nodiscount_linetotal;
1118       $nodiscount_subtotal += $nodiscount_linetotal;
1119       $form->{discount_total} += $form->parse_amount($myconfig, $discount);
1120
1121       if ($form->{"subtotal_$i"} && $subtotal_header && ($subtotal_header != $i)) {
1122         $discount_subtotal = $form->format_amount($myconfig, $discount_subtotal, 2);
1123         push(@{ $form->{discount_sub} },  $discount_subtotal);
1124         $nodiscount_subtotal = $form->format_amount($myconfig, $nodiscount_subtotal, 2);
1125         push(@{ $form->{nodiscount_sub} }, $nodiscount_subtotal);
1126         $discount_subtotal = 0;
1127         $nodiscount_subtotal = 0;
1128         $subtotal_header = 0;
1129       } else {
1130         push(@{ $form->{discount_sub} }, "");
1131         push(@{ $form->{nodiscount_sub} }, "");
1132       }
1133
1134       if ($linetotal == $netto_linetotal) {
1135         $nodiscount += $linetotal;
1136       }
1137       push(@{ $form->{linetotal} },
1138            $form->format_amount($myconfig, $linetotal, 2));
1139       push(@{ $form->{nodiscount_linetotal} },
1140            $form->format_amount($myconfig, $nodiscount_linetotal, 2));
1141
1142       my ($taxamount, $taxbase);
1143       my $taxrate = 0;
1144
1145       map { $taxrate += $form->{"${_}_rate"} } split / /,
1146         $form->{"taxaccounts_$i"};
1147
1148       if ($form->{taxincluded}) {
1149
1150         # calculate tax
1151         $taxamount = $linetotal * $taxrate / (1 + $taxrate);
1152         $taxbase = $linetotal / (1 + $taxrate);
1153       } else {
1154         $taxamount = $linetotal * $taxrate;
1155         $taxbase   = $linetotal;
1156       }
1157
1158       if ($taxamount != 0) {
1159         foreach my $item (split / /, $form->{"taxaccounts_$i"}) {
1160           $taxaccounts{$item} +=
1161             $taxamount * $form->{"${item}_rate"} / $taxrate;
1162           $taxbase{$item} += $taxbase;
1163         }
1164       }
1165
1166       $tax_rate = $taxrate * 100;
1167       push(@{ $form->{tax_rate} }, qq|$tax_rate|);
1168
1169       if ($form->{"assembly_$i"}) {
1170         $sameitem = "";
1171
1172         # get parts and push them onto the stack
1173         my $sortorder = "";
1174         if ($form->{groupitems}) {
1175           $sortorder =
1176             qq|ORDER BY pg.partsgroup, a.$oid{$myconfig->{dbdriver}}|;
1177         } else {
1178           $sortorder = qq|ORDER BY a.$oid{$myconfig->{dbdriver}}|;
1179         }
1180
1181         $query = qq|SELECT p.partnumber, p.description, p.unit, a.qty,
1182                     pg.partsgroup
1183                     FROM assembly a
1184                     JOIN parts p ON (a.parts_id = p.id)
1185                     LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
1186                     WHERE a.bom = '1'
1187                     AND a.id = '$form->{"id_$i"}'
1188                     $sortorder|;
1189         $sth = $dbh->prepare($query);
1190         $sth->execute || $form->dberror($query);
1191
1192         while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
1193           if ($form->{groupitems} && $ref->{partsgroup} ne $sameitem) {
1194             map { push(@{ $form->{$_} }, "") }
1195               qw(runningnumber ship bin serialnumber number unit bin qty 
1196                  reqdate sellprice listprice netprice discount p_discount
1197                  linetotal nodiscount_linetotal);
1198             $sameitem = ($ref->{partsgroup}) ? $ref->{partsgroup} : "--";
1199             push(@{ $form->{description} }, $sameitem);
1200           }
1201
1202           push(@{ $form->{description} },
1203                $form->format_amount($myconfig, $ref->{qty} * $form->{"qty_$i"}
1204                  )
1205                  . qq|, $ref->{partnumber}, $ref->{description}|);
1206
1207           map { push(@{ $form->{$_} }, "") }
1208             qw(number unit qty runningnumber ship bin serialnumber reqdate 
1209                sellprice listprice netprice discount p_discount linetotal 
1210                nodiscount_linetotal);
1211
1212         }
1213         $sth->finish;
1214       }
1215
1216     }
1217   }
1218
1219   my $tax = 0;
1220   foreach $item (sort keys %taxaccounts) {
1221       push(@{ $form->{taxbase} },
1222            $form->format_amount($myconfig, $taxbase{$item}, 2));
1223
1224       $tax += $taxamount = $form->round_amount($taxaccounts{$item}, 2);
1225
1226       push(@{ $form->{tax} }, $form->format_amount($myconfig, $taxamount, 2));
1227       push(@{ $form->{taxdescription} }, $form->{"${item}_description"});
1228       push(@{ $form->{taxrate} },
1229            $form->format_amount($myconfig, $form->{"${item}_rate"} * 100));
1230       push(@{ $form->{taxnumber} }, $form->{"${item}_taxnumber"});
1231   }
1232   $form->{subtotal} = $form->format_amount($myconfig, $form->{total}, 2);
1233   $yesdiscount = $form->{nodiscount_total} - $nodiscount;
1234   $form->{nodiscount_subtotal} = $form->format_amount($myconfig, $form->{nodiscount_total}, 2);
1235   $form->{discount_total} = $form->format_amount($myconfig, $form->{discount_total}, 2);
1236   $form->{nodiscount} = $form->format_amount($myconfig, $nodiscount, 2);
1237   $form->{yesdiscount} = $form->format_amount($myconfig, $yesdiscount, 2);
1238
1239   $form->{subtotal} = $form->format_amount($myconfig, $form->{ordtotal}, 2);
1240   $form->{ordtotal} =
1241     ($form->{taxincluded}) ? $form->{ordtotal} : $form->{ordtotal} + $tax;
1242
1243   # format amounts
1244   $form->{quototal} = $form->{ordtotal} =
1245     $form->format_amount($myconfig, $form->{ordtotal}, 2);
1246
1247   if ($form->{type} =~ /_quotation/) {
1248     $form->set_payment_options($myconfig, $form->{quodate});
1249   } else {
1250     $form->set_payment_options($myconfig, $form->{orddate});
1251   }
1252
1253   # myconfig variables
1254   map { $form->{$_} = $myconfig->{$_} }
1255     (qw(company address tel fax signature businessnumber));
1256   $form->{username} = $myconfig->{name};
1257
1258   $dbh->disconnect;
1259
1260   $main::lxdebug->leave_sub();
1261 }
1262
1263 sub project_description {
1264   $main::lxdebug->enter_sub();
1265
1266   my ($self, $dbh, $id) = @_;
1267
1268   my $query = qq|SELECT p.description
1269                  FROM project p
1270                  WHERE p.id = $id|;
1271   my $sth = $dbh->prepare($query);
1272   $sth->execute || $form->dberror($query);
1273
1274   ($_) = $sth->fetchrow_array;
1275
1276   $sth->finish;
1277
1278   $main::lxdebug->leave_sub();
1279
1280   return $_;
1281 }
1282
1283 sub get_warehouses {
1284   $main::lxdebug->enter_sub();
1285
1286   my ($self, $myconfig, $form) = @_;
1287
1288   my $dbh = $form->dbconnect($myconfig);
1289
1290   # setup warehouses
1291   my $query = qq|SELECT id, description
1292                  FROM warehouse|;
1293
1294   my $sth = $dbh->prepare($query);
1295   $sth->execute || $form->dberror($query);
1296
1297   while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
1298     push @{ $form->{all_warehouses} }, $ref;
1299   }
1300   $sth->finish;
1301
1302   $dbh->disconnect;
1303
1304   $main::lxdebug->leave_sub();
1305 }
1306
1307 sub save_inventory {
1308   $main::lxdebug->enter_sub();
1309
1310   my ($self, $myconfig, $form) = @_;
1311
1312   my ($null, $warehouse_id) = split /--/, $form->{warehouse};
1313   $warehouse_id *= 1;
1314
1315   my $employee_id;
1316   ($null, $employee_id) = split /--/, $form->{employee};
1317
1318   my $ml = ($form->{type} eq 'ship_order') ? -1 : 1;
1319
1320   my $dbh = $form->dbconnect_noauto($myconfig);
1321   my $sth;
1322   my $wth;
1323   my $serialnumber;
1324   my $ship;
1325
1326   $query = qq|SELECT o.serialnumber, o.ship
1327               FROM orderitems o
1328               WHERE o.trans_id = ?
1329               AND o.id = ?
1330               FOR UPDATE|;
1331   $sth = $dbh->prepare($query) || $form->dberror($query);
1332
1333   $query = qq|SELECT sum(i.qty)
1334               FROM inventory i
1335               WHERE i.parts_id = ?
1336               AND i.warehouse_id = ?|;
1337   $wth = $dbh->prepare($query) || $form->dberror($query);
1338
1339   for my $i (1 .. $form->{rowcount} - 1) {
1340
1341     $ship =
1342       (abs($form->{"ship_$i"}) > abs($form->{"qty_$i"}))
1343       ? $form->{"qty_$i"}
1344       : $form->{"ship_$i"};
1345
1346     if ($warehouse_id && $form->{type} eq 'ship_order') {
1347
1348       $wth->execute($form->{"id_$i"}, $warehouse_id) || $form->dberror;
1349
1350       ($qty) = $wth->fetchrow_array;
1351       $wth->finish;
1352
1353       if ($ship > $qty) {
1354         $ship = $qty;
1355       }
1356     }
1357
1358     if ($ship != 0) {
1359
1360       $ship *= $ml;
1361       $query = qq|INSERT INTO inventory (parts_id, warehouse_id,
1362                   qty, oe_id, orderitems_id, shippingdate, employee_id)
1363                   VALUES ($form->{"id_$i"}, $warehouse_id,
1364                   $ship, $form->{"id"},
1365                   $form->{"orderitems_id_$i"}, '$form->{shippingdate}',
1366                   $employee_id)|;
1367       $dbh->do($query) || $form->dberror($query);
1368
1369       # add serialnumber, ship to orderitems
1370       $sth->execute($form->{id}, $form->{"orderitems_id_$i"})
1371         || $form->dberror;
1372       ($serialnumber, $ship) = $sth->fetchrow_array;
1373       $sth->finish;
1374
1375       $serialnumber .= " " if $serialnumber;
1376       $serialnumber .= qq|$form->{"serialnumber_$i"}|;
1377       $ship += $form->{"ship_$i"};
1378
1379       $query = qq|UPDATE orderitems SET
1380                   serialnumber = '$serialnumber',
1381                   ship = $ship
1382                   WHERE trans_id = $form->{id}
1383                   AND id = $form->{"orderitems_id_$i"}|;
1384       $dbh->do($query) || $form->dberror($query);
1385
1386       # update order with ship via
1387       $query = qq|UPDATE oe SET
1388                   shippingpoint = '$form->{shippingpoint}',
1389                   shipvia = '$form->{shipvia}'
1390                   WHERE id = $form->{id}|;
1391       $dbh->do($query) || $form->dberror($query);
1392
1393       # update onhand for parts
1394       $form->update_balance($dbh, "parts", "onhand",
1395                             qq|id = $form->{"id_$i"}|,
1396                             $form->{"ship_$i"} * $ml);
1397
1398     }
1399   }
1400
1401   my $rc = $dbh->commit;
1402   $dbh->disconnect;
1403
1404   $main::lxdebug->leave_sub();
1405
1406   return $rc;
1407 }
1408
1409 sub adj_onhand {
1410   $main::lxdebug->enter_sub();
1411
1412   my ($dbh, $form, $ml) = @_;
1413
1414   my $service_units = $form->{service_units};
1415   my $part_units = $form->{part_units};
1416
1417   my $query = qq|SELECT oi.parts_id, oi.ship, oi.unit, p.inventory_accno_id, p.assembly
1418                  FROM orderitems oi
1419                  JOIN parts p ON (p.id = oi.parts_id)
1420                  WHERE oi.trans_id = $form->{id}|;
1421   my $sth = $dbh->prepare($query);
1422   $sth->execute || $form->dberror($query);
1423
1424   $query = qq|SELECT sum(p.inventory_accno_id)
1425               FROM parts p
1426               JOIN assembly a ON (a.parts_id = p.id)
1427               WHERE a.id = ?|;
1428   my $ath = $dbh->prepare($query) || $form->dberror($query);
1429
1430   my $ispa;
1431
1432   while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
1433   #print(STDERR "Bin in Schleife $ref->{inventory_accno_id}\n");
1434
1435     if ($ref->{inventory_accno_id} || $ref->{assembly}) {
1436
1437       # do not update if assembly consists of all services
1438       if ($ref->{assembly}) {
1439         $ath->execute($ref->{parts_id}) || $form->dberror($query);
1440
1441         ($ispa) = $sth->fetchrow_array;
1442         $ath->finish;
1443
1444         next unless $ispa;
1445
1446       }
1447
1448       # get item baseunit
1449       $query = qq|SELECT p.unit
1450                   FROM parts p
1451                   WHERE p.id = $ref->{parts_id}|;
1452       my $stw = $dbh->prepare($query);
1453       $stw->execute || $form->dberror($query);
1454
1455       my ($item_unit) = $stw->fetchrow_array();
1456       $stw->finish;
1457
1458       if ($ref->{inventory_accno_id}) {        
1459         if (defined($part_units->{$item_unit}->{factor}) && $part_units->{$item_unit}->{factor} ne '' && $part_units->{$item_unit}->{factor} ne '0') {
1460           $basefactor = $part_units->{$ref->{unit}}->{factor} / $part_units->{$item_unit}->{factor};
1461         } else {
1462           $basefactor = 1;
1463         }
1464         $baseqty = $ref->{ship} * $basefactor;
1465       } else {
1466         if (defined($service_units->{$item_unit}->{factor}) && $service_units->{$item_unit}->{factor} ne '' && $service_units->{$item_unit}->{factor} ne '0') {
1467           $basefactor = $service_units->{$ref->{unit}}->{factor} / $part_units->{$item_unit}->{factor};
1468         } else {
1469           $basefactor = 1;
1470         }
1471         $baseqty = $ref->{ship} * $basefactor;
1472       }  
1473       #print(STDERR "$baseqty Basismenge\n");
1474
1475       # adjust onhand in parts table
1476       $form->update_balance($dbh, "parts", "onhand",
1477                             qq|id = $ref->{parts_id}|,
1478                             $baseqty * $ml);
1479     }
1480   }
1481
1482   $sth->finish;
1483
1484   $main::lxdebug->leave_sub();
1485 }
1486
1487 sub adj_inventory {
1488   $main::lxdebug->enter_sub();
1489
1490   my ($dbh, $myconfig, $form) = @_;
1491
1492   my %oid = ('Pg'     => 'oid',
1493              'Oracle' => 'rowid');
1494
1495   # increase/reduce qty in inventory table
1496   my $query = qq|SELECT oi.id, oi.parts_id, oi.ship
1497                  FROM orderitems oi
1498                  WHERE oi.trans_id = $form->{id}|;
1499   my $sth = $dbh->prepare($query);
1500   $sth->execute || $form->dberror($query);
1501
1502   $query = qq|SELECT $oid{$myconfig->{dbdriver}} AS oid, qty,
1503                      (SELECT SUM(qty) FROM inventory
1504                       WHERE oe_id = $form->{id}
1505                       AND orderitems_id = ?) AS total
1506               FROM inventory
1507               WHERE oe_id = $form->{id}
1508               AND orderitems_id = ?|;
1509   my $ith = $dbh->prepare($query) || $form->dberror($query);
1510
1511   my $qty;
1512   my $ml = ($form->{type} =~ /(ship|sales)_order/) ? -1 : 1;
1513
1514   while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
1515
1516     $ith->execute($ref->{id}, $ref->{id}) || $form->dberror($query);
1517
1518     while (my $inv = $ith->fetchrow_hashref(NAME_lc)) {
1519
1520       if (($qty = (($inv->{total} * $ml) - $ref->{ship})) >= 0) {
1521         $qty = $inv->{qty} if ($qty > ($inv->{qty} * $ml));
1522
1523         $form->update_balance($dbh, "inventory", "qty",
1524                               qq|$oid{$myconfig->{dbdriver}} = $inv->{oid}|,
1525                               $qty * -1 * $ml);
1526       }
1527     }
1528     $ith->finish;
1529
1530   }
1531   $sth->finish;
1532
1533   # delete inventory entries if qty = 0
1534   $query = qq|DELETE FROM inventory
1535               WHERE oe_id = $form->{id}
1536               AND qty = 0|;
1537   $dbh->do($query) || $form->dberror($query);
1538
1539   $main::lxdebug->leave_sub();
1540 }
1541
1542 sub get_inventory {
1543   $main::lxdebug->enter_sub();
1544
1545   my ($self, $myconfig, $form) = @_;
1546
1547   my ($null, $warehouse_id) = split /--/, $form->{warehouse};
1548   $warehouse_id *= 1;
1549
1550   my $dbh = $form->dbconnect($myconfig);
1551
1552   my $query = qq|SELECT p.id, p.partnumber, p.description, p.onhand,
1553                  pg.partsgroup
1554                  FROM parts p
1555                  LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
1556                  WHERE p.onhand > 0|;
1557
1558   if ($form->{partnumber}) {
1559     $var = $form->like(lc $form->{partnumber});
1560     $query .= "
1561                  AND lower(p.partnumber) LIKE '$var'";
1562   }
1563   if ($form->{description}) {
1564     $var = $form->like(lc $form->{description});
1565     $query .= "
1566                  AND lower(p.description) LIKE '$var'";
1567   }
1568   if ($form->{partsgroup}) {
1569     $var = $form->like(lc $form->{partsgroup});
1570     $query .= "
1571                  AND lower(pg.partsgroup) LIKE '$var'";
1572   }
1573
1574   $sth = $dbh->prepare($query);
1575   $sth->execute || $form->dberror($query);
1576
1577   $query = qq|SELECT sum(i.qty), w.description, w.id
1578               FROM inventory i
1579               LEFT JOIN warehouse w ON (w.id = i.warehouse_id)
1580               WHERE i.parts_id = ?
1581               AND NOT i.warehouse_id = $warehouse_id
1582               GROUP BY w.description, w.id|;
1583   $wth = $dbh->prepare($query) || $form->dberror($query);
1584
1585   while ($ref = $sth->fetchrow_hashref(NAME_lc)) {
1586
1587     $wth->execute($ref->{id}) || $form->dberror;
1588
1589     while (($qty, $warehouse, $warehouse_id) = $wth->fetchrow_array) {
1590       push @{ $form->{all_inventory} },
1591         { 'id'           => $ref->{id},
1592           'partnumber'   => $ref->{partnumber},
1593           'description'  => $ref->{description},
1594           'partsgroup'   => $ref->{partsgroup},
1595           'qty'          => $qty,
1596           'warehouse_id' => $warehouse_id,
1597           'warehouse'    => $warehouse }
1598         if $qty > 0;
1599     }
1600     $wth->finish;
1601   }
1602   $sth->finish;
1603
1604   $dbh->disconnect;
1605
1606   # sort inventory
1607   @{ $form->{all_inventory} } =
1608     sort { $a->{ $form->{sort} } cmp $b->{ $form->{sort} } }
1609     @{ $form->{all_inventory} };
1610
1611   $main::lxdebug->leave_sub();
1612
1613   return @{ $form->{all_inventory} };
1614 }
1615
1616 sub transfer {
1617   $main::lxdebug->enter_sub();
1618
1619   my ($self, $myconfig, $form) = @_;
1620
1621   my $dbh = $form->dbconnect_noauto($myconfig);
1622
1623   my $query = qq|INSERT INTO inventory
1624                  (warehouse_id, parts_id, qty, shippingdate, employee_id)
1625                  VALUES (?, ?, ?, ?, ?)|;
1626   $sth = $dbh->prepare($query) || $form->dberror($query);
1627
1628   $form->get_employee($dbh);
1629
1630   my @a = localtime;
1631   $a[5] += 1900;
1632   $a[4]++;
1633   $shippingdate = "$a[5]-$a[4]-$a[3]";
1634
1635   for my $i (1 .. $form->{rowcount}) {
1636     $qty = $form->parse_amount($myconfig, $form->{"transfer_$i"});
1637
1638     $qty = $form->{"qty_$i"} if ($qty > $form->{"qty_$i"});
1639
1640     if ($qty) {
1641
1642       # to warehouse
1643       $sth->execute($form->{warehouse_id}, $form->{"id_$i"}, $qty,
1644                     $shippingdate, $form->{employee_id})
1645         || $form->dberror;
1646
1647       $sth->finish;
1648
1649       # from warehouse
1650       $sth->execute($form->{"warehouse_id_$i"},
1651                     $form->{"id_$i"}, $qty * -1, $shippingdate,
1652                     $form->{employee_id})
1653         || $form->dberror;
1654
1655       $sth->finish;
1656     }
1657   }
1658
1659   my $rc = $dbh->commit;
1660   $dbh->disconnect;
1661
1662   $main::lxdebug->leave_sub();
1663
1664   return $rc;
1665 }
1666
1667 sub webdav_folder {
1668   $main::lxdebug->enter_sub();
1669
1670   my ($myconfig, $form) = @_;
1671
1672 SWITCH: {
1673     $path = "webdav/angebote/" . $form->{quonumber}, last SWITCH
1674       if ($form->{type} eq "sales_quotation");
1675     $path = "webdav/bestellungen/" . $form->{ordnumber}, last SWITCH
1676       if ($form->{type} eq "sales_order");
1677     $path = "webdav/anfragen/" . $form->{quonumber}, last SWITCH
1678       if ($form->{type} eq "request_quotation");
1679     $path = "webdav/lieferantenbestellungen/" . $form->{ordnumber}, last SWITCH
1680       if ($form->{type} eq "purchase_order");
1681   }
1682
1683   if (!-d $path) {
1684     mkdir($path, 0770) or die "can't make directory $!\n";
1685   } else {
1686     if ($form->{id}) {
1687       @files = <$path/*>;
1688       foreach $file (@files) {
1689         $file =~ /\/([^\/]*)$/;
1690         $fname = $1;
1691         $ENV{'SCRIPT_NAME'} =~ /\/([^\/]*)\//;
1692         $lxerp = $1;
1693         $link  = "http://" . $ENV{'SERVER_NAME'} . "/" . $lxerp . "/" . $file;
1694         $form->{WEBDAV}{$fname} = $link;
1695       }
1696     }
1697   }
1698
1699   $main::lxdebug->leave_sub();
1700 }
1701 1;
1702