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