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