Whitespace an den Zeilenenden entfernt.
[kivitendo-erp.git] / SL / IC.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) 2001
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 # Inventory Control backend
32 #
33 #======================================================================
34
35 package IC;
36
37 sub get_part {
38   $main::lxdebug->enter_sub();
39
40   my ($self, $myconfig, $form) = @_;
41
42   # connect to db
43   my $dbh = $form->dbconnect($myconfig);
44
45   my $query = qq|SELECT p.*,
46                  c1.accno AS inventory_accno,
47                  c2.accno AS income_accno,
48                  c3.accno AS expense_accno,
49                  pg.partsgroup
50                  FROM parts p
51                  LEFT JOIN chart c1 ON (p.inventory_accno_id = c1.id)
52                  LEFT JOIN chart c2 ON (p.income_accno_id = c2.id)
53                  LEFT JOIN chart c3 ON (p.expense_accno_id = c3.id)
54                  LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
55                  WHERE p.id = $form->{id}|;
56   my $sth = $dbh->prepare($query);
57   $sth->execute || $form->dberror($query);
58   my $ref = $sth->fetchrow_hashref(NAME_lc);
59
60   # copy to $form variables
61   map { $form->{$_} = $ref->{$_} } (keys %{$ref});
62
63   $sth->finish;
64
65   my %oid = ('Pg'     => 'a.oid',
66              'Oracle' => 'a.rowid');
67
68   # part or service item
69   $form->{item} = ($form->{inventory_accno}) ? 'part' : 'service';
70   if ($form->{assembly}) {
71     $form->{item} = 'assembly';
72
73     # retrieve assembly items
74     $query = qq|SELECT p.id, p.partnumber, p.description,
75                 p.sellprice, p.weight, a.qty, a.bom, p.unit,
76                 pg.partsgroup
77                 FROM parts p
78                 JOIN assembly a ON (a.parts_id = p.id)
79                 LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
80                 WHERE a.id = $form->{id}
81                 ORDER BY $oid{$myconfig->{dbdriver}}|;
82
83     $sth = $dbh->prepare($query);
84     $sth->execute || $form->dberror($query);
85
86     $form->{assembly_rows} = 0;
87     while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
88       $form->{assembly_rows}++;
89       foreach my $key (keys %{$ref}) {
90         $form->{"${key}_$form->{assembly_rows}"} = $ref->{$key};
91       }
92     }
93     $sth->finish;
94
95   }
96
97   # setup accno hash for <option checked> {amount} is used in create_links
98   $form->{amount}{IC}         = $form->{inventory_accno};
99   $form->{amount}{IC_income}  = $form->{income_accno};
100   $form->{amount}{IC_sale}    = $form->{income_accno};
101   $form->{amount}{IC_expense} = $form->{expense_accno};
102   $form->{amount}{IC_cogs}    = $form->{expense_accno};
103
104   unless ($form->{item} eq 'service') {
105
106     # get makes
107     if ($form->{makemodel}) {
108       $query = qq|SELECT m.make, m.model FROM makemodel m
109                   WHERE m.parts_id = $form->{id}|;
110
111       $sth = $dbh->prepare($query);
112       $sth->execute || $form->dberror($query);
113
114       my $i = 1;
115       while (($form->{"make_$i"}, $form->{"model_$i"}) = $sth->fetchrow_array)
116       {
117         $i++;
118       }
119       $sth->finish;
120       $form->{makemodel_rows} = $i - 1;
121
122     }
123   }
124
125   # now get accno for taxes
126   $query = qq|SELECT c.accno
127               FROM chart c, partstax pt
128               WHERE pt.chart_id = c.id
129               AND pt.parts_id = $form->{id}|;
130
131   $sth = $dbh->prepare($query);
132   $sth->execute || $form->dberror($query);
133
134   while (($key) = $sth->fetchrow_array) {
135     $form->{amount}{$key} = $key;
136   }
137
138   $sth->finish;
139
140   # is it an orphan
141   $query = qq|SELECT i.parts_id
142               FROM invoice i
143               WHERE i.parts_id = $form->{id}
144             UNION
145               SELECT o.parts_id
146               FROM orderitems o
147               WHERE o.parts_id = $form->{id}
148             UNION
149               SELECT a.parts_id
150               FROM assembly a
151               WHERE a.parts_id = $form->{id}|;
152   $sth = $dbh->prepare($query);
153   $sth->execute || $form->dberror($query);
154
155   ($form->{orphaned}) = $sth->fetchrow_array;
156   $form->{orphaned} = !$form->{orphaned};
157   $sth->finish;
158
159   $dbh->disconnect;
160
161   $main::lxdebug->leave_sub();
162 }
163
164 sub save {
165   $main::lxdebug->enter_sub();
166
167   my ($self, $myconfig, $form) = @_;
168
169   if ($form->{eur} && ($form->{item} ne 'service')) {
170     $form->{IC} = $form->{IC_expense};
171   }
172
173   ($form->{inventory_accno}) = split(/--/, $form->{IC});
174   ($form->{expense_accno})   = split(/--/, $form->{IC_expense});
175   ($form->{income_accno})    = split(/--/, $form->{IC_income});
176
177   # connect to database, turn off AutoCommit
178   my $dbh = $form->dbconnect_noauto($myconfig);
179
180   # save the part
181   # make up a unique handle and store in partnumber field
182   # then retrieve the record based on the unique handle to get the id
183   # replace the partnumber field with the actual variable
184   # add records for makemodel
185
186   # if there is a $form->{id} then replace the old entry
187   # delete all makemodel entries and add the new ones
188
189   # escape '
190   map { $form->{$_} =~ s/\'/\'\'/g } qw(partnumber description notes unit);
191
192   # undo amount formatting
193   map { $form->{$_} = $form->parse_amount($myconfig, $form->{$_}) }
194     qw(rop weight listprice sellprice gv lastcost stock);
195
196   # set date to NULL if nothing entered
197   $form->{priceupdate} =
198     ($form->{priceupdate}) ? qq|'$form->{priceupdate}'| : "NULL";
199
200   $form->{makemodel} = (($form->{make_1}) || ($form->{model_1})) ? 1 : 0;
201
202   $form->{alternate} = 0;
203   $form->{assembly} = ($form->{item} eq 'assembly') ? 1 : 0;
204   $form->{obsolete} *= 1;
205   $form->{shop}     *= 1;
206   $form->{onhand}   *= 1;
207   $form->{ve}       *= 1;
208   $form->{ge}       *= 1;
209
210   my ($query, $sth);
211
212   if ($form->{id}) {
213
214     # get old price
215     $query = qq|SELECT p.sellprice, p.weight
216                 FROM parts p
217                 WHERE p.id = $form->{id}|;
218     $sth = $dbh->prepare($query);
219     $sth->execute || $form->dberror($query);
220     my ($sellprice, $weight) = $sth->fetchrow_array;
221     $sth->finish;
222
223     # if item is part of an assembly adjust all assemblies
224     $query = qq|SELECT a.id, a.qty
225                 FROM assembly a
226                 WHERE a.parts_id = $form->{id}|;
227     $sth = $dbh->prepare($query);
228     $sth->execute || $form->dberror($query);
229     while (my ($id, $qty) = $sth->fetchrow_array) {
230       &update_assembly($dbh, $form, $id, $qty, $sellprice * 1, $weight * 1);
231     }
232     $sth->finish;
233
234     if ($form->{item} ne 'service') {
235
236       # delete makemodel records
237       $query = qq|DELETE FROM makemodel
238                   WHERE parts_id = $form->{id}|;
239       $dbh->do($query) || $form->dberror($query);
240     }
241
242     if ($form->{item} eq 'assembly') {
243       if ($form->{onhand} != 0) {
244         &adjust_inventory($dbh, $form, $form->{id}, $form->{onhand} * -1);
245       }
246
247       # delete assembly records
248       $query = qq|DELETE FROM assembly
249                   WHERE id = $form->{id}|;
250       $dbh->do($query) || $form->dberror($query);
251
252       $form->{onhand} += $form->{stock};
253     }
254
255     # delete tax records
256     $query = qq|DELETE FROM partstax
257                 WHERE parts_id = $form->{id}|;
258     $dbh->do($query) || $form->dberror($query);
259
260   } else {
261     my $uid = time;
262     $uid .= $form->{login};
263
264     $query = qq|SELECT p.id FROM parts p
265                 WHERE p.partnumber = '$form->{partnumber}'|;
266     $sth = $dbh->prepare($query);
267     $sth->execute || $form->dberror($query);
268     ($form->{id}) = $sth->fetchrow_array;
269     $sth->finish;
270
271     if ($form->{id} ne "") {
272       $main::lxdebug->leave_sub();
273       return 3;
274     }
275     $query = qq|INSERT INTO parts (partnumber)
276                 VALUES ('$uid')|;
277     $dbh->do($query) || $form->dberror($query);
278
279     $query = qq|SELECT p.id FROM parts p
280                 WHERE p.partnumber = '$uid'|;
281     $sth = $dbh->prepare($query);
282     $sth->execute || $form->dberror($query);
283
284     ($form->{id}) = $sth->fetchrow_array;
285     $sth->finish;
286
287     $form->{orphaned} = 1;
288     $form->{onhand} = $form->{stock} if $form->{item} eq 'assembly';
289     if ($form->{partnumber} eq "" && $form->{inventory_accno} eq "") {
290       $form->{partnumber} = $form->update_defaults($myconfig, "servicenumber");
291     }
292     if ($form->{partnumber} eq "" && $form->{inventory_accno} ne "") {
293       $form->{partnumber} = $form->update_defaults($myconfig, "articlenumber");
294     }
295
296   }
297   my $partsgroup_id = 0;
298
299   if ($form->{partsgroup}) {
300     ($partsgroup, $partsgroup_id) = split /--/, $form->{partsgroup};
301   }
302
303   $query = qq|UPDATE parts SET
304               partnumber = '$form->{partnumber}',
305               description = '$form->{description}',
306               makemodel = '$form->{makemodel}',
307               alternate = '$form->{alternate}',
308               assembly = '$form->{assembly}',
309               listprice = $form->{listprice},
310               sellprice = $form->{sellprice},
311               lastcost = $form->{lastcost},
312               weight = $form->{weight},
313               priceupdate = $form->{priceupdate},
314               unit = '$form->{unit}',
315               notes = '$form->{notes}',
316               rop = $form->{rop},
317               bin = '$form->{bin}',
318               inventory_accno_id = (SELECT c.id FROM chart c
319                                     WHERE c.accno = '$form->{inventory_accno}'),
320               income_accno_id = (SELECT c.id FROM chart c
321                                  WHERE c.accno = '$form->{income_accno}'),
322               expense_accno_id = (SELECT c.id FROM chart c
323                                   WHERE c.accno = '$form->{expense_accno}'),
324               obsolete = '$form->{obsolete}',
325               image = '$form->{image}',
326               drawing = '$form->{drawing}',
327               shop = '$form->{shop}',
328               ve = '$form->{ve}',
329               gv = '$form->{gv}',
330               microfiche = '$form->{microfiche}',
331               partsgroup_id = $partsgroup_id
332               WHERE id = $form->{id}|;
333   $dbh->do($query) || $form->dberror($query);
334
335   # insert makemodel records
336   unless ($form->{item} eq 'service') {
337     for my $i (1 .. $form->{makemodel_rows}) {
338       if (($form->{"make_$i"}) || ($form->{"model_$i"})) {
339         map { $form->{"${_}_$i"} =~ s/\'/\'\'/g } qw(make model);
340
341         $query = qq|INSERT INTO makemodel (parts_id, make, model)
342                     VALUES ($form->{id},
343                     '$form->{"make_$i"}', '$form->{"model_$i"}')|;
344         $dbh->do($query) || $form->dberror($query);
345       }
346     }
347   }
348
349   # insert taxes
350   foreach $item (split / /, $form->{taxaccounts}) {
351     if ($form->{"IC_tax_$item"}) {
352       $query = qq|INSERT INTO partstax (parts_id, chart_id)
353                   VALUES ($form->{id},
354                           (SELECT c.id
355                            FROM chart c
356                            WHERE c.accno = '$item'))|;
357       $dbh->do($query) || $form->dberror($query);
358     }
359   }
360
361   # add assembly records
362   if ($form->{item} eq 'assembly') {
363
364     for my $i (1 .. $form->{assembly_rows}) {
365       $form->{"qty_$i"} = $form->parse_amount($myconfig, $form->{"qty_$i"});
366
367       if ($form->{"qty_$i"} != 0) {
368         $form->{"bom_$i"} *= 1;
369         $query = qq|INSERT INTO assembly (id, parts_id, qty, bom)
370                     VALUES ($form->{id}, $form->{"id_$i"},
371                     $form->{"qty_$i"}, '$form->{"bom_$i"}')|;
372         $dbh->do($query) || $form->dberror($query);
373       }
374     }
375
376     # adjust onhand for the parts
377     if ($form->{onhand} != 0) {
378       &adjust_inventory($dbh, $form, $form->{id}, $form->{onhand});
379     }
380
381     @a = localtime;
382     $a[5] += 1900;
383     $a[4]++;
384     my $shippingdate = "$a[5]-$a[4]-$a[3]";
385
386     $form->get_employee($dbh);
387
388     # add inventory record
389     $query = qq|INSERT INTO inventory (warehouse_id, parts_id, qty,
390                 shippingdate, employee_id) VALUES (
391                 0, $form->{id}, $form->{stock}, '$shippingdate',
392                 $form->{employee_id})|;
393     $dbh->do($query) || $form->dberror($query);
394
395   }
396
397   #set expense_accno=inventory_accno if they are different => bilanz
398   $vendor_accno =
399     ($form->{expense_accno} != $form->{inventory_accno})
400     ? $form->{inventory_accno}
401     : $form->{expense_accno};
402
403   # get tax rates and description
404   $accno_id =
405     ($form->{vc} eq "customer") ? $form->{income_accno} : $vendor_accno;
406   $query = qq|SELECT c.accno, c.description, t.rate, t.taxnumber
407               FROM chart c, tax t
408               WHERE c.id=t.chart_id AND t.taxkey in (SELECT taxkey_id from chart where accno = '$accno_id')
409               ORDER BY c.accno|;
410   $stw = $dbh->prepare($query);
411
412   $stw->execute || $form->dberror($query);
413
414   $form->{taxaccount} = "";
415   while ($ptr = $stw->fetchrow_hashref(NAME_lc)) {
416
417     #    if ($customertax{$ref->{accno}}) {
418     $form->{taxaccount} .= "$ptr->{accno} ";
419     if (!($form->{taxaccount2} =~ /$ptr->{accno}/)) {
420       $form->{"$ptr->{accno}_rate"}        = $ptr->{rate};
421       $form->{"$ptr->{accno}_description"} = $ptr->{description};
422       $form->{"$ptr->{accno}_taxnumber"}   = $ptr->{taxnumber};
423       $form->{taxaccount2} .= " $ptr->{accno} ";
424     }
425
426   }
427
428   # commit
429   my $rc = $dbh->commit;
430   $dbh->disconnect;
431
432   $main::lxdebug->leave_sub();
433
434   return $rc;
435 }
436
437 sub update_assembly {
438   $main::lxdebug->enter_sub();
439
440   my ($dbh, $form, $id, $qty, $sellprice, $weight) = @_;
441
442   my $query = qq|SELECT a.id, a.qty
443                  FROM assembly a
444                  WHERE a.parts_id = $id|;
445   my $sth = $dbh->prepare($query);
446   $sth->execute || $form->dberror($query);
447
448   while (my ($pid, $aqty) = $sth->fetchrow_array) {
449     &update_assembly($dbh, $form, $pid, $aqty * $qty, $sellprice, $weight);
450   }
451   $sth->finish;
452
453   $query = qq|UPDATE parts
454               SET sellprice = sellprice +
455                   $qty * ($form->{sellprice} - $sellprice),
456                   weight = weight +
457                   $qty * ($form->{weight} - $weight)
458               WHERE id = $id|;
459   $dbh->do($query) || $form->dberror($query);
460
461   $main::lxdebug->leave_sub();
462 }
463
464 sub retrieve_assemblies {
465   $main::lxdebug->enter_sub();
466
467   my ($self, $myconfig, $form) = @_;
468
469   # connect to database
470   my $dbh = $form->dbconnect($myconfig);
471
472   my $where = '1 = 1';
473
474   if ($form->{partnumber}) {
475     my $partnumber = $form->like(lc $form->{partnumber});
476     $where .= " AND lower(p.partnumber) LIKE '$partnumber'";
477   }
478
479   if ($form->{description}) {
480     my $description = $form->like(lc $form->{description});
481     $where .= " AND lower(p.description) LIKE '$description'";
482   }
483   $where .= " AND NOT p.obsolete = '1'";
484
485   # retrieve assembly items
486   my $query = qq|SELECT p.id, p.partnumber, p.description,
487                  p.bin, p.onhand, p.rop,
488                    (SELECT sum(p2.inventory_accno_id)
489                     FROM parts p2, assembly a
490                     WHERE p2.id = a.parts_id
491                     AND a.id = p.id) AS inventory
492                  FROM parts p
493                  WHERE $where
494                  AND assembly = '1'|;
495
496   my $sth = $dbh->prepare($query);
497   $sth->execute || $form->dberror($query);
498
499   while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
500     push @{ $form->{assembly_items} }, $ref if $ref->{inventory};
501   }
502   $sth->finish;
503
504   $dbh->disconnect;
505
506   $main::lxdebug->leave_sub();
507 }
508
509 sub restock_assemblies {
510   $main::lxdebug->enter_sub();
511
512   my ($self, $myconfig, $form) = @_;
513
514   # connect to database
515   my $dbh = $form->dbconnect_noauto($myconfig);
516
517   for my $i (1 .. $form->{rowcount}) {
518
519     $form->{"qty_$i"} = $form->parse_amount($myconfig, $form->{"qty_$i"});
520
521     if ($form->{"qty_$i"} != 0) {
522       &adjust_inventory($dbh, $form, $form->{"id_$i"}, $form->{"qty_$i"});
523     }
524
525   }
526
527   my $rc = $dbh->commit;
528   $dbh->disconnect;
529
530   $main::lxdebug->leave_sub();
531
532   return $rc;
533 }
534
535 sub adjust_inventory {
536   $main::lxdebug->enter_sub();
537
538   my ($dbh, $form, $id, $qty) = @_;
539
540   my $query = qq|SELECT p.id, p.inventory_accno_id, p.assembly, a.qty
541                  FROM parts p, assembly a
542                  WHERE a.parts_id = p.id
543                  AND a.id = $id|;
544   my $sth = $dbh->prepare($query);
545   $sth->execute || $form->dberror($query);
546
547   while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
548
549     my $allocate = $qty * $ref->{qty};
550
551     # is it a service item, then loop
552     $ref->{inventory_accno_id} *= 1;
553     next if (($ref->{inventory_accno_id} == 0) && !$ref->{assembly});
554
555     # adjust parts onhand
556     $form->update_balance($dbh, "parts", "onhand",
557                           qq|id = $ref->{id}|,
558                           $allocate * -1);
559   }
560
561   $sth->finish;
562
563   # update assembly
564   my $rc = $form->update_balance($dbh, "parts", "onhand", qq|id = $id|, $qty);
565
566   $main::lxdebug->leave_sub();
567
568   return $rc;
569 }
570
571 sub delete {
572   $main::lxdebug->enter_sub();
573
574   my ($self, $myconfig, $form) = @_;
575
576   # connect to database, turn off AutoCommit
577   my $dbh = $form->dbconnect_noauto($myconfig);
578
579   my $query = qq|DELETE FROM parts
580                  WHERE id = $form->{id}|;
581   $dbh->do($query) || $form->dberror($query);
582
583   $query = qq|DELETE FROM partstax
584               WHERE parts_id = $form->{id}|;
585   $dbh->do($query) || $form->dberror($query);
586
587   # check if it is a part, assembly or service
588   if ($form->{item} ne 'service') {
589     $query = qq|DELETE FROM makemodel
590                 WHERE parts_id = $form->{id}|;
591     $dbh->do($query) || $form->dberror($query);
592   }
593
594   if ($form->{item} eq 'assembly') {
595
596     # delete inventory
597     $query = qq|DELETE FROM inventory
598                 WHERE parts_id = $form->{id}|;
599     $dbh->do($query) || $form->dberror($query);
600
601     $query = qq|DELETE FROM assembly
602                 WHERE id = $form->{id}|;
603     $dbh->do($query) || $form->dberror($query);
604   }
605
606   if ($form->{item} eq 'alternate') {
607     $query = qq|DELETE FROM alternate
608                 WHERE id = $form->{id}|;
609     $dbh->do($query) || $form->dberror($query);
610   }
611
612   # commit
613   my $rc = $dbh->commit;
614   $dbh->disconnect;
615
616   $main::lxdebug->leave_sub();
617
618   return $rc;
619 }
620
621 sub assembly_item {
622   $main::lxdebug->enter_sub();
623
624   my ($self, $myconfig, $form) = @_;
625
626   my $i = $form->{assembly_rows};
627   my $var;
628   my $where = "1 = 1";
629
630   if ($form->{"partnumber_$i"}) {
631     $var = $form->like(lc $form->{"partnumber_$i"});
632     $where .= " AND lower(p.partnumber) LIKE '$var'";
633   }
634   if ($form->{"description_$i"}) {
635     $var = $form->like(lc $form->{"description_$i"});
636     $where .= " AND lower(p.description) LIKE '$var'";
637   }
638   if ($form->{"partsgroup_$i"}) {
639     $var = $form->like(lc $form->{"partsgroup_$i"});
640     $where .= " AND lower(pg.partsgroup) LIKE '$var'";
641   }
642
643   if ($form->{id}) {
644     $where .= " AND NOT p.id = $form->{id}";
645   }
646
647   if ($partnumber) {
648     $where .= " ORDER BY p.partnumber";
649   } else {
650     $where .= " ORDER BY p.description";
651   }
652
653   # connect to database
654   my $dbh = $form->dbconnect($myconfig);
655
656   my $query = qq|SELECT p.id, p.partnumber, p.description, p.sellprice,
657                  p.weight, p.onhand, p.unit,
658                  pg.partsgroup
659                  FROM parts p
660                  LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
661                  WHERE $where|;
662   my $sth = $dbh->prepare($query);
663   $sth->execute || $form->dberror($query);
664
665   while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
666     push @{ $form->{item_list} }, $ref;
667   }
668
669   $sth->finish;
670   $dbh->disconnect;
671
672   $main::lxdebug->leave_sub();
673 }
674
675 sub all_parts {
676   $main::lxdebug->enter_sub();
677
678   my ($self, $myconfig, $form) = @_;
679
680   my $where = '1 = 1';
681   my $var;
682
683   my $group;
684   my $limit;
685
686   foreach my $item (qw(partnumber drawing microfiche make model)) {
687     if ($form->{$item}) {
688       $var = $form->like(lc $form->{$item});
689
690       # make will build later Bugfix 145
691       if ($item ne 'make') {
692         $where .= " AND lower(p.$item) LIKE '$var'";
693       }
694     }
695   }
696
697   # special case for description
698   if ($form->{description}) {
699     unless (   $form->{bought}
700             || $form->{sold}
701             || $form->{onorder}
702             || $form->{ordered}
703             || $form->{rfq}
704             || $form->{quoted}) {
705       $var = $form->like(lc $form->{description});
706       $where .= " AND lower(p.description) LIKE '$var'";
707     }
708   }
709
710   # special case for serialnumber
711   if ($form->{l_serialnumber}) {
712     if ($form->{serialnumber}) {
713       $var = $form->like(lc $form->{serialnumber});
714       $where .= " AND lower(serialnumber) LIKE '$var'";
715     }
716   }
717
718   if ($form->{searchitems} eq 'part') {
719     $where .= " AND p.inventory_accno_id > 0";
720   }
721   if ($form->{searchitems} eq 'assembly') {
722     $form->{bought} = "";
723     $where .= " AND p.assembly = '1'";
724   }
725   if ($form->{searchitems} eq 'service') {
726     $where .= " AND p.inventory_accno_id IS NULL AND NOT p.assembly = '1'";
727
728     # irrelevant for services
729     $form->{make} = $form->{model} = "";
730   }
731
732   # items which were never bought, sold or on an order
733   if ($form->{itemstatus} eq 'orphaned') {
734     $form->{onhand}  = $form->{short}   = 0;
735     $form->{bought}  = $form->{sold}    = 0;
736     $form->{onorder} = $form->{ordered} = 0;
737     $form->{rfq}     = $form->{quoted}  = 0;
738
739     $form->{transdatefrom} = $form->{transdateto} = "";
740
741     $where .= " AND p.onhand = 0
742                 AND p.id NOT IN (SELECT p.id FROM parts p, invoice i
743                                  WHERE p.id = i.parts_id)
744                 AND p.id NOT IN (SELECT p.id FROM parts p, assembly a
745                                  WHERE p.id = a.parts_id)
746                 AND p.id NOT IN (SELECT p.id FROM parts p, orderitems o
747                                  WHERE p.id = o.parts_id)";
748   }
749
750   if ($form->{itemstatus} eq 'active') {
751     $where .= " AND p.obsolete = '0'";
752   }
753   if ($form->{itemstatus} eq 'obsolete') {
754     $where .= " AND p.obsolete = '1'";
755     $form->{onhand} = $form->{short} = 0;
756   }
757   if ($form->{itemstatus} eq 'onhand') {
758     $where .= " AND p.onhand > 0";
759   }
760   if ($form->{itemstatus} eq 'short') {
761     $where .= " AND p.onhand < p.rop";
762   }
763   if ($form->{make}) {
764     $var = $form->like(lc $form->{make});
765     $where .= " AND p.id IN (SELECT DISTINCT ON (m.parts_id) m.parts_id
766                            FROM makemodel m WHERE lower(m.make) LIKE '$var')";
767   }
768   if ($form->{model}) {
769     $var = $form->like(lc $form->{model});
770     $where .= " AND p.id IN (SELECT DISTINCT ON (m.parts_id) m.parts_id
771                            FROM makemodel m WHERE lower(m.model) LIKE '$var')";
772   }
773   if ($form->{partsgroup}) {
774     $var = $form->like(lc $form->{partsgroup});
775     $where .= " AND lower(pg.partsgroup) LIKE '$var'";
776   }
777   if ($form->{l_soldtotal}) {
778     $where .= " AND p.id=i.parts_id AND  i.qty >= 0";
779     $group =
780       " GROUP BY  p.id,p.partnumber,p.description,p.onhand,p.unit,p.bin, p.sellprice,p.listprice,p.lastcost,p.priceupdate,pg.partsgroup";
781   }
782   if ($form->{top100}) {
783     $limit = " LIMIT 100";
784   }
785
786   # tables revers?
787   if ($form->{revers} == 1) {
788     $form->{desc} = " DESC";
789   } else {
790     $form->{desc} = "";
791   }
792
793   # connect to database
794   my $dbh = $form->dbconnect($myconfig);
795
796   my $sortorder = $form->{sort};
797   $sortorder .= $form->{desc};
798   $sortorder = $form->{sort} unless $sortorder;
799
800   my $query = "";
801
802   if ($form->{l_soldtotal}) {
803     $form->{soldtotal} = 'soldtotal';
804     $query =
805       qq|SELECT p.id,p.partnumber,p.description,p.onhand,p.unit,p.bin,p.sellprice,p.listprice,
806                 p.lastcost,p.priceupdate,pg.partsgroup,sum(i.qty) as soldtotal FROM parts
807                 p LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id), invoice i
808                 WHERE $where
809                 $group
810                 ORDER BY $sortorder
811                 $limit|;
812   } else {
813     $query = qq|SELECT p.id, p.partnumber, p.description, p.onhand, p.unit,
814                  p.bin, p.sellprice, p.listprice, p.lastcost, p.rop, p.weight,
815                  p.priceupdate, p.image, p.drawing, p.microfiche,
816                  pg.partsgroup
817                  FROM parts p
818                  LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
819                  WHERE $where
820                  $group
821                  ORDER BY $sortorder|;
822   }
823
824   # rebuild query for bought and sold items
825   if (   $form->{bought}
826       || $form->{sold}
827       || $form->{onorder}
828       || $form->{ordered}
829       || $form->{rfq}
830       || $form->{quoted}) {
831
832     my @a = qw(partnumber description bin priceupdate name);
833
834     push @a, qw(invnumber serialnumber) if ($form->{bought} || $form->{sold});
835     push @a, "ordnumber" if ($form->{onorder} || $form->{ordered});
836     push @a, "quonumber" if ($form->{rfq}     || $form->{quoted});
837
838     my $union = "";
839     $query = "";
840
841     if ($form->{bought} || $form->{sold}) {
842
843       my $invwhere = "$where";
844       $invwhere .= " AND i.assemblyitem = '0'";
845       $invwhere .= " AND a.transdate >= '$form->{transdatefrom}'"
846         if $form->{transdatefrom};
847       $invwhere .= " AND a.transdate <= '$form->{transdateto}'"
848         if $form->{transdateto};
849
850       if ($form->{description}) {
851         $var = $form->like(lc $form->{description});
852         $invwhere .= " AND lower(i.description) LIKE '$var'";
853       }
854
855       my $flds = qq|p.id, p.partnumber, i.description, i.serialnumber,
856                     i.qty AS onhand, i.unit, p.bin, i.sellprice,
857                     p.listprice, p.lastcost, p.rop, p.weight,
858                     p.priceupdate, p.image, p.drawing, p.microfiche,
859                     pg.partsgroup,
860                     a.invnumber, a.ordnumber, a.quonumber, i.trans_id,
861                     ct.name|;
862
863       if ($form->{bought}) {
864         $query = qq|
865                     SELECT $flds, 'ir' AS module, '' AS type,
866                     1 AS exchangerate
867                     FROM invoice i
868                     JOIN parts p ON (p.id = i.parts_id)
869                     JOIN ap a ON (a.id = i.trans_id)
870                     JOIN vendor ct ON (a.vendor_id = ct.id)
871                     LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
872                     WHERE $invwhere|;
873         $union = "
874                   UNION";
875       }
876
877       if ($form->{sold}) {
878         $query .= qq|$union
879                      SELECT $flds, 'is' AS module, '' AS type,
880                      1 As exchangerate
881                      FROM invoice i
882                      JOIN parts p ON (p.id = i.parts_id)
883                      JOIN ar a ON (a.id = i.trans_id)
884                      JOIN customer ct ON (a.customer_id = ct.id)
885                      LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
886                      WHERE $invwhere|;
887         $union = "
888                   UNION";
889       }
890     }
891
892     if ($form->{onorder} || $form->{ordered}) {
893       my $ordwhere = "$where
894                      AND o.quotation = '0'";
895       $ordwhere .= " AND o.transdate >= '$form->{transdatefrom}'"
896         if $form->{transdatefrom};
897       $ordwhere .= " AND o.transdate <= '$form->{transdateto}'"
898         if $form->{transdateto};
899
900       if ($form->{description}) {
901         $var = $form->like(lc $form->{description});
902         $ordwhere .= " AND lower(oi.description) LIKE '$var'";
903       }
904
905       $flds = qq|p.id, p.partnumber, oi.description, '' AS serialnumber,
906                  oi.qty AS onhand, oi.unit, p.bin, oi.sellprice,
907                  p.listprice, p.lastcost, p.rop, p.weight,
908                  p.priceupdate, p.image, p.drawing, p.microfiche,
909                  pg.partsgroup,
910                  '' AS invnumber, o.ordnumber, o.quonumber, oi.trans_id,
911                  ct.name|;
912
913       if ($form->{ordered}) {
914         $query .= qq|$union
915                      SELECT $flds, 'oe' AS module, 'sales_order' AS type,
916                     (SELECT buy FROM exchangerate ex
917                      WHERE ex.curr = o.curr
918                      AND ex.transdate = o.transdate) AS exchangerate
919                      FROM orderitems oi
920                      JOIN parts p ON (oi.parts_id = p.id)
921                      JOIN oe o ON (oi.trans_id = o.id)
922                      JOIN customer ct ON (o.customer_id = ct.id)
923                      LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
924                      WHERE $ordwhere
925                      AND o.customer_id > 0|;
926         $union = "
927                   UNION";
928       }
929
930       if ($form->{onorder}) {
931         $flds = qq|p.id, p.partnumber, oi.description, '' AS serialnumber,
932                    oi.qty * -1 AS onhand, oi.unit, p.bin, oi.sellprice,
933                    p.listprice, p.lastcost, p.rop, p.weight,
934                    p.priceupdate, p.image, p.drawing, p.microfiche,
935                    pg.partsgroup,
936                    '' AS invnumber, o.ordnumber, o.quonumber, oi.trans_id,
937                    ct.name|;
938
939         $query .= qq|$union
940                     SELECT $flds, 'oe' AS module, 'purchase_order' AS type,
941                     (SELECT sell FROM exchangerate ex
942                      WHERE ex.curr = o.curr
943                      AND ex.transdate = o.transdate) AS exchangerate
944                     FROM orderitems oi
945                     JOIN parts p ON (oi.parts_id = p.id)
946                     JOIN oe o ON (oi.trans_id = o.id)
947                     JOIN vendor ct ON (o.vendor_id = ct.id)
948                     LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
949                     WHERE $ordwhere
950                     AND o.vendor_id > 0|;
951       }
952
953     }
954
955     if ($form->{rfq} || $form->{quoted}) {
956       my $quowhere = "$where
957                      AND o.quotation = '1'";
958       $quowhere .= " AND o.transdate >= '$form->{transdatefrom}'"
959         if $form->{transdatefrom};
960       $quowhere .= " AND o.transdate <= '$form->{transdateto}'"
961         if $form->{transdateto};
962
963       if ($form->{description}) {
964         $var = $form->like(lc $form->{description});
965         $quowhere .= " AND lower(oi.description) LIKE '$var'";
966       }
967
968       $flds = qq|p.id, p.partnumber, oi.description, '' AS serialnumber,
969                  oi.qty AS onhand, oi.unit, p.bin, oi.sellprice,
970                  p.listprice, p.lastcost, p.rop, p.weight,
971                  p.priceupdate, p.image, p.drawing, p.microfiche,
972                  pg.partsgroup,
973                  '' AS invnumber, o.ordnumber, o.quonumber, oi.trans_id,
974                  ct.name|;
975
976       if ($form->{quoted}) {
977         $query .= qq|$union
978                      SELECT $flds, 'oe' AS module, 'sales_quotation' AS type,
979                     (SELECT buy FROM exchangerate ex
980                      WHERE ex.curr = o.curr
981                      AND ex.transdate = o.transdate) AS exchangerate
982                      FROM orderitems oi
983                      JOIN parts p ON (oi.parts_id = p.id)
984                      JOIN oe o ON (oi.trans_id = o.id)
985                      JOIN customer ct ON (o.customer_id = ct.id)
986                      LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
987                      WHERE $quowhere
988                      AND o.customer_id > 0|;
989         $union = "
990                   UNION";
991       }
992
993       if ($form->{rfq}) {
994         $flds = qq|p.id, p.partnumber, oi.description, '' AS serialnumber,
995                    oi.qty * -1 AS onhand, oi.unit, p.bin, oi.sellprice,
996                    p.listprice, p.lastcost, p.rop, p.weight,
997                    p.priceupdate, p.image, p.drawing, p.microfiche,
998                    pg.partsgroup,
999                    '' AS invnumber, o.ordnumber, o.quonumber, oi.trans_id,
1000                    ct.name|;
1001
1002         $query .= qq|$union
1003                     SELECT $flds, 'oe' AS module, 'request_quotation' AS type,
1004                     (SELECT sell FROM exchangerate ex
1005                      WHERE ex.curr = o.curr
1006                      AND ex.transdate = o.transdate) AS exchangerate
1007                     FROM orderitems oi
1008                     JOIN parts p ON (oi.parts_id = p.id)
1009                     JOIN oe o ON (oi.trans_id = o.id)
1010                     JOIN vendor ct ON (o.vendor_id = ct.id)
1011                     LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
1012                     WHERE $quowhere
1013                     AND o.vendor_id > 0|;
1014       }
1015
1016     }
1017     $query .= qq|
1018                  ORDER BY $sortorder|;
1019
1020   }
1021   my $sth = $dbh->prepare($query);
1022   $sth->execute || $form->dberror($query);
1023
1024   while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
1025     push @{ $form->{parts} }, $ref;
1026   }
1027
1028   $sth->finish;
1029
1030   # include individual items for assemblies
1031   if ($form->{searchitems} eq 'assembly' && $form->{bom}) {
1032     foreach $item (@{ $form->{parts} }) {
1033       push @assemblies, $item;
1034       $query = qq|SELECT p.id, p.partnumber, p.description, a.qty AS onhand,
1035                   p.unit, p.bin,
1036                   p.sellprice, p.listprice, p.lastcost,
1037                   p.rop, p.weight, p.priceupdate,
1038                   p.image, p.drawing, p.microfiche
1039                   FROM parts p, assembly a
1040                   WHERE p.id = a.parts_id
1041                   AND a.id = $item->{id}|;
1042
1043       $sth = $dbh->prepare($query);
1044       $sth->execute || $form->dberror($query);
1045
1046       while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
1047         $ref->{assemblyitem} = 1;
1048         push @assemblies, $ref;
1049       }
1050       $sth->finish;
1051
1052       push @assemblies, { id => $item->{id} };
1053
1054     }
1055
1056     # copy assemblies to $form->{parts}
1057     @{ $form->{parts} } = @assemblies;
1058   }
1059
1060   $dbh->disconnect;
1061   $main::lxdebug->leave_sub();
1062 }
1063
1064 sub create_links {
1065   $main::lxdebug->enter_sub();
1066
1067   my ($self, $module, $myconfig, $form) = @_;
1068
1069   # connect to database
1070   my $dbh = $form->dbconnect($myconfig);
1071
1072   if ($form->{id}) {
1073     $query = qq|SELECT c.accno, c.description, c.link, c.id,
1074                         p.inventory_accno_id, p.income_accno_id, p.expense_accno_id
1075                         FROM chart c, parts p
1076                         WHERE c.link LIKE '%$module%'
1077                         AND p.id = $form->{id}
1078                         ORDER BY c.accno|;
1079   } else {
1080     $query = qq|SELECT c.accno, c.description, c.link, c.id,
1081                 d.inventory_accno_id, d.income_accno_id, d.expense_accno_id
1082                 FROM chart c, defaults d
1083                 WHERE c.link LIKE '%$module%'
1084                 ORDER BY c.accno|;
1085   }
1086
1087   my $sth = $dbh->prepare($query);
1088   $sth->execute || $form->dberror($query);
1089   while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
1090     foreach my $key (split /:/, $ref->{link}) {
1091       if ($key =~ /$module/) {
1092         if (   ($ref->{id} eq $ref->{inventory_accno_id})
1093             || ($ref->{id} eq $ref->{income_accno_id})
1094             || ($ref->{id} eq $ref->{expense_accno_id})) {
1095           push @{ $form->{"${module}_links"}{$key} },
1096             { accno       => $ref->{accno},
1097               description => $ref->{description},
1098               selected    => "selected" };
1099             } else {
1100           push @{ $form->{"${module}_links"}{$key} },
1101             { accno       => $ref->{accno},
1102               description => $ref->{description},
1103               selected    => "" };
1104         }
1105       }
1106     }
1107   }
1108   $sth->finish;
1109
1110   if ($form->{id}) {
1111     $query = qq|SELECT weightunit
1112                 FROM defaults|;
1113     $sth = $dbh->prepare($query);
1114     $sth->execute || $form->dberror($query);
1115
1116     ($form->{weightunit}) = $sth->fetchrow_array;
1117     $sth->finish;
1118
1119   } else {
1120     $query = qq|SELECT weightunit, current_date
1121                 FROM defaults|;
1122     $sth = $dbh->prepare($query);
1123     $sth->execute || $form->dberror($query);
1124
1125     ($form->{weightunit}, $form->{priceupdate}) = $sth->fetchrow_array;
1126     $sth->finish;
1127   }
1128
1129   $dbh->disconnect;
1130   $main::lxdebug->leave_sub();
1131 }
1132
1133 # get partnumber, description, unit, sellprice and soldtotal with choice through $sortorder for Top100
1134 sub get_parts {
1135   $main::lxdebug->enter_sub();
1136
1137   my ($self, $myconfig, $form, $sortorder) = @_;
1138   my $dbh   = $form->dbconnect($myconfig);
1139   my $order = " p.partnumber";
1140   my $where = "1 = 1";
1141
1142   if ($sortorder eq "all") {
1143     $where .= " AND p.partnumber LIKE '%$form->{partnumber}%'";
1144     $where .= " AND p.description LIKE '%$form->{description}%'";
1145   } else {
1146     if ($sortorder eq "partnumber") {
1147       $where .= " AND p.partnumber LIKE '%$form->{partnumber}%'";
1148       $order = qq|p.$sortorder|;
1149     }
1150     if ($sortorder eq "description") {
1151       $where .= " AND p.description LIKE '%$form->{description}%'";
1152     }
1153   }
1154
1155   my $query =
1156     qq|SELECT p.id, p.partnumber, p.description, p.unit, p.sellprice FROM parts p WHERE $where ORDER BY $order|;
1157   my $sth = $dbh->prepare($query);
1158   $sth->execute || $self->dberror($query);
1159   my $j = 0;
1160   while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
1161     if (($ref->{partnumber} eq "*") && ($ref->{description} eq "")) {
1162     } else {
1163       $j++;
1164       $form->{"id_$j"}          = $ref->{id};
1165       $form->{"partnumber_$j"}  = $ref->{partnumber};
1166       $form->{"description_$j"} = $ref->{description};
1167       $form->{"unit_$j"}        = $ref->{unit};
1168       $form->{"sellprice_$j"}   = $ref->{sellprice};
1169       $form->{"soldtotal_$j"}   = get_soldtotal($dbh, $ref->{id});
1170     }    #fi
1171   }    #while
1172   $form->{rows} = $j;
1173   $sth->finish;
1174   $dbh->disconnect;
1175
1176   $main::lxdebug->leave_sub();
1177
1178   return $self;
1179 }    #end get_parts()
1180
1181 # gets sum of sold part with part_id
1182 sub get_soldtotal {
1183   $main::lxdebug->enter_sub();
1184
1185   my ($dbh, $id) = @_;
1186
1187   my $query =
1188     qq|SELECT sum(i.qty) as totalsold FROM invoice i WHERE i.parts_id = $id|;
1189
1190   my $sth = $dbh->prepare($query);
1191   $sth->execute || $form->dberror($query);
1192
1193   my $sum = 0;
1194   while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
1195
1196     $sum = $ref->{totalsold};
1197   }    #while
1198   $sth->finish;
1199
1200   if ($sum eq undef) {
1201     $sum = 0;
1202   }    #fi
1203
1204   $main::lxdebug->leave_sub();
1205
1206   return $sum;
1207 }    #end get_soldtotal
1208
1209 sub retrieve_item {
1210   $main::lxdebug->enter_sub();
1211
1212   my ($self, $myconfig, $form) = @_;
1213   my $i     = $form->{rowcount};
1214   my $where = "NOT p.obsolete = '1'";
1215
1216   if ($form->{"partnumber_$i"}) {
1217     my $partnumber = $form->like(lc $form->{"partnumber_$i"});
1218     $where .= " AND lower(p.partnumber) LIKE '$partnumber'";
1219   }
1220   if ($form->{"description_$i"}) {
1221     my $description = $form->like(lc $form->{"description_$i"});
1222     $where .= " AND lower(p.description) LIKE '$description'";
1223   }
1224
1225   if ($form->{"partsgroup_$i"}) {
1226     my $partsgroup = $form->like(lc $form->{"partsgroup_$i"});
1227     $where .= " AND lower(pg.partsgroup) LIKE '$partsgroup'";
1228   }
1229
1230   if ($form->{"description_$i"}) {
1231     $where .= " ORDER BY description";
1232   } else {
1233     $where .= " ORDER BY partnumber";
1234   }
1235
1236   # connect to database
1237   my $dbh = $form->dbconnect($myconfig);
1238
1239   my $query = qq|SELECT p.id, p.partnumber, p.description, p.sellprice,
1240                         p.listprice,
1241                         c1.accno AS inventory_accno,
1242                         c2.accno AS income_accno,
1243                         c3.accno AS expense_accno,
1244                  p.unit, p.assembly, p.bin, p.onhand, p.notes AS partnotes,
1245                  pg.partsgroup
1246                  FROM parts p
1247                  LEFT JOIN chart c1 ON (p.inventory_accno_id = c1.id)
1248                  LEFT JOIN chart c2 ON (p.income_accno_id = c2.id)
1249                  LEFT JOIN chart c3 ON (p.expense_accno_id = c3.id)
1250                  LEFT JOIN partsgroup pg ON (pg.id = p.partsgroup_id)
1251                  WHERE $where|;
1252   my $sth = $dbh->prepare($query);
1253   $sth->execute || $form->dberror($query);
1254
1255   #while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
1256
1257   # get tax rates and description
1258   #$accno_id = ($form->{vc} eq "customer") ? $ref->{income_accno} : $ref->{inventory_accno};
1259   #$query = qq|SELECT c.accno, c.description, t.rate, t.taxnumber
1260   #           FROM chart c, tax t
1261   #           WHERE c.id=t.chart_id AND t.taxkey in (SELECT taxkey_id from chart where accno = '$accno_id')
1262   #           ORDER BY accno|;
1263   # $stw = $dbh->prepare($query);
1264   #$stw->execute || $form->dberror($query);
1265
1266   #$ref->{taxaccounts} = "";
1267   #while ($ptr = $stw->fetchrow_hashref(NAME_lc)) {
1268
1269   #   $form->{"$ptr->{accno}_rate"} = $ptr->{rate};
1270   #  $form->{"$ptr->{accno}_description"} = $ptr->{description};
1271   #   $form->{"$ptr->{accno}_taxnumber"} = $ptr->{taxnumber};
1272   #   $form->{taxaccounts} .= "$ptr->{accno} ";
1273   #   $ref->{taxaccounts} .= "$ptr->{accno} ";
1274
1275   #}
1276
1277   #$stw->finish;
1278   #chop $ref->{taxaccounts};
1279
1280   push @{ $form->{item_list} }, $ref;
1281
1282   #}
1283   $sth->finish;
1284   $dbh->disconnect;
1285
1286   $main::lxdebug->leave_sub();
1287 }
1288
1289 1;