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