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