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