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