4c65c05452aed199d01aed1c29840b807b15a485
[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   # get ids from $form
471   map { push @ids, $form->{"ordnumber_$_"} if $form->{"ordnumber_$_"} } (1 .. $form->{rowcount});
472   
473   my $dbh = $form->dbconnect($myconfig);
474   $query = qq|UPDATE oe SET
475               closed = TRUE
476               WHERE ordnumber IN (|.join(', ', map{ $dbh->quote($_) }@ids).qq|)|;
477   $dbh->do($query) || $form->dberror($query);
478   $dbh->disconnect;
479
480   $main::lxdebug->leave_sub();
481 }
482
483 sub delete {
484   $main::lxdebug->enter_sub();
485
486   my ($self, $myconfig, $form, $spool) = @_;
487
488   # connect to database
489   my $dbh = $form->dbconnect_noauto($myconfig);
490
491   # delete spool files
492   my $query = qq|SELECT s.spoolfile FROM status s
493                  WHERE s.trans_id = $form->{id}|;
494   $sth = $dbh->prepare($query);
495   $sth->execute || $self->dberror($query);
496
497   my $spoolfile;
498   my @spoolfiles = ();
499
500   while (($spoolfile) = $sth->fetchrow_array) {
501     push @spoolfiles, $spoolfile;
502   }
503   $sth->finish;
504
505   $query = qq|SELECT o.parts_id, o.ship FROM orderitems o
506               WHERE o.trans_id = $form->{id}|;
507   $sth = $dbh->prepare($query);
508   $sth->execute || $self->dberror($query);
509
510   while (my ($id, $ship) = $sth->fetchrow_array) {
511     $form->update_balance($dbh, "parts", "onhand", qq|id = $id|, $ship * -1);
512   }
513   $sth->finish;
514
515   # delete inventory
516   $query = qq|DELETE FROM inventory
517               WHERE oe_id = $form->{id}|;
518   $dbh->do($query) || $form->dberror($query);
519
520   # delete status entries
521   $query = qq|DELETE FROM status
522               WHERE trans_id = $form->{id}|;
523   $dbh->do($query) || $form->dberror($query);
524
525   # delete OE record
526   $query = qq|DELETE FROM oe
527               WHERE id = $form->{id}|;
528   $dbh->do($query) || $form->dberror($query);
529
530   # delete individual entries
531   $query = qq|DELETE FROM orderitems
532               WHERE trans_id = $form->{id}|;
533   $dbh->do($query) || $form->dberror($query);
534
535   $query = qq|DELETE FROM shipto
536               WHERE trans_id = $form->{id}|;
537   $dbh->do($query) || $form->dberror($query);
538
539   my $rc = $dbh->commit;
540   $dbh->disconnect;
541
542   if ($rc) {
543     foreach $spoolfile (@spoolfiles) {
544       unlink "$spool/$spoolfile" if $spoolfile;
545     }
546   }
547
548   $main::lxdebug->leave_sub();
549
550   return $rc;
551 }
552
553 sub retrieve {
554   $main::lxdebug->enter_sub();
555
556   my ($self, $myconfig, $form) = @_;
557
558   # connect to database
559   my $dbh = $form->dbconnect_noauto($myconfig);
560
561   my $query;
562
563   # translate the ids (given by id_# and trans_id_#) into one array of ids, so we can join them later
564   map { push @ids, $form->{"trans_id_$_"} if ($form->{"id_$_"}) } (1 .. $form->{"rowcount"});
565
566   # if called in multi id mode, and still only got one id, switch back to single id 
567   if ($form->{"rowcount"} and $#ids == 0) {
568     $form->{"id"} = $ids[0];
569     undef @ids;
570   }
571
572   if ($form->{id}) {
573
574     # get default accounts and last order number
575     $query = qq|SELECT (SELECT c.accno FROM chart c
576                         WHERE d.inventory_accno_id = c.id) AS inventory_accno,
577                        (SELECT c.accno FROM chart c
578                         WHERE d.income_accno_id = c.id) AS income_accno,
579                        (SELECT c.accno FROM chart c
580                         WHERE d.expense_accno_id = c.id) AS expense_accno,
581                        (SELECT c.accno FROM chart c
582                         WHERE d.fxgain_accno_id = c.id) AS fxgain_accno,
583                        (SELECT c.accno FROM chart c
584                         WHERE d.fxloss_accno_id = c.id) AS fxloss_accno,
585                 d.curr AS currencies
586                 FROM defaults d|;
587   } else {
588     $query = qq|SELECT (SELECT c.accno FROM chart c
589                         WHERE d.inventory_accno_id = c.id) AS inventory_accno,
590                        (SELECT c.accno FROM chart c
591                         WHERE d.income_accno_id = c.id) AS income_accno,
592                        (SELECT c.accno FROM chart c
593                         WHERE d.expense_accno_id = c.id) AS expense_accno,
594                        (SELECT c.accno FROM chart c
595                         WHERE d.fxgain_accno_id = c.id) AS fxgain_accno,
596                        (SELECT c.accno FROM chart c
597                         WHERE d.fxloss_accno_id = c.id) AS fxloss_accno,
598                 d.curr AS currencies,
599                 current_date AS transdate, current_date AS reqdate
600                 FROM defaults d|;
601   }
602   my $sth = $dbh->prepare($query);
603   $sth->execute || $form->dberror($query);
604
605   my $ref = $sth->fetchrow_hashref(NAME_lc);
606   map { $form->{$_} = $ref->{$_} } keys %$ref;
607   $sth->finish;
608
609   ($form->{currency}) = split /:/, $form->{currencies};
610
611   if ($form->{id} or @ids) {
612
613     # retrieve order for single id
614     # NOTE: this query is intended to fetch all information only ONCE.
615     # so if any of these infos is important (or even different) for any item, 
616     # it will be killed out and then has to be fetched from the item scope query further down
617     $query = qq|SELECT o.cp_id, o.ordnumber, o.transdate, o.reqdate,
618                 o.taxincluded, o.shippingpoint, o.shipvia, o.notes, o.intnotes,
619                 o.curr AS currency, e.name AS employee, o.employee_id,
620                 o.$form->{vc}_id, cv.name AS $form->{vc}, o.amount AS invtotal,
621                 o.closed, o.reqdate, o.quonumber, o.department_id, o.cusordnumber,
622                 d.description AS department
623                 FROM oe o
624                 JOIN $form->{vc} cv ON (o.$form->{vc}_id = cv.id)
625                 LEFT JOIN employee e ON (o.employee_id = e.id)
626                 LEFT JOIN department d ON (o.department_id = d.id)
627                 |. ($form->{id} 
628                    ? qq|WHERE o.id = $form->{id}| 
629                    : qq|WHERE o.id IN (|.join(', ', @ids).qq|)|
630                    );
631
632 #$main::lxdebug->message(0, $query);
633
634     $sth = $dbh->prepare($query);
635     $sth->execute || $form->dberror($query);
636
637     $ref = $sth->fetchrow_hashref(NAME_lc);
638     map { $form->{$_} = $ref->{$_} } keys %$ref;
639
640     # destroy all entries for multiple ids that yield different information
641     while ($ref = $sth->fetchrow_hashref(NAME_lc)) {
642       map { undef $form->{$_} if ($ref->{$_} ne $form->{$_}) } keys %$ref;
643     }
644
645     # if not given, fill transdate with current_date
646     $form->{transdate} = $form->current_date($myconfig) unless $form->{transdate};
647
648     $sth->finish;
649
650     # shipto and pinted/mailed/queued status makes only sense for single id retrieve 
651     if (!@ids) {
652       $query = qq|SELECT s.* FROM shipto s
653                   WHERE s.trans_id = $form->{id}|;
654       $sth = $dbh->prepare($query);
655       $sth->execute || $form->dberror($query);
656
657       $ref = $sth->fetchrow_hashref(NAME_lc);
658       map { $form->{$_} = $ref->{$_} } keys %$ref;
659       $sth->finish;
660
661       # get printed, emailed and queued
662       $query = qq|SELECT s.printed, s.emailed, s.spoolfile, s.formname
663                   FROM status s
664                   WHERE s.trans_id = $form->{id}|;
665       $sth = $dbh->prepare($query);
666       $sth->execute || $form->dberror($query);
667
668       while ($ref = $sth->fetchrow_hashref(NAME_lc)) {
669         $form->{printed} .= "$ref->{formname} " if $ref->{printed};
670         $form->{emailed} .= "$ref->{formname} " if $ref->{emailed};
671         $form->{queued} .= "$ref->{formname} $ref->{spoolfile} " if $ref->{spoolfile};
672       }
673       $sth->finish;
674       map { $form->{$_} =~ s/ +$//g } qw(printed emailed queued);
675     } # if !@ids
676
677     my %oid = ('Pg'     => 'oid',
678                'Oracle' => 'rowid');
679
680     # retrieve individual items
681     # this query looks up all information about the items
682     # stuff different from the whole will not be overwritten, but saved with a suffix.
683     $query = qq|SELECT o.id AS orderitems_id,
684                 c1.accno AS inventory_accno,
685                 c2.accno AS income_accno,
686                 c3.accno AS expense_accno,
687                 oe.ordnumber, oe.transdate, oe.cusordnumber, 
688                 p.partnumber, p.assembly, o.description, o.qty,
689                 o.sellprice, o.parts_id AS id, o.unit, o.discount, p.bin, p.notes AS partnotes,
690                 o.reqdate, o.project_id, o.serialnumber, o.ship,
691                 pr.projectnumber,
692                 pg.partsgroup, o.pricegroup_id, (SELECT pricegroup FROM pricegroup WHERE id=o.pricegroup_id) as pricegroup
693                 FROM orderitems o
694                 JOIN parts p ON (o.parts_id = p.id)
695                 JOIN oe ON (o.trans_id = oe.id)
696                 LEFT JOIN chart c1 ON (p.inventory_accno_id = c1.id)
697                 LEFT JOIN chart c2 ON (p.income_accno_id = c2.id)
698                 LEFT JOIN chart c3 ON (p.expense_accno_id = c3.id)
699                 LEFT JOIN project pr ON (o.project_id = pr.id)
700                 LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
701                 |. ($form->{id} 
702                    ? qq|WHERE o.trans_id = $form->{id}| 
703                    : qq|WHERE o.trans_id IN (|.join(", ", @ids).qq|)| 
704                    ).qq|
705                 ORDER BY o.$oid{$myconfig->{dbdriver}}|;
706     
707     $sth = $dbh->prepare($query);
708     $sth->execute || $form->dberror($query);
709
710     while ($ref = $sth->fetchrow_hashref(NAME_lc)) {
711
712       #set expense_accno=inventory_accno if they are different => bilanz
713       $vendor_accno =
714         ($ref->{expense_accno} != $ref->{inventory_accno})
715         ? $ref->{inventory_accno}
716         : $ref->{expense_accno};
717
718       # get tax rates and description
719       $accno_id =
720         ($form->{vc} eq "customer") ? $ref->{income_accno} : $vendor_accno;
721       $query = qq|SELECT c.accno, c.description, t.rate, t.taxnumber
722                  FROM chart c, tax t
723                  WHERE c.id=t.chart_id AND t.taxkey in (SELECT taxkey_id from chart where accno = '$accno_id')
724                  ORDER BY accno|;
725       $stw = $dbh->prepare($query);
726       $stw->execute || $form->dberror($query);
727       $ref->{taxaccounts} = "";
728       while ($ptr = $stw->fetchrow_hashref(NAME_lc)) {
729
730         #    if ($customertax{$ref->{accno}}) {
731         $ref->{taxaccounts} .= "$ptr->{accno} ";
732         if (!($form->{taxaccounts} =~ /$ptr->{accno}/)) {
733           $form->{"$ptr->{accno}_rate"}        = $ptr->{rate};
734           $form->{"$ptr->{accno}_description"} = $ptr->{description};
735           $form->{"$ptr->{accno}_taxnumber"}   = $ptr->{taxnumber};
736           $form->{taxaccounts} .= "$ptr->{accno} ";
737         }
738
739       }
740
741       chop $ref->{taxaccounts};
742       push @{ $form->{form_details} }, $ref;
743       $stw->finish;
744     }
745     $sth->finish;
746
747   } else {
748
749     # get last name used
750     $form->lastname_used($dbh, $myconfig, $form->{vc})
751       unless $form->{"$form->{vc}_id"};
752
753   }
754
755   $form->{exchangerate} =
756     $form->get_exchangerate($dbh, $form->{currency}, $form->{transdate},
757                             ($form->{vc} eq 'customer') ? "buy" : "sell");
758
759   if ($form->{webdav}) {
760     &webdav_folder($myconfig, $form);
761   }
762
763   my $rc = $dbh->commit;
764   $dbh->disconnect;
765
766   $main::lxdebug->leave_sub();
767
768   return $rc;
769 }
770
771 sub order_details {
772   $main::lxdebug->enter_sub();
773
774   my ($self, $myconfig, $form) = @_;
775
776   # connect to database
777   my $dbh = $form->dbconnect($myconfig);
778   my $query;
779   my $sth;
780
781   my $item;
782   my $i;
783   my @partsgroup = ();
784   my $partsgroup;
785   my %oid = ('Pg'     => 'oid',
786              'Oracle' => 'rowid');
787
788   # sort items by partsgroup
789   for $i (1 .. $form->{rowcount}) {
790     $partsgroup = "";
791     if ($form->{"partsgroup_$i"} && $form->{groupitems}) {
792       $form->format_string("partsgroup_$i");
793       $partsgroup = $form->{"partsgroup_$i"};
794     }
795     push @partsgroup, [$i, $partsgroup];
796   }
797
798   # if there is a warehouse limit picking
799   if ($form->{warehouse_id} && $form->{formname} =~ /(pick|packing)_list/) {
800
801     # run query to check for inventory
802     $query = qq|SELECT sum(i.qty) AS qty
803                 FROM inventory i
804                 WHERE i.parts_id = ?
805                 AND i.warehouse_id = ?|;
806     $sth = $dbh->prepare($query) || $form->dberror($query);
807
808     for $i (1 .. $form->{rowcount}) {
809       $sth->execute($form->{"id_$i"}, $form->{warehouse_id}) || $form->dberror;
810
811       ($qty) = $sth->fetchrow_array;
812       $sth->finish;
813
814       $form->{"qty_$i"} = 0 if $qty == 0;
815
816       if ($form->parse_amount($myconfig, $form->{"ship_$i"}) > $qty) {
817         $form->{"ship_$i"} = $form->format_amount($myconfig, $qty);
818       }
819     }
820   }
821
822   my $sameitem = "";
823   foreach $item (sort { $a->[1] cmp $b->[1] } @partsgroup) {
824     $i = $item->[0];
825
826     if ($item->[1] ne $sameitem) {
827       push(@{ $form->{description} }, qq|$item->[1]|);
828       $sameitem = $item->[1];
829
830       map { push(@{ $form->{$_} }, "") }
831         qw(runningnumber number qty ship unit bin partnotes serialnumber reqdate sellprice listprice netprice discount linetotal);
832     }
833
834     $form->{"qty_$i"} = $form->parse_amount($myconfig, $form->{"qty_$i"});
835
836     if ($form->{"qty_$i"} != 0) {
837
838       # add number, description and qty to $form->{number}, ....
839       push(@{ $form->{runningnumber} }, $i);
840       push(@{ $form->{number} },        qq|$form->{"partnumber_$i"}|);
841       push(@{ $form->{description} },   qq|$form->{"description_$i"}|);
842       push(@{ $form->{qty} },
843            $form->format_amount($myconfig, $form->{"qty_$i"}));
844       push(@{ $form->{ship} },
845            $form->format_amount($myconfig, $form->{"ship_$i"}));
846       push(@{ $form->{unit} },         qq|$form->{"unit_$i"}|);
847       push(@{ $form->{bin} },          qq|$form->{"bin_$i"}|);
848       push(@{ $form->{"partnotes"} },  qq|$form->{"partnotes_$i"}|);
849       push(@{ $form->{serialnumber} }, qq|$form->{"serialnumber_$i"}|);
850       push(@{ $form->{reqdate} },      qq|$form->{"reqdate_$i"}|);
851
852       push(@{ $form->{sellprice} }, $form->{"sellprice_$i"});
853
854       push(@{ $form->{listprice} }, $form->{"listprice_$i"});
855
856       my $sellprice = $form->parse_amount($myconfig, $form->{"sellprice_$i"});
857       my ($dec) = ($sellprice =~ /\.(\d+)/);
858       $dec = length $dec;
859       my $decimalplaces = ($dec > 2) ? $dec : 2;
860
861       my $discount =
862         $form->round_amount(
863                             $sellprice * $form->parse_amount($myconfig,
864                                                  $form->{"discount_$i"}) / 100,
865                             $decimalplaces);
866
867       # keep a netprice as well, (sellprice - discount)
868       $form->{"netprice_$i"} = $sellprice - $discount;
869
870       my $linetotal =
871         $form->round_amount($form->{"qty_$i"} * $form->{"netprice_$i"}, 2);
872
873       push(@{ $form->{netprice} },
874            ($form->{"netprice_$i"} != 0)
875            ? $form->format_amount(
876                                  $myconfig, $form->{"netprice_$i"},
877                                  $decimalplaces
878              )
879            : " ");
880
881       $discount =
882         ($discount != 0)
883         ? $form->format_amount($myconfig, $discount * -1, $decimalplaces)
884         : " ";
885       $linetotal = ($linetotal != 0) ? $linetotal : " ";
886
887       push(@{ $form->{discount} }, $discount);
888
889       $form->{ordtotal} += $linetotal;
890
891       push(@{ $form->{linetotal} },
892            $form->format_amount($myconfig, $linetotal, 2));
893
894       my ($taxamount, $taxbase);
895       my $taxrate = 0;
896
897       map { $taxrate += $form->{"${_}_rate"} } split / /,
898         $form->{"taxaccounts_$i"};
899
900       if ($form->{taxincluded}) {
901
902         # calculate tax
903         $taxamount = $linetotal * $taxrate / (1 + $taxrate);
904         $taxbase = $linetotal / (1 + $taxrate);
905       } else {
906         $taxamount = $linetotal * $taxrate;
907         $taxbase   = $linetotal;
908       }
909
910       if ($taxamount != 0) {
911         foreach my $item (split / /, $form->{"taxaccounts_$i"}) {
912           $taxaccounts{$item} +=
913             $taxamount * $form->{"${item}_rate"} / $taxrate;
914           $taxbase{$item} += $taxbase;
915         }
916       }
917
918       $tax_rate = $taxrate*100;
919       push(@{ $form->{tax_rate} }, qq|$tax_rate|);
920
921       if ($form->{"assembly_$i"}) {
922         $sameitem = "";
923
924         # get parts and push them onto the stack
925         my $sortorder = "";
926         if ($form->{groupitems}) {
927           $sortorder =
928             qq|ORDER BY pg.partsgroup, a.$oid{$myconfig->{dbdriver}}|;
929         } else {
930           $sortorder = qq|ORDER BY a.$oid{$myconfig->{dbdriver}}|;
931         }
932
933         $query = qq|SELECT p.partnumber, p.description, p.unit, a.qty,
934                     pg.partsgroup
935                     FROM assembly a
936                     JOIN parts p ON (a.parts_id = p.id)
937                     LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
938                     WHERE a.bom = '1'
939                     AND a.id = '$form->{"id_$i"}'
940                     $sortorder|;
941         $sth = $dbh->prepare($query);
942         $sth->execute || $form->dberror($query);
943
944         while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
945           if ($form->{groupitems} && $ref->{partsgroup} ne $sameitem) {
946             map { push(@{ $form->{$_} }, "") }
947               qw(runningnumber ship bin serialnumber number unit bin qty reqdate sellprice listprice netprice discount linetotal);
948             $sameitem = ($ref->{partsgroup}) ? $ref->{partsgroup} : "--";
949             push(@{ $form->{description} }, $sameitem);
950           }
951
952           push(@{ $form->{description} },
953                $form->format_amount($myconfig, $ref->{qty} * $form->{"qty_$i"}
954                  )
955                  . qq|, $ref->{partnumber}, $ref->{description}|);
956
957           map { push(@{ $form->{$_} }, "") }
958             qw(number unit qty runningnumber ship bin serialnumber reqdate sellprice listprice netprice discount linetotal);
959
960         }
961         $sth->finish;
962       }
963
964     }
965   }
966
967   my $tax = 0;
968   foreach $item (sort keys %taxaccounts) {
969     if ($form->round_amount($taxaccounts{$item}, 2) != 0) {
970       push(@{ $form->{taxbase} },
971            $form->format_amount($myconfig, $taxbase{$item}, 2));
972
973       $tax += $taxamount = $form->round_amount($taxaccounts{$item}, 2);
974
975       push(@{ $form->{tax} }, $form->format_amount($myconfig, $taxamount, 2));
976       push(@{ $form->{taxdescription} }, $form->{"${item}_description"});
977       push(@{ $form->{taxrate} },
978            $form->format_amount($myconfig, $form->{"${item}_rate"} * 100));
979       push(@{ $form->{taxnumber} }, $form->{"${item}_taxnumber"});
980     }
981   }
982
983   $form->{subtotal} = $form->format_amount($myconfig, $form->{ordtotal}, 2);
984   $form->{ordtotal} =
985     ($form->{taxincluded}) ? $form->{ordtotal} : $form->{ordtotal} + $tax;
986
987   # format amounts
988   $form->{quototal} = $form->{ordtotal} =
989     $form->format_amount($myconfig, $form->{ordtotal}, 2);
990
991   # myconfig variables
992   map { $form->{$_} = $myconfig->{$_} }
993     (qw(company address tel fax signature businessnumber));
994   $form->{username} = $myconfig->{name};
995
996   $dbh->disconnect;
997
998   $main::lxdebug->leave_sub();
999 }
1000
1001 sub project_description {
1002   $main::lxdebug->enter_sub();
1003
1004   my ($self, $dbh, $id) = @_;
1005
1006   my $query = qq|SELECT p.description
1007                  FROM project p
1008                  WHERE p.id = $id|;
1009   my $sth = $dbh->prepare($query);
1010   $sth->execute || $form->dberror($query);
1011
1012   ($_) = $sth->fetchrow_array;
1013
1014   $sth->finish;
1015
1016   $main::lxdebug->leave_sub();
1017
1018   return $_;
1019 }
1020
1021 sub get_warehouses {
1022   $main::lxdebug->enter_sub();
1023
1024   my ($self, $myconfig, $form) = @_;
1025
1026   my $dbh = $form->dbconnect($myconfig);
1027
1028   # setup warehouses
1029   my $query = qq|SELECT id, description
1030                  FROM warehouse|;
1031
1032   my $sth = $dbh->prepare($query);
1033   $sth->execute || $form->dberror($query);
1034
1035   while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
1036     push @{ $form->{all_warehouses} }, $ref;
1037   }
1038   $sth->finish;
1039
1040   $dbh->disconnect;
1041
1042   $main::lxdebug->leave_sub();
1043 }
1044
1045 sub save_inventory {
1046   $main::lxdebug->enter_sub();
1047
1048   my ($self, $myconfig, $form) = @_;
1049
1050   my ($null, $warehouse_id) = split /--/, $form->{warehouse};
1051   $warehouse_id *= 1;
1052
1053   my $employee_id;
1054   ($null, $employee_id) = split /--/, $form->{employee};
1055
1056   my $ml = ($form->{type} eq 'ship_order') ? -1 : 1;
1057
1058   my $dbh = $form->dbconnect_noauto($myconfig);
1059   my $sth;
1060   my $wth;
1061   my $serialnumber;
1062   my $ship;
1063
1064   $query = qq|SELECT o.serialnumber, o.ship
1065               FROM orderitems o
1066               WHERE o.trans_id = ?
1067               AND o.id = ?
1068               FOR UPDATE|;
1069   $sth = $dbh->prepare($query) || $form->dberror($query);
1070
1071   $query = qq|SELECT sum(i.qty)
1072               FROM inventory i
1073               WHERE i.parts_id = ?
1074               AND i.warehouse_id = ?|;
1075   $wth = $dbh->prepare($query) || $form->dberror($query);
1076
1077   for my $i (1 .. $form->{rowcount} - 1) {
1078
1079     $ship =
1080       (abs($form->{"ship_$i"}) > abs($form->{"qty_$i"}))
1081       ? $form->{"qty_$i"}
1082       : $form->{"ship_$i"};
1083
1084     if ($warehouse_id && $form->{type} eq 'ship_order') {
1085
1086       $wth->execute($form->{"id_$i"}, $warehouse_id) || $form->dberror;
1087
1088       ($qty) = $wth->fetchrow_array;
1089       $wth->finish;
1090
1091       if ($ship > $qty) {
1092         $ship = $qty;
1093       }
1094     }
1095
1096     if ($ship != 0) {
1097
1098       $ship *= $ml;
1099       $query = qq|INSERT INTO inventory (parts_id, warehouse_id,
1100                   qty, oe_id, orderitems_id, shippingdate, employee_id)
1101                   VALUES ($form->{"id_$i"}, $warehouse_id,
1102                   $ship, $form->{"id"},
1103                   $form->{"orderitems_id_$i"}, '$form->{shippingdate}',
1104                   $employee_id)|;
1105       $dbh->do($query) || $form->dberror($query);
1106
1107       # add serialnumber, ship to orderitems
1108       $sth->execute($form->{id}, $form->{"orderitems_id_$i"})
1109         || $form->dberror;
1110       ($serialnumber, $ship) = $sth->fetchrow_array;
1111       $sth->finish;
1112
1113       $serialnumber .= " " if $serialnumber;
1114       $serialnumber .= qq|$form->{"serialnumber_$i"}|;
1115       $ship += $form->{"ship_$i"};
1116
1117       $query = qq|UPDATE orderitems SET
1118                   serialnumber = '$serialnumber',
1119                   ship = $ship
1120                   WHERE trans_id = $form->{id}
1121                   AND id = $form->{"orderitems_id_$i"}|;
1122       $dbh->do($query) || $form->dberror($query);
1123
1124       # update order with ship via
1125       $query = qq|UPDATE oe SET
1126                   shippingpoint = '$form->{shippingpoint}',
1127                   shipvia = '$form->{shipvia}'
1128                   WHERE id = $form->{id}|;
1129       $dbh->do($query) || $form->dberror($query);
1130
1131       # update onhand for parts
1132       $form->update_balance($dbh, "parts", "onhand",
1133                             qq|id = $form->{"id_$i"}|,
1134                             $form->{"ship_$i"} * $ml);
1135
1136     }
1137   }
1138
1139   my $rc = $dbh->commit;
1140   $dbh->disconnect;
1141
1142   $main::lxdebug->leave_sub();
1143
1144   return $rc;
1145 }
1146
1147 sub adj_onhand {
1148   $main::lxdebug->enter_sub();
1149
1150   my ($dbh, $form, $ml) = @_;
1151
1152   my $query = qq|SELECT oi.parts_id, oi.ship, p.inventory_accno_id, p.assembly
1153                  FROM orderitems oi
1154                  JOIN parts p ON (p.id = oi.parts_id)
1155                  WHERE oi.trans_id = $form->{id}|;
1156   my $sth = $dbh->prepare($query);
1157   $sth->execute || $form->dberror($query);
1158
1159   $query = qq|SELECT sum(p.inventory_accno_id)
1160               FROM parts p
1161               JOIN assembly a ON (a.parts_id = p.id)
1162               WHERE a.id = ?|;
1163   my $ath = $dbh->prepare($query) || $form->dberror($query);
1164
1165   my $ispa;
1166
1167   while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
1168
1169     if ($ref->{inventory_accno_id} || $ref->{assembly}) {
1170
1171       # do not update if assembly consists of all services
1172       if ($ref->{assembly}) {
1173         $ath->execute($ref->{parts_id}) || $form->dberror($query);
1174
1175         ($ispa) = $sth->fetchrow_array;
1176         $ath->finish;
1177
1178         next unless $ispa;
1179
1180       }
1181
1182       # adjust onhand in parts table
1183       $form->update_balance($dbh, "parts", "onhand",
1184                             qq|id = $ref->{parts_id}|,
1185                             $ref->{ship} * $ml);
1186     }
1187   }
1188
1189   $sth->finish;
1190
1191   $main::lxdebug->leave_sub();
1192 }
1193
1194 sub adj_inventory {
1195   $main::lxdebug->enter_sub();
1196
1197   my ($dbh, $myconfig, $form) = @_;
1198
1199   my %oid = ('Pg'     => 'oid',
1200              'Oracle' => 'rowid');
1201
1202   # increase/reduce qty in inventory table
1203   my $query = qq|SELECT oi.id, oi.parts_id, oi.ship
1204                  FROM orderitems oi
1205                  WHERE oi.trans_id = $form->{id}|;
1206   my $sth = $dbh->prepare($query);
1207   $sth->execute || $form->dberror($query);
1208
1209   $query = qq|SELECT $oid{$myconfig->{dbdriver}} AS oid, qty,
1210                      (SELECT SUM(qty) FROM inventory
1211                       WHERE oe_id = $form->{id}
1212                       AND orderitems_id = ?) AS total
1213               FROM inventory
1214               WHERE oe_id = $form->{id}
1215               AND orderitems_id = ?|;
1216   my $ith = $dbh->prepare($query) || $form->dberror($query);
1217
1218   my $qty;
1219   my $ml = ($form->{type} =~ /(ship|sales)_order/) ? -1 : 1;
1220
1221   while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
1222
1223     $ith->execute($ref->{id}, $ref->{id}) || $form->dberror($query);
1224
1225     while (my $inv = $ith->fetchrow_hashref(NAME_lc)) {
1226
1227       if (($qty = (($inv->{total} * $ml) - $ref->{ship})) >= 0) {
1228         $qty = $inv->{qty} if ($qty > ($inv->{qty} * $ml));
1229
1230         $form->update_balance($dbh, "inventory", "qty",
1231                               qq|$oid{$myconfig->{dbdriver}} = $inv->{oid}|,
1232                               $qty * -1 * $ml);
1233       }
1234     }
1235     $ith->finish;
1236
1237   }
1238   $sth->finish;
1239
1240   # delete inventory entries if qty = 0
1241   $query = qq|DELETE FROM inventory
1242               WHERE oe_id = $form->{id}
1243               AND qty = 0|;
1244   $dbh->do($query) || $form->dberror($query);
1245
1246   $main::lxdebug->leave_sub();
1247 }
1248
1249 sub get_inventory {
1250   $main::lxdebug->enter_sub();
1251
1252   my ($self, $myconfig, $form) = @_;
1253
1254   my ($null, $warehouse_id) = split /--/, $form->{warehouse};
1255   $warehouse_id *= 1;
1256
1257   my $dbh = $form->dbconnect($myconfig);
1258
1259   my $query = qq|SELECT p.id, p.partnumber, p.description, p.onhand,
1260                  pg.partsgroup
1261                  FROM parts p
1262                  LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
1263                  WHERE p.onhand > 0|;
1264
1265   if ($form->{partnumber}) {
1266     $var = $form->like(lc $form->{partnumber});
1267     $query .= "
1268                  AND lower(p.partnumber) LIKE '$var'";
1269   }
1270   if ($form->{description}) {
1271     $var = $form->like(lc $form->{description});
1272     $query .= "
1273                  AND lower(p.description) LIKE '$var'";
1274   }
1275   if ($form->{partsgroup}) {
1276     $var = $form->like(lc $form->{partsgroup});
1277     $query .= "
1278                  AND lower(pg.partsgroup) LIKE '$var'";
1279   }
1280
1281   $sth = $dbh->prepare($query);
1282   $sth->execute || $form->dberror($query);
1283
1284   $query = qq|SELECT sum(i.qty), w.description, w.id
1285               FROM inventory i
1286               LEFT JOIN warehouse w ON (w.id = i.warehouse_id)
1287               WHERE i.parts_id = ?
1288               AND NOT i.warehouse_id = $warehouse_id
1289               GROUP BY w.description, w.id|;
1290   $wth = $dbh->prepare($query) || $form->dberror($query);
1291
1292   while ($ref = $sth->fetchrow_hashref(NAME_lc)) {
1293
1294     $wth->execute($ref->{id}) || $form->dberror;
1295
1296     while (($qty, $warehouse, $warehouse_id) = $wth->fetchrow_array) {
1297       push @{ $form->{all_inventory} },
1298         { 'id'           => $ref->{id},
1299           'partnumber'   => $ref->{partnumber},
1300           'description'  => $ref->{description},
1301           'partsgroup'   => $ref->{partsgroup},
1302           'qty'          => $qty,
1303           'warehouse_id' => $warehouse_id,
1304           'warehouse'    => $warehouse }
1305         if $qty > 0;
1306     }
1307     $wth->finish;
1308   }
1309   $sth->finish;
1310
1311   $dbh->disconnect;
1312
1313   # sort inventory
1314   @{ $form->{all_inventory} } =
1315     sort { $a->{ $form->{sort} } cmp $b->{ $form->{sort} } }
1316     @{ $form->{all_inventory} };
1317
1318   $main::lxdebug->leave_sub();
1319
1320   return @{ $form->{all_inventory} };
1321 }
1322
1323 sub transfer {
1324   $main::lxdebug->enter_sub();
1325
1326   my ($self, $myconfig, $form) = @_;
1327
1328   my $dbh = $form->dbconnect_noauto($myconfig);
1329
1330   my $query = qq|INSERT INTO inventory
1331                  (warehouse_id, parts_id, qty, shippingdate, employee_id)
1332                  VALUES (?, ?, ?, ?, ?)|;
1333   $sth = $dbh->prepare($query) || $form->dberror($query);
1334
1335   $form->get_employee($dbh);
1336
1337   my @a = localtime;
1338   $a[5] += 1900;
1339   $a[4]++;
1340   $shippingdate = "$a[5]-$a[4]-$a[3]";
1341
1342   for my $i (1 .. $form->{rowcount}) {
1343     $qty = $form->parse_amount($myconfig, $form->{"transfer_$i"});
1344
1345     $qty = $form->{"qty_$i"} if ($qty > $form->{"qty_$i"});
1346
1347     if ($qty) {
1348
1349       # to warehouse
1350       $sth->execute($form->{warehouse_id}, $form->{"id_$i"}, $qty,
1351                     $shippingdate, $form->{employee_id})
1352         || $form->dberror;
1353
1354       $sth->finish;
1355
1356       # from warehouse
1357       $sth->execute($form->{"warehouse_id_$i"},
1358                     $form->{"id_$i"}, $qty * -1, $shippingdate,
1359                     $form->{employee_id})
1360         || $form->dberror;
1361
1362       $sth->finish;
1363     }
1364   }
1365
1366   my $rc = $dbh->commit;
1367   $dbh->disconnect;
1368
1369   $main::lxdebug->leave_sub();
1370
1371   return $rc;
1372 }
1373
1374 sub webdav_folder {
1375   $main::lxdebug->enter_sub();
1376
1377   my ($myconfig, $form) = @_;
1378
1379 SWITCH: {
1380     $path = "webdav/angebote/" . $form->{quonumber}, last SWITCH
1381       if ($form->{type} eq "sales_quotation");
1382     $path = "webdav/bestellungen/" . $form->{ordnumber}, last SWITCH
1383       if ($form->{type} eq "sales_order");
1384     $path = "webdav/anfragen/" . $form->{quonumber}, last SWITCH
1385       if ($form->{type} eq "request_quotation");
1386     $path = "webdav/lieferantenbestellungen/" . $form->{ordnumber}, last SWITCH
1387       if ($form->{type} eq "purchase_order");
1388   }
1389
1390   if (!-d $path) {
1391     mkdir($path, 0770) or die "can't make directory $!\n";
1392   } else {
1393     if ($form->{id}) {
1394       @files = <$path/*>;
1395       foreach $file (@files) {
1396         $file =~ /\/([^\/]*)$/;
1397         $fname = $1;
1398         $ENV{'SCRIPT_NAME'} =~ /\/([^\/]*)\//;
1399         $lxerp = $1;
1400         $link  = "http://" . $ENV{'SERVER_NAME'} . "/" . $lxerp . "/" . $file;
1401         $form->{WEBDAV}{$fname} = $link;
1402       }
1403     }
1404   }
1405
1406   $main::lxdebug->leave_sub();
1407 }
1408 1;
1409