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