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