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