Drop-Down-Auswahlboxen für Ansprechpartner und Lieferadresse bei jedem Maskenaufbau...
[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::DBUtils;
39
40 sub transactions {
41   $main::lxdebug->enter_sub();
42
43   my ($self, $myconfig, $form) = @_;
44
45   # connect to database
46   my $dbh = $form->dbconnect($myconfig);
47
48   my $query;
49   my $ordnumber = 'ordnumber';
50   my $quotation = '0';
51   my ($null, $department_id) = split /--/, $form->{department};
52
53   my $department = " AND o.department_id = $department_id" if $department_id;
54
55   my $rate = ($form->{vc} eq 'customer') ? 'buy' : 'sell';
56
57   if ($form->{type} =~ /_quotation$/) {
58     $quotation = '1';
59     $ordnumber = 'quonumber';
60   }
61
62   my $number = $form->like(lc $form->{$ordnumber});
63   my $name   = $form->like(lc $form->{ $form->{vc} });
64
65   my $query = qq|SELECT o.id, o.ordnumber, o.transdate, o.reqdate,
66                  o.amount, ct.name, o.netamount, o.$form->{vc}_id,
67                  ex.$rate AS exchangerate,
68                  o.closed, o.delivered, o.quonumber, o.shippingpoint, o.shipvia,
69                  e.name AS employee
70                  FROM oe o
71                  JOIN $form->{vc} ct ON (o.$form->{vc}_id = ct.id)
72                  LEFT JOIN employee e ON (o.employee_id = e.id)
73                  LEFT JOIN exchangerate ex ON (ex.curr = o.curr
74                                                AND ex.transdate = o.transdate)
75                  WHERE o.quotation = '$quotation'
76                  $department|;
77
78   # build query if type eq (ship|receive)_order
79   if ($form->{type} =~ /(ship|receive)_order/) {
80     my ($warehouse, $warehouse_id) = split /--/, $form->{warehouse};
81
82     $query = qq|SELECT DISTINCT ON (o.id) o.id, o.ordnumber, o.transdate,
83                  o.reqdate, o.amount, ct.name, o.netamount, o.$form->{vc}_id,
84                  ex.$rate AS exchangerate,
85                  o.closed, o.quonumber, o.shippingpoint, o.shipvia,
86                  e.name AS employee
87                  FROM oe o
88                  JOIN $form->{vc} ct ON (o.$form->{vc}_id = ct.id)
89                  JOIN orderitems oi ON (oi.trans_id = o.id)
90                  JOIN parts p ON (p.id = oi.parts_id)|;
91
92     if ($warehouse_id && $form->{type} eq 'ship_order') {
93       $query .= qq|
94                  JOIN inventory i ON (oi.parts_id = i.parts_id)
95                  |;
96     }
97
98     $query .= qq|
99                  LEFT JOIN employee e ON (o.employee_id = e.id)
100                  LEFT JOIN exchangerate ex ON (ex.curr = o.curr
101                                                AND ex.transdate = o.transdate)
102                  WHERE o.quotation = '0'
103                  AND (p.inventory_accno_id > 0 OR p.assembly = '1')
104                  AND oi.qty <> oi.ship
105                  $department|;
106
107     if ($warehouse_id && $form->{type} eq 'ship_order') {
108       $query .= qq|
109                  AND i.warehouse_id = $warehouse_id
110                  AND i.qty >= (oi.qty - oi.ship)
111                  |;
112     }
113
114   }
115
116   if ($form->{"$form->{vc}_id"}) {
117     $query .= qq| AND o.$form->{vc}_id = $form->{"$form->{vc}_id"}|;
118   } else {
119     if ($form->{ $form->{vc} }) {
120       $query .= " AND lower(ct.name) LIKE '$name'";
121     }
122   }
123   if (!$form->{open} && !$form->{closed}) {
124     $query .= " AND o.id = 0";
125   } elsif (!($form->{open} && $form->{closed})) {
126     $query .= ($form->{open}) ? " AND o.closed = '0'" : " AND o.closed = '1'";
127   }
128
129   if (($form->{"notdelivered"} || $form->{"delivered"}) &&
130       ($form->{"notdelivered"} ne $form->{"delivered"})) {
131     $query .= $form->{"delivered"} ?
132       " AND o.delivered " : " AND NOT o.delivered";
133   }
134
135   my $sortorder = join ', ',
136     ("o.id", $form->sort_columns(transdate, $ordnumber, name));
137   $sortorder = $form->{sort} if $form->{sort};
138
139   $query .= " AND lower($ordnumber) LIKE '$number'" if $form->{$ordnumber};
140   $query .= " AND o.transdate >= '$form->{transdatefrom}'"
141     if $form->{transdatefrom};
142   $query .= " AND o.transdate <= '$form->{transdateto}'"
143     if $form->{transdateto};
144   $query .= " ORDER by $sortorder";
145
146   my $sth = $dbh->prepare($query);
147   $sth->execute || $form->dberror($query);
148
149   my %id = ();
150   while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
151     $ref->{exchangerate} = 1 unless $ref->{exchangerate};
152     push @{ $form->{OE} }, $ref if $ref->{id} != $id{ $ref->{id} };
153     $id{ $ref->{id} } = $ref->{id};
154   }
155
156   $sth->finish;
157   $dbh->disconnect;
158
159   $main::lxdebug->leave_sub();
160 }
161
162 sub save {
163   $main::lxdebug->enter_sub();
164
165   my ($self, $myconfig, $form) = @_;
166
167   # connect to database, turn off autocommit
168   my $dbh = $form->dbconnect_noauto($myconfig);
169
170   my ($query, $sth, $null);
171   my $exchangerate = 0;
172
173   my $service_units = AM->retrieve_units($myconfig,$form,"service");
174   my $part_units = AM->retrieve_units($myconfig,$form,"dimension");
175   $form->{service_units} =$service_units;
176   $form->{part_units} =$part_units;
177
178   ($null, $form->{employee_id}) = split /--/, $form->{employee};
179   unless ($form->{employee_id}) {
180     $form->get_employee($dbh);
181   }
182
183   $form->{payment_id} *= 1;
184   $form->{language_id} *= 1;
185   $form->{shipto_id} *= 1;
186   $form->{delivery_customer_id} *= 1;
187   $form->{delivery_vendor_id} *= 1;
188
189   my $ml = ($form->{type} eq 'sales_order') ? 1 : -1;
190
191   if ($form->{id}) {
192
193     &adj_onhand($dbh, $form, $ml) if $form->{type} =~ /_order$/;
194
195     $query = qq|DELETE FROM orderitems
196                 WHERE trans_id = $form->{id}|;
197     $dbh->do($query) || $form->dberror($query);
198
199     $query = qq|DELETE FROM shipto
200                 WHERE trans_id = $form->{id} AND module = 'OE'|;
201     $dbh->do($query) || $form->dberror($query);
202
203   } else {
204
205     my $uid = rand() . time;
206
207     $uid .= $form->{login};
208
209     $uid = substr($uid, 2, 75);
210
211     $query = qq|INSERT INTO oe (ordnumber, employee_id)
212                 VALUES ('$uid', $form->{employee_id})|;
213     $dbh->do($query) || $form->dberror($query);
214
215     $query = qq|SELECT o.id FROM oe o
216                 WHERE o.ordnumber = '$uid'|;
217     $sth = $dbh->prepare($query);
218     $sth->execute || $form->dberror($query);
219
220     ($form->{id}) = $sth->fetchrow_array;
221     $sth->finish;
222   }
223
224   map { $form->{$_} =~ s/\'/\'\'/g }
225     qw(ordnumber quonumber shippingpoint shipvia notes intnotes message);
226
227   my $amount;
228   my $linetotal;
229   my $discount;
230   my $project_id;
231   my $reqdate;
232   my $taxrate;
233   my $taxamount;
234   my $fxsellprice;
235   my %taxbase;
236   my @taxaccounts;
237   my %taxaccounts;
238   my $netamount = 0;
239
240   for my $i (1 .. $form->{rowcount}) {
241
242     map {
243       $form->{"${_}_$i"} =
244         $form->parse_amount($myconfig, $form->{"${_}_$i"})
245     } qw(qty ship);
246
247     if ($form->{"id_$i"}) {
248
249       # get item baseunit
250       $query = qq|SELECT p.unit
251                   FROM parts p
252                   WHERE p.id = $form->{"id_$i"}|;
253       $sth = $dbh->prepare($query);
254       $sth->execute || $form->dberror($query);
255
256       my ($item_unit) = $sth->fetchrow_array();
257       $sth->finish;
258
259       if ($form->{"inventory_accno_$i"}) {
260         if (defined($part_units->{$item_unit}->{factor}) && $part_units->{$item_unit}->{factor} ne '' && $part_units->{$item_unit}->{factor} ne '0') {
261           $basefactor = $part_units->{$form->{"unit_$i"}}->{factor} / $part_units->{$item_unit}->{factor};
262         } else {
263           $basefactor = 1;
264         }
265         $baseqty = $form->{"qty_$i"} * $basefactor;
266       } else {
267         if (defined($service_units->{$item_unit}->{factor}) && $service_units->{$item_unit}->{factor} ne '' && $service_units->{$item_unit}->{factor} ne '0') {
268           $basefactor = $service_units->{$form->{"unit_$i"}}->{factor} / $service_units->{$item_unit}->{factor};
269         } else {
270           $basefactor = 1;
271         }
272         $baseqty = $form->{"qty_$i"} * $basefactor;
273       }
274
275       map { $form->{"${_}_$i"} =~ s/\'/\'\'/g }
276         qw(partnumber description unit);
277
278       # set values to 0 if nothing entered
279       $form->{"discount_$i"} =
280         $form->parse_amount($myconfig, $form->{"discount_$i"}) / 100;
281
282       $form->{"sellprice_$i"} =
283         $form->parse_amount($myconfig, $form->{"sellprice_$i"});
284       $fxsellprice = $form->{"sellprice_$i"};
285
286       my ($dec) = ($form->{"sellprice_$i"} =~ /\.(\d+)/);
287       $dec = length $dec;
288       my $decimalplaces = ($dec > 2) ? $dec : 2;
289
290       $discount =
291         $form->round_amount($form->{"sellprice_$i"} * $form->{"discount_$i"},
292                             $decimalplaces);
293       $form->{"sellprice_$i"} =
294         $form->round_amount($form->{"sellprice_$i"} - $discount,
295                             $decimalplaces);
296
297       $form->{"inventory_accno_$i"} *= 1;
298       $form->{"expense_accno_$i"}   *= 1;
299
300       $linetotal =
301         $form->round_amount($form->{"sellprice_$i"} * $form->{"qty_$i"}, 2);
302
303       @taxaccounts = split / /, $form->{"taxaccounts_$i"};
304       $taxrate     = 0;
305       $taxdiff     = 0;
306
307       map { $taxrate += $form->{"${_}_rate"} } @taxaccounts;
308
309       if ($form->{taxincluded}) {
310         $taxamount = $linetotal * $taxrate / (1 + $taxrate);
311         $taxbase   = $linetotal - $taxamount;
312
313         # we are not keeping a natural price, do not round
314         $form->{"sellprice_$i"} =
315           $form->{"sellprice_$i"} * (1 / (1 + $taxrate));
316       } else {
317         $taxamount = $linetotal * $taxrate;
318         $taxbase   = $linetotal;
319       }
320
321       if ($form->round_amount($taxrate, 7) == 0) {
322         if ($form->{taxincluded}) {
323           foreach $item (@taxaccounts) {
324             $taxamount =
325               $form->round_amount($linetotal * $form->{"${item}_rate"} /
326                                     (1 + abs($form->{"${item}_rate"})),
327                                   2);
328
329             $taxaccounts{$item} += $taxamount;
330             $taxdiff            += $taxamount;
331
332             $taxbase{$item} += $taxbase;
333           }
334           $taxaccounts{ $taxaccounts[0] } += $taxdiff;
335         } else {
336           foreach $item (@taxaccounts) {
337             $taxaccounts{$item} += $linetotal * $form->{"${item}_rate"};
338             $taxbase{$item}     += $taxbase;
339           }
340         }
341       } else {
342         foreach $item (@taxaccounts) {
343           $taxaccounts{$item} +=
344             $taxamount * $form->{"${item}_rate"} / $taxrate;
345           $taxbase{$item} += $taxbase;
346         }
347       }
348
349       $netamount += $form->{"sellprice_$i"} * $form->{"qty_$i"};
350
351       $project_id = 'NULL';
352       if ($form->{"projectnumber_$i"}) {
353         $project_id = $form->{"projectnumber_$i"};
354       }
355       $reqdate =
356         ($form->{"reqdate_$i"}) ? qq|'$form->{"reqdate_$i"}'| : "NULL";
357
358       # get pricegroup_id and save ist
359       ($null, my $pricegroup_id) = split /--/, $form->{"sellprice_pg_$i"};
360       $pricegroup_id *= 1;
361       $subtotal = $form->{"subtotal_$i"} * 1;
362
363       # save detail record in orderitems table
364       $query = qq|INSERT INTO orderitems (|;
365       $query .= "id, " if $form->{"orderitems_id_$i"};
366       $query .= qq|trans_id, parts_id, description, longdescription, qty, base_qty, sellprice, discount,
367                    unit, reqdate, project_id, serialnumber, ship, pricegroup_id,
368                    ordnumber, transdate, cusordnumber, subtotal)
369                    VALUES (|;
370       $query .= qq|$form->{"orderitems_id_$i"},|
371         if $form->{"orderitems_id_$i"};
372       $query .= qq|$form->{id}, $form->{"id_$i"},
373                    '$form->{"description_$i"}', '$form->{"longdescription_$i"}', $form->{"qty_$i"}, $baseqty,
374                    $fxsellprice, $form->{"discount_$i"},
375                    '$form->{"unit_$i"}', $reqdate, (SELECT id from project where projectnumber = '$project_id'),
376                    '$form->{"serialnumber_$i"}', $form->{"ship_$i"}, '$pricegroup_id',
377                    '$form->{"ordnumber_$i"}', '$form->{"transdate_$i"}', '$form->{"cusordnumber_$i"}', '$subtotal')|;
378       $dbh->do($query) || $form->dberror($query);
379
380       $form->{"sellprice_$i"} = $fxsellprice;
381       $form->{"discount_$i"} *= 100;
382     }
383   }
384
385   # set values which could be empty
386   map { $form->{$_} *= 1 }
387     qw(vendor_id customer_id taxincluded closed quotation);
388
389   $reqdate = ($form->{reqdate}) ? qq|'$form->{reqdate}'| : "NULL";
390
391   # add up the tax
392   my $tax = 0;
393   map { $tax += $form->round_amount($taxaccounts{$_}, 2) } keys %taxaccounts;
394
395   $amount = $form->round_amount($netamount + $tax, 2);
396   $netamount = $form->round_amount($netamount, 2);
397
398   if ($form->{currency} eq $form->{defaultcurrency}) {
399     $form->{exchangerate} = 1;
400   } else {
401     $exchangerate =
402       $form->check_exchangerate($myconfig,
403                                 $form->{currency},
404                                 $form->{transdate},
405                                 ($form->{vc} eq 'customer') ? 'buy' : 'sell');
406   }
407
408   $form->{exchangerate} =
409     ($exchangerate)
410     ? $exchangerate
411     : $form->parse_amount($myconfig, $form->{exchangerate});
412
413   my $quotation;
414
415   # fill in subject if there is none
416   if ($form->{type} =~ /_order$/) {
417     $quotation = '0';
418     $form->{subject} = qq|$form->{label} $form->{ordnumber}|
419       unless $form->{subject};
420   } else {
421     $quotation = '1';
422     $form->{subject} = qq|$form->{label} $form->{quonumber}|
423       unless $form->{subject};
424   }
425
426   # if there is a message stuff it into the intnotes
427   my $cc  = "Cc: $form->{cc}\\r\n"   if $form->{cc};
428   my $bcc = "Bcc: $form->{bcc}\\r\n" if $form->{bcc};
429   my $now = scalar localtime;
430   $form->{intnotes} .= qq|\r
431 \r| if $form->{intnotes};
432
433   $form->{intnotes} .= qq|[email]\r
434 Date: $now
435 To: $form->{email}\r
436 $cc${bcc}Subject: $form->{subject}\r
437 \r
438 Message: $form->{message}\r| if $form->{message};
439
440   ($null, $form->{department_id}) = split(/--/, $form->{department});
441   $form->{department_id} *= 1;
442   $form->{payment_id} *= 1;
443   $form->{language_id} *= 1;
444   $form->{taxzone_id} *= 1;
445   $form->{proforma} *= 1;
446
447
448
449   # save OE record
450   $query = qq|UPDATE oe set
451               ordnumber = '$form->{ordnumber}',
452               quonumber = '$form->{quonumber}',
453               cusordnumber = '$form->{cusordnumber}',
454               transdate = '$form->{transdate}',
455               vendor_id = $form->{vendor_id},
456               customer_id = $form->{customer_id},
457               amount = $amount,
458               netamount = $netamount,
459               reqdate = $reqdate,
460               taxincluded = '$form->{taxincluded}',
461               shippingpoint = '$form->{shippingpoint}',
462               shipvia = '$form->{shipvia}',
463               notes = '$form->{notes}',
464               intnotes = '$form->{intnotes}',
465               curr = '$form->{currency}',
466               closed = '$form->{closed}',
467               delivered = '| . ($form->{delivered} ? "t" : "f") . qq|',
468               proforma = '$form->{proforma}',
469               quotation = '$quotation',
470               department_id = $form->{department_id},
471               language_id = $form->{language_id},
472               taxzone_id = $form->{taxzone_id},
473               shipto_id = $form->{shipto_id},
474               payment_id = $form->{payment_id},
475               delivery_vendor_id = $form->{delivery_vendor_id},
476               delivery_customer_id = $form->{delivery_customer_id},
477               employee_id = $form->{employee_id},
478               cp_id = | . conv_i($form->{cp_id}, 'NULL') . qq|
479               WHERE id = $form->{id}|;
480   $dbh->do($query) || $form->dberror($query);
481
482   $form->{ordtotal} = $amount;
483
484   if ($form->{webdav}) {
485     &webdav_folder($myconfig, $form);
486   }
487
488   # add shipto
489   $form->{name} = $form->{ $form->{vc} };
490   $form->{name} =~ s/--$form->{"$form->{vc}_id"}//;
491
492   if (!$form->{shipto_id}) {
493     $form->add_shipto($dbh, $form->{id}, "OE");
494   }
495
496   # save printed, emailed, queued
497   $form->save_status($dbh);
498
499   if (($form->{currency} ne $form->{defaultcurrency}) && !$exchangerate) {
500     if ($form->{vc} eq 'customer') {
501       $form->update_exchangerate($dbh, $form->{currency}, $form->{transdate},
502                                  $form->{exchangerate}, 0);
503     }
504     if ($form->{vc} eq 'vendor') {
505       $form->update_exchangerate($dbh, $form->{currency}, $form->{transdate},
506                                  0, $form->{exchangerate});
507     }
508   }
509
510   if ($form->{type} =~ /_order$/) {
511
512     # adjust onhand
513     &adj_onhand($dbh, $form, $ml * -1);
514     &adj_inventory($dbh, $myconfig, $form);
515   }
516
517   my $rc = $dbh->commit;
518   $dbh->disconnect;
519
520   $main::lxdebug->leave_sub();
521
522   return $rc;
523 }
524
525 # this function closes multiple orders given in $form->{ordnumber_#}.
526 # use this for multiple orders that don't have to be saved back
527 # single orders should use OE::save instead.
528 sub close_orders {
529   $main::lxdebug->enter_sub();
530
531   my ($self, $myconfig, $form) = @_;
532
533   # get ids from $form
534   map { push @ids, $form->{"ordnumber_$_"} if $form->{"ordnumber_$_"} }
535     (1 .. $form->{rowcount});
536
537   my $dbh = $form->dbconnect($myconfig);
538   $query = qq|UPDATE oe SET
539               closed = TRUE
540               WHERE ordnumber IN (|
541     . join(', ', map { $dbh->quote($_) } @ids) . qq|)|;
542   $dbh->do($query) || $form->dberror($query);
543   $dbh->disconnect;
544
545   $main::lxdebug->leave_sub();
546 }
547
548 sub close_order {
549   $main::lxdebug->enter_sub();
550
551   my ($self, $myconfig, $form) = @_;
552
553   $main::lxdebug->leave_sub() unless ($form->{"id"});
554
555   my $dbh = $form->dbconnect($myconfig);
556   do_query($form, $dbh, qq|UPDATE oe SET closed = TRUE where id = ?|,
557            $form->{"id"});
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,
712                 o.delivery_customer_id, o.delivery_vendor_id, o.proforma, o.shipto_id,
713                 o.delivered
714                 FROM oe o
715                 JOIN $form->{vc} cv ON (o.$form->{vc}_id = cv.id)
716                 LEFT JOIN employee e ON (o.employee_id = e.id)
717                 LEFT JOIN department d ON (o.department_id = d.id)
718                 |
719       . ($form->{id}
720          ? qq|WHERE o.id = $form->{id}|
721          : qq|WHERE o.id IN (| . join(', ', @ids) . qq|)|);
722
723     #$main::lxdebug->message(0, $query);
724
725     $sth = $dbh->prepare($query);
726     $sth->execute || $form->dberror($query);
727
728     $ref = $sth->fetchrow_hashref(NAME_lc);
729     map { $form->{$_} = $ref->{$_} } keys %$ref;
730
731
732
733     # set all entries for multiple ids blank that yield different information
734     while ($ref = $sth->fetchrow_hashref(NAME_lc)) {
735       map { $form->{$_} = '' if ($ref->{$_} ne $form->{$_}) } keys %$ref;
736     }
737
738     # if not given, fill transdate with current_date
739     $form->{transdate} = $form->current_date($myconfig)
740       unless $form->{transdate};
741
742     $sth->finish;
743
744     if ($form->{delivery_customer_id}) {
745       $query = qq|SELECT name FROM customer WHERE id=$form->{delivery_customer_id}|;
746       $sth = $dbh->prepare($query);
747       $sth->execute || $form->dberror($query);
748       ($form->{delivery_customer_string}) = $sth->fetchrow_array();
749       $sth->finish;
750     }
751
752     if ($form->{delivery_vendor_id}) {
753       $query = qq|SELECT name FROM customer WHERE id=$form->{delivery_vendor_id}|;
754       $sth = $dbh->prepare($query);
755       $sth->execute || $form->dberror($query);
756       ($form->{delivery_vendor_string}) = $sth->fetchrow_array();
757       $sth->finish;
758     }
759
760     # shipto and pinted/mailed/queued status makes only sense for single id retrieve
761     if (!@ids) {
762       $query = qq|SELECT s.* FROM shipto s
763                   WHERE s.trans_id = $form->{id} AND s.module = 'OE'|;
764       $sth = $dbh->prepare($query);
765       $sth->execute || $form->dberror($query);
766
767       $ref = $sth->fetchrow_hashref(NAME_lc);
768       delete($ref->{id});
769       map { $form->{$_} = $ref->{$_} } keys %$ref;
770       $sth->finish;
771
772       # get printed, emailed and queued
773       $query = qq|SELECT s.printed, s.emailed, s.spoolfile, s.formname
774                   FROM status s
775                   WHERE s.trans_id = $form->{id}|;
776       $sth = $dbh->prepare($query);
777       $sth->execute || $form->dberror($query);
778
779       while ($ref = $sth->fetchrow_hashref(NAME_lc)) {
780         $form->{printed} .= "$ref->{formname} " if $ref->{printed};
781         $form->{emailed} .= "$ref->{formname} " if $ref->{emailed};
782         $form->{queued} .= "$ref->{formname} $ref->{spoolfile} "
783           if $ref->{spoolfile};
784       }
785       $sth->finish;
786       map { $form->{$_} =~ s/ +$//g } qw(printed emailed queued);
787     }    # if !@ids
788
789     my %oid = ('Pg'     => 'oid',
790                'Oracle' => 'rowid');
791
792     my $transdate =
793       $form->{transdate} ? $dbh->quote($form->{transdate}) : "current_date";
794
795     if(!$form->{taxzone_id}) {
796       $form->{taxzone_id} = 0;
797     }
798     # retrieve individual items
799     # this query looks up all information about the items
800     # stuff different from the whole will not be overwritten, but saved with a suffix.
801     $query = qq|SELECT o.id AS orderitems_id,
802                 c1.accno AS inventory_accno, c1.new_chart_id AS inventory_new_chart, date($transdate) - c1.valid_from as inventory_valid,
803                 c2.accno AS income_accno, c2.new_chart_id AS income_new_chart, date($transdate)  - c2.valid_from as income_valid,
804                 c3.accno AS expense_accno, c3.new_chart_id AS expense_new_chart, date($transdate) - c3.valid_from as expense_valid,
805                 oe.ordnumber AS ordnumber_oe, oe.transdate AS transdate_oe, oe.cusordnumber AS cusordnumber_oe, 
806                 p.partnumber, p.assembly, o.description, o.qty,
807                 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,
808                 o.reqdate, o.project_id, o.serialnumber, o.ship,
809                 o.ordnumber, o.transdate, o.cusordnumber, o.subtotal, o.longdescription,
810                 pr.projectnumber, p.formel,
811                 pg.partsgroup, o.pricegroup_id, (SELECT pricegroup FROM pricegroup WHERE id=o.pricegroup_id) as pricegroup
812                 FROM orderitems o
813                 JOIN parts p ON (o.parts_id = p.id)
814                 JOIN oe ON (o.trans_id = oe.id)
815                 LEFT JOIN chart c1 ON ((select inventory_accno_id from buchungsgruppen where id=p.buchungsgruppen_id) = c1.id)
816                 LEFT JOIN chart c2 ON ((select income_accno_id_$form->{taxzone_id} from buchungsgruppen where id=p.buchungsgruppen_id) = c2.id)
817                 LEFT JOIN chart c3 ON ((select expense_accno_id_$form->{taxzone_id} from buchungsgruppen where id=p.buchungsgruppen_id) = c3.id)
818                 LEFT JOIN project pr ON (o.project_id = pr.id)
819                 LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
820                 |
821       . ($form->{id}
822          ? qq|WHERE o.trans_id = $form->{id}|
823          : qq|WHERE o.trans_id IN (| . join(", ", @ids) . qq|)|)
824       . qq|
825                 ORDER BY o.$oid{$myconfig->{dbdriver}}|;
826
827     $sth = $dbh->prepare($query);
828     $sth->execute || $form->dberror($query);
829
830     while ($ref = $sth->fetchrow_hashref(NAME_lc)) {
831       if (!$ref->{"part_inventory_accno_id"}) {
832         map({ delete($ref->{$_}); } qw(inventory_accno inventory_new_chart inventory_valid));
833       }
834       delete($ref->{"part_inventory_accno_id"});
835
836       # in collective order, copy global ordnumber, transdate, cusordnumber into item scope
837       #   unless already present there
838       # remove _oe entries afterwards
839       map { $ref->{$_} = $ref->{"${_}_oe"} if ($ref->{$_} eq '') }
840         qw|ordnumber transdate cusordnumber|
841         if (@ids);
842       map { delete $ref->{$_} } qw|ordnumber_oe transdate_oe cusordnumber_oe|;
843
844
845
846     while ($ref->{inventory_new_chart} && ($ref->{inventory_valid} >=0)) {
847       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}|;
848       my $stw = $dbh->prepare($query);
849       $stw->execute || $form->dberror($query);
850       ($ref->{inventory_accno}, $ref->{inventory_new_chart}, $ref->{inventory_valid}) = $stw->fetchrow_array;
851       $stw->finish;
852     }
853
854     while ($ref->{income_new_chart} && ($ref->{income_valid} >=0)) {
855       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}|;
856       my $stw = $dbh->prepare($query);
857       $stw->execute || $form->dberror($query);
858       ($ref->{income_accno}, $ref->{income_new_chart}, $ref->{income_valid}) = $stw->fetchrow_array;
859       $stw->finish;
860     }
861
862     while ($ref->{expense_new_chart} && ($ref->{expense_valid} >=0)) {
863       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}|;
864       my $stw = $dbh->prepare($query);
865       $stw->execute || $form->dberror($query);
866       ($ref->{expense_accno}, $ref->{expense_new_chart}, $ref->{expense_valid}) = $stw->fetchrow_array;
867       $stw->finish;
868     }
869
870       # delete orderitems_id in collective orders, so that they get cloned no matter what
871       delete $ref->{orderitems_id} if (@ids);
872
873       # get tax rates and description
874       $accno_id =
875         ($form->{vc} eq "customer") ? $ref->{income_accno} : $ref->{expense_accno};
876       $query = qq|SELECT c.accno, t.taxdescription, t.rate, t.taxnumber
877               FROM tax t LEFT JOIN chart c on (c.id=t.chart_id)
878               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)
879               ORDER BY c.accno|;
880       $stw = $dbh->prepare($query);
881       $stw->execute || $form->dberror($query);
882       $ref->{taxaccounts} = "";
883       my $i = 0;
884       while ($ptr = $stw->fetchrow_hashref(NAME_lc)) {
885
886         #    if ($customertax{$ref->{accno}}) {
887         if (($ptr->{accno} eq "") && ($ptr->{rate} == 0)) {
888           $i++;
889           $ptr->{accno} = $i;
890         }
891         $ref->{taxaccounts} .= "$ptr->{accno} ";
892         if (!($form->{taxaccounts} =~ /$ptr->{accno}/)) {
893           $form->{"$ptr->{accno}_rate"}        = $ptr->{rate};
894           $form->{"$ptr->{accno}_description"} = $ptr->{taxdescription};
895           $form->{"$ptr->{accno}_taxnumber"}   = $ptr->{taxnumber};
896           $form->{taxaccounts} .= "$ptr->{accno} ";
897         }
898
899       }
900
901       chop $ref->{taxaccounts};
902       push @{ $form->{form_details} }, $ref;
903       $stw->finish;
904     }
905     $sth->finish;
906
907   } else {
908
909     # get last name used
910     $form->lastname_used($dbh, $myconfig, $form->{vc})
911       unless $form->{"$form->{vc}_id"};
912
913   }
914
915   $form->{exchangerate} =
916     $form->get_exchangerate($dbh, $form->{currency}, $form->{transdate},
917                             ($form->{vc} eq 'customer') ? "buy" : "sell");
918
919   if ($form->{webdav}) {
920     &webdav_folder($myconfig, $form);
921   }
922
923   # get tax zones
924   $query = qq|SELECT id, description
925               FROM tax_zones|;
926   $sth = $dbh->prepare($query);
927   $sth->execute || $form->dberror($query);
928
929
930   while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
931     push @{ $form->{TAXZONE} }, $ref;
932   }
933   $sth->finish;
934
935
936   my $rc = $dbh->commit;
937   $dbh->disconnect;
938
939   $main::lxdebug->leave_sub();
940
941   return $rc;
942 }
943
944 sub order_details {
945   $main::lxdebug->enter_sub();
946
947   my ($self, $myconfig, $form) = @_;
948
949   # connect to database
950   my $dbh = $form->dbconnect($myconfig);
951   my $query;
952   my $sth;
953   my $nodiscount;
954   my $yesdiscount;
955   my $nodiscount_subtotal = 0;
956   my $discount_subtotal = 0;
957   my $item;
958   my $i;
959   my @partsgroup = ();
960   my $partsgroup;
961   my $position = 0;
962   my $subtotal_header = 0;
963   my $subposition = 0;
964
965   my %oid = ('Pg'     => 'oid',
966              'Oracle' => 'rowid');
967
968   # sort items by partsgroup
969   for $i (1 .. $form->{rowcount}) {
970     $partsgroup = "";
971     if ($form->{"partsgroup_$i"} && $form->{groupitems}) {
972       $partsgroup = $form->{"partsgroup_$i"};
973     }
974     push @partsgroup, [$i, $partsgroup];
975   }
976
977   # if there is a warehouse limit picking
978   if ($form->{warehouse_id} && $form->{formname} =~ /(pick|packing)_list/) {
979
980     # run query to check for inventory
981     $query = qq|SELECT sum(i.qty) AS qty
982                 FROM inventory i
983                 WHERE i.parts_id = ?
984                 AND i.warehouse_id = ?|;
985     $sth = $dbh->prepare($query) || $form->dberror($query);
986
987     for $i (1 .. $form->{rowcount}) {
988       $sth->execute($form->{"id_$i"}, $form->{warehouse_id}) || $form->dberror;
989
990       ($qty) = $sth->fetchrow_array;
991       $sth->finish;
992
993       $form->{"qty_$i"} = 0 if $qty == 0;
994
995       if ($form->parse_amount($myconfig, $form->{"ship_$i"}) > $qty) {
996         $form->{"ship_$i"} = $form->format_amount($myconfig, $qty);
997       }
998     }
999   }
1000
1001   my $sameitem = "";
1002   foreach $item (sort { $a->[1] cmp $b->[1] } @partsgroup) {
1003     $i = $item->[0];
1004
1005     if ($item->[1] ne $sameitem) {
1006       push(@{ $form->{description} }, qq|$item->[1]|);
1007       $sameitem = $item->[1];
1008
1009       map { push(@{ $form->{$_} }, "") }
1010         qw(runningnumber number qty ship unit bin partnotes
1011            serialnumber reqdate sellprice listprice netprice
1012            discount p_discount linetotal);
1013     }
1014
1015     $form->{"qty_$i"} = $form->parse_amount($myconfig, $form->{"qty_$i"});
1016
1017     if ($form->{"id_$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 
1173                  reqdate sellprice listprice netprice discount p_discount
1174                  linetotal nodiscount_linetotal);
1175             $sameitem = ($ref->{partsgroup}) ? $ref->{partsgroup} : "--";
1176             push(@{ $form->{description} }, $sameitem);
1177           }
1178
1179           push(@{ $form->{description} },
1180                $form->format_amount($myconfig, $ref->{qty} * $form->{"qty_$i"}
1181                  )
1182                  . qq|, $ref->{partnumber}, $ref->{description}|);
1183
1184           map { push(@{ $form->{$_} }, "") }
1185             qw(number unit qty runningnumber ship bin serialnumber reqdate 
1186                sellprice listprice netprice discount p_discount linetotal 
1187                nodiscount_linetotal);
1188
1189         }
1190         $sth->finish;
1191       }
1192
1193     }
1194   }
1195
1196   my $tax = 0;
1197   foreach $item (sort keys %taxaccounts) {
1198       push(@{ $form->{taxbase} },
1199            $form->format_amount($myconfig, $taxbase{$item}, 2));
1200
1201       $tax += $taxamount = $form->round_amount($taxaccounts{$item}, 2);
1202
1203       push(@{ $form->{tax} }, $form->format_amount($myconfig, $taxamount, 2));
1204       push(@{ $form->{taxdescription} }, $form->{"${item}_description"});
1205       push(@{ $form->{taxrate} },
1206            $form->format_amount($myconfig, $form->{"${item}_rate"} * 100));
1207       push(@{ $form->{taxnumber} }, $form->{"${item}_taxnumber"});
1208   }
1209   $form->{subtotal} = $form->format_amount($myconfig, $form->{total}, 2);
1210   $yesdiscount = $form->{nodiscount_total} - $nodiscount;
1211   $form->{nodiscount_subtotal} = $form->format_amount($myconfig, $form->{nodiscount_total}, 2);
1212   $form->{discount_total} = $form->format_amount($myconfig, $form->{discount_total}, 2);
1213   $form->{nodiscount} = $form->format_amount($myconfig, $nodiscount, 2);
1214   $form->{yesdiscount} = $form->format_amount($myconfig, $yesdiscount, 2);
1215
1216   $form->{subtotal} = $form->format_amount($myconfig, $form->{ordtotal}, 2);
1217   $form->{ordtotal} =
1218     ($form->{taxincluded}) ? $form->{ordtotal} : $form->{ordtotal} + $tax;
1219
1220   # format amounts
1221   $form->{quototal} = $form->{ordtotal} =
1222     $form->format_amount($myconfig, $form->{ordtotal}, 2);
1223
1224   if ($form->{type} =~ /_quotation/) {
1225     $form->set_payment_options($myconfig, $form->{quodate});
1226   } else {
1227     $form->set_payment_options($myconfig, $form->{orddate});
1228   }
1229
1230   # myconfig variables
1231   map { $form->{$_} = $myconfig->{$_} }
1232     (qw(company address tel fax signature businessnumber));
1233   $form->{username} = $myconfig->{name};
1234
1235   $dbh->disconnect;
1236
1237   $main::lxdebug->leave_sub();
1238 }
1239
1240 sub project_description {
1241   $main::lxdebug->enter_sub();
1242
1243   my ($self, $dbh, $id) = @_;
1244
1245   my $query = qq|SELECT p.description
1246                  FROM project p
1247                  WHERE p.id = $id|;
1248   my $sth = $dbh->prepare($query);
1249   $sth->execute || $form->dberror($query);
1250
1251   ($_) = $sth->fetchrow_array;
1252
1253   $sth->finish;
1254
1255   $main::lxdebug->leave_sub();
1256
1257   return $_;
1258 }
1259
1260 sub get_warehouses {
1261   $main::lxdebug->enter_sub();
1262
1263   my ($self, $myconfig, $form) = @_;
1264
1265   my $dbh = $form->dbconnect($myconfig);
1266
1267   # setup warehouses
1268   my $query = qq|SELECT id, description
1269                  FROM warehouse|;
1270
1271   my $sth = $dbh->prepare($query);
1272   $sth->execute || $form->dberror($query);
1273
1274   while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
1275     push @{ $form->{all_warehouses} }, $ref;
1276   }
1277   $sth->finish;
1278
1279   $dbh->disconnect;
1280
1281   $main::lxdebug->leave_sub();
1282 }
1283
1284 sub save_inventory {
1285   $main::lxdebug->enter_sub();
1286
1287   my ($self, $myconfig, $form) = @_;
1288
1289   my ($null, $warehouse_id) = split /--/, $form->{warehouse};
1290   $warehouse_id *= 1;
1291
1292   my $employee_id;
1293   ($null, $employee_id) = split /--/, $form->{employee};
1294
1295   my $ml = ($form->{type} eq 'ship_order') ? -1 : 1;
1296
1297   my $dbh = $form->dbconnect_noauto($myconfig);
1298   my $sth;
1299   my $wth;
1300   my $serialnumber;
1301   my $ship;
1302
1303   $query = qq|SELECT o.serialnumber, o.ship
1304               FROM orderitems o
1305               WHERE o.trans_id = ?
1306               AND o.id = ?
1307               FOR UPDATE|;
1308   $sth = $dbh->prepare($query) || $form->dberror($query);
1309
1310   $query = qq|SELECT sum(i.qty)
1311               FROM inventory i
1312               WHERE i.parts_id = ?
1313               AND i.warehouse_id = ?|;
1314   $wth = $dbh->prepare($query) || $form->dberror($query);
1315
1316   for my $i (1 .. $form->{rowcount} - 1) {
1317
1318     $ship =
1319       (abs($form->{"ship_$i"}) > abs($form->{"qty_$i"}))
1320       ? $form->{"qty_$i"}
1321       : $form->{"ship_$i"};
1322
1323     if ($warehouse_id && $form->{type} eq 'ship_order') {
1324
1325       $wth->execute($form->{"id_$i"}, $warehouse_id) || $form->dberror;
1326
1327       ($qty) = $wth->fetchrow_array;
1328       $wth->finish;
1329
1330       if ($ship > $qty) {
1331         $ship = $qty;
1332       }
1333     }
1334
1335     if ($ship != 0) {
1336
1337       $ship *= $ml;
1338       $query = qq|INSERT INTO inventory (parts_id, warehouse_id,
1339                   qty, oe_id, orderitems_id, shippingdate, employee_id)
1340                   VALUES ($form->{"id_$i"}, $warehouse_id,
1341                   $ship, $form->{"id"},
1342                   $form->{"orderitems_id_$i"}, '$form->{shippingdate}',
1343                   $employee_id)|;
1344       $dbh->do($query) || $form->dberror($query);
1345
1346       # add serialnumber, ship to orderitems
1347       $sth->execute($form->{id}, $form->{"orderitems_id_$i"})
1348         || $form->dberror;
1349       ($serialnumber, $ship) = $sth->fetchrow_array;
1350       $sth->finish;
1351
1352       $serialnumber .= " " if $serialnumber;
1353       $serialnumber .= qq|$form->{"serialnumber_$i"}|;
1354       $ship += $form->{"ship_$i"};
1355
1356       $query = qq|UPDATE orderitems SET
1357                   serialnumber = '$serialnumber',
1358                   ship = $ship
1359                   WHERE trans_id = $form->{id}
1360                   AND id = $form->{"orderitems_id_$i"}|;
1361       $dbh->do($query) || $form->dberror($query);
1362
1363       # update order with ship via
1364       $query = qq|UPDATE oe SET
1365                   shippingpoint = '$form->{shippingpoint}',
1366                   shipvia = '$form->{shipvia}'
1367                   WHERE id = $form->{id}|;
1368       $dbh->do($query) || $form->dberror($query);
1369
1370       # update onhand for parts
1371       $form->update_balance($dbh, "parts", "onhand",
1372                             qq|id = $form->{"id_$i"}|,
1373                             $form->{"ship_$i"} * $ml);
1374
1375     }
1376   }
1377
1378   my $rc = $dbh->commit;
1379   $dbh->disconnect;
1380
1381   $main::lxdebug->leave_sub();
1382
1383   return $rc;
1384 }
1385
1386 sub adj_onhand {
1387   $main::lxdebug->enter_sub();
1388
1389   my ($dbh, $form, $ml) = @_;
1390
1391   my $service_units = $form->{service_units};
1392   my $part_units = $form->{part_units};
1393
1394   my $query = qq|SELECT oi.parts_id, oi.ship, oi.unit, p.inventory_accno_id, p.assembly
1395                  FROM orderitems oi
1396                  JOIN parts p ON (p.id = oi.parts_id)
1397                  WHERE oi.trans_id = $form->{id}|;
1398   my $sth = $dbh->prepare($query);
1399   $sth->execute || $form->dberror($query);
1400
1401   $query = qq|SELECT sum(p.inventory_accno_id)
1402               FROM parts p
1403               JOIN assembly a ON (a.parts_id = p.id)
1404               WHERE a.id = ?|;
1405   my $ath = $dbh->prepare($query) || $form->dberror($query);
1406
1407   my $ispa;
1408
1409   while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
1410   #print(STDERR "Bin in Schleife $ref->{inventory_accno_id}\n");
1411
1412     if ($ref->{inventory_accno_id} || $ref->{assembly}) {
1413
1414       # do not update if assembly consists of all services
1415       if ($ref->{assembly}) {
1416         $ath->execute($ref->{parts_id}) || $form->dberror($query);
1417
1418         ($ispa) = $sth->fetchrow_array;
1419         $ath->finish;
1420
1421         next unless $ispa;
1422
1423       }
1424
1425       # get item baseunit
1426       $query = qq|SELECT p.unit
1427                   FROM parts p
1428                   WHERE p.id = $ref->{parts_id}|;
1429       my $stw = $dbh->prepare($query);
1430       $stw->execute || $form->dberror($query);
1431
1432       my ($item_unit) = $stw->fetchrow_array();
1433       $stw->finish;
1434
1435       if ($ref->{inventory_accno_id}) {        
1436         if (defined($part_units->{$item_unit}->{factor}) && $part_units->{$item_unit}->{factor} ne '' && $part_units->{$item_unit}->{factor} ne '0') {
1437           $basefactor = $part_units->{$ref->{unit}}->{factor} / $part_units->{$item_unit}->{factor};
1438         } else {
1439           $basefactor = 1;
1440         }
1441         $baseqty = $ref->{ship} * $basefactor;
1442       } else {
1443         if (defined($service_units->{$item_unit}->{factor}) && $service_units->{$item_unit}->{factor} ne '' && $service_units->{$item_unit}->{factor} ne '0') {
1444           $basefactor = $service_units->{$ref->{unit}}->{factor} / $part_units->{$item_unit}->{factor};
1445         } else {
1446           $basefactor = 1;
1447         }
1448         $baseqty = $ref->{ship} * $basefactor;
1449       }  
1450       #print(STDERR "$baseqty Basismenge\n");
1451
1452       # adjust onhand in parts table
1453       $form->update_balance($dbh, "parts", "onhand",
1454                             qq|id = $ref->{parts_id}|,
1455                             $baseqty * $ml);
1456     }
1457   }
1458
1459   $sth->finish;
1460
1461   $main::lxdebug->leave_sub();
1462 }
1463
1464 sub adj_inventory {
1465   $main::lxdebug->enter_sub();
1466
1467   my ($dbh, $myconfig, $form) = @_;
1468
1469   my %oid = ('Pg'     => 'oid',
1470              'Oracle' => 'rowid');
1471
1472   # increase/reduce qty in inventory table
1473   my $query = qq|SELECT oi.id, oi.parts_id, oi.ship
1474                  FROM orderitems oi
1475                  WHERE oi.trans_id = $form->{id}|;
1476   my $sth = $dbh->prepare($query);
1477   $sth->execute || $form->dberror($query);
1478
1479   $query = qq|SELECT $oid{$myconfig->{dbdriver}} AS oid, qty,
1480                      (SELECT SUM(qty) FROM inventory
1481                       WHERE oe_id = $form->{id}
1482                       AND orderitems_id = ?) AS total
1483               FROM inventory
1484               WHERE oe_id = $form->{id}
1485               AND orderitems_id = ?|;
1486   my $ith = $dbh->prepare($query) || $form->dberror($query);
1487
1488   my $qty;
1489   my $ml = ($form->{type} =~ /(ship|sales)_order/) ? -1 : 1;
1490
1491   while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
1492
1493     $ith->execute($ref->{id}, $ref->{id}) || $form->dberror($query);
1494
1495     while (my $inv = $ith->fetchrow_hashref(NAME_lc)) {
1496
1497       if (($qty = (($inv->{total} * $ml) - $ref->{ship})) >= 0) {
1498         $qty = $inv->{qty} if ($qty > ($inv->{qty} * $ml));
1499
1500         $form->update_balance($dbh, "inventory", "qty",
1501                               qq|$oid{$myconfig->{dbdriver}} = $inv->{oid}|,
1502                               $qty * -1 * $ml);
1503       }
1504     }
1505     $ith->finish;
1506
1507   }
1508   $sth->finish;
1509
1510   # delete inventory entries if qty = 0
1511   $query = qq|DELETE FROM inventory
1512               WHERE oe_id = $form->{id}
1513               AND qty = 0|;
1514   $dbh->do($query) || $form->dberror($query);
1515
1516   $main::lxdebug->leave_sub();
1517 }
1518
1519 sub get_inventory {
1520   $main::lxdebug->enter_sub();
1521
1522   my ($self, $myconfig, $form) = @_;
1523
1524   my ($null, $warehouse_id) = split /--/, $form->{warehouse};
1525   $warehouse_id *= 1;
1526
1527   my $dbh = $form->dbconnect($myconfig);
1528
1529   my $query = qq|SELECT p.id, p.partnumber, p.description, p.onhand,
1530                  pg.partsgroup
1531                  FROM parts p
1532                  LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
1533                  WHERE p.onhand > 0|;
1534
1535   if ($form->{partnumber}) {
1536     $var = $form->like(lc $form->{partnumber});
1537     $query .= "
1538                  AND lower(p.partnumber) LIKE '$var'";
1539   }
1540   if ($form->{description}) {
1541     $var = $form->like(lc $form->{description});
1542     $query .= "
1543                  AND lower(p.description) LIKE '$var'";
1544   }
1545   if ($form->{partsgroup}) {
1546     $var = $form->like(lc $form->{partsgroup});
1547     $query .= "
1548                  AND lower(pg.partsgroup) LIKE '$var'";
1549   }
1550
1551   $sth = $dbh->prepare($query);
1552   $sth->execute || $form->dberror($query);
1553
1554   $query = qq|SELECT sum(i.qty), w.description, w.id
1555               FROM inventory i
1556               LEFT JOIN warehouse w ON (w.id = i.warehouse_id)
1557               WHERE i.parts_id = ?
1558               AND NOT i.warehouse_id = $warehouse_id
1559               GROUP BY w.description, w.id|;
1560   $wth = $dbh->prepare($query) || $form->dberror($query);
1561
1562   while ($ref = $sth->fetchrow_hashref(NAME_lc)) {
1563
1564     $wth->execute($ref->{id}) || $form->dberror;
1565
1566     while (($qty, $warehouse, $warehouse_id) = $wth->fetchrow_array) {
1567       push @{ $form->{all_inventory} },
1568         { 'id'           => $ref->{id},
1569           'partnumber'   => $ref->{partnumber},
1570           'description'  => $ref->{description},
1571           'partsgroup'   => $ref->{partsgroup},
1572           'qty'          => $qty,
1573           'warehouse_id' => $warehouse_id,
1574           'warehouse'    => $warehouse }
1575         if $qty > 0;
1576     }
1577     $wth->finish;
1578   }
1579   $sth->finish;
1580
1581   $dbh->disconnect;
1582
1583   # sort inventory
1584   @{ $form->{all_inventory} } =
1585     sort { $a->{ $form->{sort} } cmp $b->{ $form->{sort} } }
1586     @{ $form->{all_inventory} };
1587
1588   $main::lxdebug->leave_sub();
1589
1590   return @{ $form->{all_inventory} };
1591 }
1592
1593 sub transfer {
1594   $main::lxdebug->enter_sub();
1595
1596   my ($self, $myconfig, $form) = @_;
1597
1598   my $dbh = $form->dbconnect_noauto($myconfig);
1599
1600   my $query = qq|INSERT INTO inventory
1601                  (warehouse_id, parts_id, qty, shippingdate, employee_id)
1602                  VALUES (?, ?, ?, ?, ?)|;
1603   $sth = $dbh->prepare($query) || $form->dberror($query);
1604
1605   $form->get_employee($dbh);
1606
1607   my @a = localtime;
1608   $a[5] += 1900;
1609   $a[4]++;
1610   $shippingdate = "$a[5]-$a[4]-$a[3]";
1611
1612   for my $i (1 .. $form->{rowcount}) {
1613     $qty = $form->parse_amount($myconfig, $form->{"transfer_$i"});
1614
1615     $qty = $form->{"qty_$i"} if ($qty > $form->{"qty_$i"});
1616
1617     if ($qty) {
1618
1619       # to warehouse
1620       $sth->execute($form->{warehouse_id}, $form->{"id_$i"}, $qty,
1621                     $shippingdate, $form->{employee_id})
1622         || $form->dberror;
1623
1624       $sth->finish;
1625
1626       # from warehouse
1627       $sth->execute($form->{"warehouse_id_$i"},
1628                     $form->{"id_$i"}, $qty * -1, $shippingdate,
1629                     $form->{employee_id})
1630         || $form->dberror;
1631
1632       $sth->finish;
1633     }
1634   }
1635
1636   my $rc = $dbh->commit;
1637   $dbh->disconnect;
1638
1639   $main::lxdebug->leave_sub();
1640
1641   return $rc;
1642 }
1643
1644 sub webdav_folder {
1645   $main::lxdebug->enter_sub();
1646
1647   my ($myconfig, $form) = @_;
1648
1649 SWITCH: {
1650     $path = "webdav/angebote/" . $form->{quonumber}, last SWITCH
1651       if ($form->{type} eq "sales_quotation");
1652     $path = "webdav/bestellungen/" . $form->{ordnumber}, last SWITCH
1653       if ($form->{type} eq "sales_order");
1654     $path = "webdav/anfragen/" . $form->{quonumber}, last SWITCH
1655       if ($form->{type} eq "request_quotation");
1656     $path = "webdav/lieferantenbestellungen/" . $form->{ordnumber}, last SWITCH
1657       if ($form->{type} eq "purchase_order");
1658   }
1659
1660   if (!-d $path) {
1661     mkdir($path, 0770) or die "can't make directory $!\n";
1662   } else {
1663     if ($form->{id}) {
1664       @files = <$path/*>;
1665       foreach $file (@files) {
1666         $file =~ /\/([^\/]*)$/;
1667         $fname = $1;
1668         $ENV{'SCRIPT_NAME'} =~ /\/([^\/]*)\//;
1669         $lxerp = $1;
1670         $link  = "http://" . $ENV{'SERVER_NAME'} . "/" . $lxerp . "/" . $file;
1671         $form->{WEBDAV}{$fname} = $link;
1672       }
1673     }
1674   }
1675
1676   $main::lxdebug->leave_sub();
1677 }
1678 1;
1679