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