File: IC.pm

package info (click to toggle)
sql-ledger 3.0.8-1
  • links: PTS, VCS
  • area: main
  • in suites: stretch
  • size: 35,524 kB
  • ctags: 4,556
  • sloc: perl: 64,519; sql: 28,330; sh: 34; makefile: 21
file content (1892 lines) | stat: -rw-r--r-- 54,338 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
#=====================================================================
# SQL-Ledger ERP
# Copyright (C) 2006
#
#  Author: DWS Systems Inc.
#     Web: http://www.sql-ledger.com
#
#======================================================================
#
# Inventory Control backend
#
#======================================================================

package IC;


sub get_part {
  my ($self, $myconfig, $form) = @_;

  # connect to db
  my $dbh = $form->dbconnect($myconfig);
  my $i;

  my $query = qq|SELECT p.*,
                 c1.accno AS inventory_accno, c1.description AS inventory_description,
		 c2.accno AS income_accno, c2.description AS income_description,
		 c3.accno AS expense_accno, c3.description AS expense_description,
		 pg.partsgroup, pg.code AS partsgroupcode,
		 l1.description AS inventory_translation,
		 l2.description AS income_translation,
		 l3.description AS expense_translation
	         FROM parts p
		 LEFT JOIN chart c1 ON (p.inventory_accno_id = c1.id)
		 LEFT JOIN translation l1 ON (l1.trans_id = c1.id AND l1.language_code = '$myconfig->{countrycode}')
		 LEFT JOIN chart c2 ON (p.income_accno_id = c2.id)
		 LEFT JOIN translation l2 ON (l2.trans_id = c2.id AND l2.language_code = '$myconfig->{countrycode}')
		 LEFT JOIN chart c3 ON (p.expense_accno_id = c3.id)
		 LEFT JOIN translation l3 ON (l3.trans_id = c3.id AND l3.language_code = '$myconfig->{countrycode}')
		 LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
                 WHERE p.id = $form->{id}|;
  my $sth = $dbh->prepare($query);
  $sth->execute || $form->dberror($query);
  my $ref = $sth->fetchrow_hashref(NAME_lc);

  # copy to $form variables
  $ref->{inventory_description} = $ref->{inventory_translation} if $ref->{inventory_translation};
  $ref->{income_description} = $ref->{income_translation} if $ref->{income_translation};
  $ref->{expense_description} = $ref->{expense_translation} if $ref->{expense_translation};
  
  for (keys %$ref) { $form->{$_} = $ref->{$_} }
  $sth->finish;
  
  # part, service item or labor
  $form->{item} = ($form->{inventory_accno_id}) ? 'part' : 'service';
  $form->{item} = 'labor' if ! $form->{income_accno_id};
    
  if ($form->{assembly}) {
    $form->{item} = 'assembly';

    # retrieve assembly items
    $query = qq|SELECT p.id, p.partnumber, p.description,
                p.sellprice, p.weight, a.qty, a.bom, a.adj, p.unit,
		p.lastcost, p.listprice,
		pg.partsgroup, p.assembly, p.partsgroup_id
                FROM parts p
		JOIN assembly a ON (a.parts_id = p.id)
		LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
		WHERE a.aid = $form->{id}
		ORDER BY a.id|;

    $sth = $dbh->prepare($query);
    $sth->execute || $form->dberror($query);
    
    $form->{assembly_rows} = 0;
    while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
      $form->{assembly_rows}++;
      foreach my $key ( keys %{ $ref } ) {
	$form->{"${key}_$form->{assembly_rows}"} = $ref->{$key};
      }
    }
    $sth->finish;

  }

  # setup accno hash for <option checked> {amount} is used in create_links
  for (qw(inventory income expense)) { $form->{amount}{"IC_$_"} = { accno => $form->{"${_}_accno"}, description => $form->{"${_}_description"} } }


  if ($form->{item} =~ /(part|assembly)/) {
    # get makes
    if ($form->{makemodel} ne "") {
      $query = qq|SELECT make, model
                  FROM makemodel
                  WHERE parts_id = $form->{id}|;

      $sth = $dbh->prepare($query);
      $sth->execute || $form->dberror($query);
      
      while ($ref = $sth->fetchrow_hashref(NAME_lc)) {
	push @{ $form->{makemodels} }, $ref;
      }
      $sth->finish;
    }
  }

  # now get accno for taxes
  $query = qq|SELECT c.accno
              FROM chart c, partstax pt
	      WHERE pt.chart_id = c.id
	      AND pt.parts_id = $form->{id}|;
  
  $sth = $dbh->prepare($query);
  $sth->execute || $form->dberror($query);

  while (($key) = $sth->fetchrow_array) {
    $form->{amount}{$key} = $key;
  }

  $sth->finish;

  # is it an orphan
  $form->{orphaned} = &orphaned("", $dbh, $form);
 
  $form->{orphaned} = 0 if $form->{project_id};

  if ($form->{orphaned}) {
    $form->{orphaned} = !$form->{onhand};
  }

  if ($form->{item} =~ /(part|service)/) {
    # get vendors
    $query = qq|SELECT v.id, v.name, pv.partnumber,
                pv.lastcost, pv.leadtime, pv.curr AS vendorcurr
		FROM partsvendor pv
		JOIN vendor v ON (v.id = pv.vendor_id)
		WHERE pv.parts_id = $form->{id}
		ORDER BY 2|;
    
    $sth = $dbh->prepare($query);
    $sth->execute || $form->dberror($query);
    
    while ($ref = $sth->fetchrow_hashref(NAME_lc)) {
      push @{ $form->{vendormatrix} }, $ref;
    }
    $sth->finish;
  }
 
  # get matrix
  if ($form->{item} ne 'labor') {
    $query = qq|SELECT pc.pricebreak, pc.sellprice AS customerprice,
		pc.curr AS customercurr,
		pc.validfrom, pc.validto,
		c.name, c.id AS cid, g.pricegroup, g.id AS gid
		FROM partscustomer pc
		LEFT JOIN customer c ON (c.id = pc.customer_id)
		LEFT JOIN pricegroup g ON (g.id = pc.pricegroup_id)
		WHERE pc.parts_id = $form->{id}
		ORDER BY c.name, g.pricegroup, pc.pricebreak|;
    $sth = $dbh->prepare($query);
    $sth->execute || $form->dberror($query);

    while ($ref = $sth->fetchrow_hashref(NAME_lc)) {
      push @{ $form->{customermatrix} }, $ref;
    }
    $sth->finish;
  }
 
  $dbh->disconnect;
  
}


sub orphaned {
  my ($self, $dbh, $form) = @_;
  
  my $query = qq|SELECT parts_id
              FROM invoice
	      WHERE parts_id = $form->{id}
	    UNION
	      SELECT parts_id
	      FROM orderitems
	      WHERE parts_id = $form->{id}
	    UNION
	      SELECT parts_id
	      FROM assembly
	      WHERE parts_id = $form->{id}
	    UNION
	      SELECT parts_id
	      FROM jcitems
	      WHERE parts_id = $form->{id}|;
  my ($orphaned) = $dbh->selectrow_array($query);

  !$orphaned;

}


sub save {
  my ($self, $myconfig, $form, $dbh) = @_;

  my $disconnect;
  
  # connect to database, turn off AutoCommit
  if (! $dbh) {
    $disconnect = 1;
    $dbh = $form->dbconnect_noauto($myconfig);
  }

  # undo amount formatting
  for (qw(rop weight listprice sellprice lastcost stock)) { $form->{$_} = $form->parse_amount($myconfig, $form->{$_}) }
  
  $form->{assembly} = $form->{item} eq 'assembly';
  for (qw(alternate obsolete onhand assembly)) { $form->{$_} *= 1 }
  
  if ($form->{id} && $form->{changeup}) {
    
    if ($form->{assembly}) {
      
      my $stock = new Form;
      $stock->{rowcount} = 1;
      $stock->{qty_1} = $form->{onhand} * -1;
      $stock->{id_1} = $form->{id};

      IC->restock_assemblies($myconfig, \%$stock, $dbh);
      
      $query = qq|UPDATE parts SET obsolete = '1'
		  WHERE id = $form->{id}|;
      $dbh->do($query) || $form->dberror($query);
      
      $form->{stock} = $form->{onhand};
      $form->{onhand} = 0;
      $form->{id} = 0;

    } else {
      $form->{id} = 0 unless $form->{orphaned};
    }
    
  }
  
  ($form->{inventory_accno}) = split(/--/, $form->{IC_inventory});
  ($form->{expense_accno}) = split(/--/, $form->{IC_expense});
  ($form->{income_accno}) = split(/--/, $form->{IC_income});

  $form->{makemodel} = (($form->{make_1}) || ($form->{model_1})) ? 1 : 0;
  
  my $query;
  my $sth;
  my $i;
  my $null;
  my $vendor_id;
  my $customer_id;
  
  if ($form->{id}) {

    # get old price
    $query = qq|SELECT id, listprice, sellprice, lastcost, weight, project_id
                FROM parts
		WHERE id = $form->{id}|;
    my ($id, $listprice, $sellprice, $lastcost, $weight, $project_id) = $dbh->selectrow_array($query);

    if ($id) {
      
      if (!$project_id) {
	# if item is part of an assembly adjust all assemblies
	$query = qq|SELECT aid, qty, adj
		    FROM assembly
		    WHERE parts_id = $form->{id}|;
	$sth = $dbh->prepare($query);
	$sth->execute || $form->dberror($query);
	while (my ($id, $qty, $adj) = $sth->fetchrow_array) {
	  &update_assembly($dbh, $form, $id, $qty, $adj, $listprice * 1, $sellprice * 1, $lastcost * 1, $weight * 1);
	}
	$sth->finish;
      }

      if ($form->{item} =~ /(part|service)/) {
	# delete partsvendor records
	$query = qq|DELETE FROM partsvendor
		    WHERE parts_id = $form->{id}|;
	$dbh->do($query) || $form->dberror($query);
      }
       
      if ($form->{item} !~ /(service|labor)/) {
	# delete makemodel records
	$query = qq|DELETE FROM makemodel
		    WHERE parts_id = $form->{id}|;
	$dbh->do($query) || $form->dberror($query);
      }

      if ($form->{item} eq 'assembly') {

	if ($form->{onhand}) {
	  &adjust_inventory($dbh, $form, $form->{id}, $form->{onhand} * -1);
	}
	
	if ($form->{orphaned}) {
	  # delete assembly records
	  $query = qq|DELETE FROM assembly
		      WHERE aid = $form->{id}|;
	  $dbh->do($query) || $form->dberror($query);
	} else {

	  for $i (1 .. $form->{assembly_rows} - 1) {
	    # update BOM, A only
	    for (qw(bom adj)) { $form->{"${_}_$i"} *= 1 }

	    $query = qq|UPDATE assembly SET
	                bom = '$form->{"bom_$i"}',
			adj = '$form->{"adj_$i"}'
			WHERE aid = $form->{id}
			AND parts_id = $form->{"id_$i"}|;
	    $dbh->do($query) || $form->dberror($query);
	  }
	}

	$form->{onhand} += $form->{stock};

      }

      # delete tax records
      $query = qq|DELETE FROM partstax
		  WHERE parts_id = $form->{id}|;
      $dbh->do($query) || $form->dberror($query);

      # delete matrix
      $query = qq|DELETE FROM partscustomer
		  WHERE parts_id = $form->{id}|;
      $dbh->do($query) || $form->dberror($query);
      
    } else {
      $query = qq|INSERT INTO parts (id)
                  VALUES ($form->{id})|;
      $dbh->do($query) || $form->dberror($query);
    }

  }
  
  
  if (!$form->{id}) {
    my $uid = localtime;
    $uid .= $$;

    $query = qq|INSERT INTO parts (partnumber)
                VALUES ('$uid')|;
    $dbh->do($query) || $form->dberror($query);

    $query = qq|SELECT id FROM parts
                WHERE partnumber = '$uid'|;
    $sth = $dbh->prepare($query);
    $sth->execute || $form->dberror($query);
    ($form->{id}) = $sth->fetchrow_array;
    $sth->finish;

    $form->{orphaned} = 1;
    $form->{onhand} = ($form->{stock} * 1) if $form->{item} eq 'assembly';
    
  }

  my $partsgroup_id;
  ($null, $partsgroup_id) = split /--/, $form->{partsgroup};
  $partsgroup_id *= 1;

  $form->{partnumber} = $form->update_defaults($myconfig, "partnumber", $dbh) if ! $form->{partnumber};

  $query = qq|UPDATE parts SET
	      partnumber = |.$dbh->quote($form->{partnumber}).qq|,
	      description = |.$dbh->quote($form->{description}).qq|,
	      makemodel = '$form->{makemodel}',
	      alternate = '$form->{alternate}',
	      assembly = '$form->{assembly}',
	      listprice = $form->{listprice},
	      sellprice = $form->{sellprice},
	      lastcost = $form->{lastcost},
	      weight = $form->{weight},
	      priceupdate = |.$form->dbquote($form->{priceupdate}, SQL_DATE).qq|,
	      unit = |.$dbh->quote($form->{unit}).qq|,
	      notes = |.$dbh->quote($form->{notes}).qq|,
	      rop = $form->{rop},
	      bin = |.$dbh->quote($form->{bin}).qq|,
	      inventory_accno_id = (SELECT id FROM chart
				    WHERE accno = '$form->{inventory_accno}'),
	      income_accno_id = (SELECT id FROM chart
				 WHERE accno = '$form->{income_accno}'),
	      expense_accno_id = (SELECT id FROM chart
				  WHERE accno = '$form->{expense_accno}'),
              obsolete = '$form->{obsolete}',
	      image = '$form->{image}',
	      drawing = '$form->{drawing}',
	      microfiche = '$form->{microfiche}',
	      partsgroup_id = $partsgroup_id,
	      toolnumber = '$form->{toolnumber}',
	      countryorigin = '$form->{countryorigin}',
	      tariff_hscode = '$form->{tariff_hscode}',
	      barcode = '$form->{barcode}'
	      WHERE id = $form->{id}|;
  $dbh->do($query) || $form->dberror($query);

 
  # insert makemodel records
  if ($form->{item} =~ /(part|assembly)/) {
    for $i (1 .. $form->{makemodel_rows}) {
      if (($form->{"make_$i"} ne "") || ($form->{"model_$i"} ne "")) {
	$query = qq|INSERT INTO makemodel (parts_id, make, model)
		    VALUES ($form->{id},|
		    .$dbh->quote($form->{"make_$i"}).qq|, |
		    .$dbh->quote($form->{"model_$i"}).qq|)|;
	$dbh->do($query) || $form->dberror($query);
      }
    }
  }


  # insert taxes
  for (split / /, $form->{taxaccounts}) {
    if ($form->{"IC_tax_$_"}) {
      $query = qq|INSERT INTO partstax (parts_id, chart_id)
                  VALUES ($form->{id}, 
		          (SELECT id
			   FROM chart
			   WHERE accno = '$_'))|;
      $dbh->do($query) || $form->dberror($query);
    }
  }
  
  
  @lt = localtime;
  $lt[5] += 1900;
  $lt[4]++;
  $lt[4] = substr("0$lt[4]", -2);
  $lt[3] = substr("0$lt[3]", -2);
  my $shippingdate = "$lt[5]$lt[4]$lt[3]";
  
  ($form->{employee}, $form->{employee_id}) = $form->get_employee($dbh);
 
  # add assembly records
  if ($form->{item} eq 'assembly' && !$project_id) {
    
    if ($form->{orphaned}) {
      for $i (1 .. $form->{assembly_rows}) {
	$form->{"qty_$i"} = $form->parse_amount($myconfig, $form->{"qty_$i"});
	
	if ($form->{"qty_$i"}) {
	  for (qw(bom adj)) { $form->{"${_}_$i"} *= 1 }
	  $query = qq|INSERT INTO assembly (aid, parts_id, qty, bom, adj)
		      VALUES ($form->{id}, $form->{"id_$i"},
		      $form->{"qty_$i"}, '$form->{"bom_$i"}',
		      '$form->{"adj_$i"}')|;
	  $dbh->do($query) || $form->dberror($query);
	}
      }
    }
    
    # adjust onhand for the parts
    if ($form->{onhand}) {
      &adjust_inventory($dbh, $form, $form->{id}, $form->{onhand});
    }

  }

  # add vendors
  if ($form->{item} ne 'assembly') {
    
    for $i (1 .. $form->{vendor_rows}) {
      if (($form->{"vendor_$i"} ne "") && $form->{"lastcost_$i"}) {

        ($null, $vendor_id) = split /--/, $form->{"vendor_$i"};
	
	for (qw(lastcost leadtime)) { $form->{"${_}_$i"} = $form->parse_amount($myconfig, $form->{"${_}_$i"})}
	
	$query = qq|INSERT INTO partsvendor (vendor_id, parts_id, partnumber,
	            lastcost, leadtime, curr)
		    VALUES ($vendor_id, $form->{id},|
		    .$dbh->quote($form->{"partnumber_$i"}).qq|,
		    $form->{"lastcost_$i"},
		    $form->{"leadtime_$i"}, '$form->{"vendorcurr_$i"}')|;
	$dbh->do($query) || $form->dberror($query);
      }
    }
  }
  
  
  # add pricematrix
  for $i (1 .. $form->{customer_rows}) {

    for (qw(pricebreak customerprice)) { $form->{"${_}_$i"} = $form->parse_amount($myconfig, $form->{"${_}_$i"})}

    if ($form->{"customerprice_$i"}) {

      ($null, $customer_id) = split /--/, $form->{"customer_$i"};
      $customer_id *= 1;
      
      ($null, $pricegroup_id) = split /--/, $form->{"pricegroup_$i"};
      $pricegroup_id *= 1;
      
      $query = qq|INSERT INTO partscustomer (parts_id, customer_id,
                  pricegroup_id, pricebreak, sellprice, curr,
		  validfrom, validto)
		  VALUES ($form->{id}, $customer_id,
		  $pricegroup_id, $form->{"pricebreak_$i"},
		  $form->{"customerprice_$i"}, '$form->{"customercurr_$i"}',|
		  .$form->dbquote($form->{"validfrom_$i"}, SQL_DATE).qq|, |
		  .$form->dbquote($form->{"validto_$i"}, SQL_DATE).qq|)|;
      $dbh->do($query) || $form->dberror($query);
    }
  }

  # commit
  my $rc = $dbh->commit;

  $dbh->disconnect if $disconnect;

  $rc;
  
}



sub update_assembly {
  my ($dbh, $form, $id, $qty, $adj, $listprice, $sellprice, $lastcost, $weight) = @_;

  my $formlistprice = $form->{listprice};
  my $formsellprice = $form->{sellprice};
  
  if (!$adj) {
    $formlistprice = $listprice;
    $formsellprice = $sellprice;
  }
  
  my $query = qq|SELECT aid, qty, adj
                 FROM assembly
	         WHERE parts_id = $id|;
  my $sth = $dbh->prepare($query);
  $sth->execute || $form->dberror($query);

  $form->{$id} = 1;
  
  while (my ($pid, $aqty, $aadj) = $sth->fetchrow_array) {
    &update_assembly($dbh, $form, $pid, $aqty * $qty, $aadj, $listprice, $sellprice, $lastcost, $weight) if !$form->{$pid};
  }
  $sth->finish;

  $query = qq|UPDATE parts
              SET listprice = listprice + $qty * ($formlistprice - $listprice),
	          sellprice = sellprice + $qty * ($formsellprice - $sellprice),
		  lastcost = lastcost + $qty * ($form->{lastcost} - $lastcost),
                  weight = weight + $qty * ($form->{weight} - $weight)
	      WHERE id = $id|;
  $dbh->do($query) || $form->dberror($query);

  delete $form->{$id};
  
}



sub retrieve_assemblies {
  my ($self, $myconfig, $form) = @_;
  
  # connect to database
  my $dbh = $form->dbconnect($myconfig);

  my $var;
  my $where = '1 = 1';
  
  if ($form->{partnumber} ne "") {
    $var = $form->like(lc $form->{partnumber});
    $where .= " AND lower(p.partnumber) LIKE '$var'";
  }
  
  if ($form->{description} ne "") {
    $var = $form->like(lc $form->{description});
    $where .= " AND lower(p.description) LIKE '$var'";
  }
  $where .= qq| AND p.obsolete = '0'
                AND p.project_id IS NULL|;

  # retrieve assembly items
  my $query = qq|SELECT p.id, p.partnumber, p.description,
                 p.bin, p.onhand, p.rop
                 FROM parts p
 		 WHERE $where
		 AND p.assembly = '1'|;

  my @sf = qw(partnumber description bin);
  my %ordinal = $form->ordinal_order($dbh, $query);
  $query .= qq| ORDER BY | .$form->sort_order(\@sf, \%ordinal);

  my $sth = $dbh->prepare($query);
  $sth->execute || $form->dberror($query);
  
  $query = qq|SELECT sum(p.inventory_accno_id), p.assembly
              FROM parts p
	      JOIN assembly a ON (a.parts_id = p.id)
	      WHERE a.aid = ?
	      GROUP BY p.assembly|;
  my $svh = $dbh->prepare($query) || $form->dberror($query);
  
  my $inh;
  if ($form->{checkinventory}) {
    $query = qq|SELECT p.id, p.onhand, a.qty
                FROM parts p
                JOIN assembly a ON (a.parts_id = p.id)
		WHERE (p.inventory_accno_id > 0 OR p.assembly)
		AND p.income_accno_id > 0
                AND a.aid = ?|;
    $inh = $dbh->prepare($query) || $form->dberror($query);
  }
  
  my %available = ();
  my %required;
  my $ref;
  my $aref;
  my $stock;
  my $howmany;
  my $ok;
  
  while ($ref = $sth->fetchrow_hashref(NAME_lc)) {
    $svh->execute($ref->{id});
    ($ref->{inventory}, $ref->{assembly}) = $svh->fetchrow_array;
    $svh->finish;
    
    if ($ref->{inventory} || $ref->{assembly}) {
      $ok = 1;
      if ($form->{checkinventory}) {
	$inh->execute($ref->{id}) || $form->dberror($query);;
	$ok = 0;
	%required = ();
	
	while ($aref = $inh->fetchrow_hashref(NAME_lc)) {
	  $available{$aref->{id}} = (exists $available{$aref->{id}}) ? $available{$aref->{id}} : $aref->{onhand};
	  $required{$aref->{id}} = $aref->{qty};
	  
	  if ($available{$aref->{id}} >= $aref->{qty}) {
	    
	    $howmany = ($aref->{qty}) ? int $available{$aref->{id}}/$aref->{qty} : 1;
	    if ($stock) {
	      $stock = ($stock > $howmany) ? $howmany : $stock;
	    } else {
	      $stock = $howmany;
	    }
	    $ok = 1;

	    $available{$aref->{id}} -= $aref->{qty} * $stock;

	  } else {
	    $ok = 0;
	    for (keys %required) { $available{$_} += $required{$_} * $stock }
	    $stock = 0;
	    last;
	  }
	}
	$inh->finish;
	$ref->{stock} = $stock;
	
      }
      push @{ $form->{assembly_items} }, $ref if $ok;
    }
  }
  $sth->finish;

  $dbh->disconnect;
  
}


sub restock_assemblies {
  my ($self, $myconfig, $form, $dbh) = @_;

  my $disconnect;
  
  # connect to database
  if (!$dbh) {
    $dbh = $form->dbconnect_noauto($myconfig);
    $disconnect = 1;
  }
   
  for my $i (1 .. $form->{rowcount}) {

    $form->{"qty_$i"} = $form->parse_amount($myconfig, $form->{"qty_$i"});

    if ($form->{"qty_$i"}) {
      &adjust_inventory($dbh, $form, $form->{"id_$i"}, $form->{"qty_$i"});
    }
 
  }

  my $rc;

  if ($disconnect) {
    $rc = $dbh->commit;
    $dbh->disconnect;
  }

  $rc;

}


sub adjust_inventory {
  my ($dbh, $form, $id, $qty) = @_;

  my $query = qq|SELECT p.id, p.inventory_accno_id, p.assembly, a.qty
		 FROM parts p
		 JOIN assembly a ON (a.parts_id = p.id)
		 WHERE a.aid = $id|;
  my $sth = $dbh->prepare($query);
  $sth->execute || $form->dberror($query);

  while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {

    # is it a service item then loop
    if (! $ref->{inventory_accno_id}) {
      next if ! $ref->{assembly};              # assembly
    }
    
    # adjust parts onhand
    $form->update_balance($dbh,
			  "parts",
			  "onhand",
			  qq|id = $ref->{id}|,
			  $qty * $ref->{qty} * -1);
  }

  $sth->finish;

  # update assembly
  $form->update_balance($dbh,
			"parts",
			"onhand",
			qq|id = $id|,
			$qty);

}


sub delete {
  my ($self, $myconfig, $form) = @_;

  # connect to database, turn off AutoCommit
  my $dbh = $form->dbconnect_noauto($myconfig);

  my $query;

  $query = qq|DELETE FROM parts
 	      WHERE id = $form->{id}|;
  $dbh->do($query) || $form->dberror($query);

  $query = qq|DELETE FROM partstax
	      WHERE parts_id = $form->{id}|;
  $dbh->do($query) || $form->dberror($query);


  if ($form->{item} ne 'assembly') {
    $query = qq|DELETE FROM partsvendor
		WHERE parts_id = $form->{id}|;
    $dbh->do($query) || $form->dberror($query);
  }

  # check if it is a part, assembly or service
  if ($form->{item} ne 'service') {
    $query = qq|DELETE FROM makemodel
		WHERE parts_id = $form->{id}|;
    $dbh->do($query) || $form->dberror($query);
  }

  if ($form->{item} eq 'assembly') {
    $query = qq|DELETE FROM assembly
		WHERE aid = $form->{id}|;
    $dbh->do($query) || $form->dberror($query);
  }
  
  if ($form->{item} eq 'alternate') {
    $query = qq|DELETE FROM alternate
		WHERE id = $form->{id}|;
    $dbh->do($query) || $form->dberror($query);
  }

  $query = qq|DELETE FROM inventory
	      WHERE parts_id = $form->{id}|;
  $dbh->do($query) || $form->dberror($query);
  
  $query = qq|DELETE FROM partscustomer
	      WHERE parts_id = $form->{id}|;
  $dbh->do($query) || $form->dberror($query);
  
  $query = qq|DELETE FROM translation
	      WHERE trans_id = $form->{id}|;
  $dbh->do($query) || $form->dberror($query);

  # commit
  my $rc = $dbh->commit;
  $dbh->disconnect;

  $rc;
  
}


sub assembly_item {
  my ($self, $myconfig, $form) = @_;

  my $i = $form->{assembly_rows};
  my $var;
  my $null;
  my $where = "p.obsolete = '0'";

  if ($form->{"partnumber_$i"} ne "") {
    $var = $form->like(lc $form->{"partnumber_$i"});
    $where .= " AND lower(p.partnumber) LIKE '$var'";
  }
  if ($form->{"description_$i"} ne "") {
    $var = $form->like(lc $form->{"description_$i"});
    $where .= " AND lower(p.description) LIKE '$var'";
  }
  if ($form->{"partsgroup_$i"} ne "") {
    ($null, $var) = split /--/, $form->{"partsgroup_$i"};
    $where .= qq| AND p.partsgroup_id = $var|;
  }

  if ($form->{id}) {
    $where .= " AND p.id != $form->{id}";
  }

  if ($form->{"description_$i"} ne "") {
    $where .= " ORDER BY p.description";
  } else {
    $where .= " ORDER BY p.partnumber";
  }

  # connect to database
  my $dbh = $form->dbconnect($myconfig);

  my $query = qq|SELECT p.id, p.partnumber, p.description, p.sellprice,
                 p.weight, p.onhand, p.unit, p.lastcost,
		 pg.partsgroup, p.partsgroup_id
		 FROM parts p
		 LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
		 WHERE $where|;
  my $sth = $dbh->prepare($query);
  $sth->execute || $form->dberror($query);

  while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
    push @{ $form->{item_list} }, $ref;
  }
  
  $sth->finish;
  $dbh->disconnect;
  
}


sub all_parts {
  my ($self, $myconfig, $form) = @_;

  my $where = '1 = 1';
  my $null;
  my $var;
  my $ref;
  
  for (qw(partnumber drawing microfiche toolnumber barcode)) {
    if ($form->{$_} ne "") {
      $var = $form->like(lc $form->{$_});
      $where .= " AND lower(p.$_) LIKE '$var'";
    }
  }
  # special case for description
  if ($form->{description} ne "") {
    unless ($form->{bought} || $form->{sold} || $form->{onorder} || $form->{ordered} || $form->{rfq} || $form->{quoted}) {
      $var = $form->like(lc $form->{description});
      $where .= " AND lower(p.description) LIKE '$var'";
    }
  }
  
  # assembly components
  my $assemblyflds;
  if ($form->{searchitems} eq 'component') {
    $assemblyflds = qq|, p1.partnumber AS assemblypartnumber, a.aid AS assembly_id|;
  }

  # special case for serialnumber
  if ($form->{l_serialnumber}) {
    if ($form->{serialnumber} ne "") {
      $var = $form->like(lc $form->{serialnumber});
      $where .= " AND lower(i.serialnumber) LIKE '$var'";
    }
  }

  if (($form->{warehouse} ne "") || $form->{l_warehouse}) {
    $form->{l_warehouse} = 1;
  }
  
  if ($form->{searchitems} eq 'part') {
    $where .= " AND p.inventory_accno_id > 0 AND p.income_accno_id > 0";
  }
  if ($form->{searchitems} =~ /assembly/) {
    $form->{bought} = "";
    $where .= " AND p.assembly = '1'";
  }
  if ($form->{searchitems} eq 'service') {
    $where .= " AND p.assembly = '0' AND p.inventory_accno_id IS NULL";
  }
  if ($form->{searchitems} eq 'labor') {
    $where .= " AND p.inventory_accno_id > 0 AND p.income_accno_id IS NULL";
  }

  # items which were never bought, sold or on an order
  if ($form->{itemstatus} eq 'orphaned') {
    $where .= qq| AND p.onhand = 0
                  AND p.id NOT IN (SELECT p.id FROM parts p
		                   JOIN invoice i ON (p.id = i.parts_id))
		  AND p.id NOT IN (SELECT p.id FROM parts p
		                   JOIN assembly a ON (p.id = a.parts_id))
                  AND p.id NOT IN (SELECT p.id FROM parts p
		                   JOIN orderitems o ON (p.id = o.parts_id))
		  AND p.id NOT IN (SELECT p.id FROM parts p
		                   JOIN jcitems j ON (p.id = j.parts_id))|;
  }
  
  if ($form->{itemstatus} eq 'active') {
    $where .= " AND p.obsolete = '0'";
  }
  if ($form->{itemstatus} eq 'obsolete') {
    $where .= " AND p.obsolete = '1'";
  }
  if ($form->{itemstatus} eq 'onhand') {
    $where .= " AND p.onhand > 0";
  }
  if ($form->{itemstatus} eq 'short') {
    $where .= " AND p.onhand < p.rop";
  }

  my $costflds;
  my $invoicejoin;

  if ($form->{l_cost}) {
    $invoicejoin = " JOIN invoice i ON (i.parts_id = p.id)";
    $costflds = qq|, i.sellprice AS cost|;
    $where .= " AND (i.qty - i.allocated) < 0";
  }
  
  my $makemodelflds = qq|, '', ''|;;
  my $makemodeljoin;
  
  if (($form->{make} ne "") || $form->{l_make} || ($form->{model} ne "") || $form->{l_model}) {
    $makemodelflds = qq|, m.make, m.model|;
    $makemodeljoin = qq|LEFT JOIN makemodel m ON (m.parts_id = p.id)|;
    
    if ($form->{make} ne "") {
      $var = $form->like(lc $form->{make});
      $where .= " AND lower(m.make) LIKE '$var'";
    }
    if ($form->{model} ne "") {
      $var = $form->like(lc $form->{model});
      $where .= " AND lower(m.model) LIKE '$var'";
    }
  }
  if ($form->{partsgroup} ne "") {
    ($null, $var) = split /--/, $form->{partsgroup};
    $where .= qq| AND p.partsgroup_id = $var|;
  }

  # connect to database
  my $dbh = $form->dbconnect($myconfig);
  
  my %defaults = $form->get_defaults($dbh, \@{['precision', 'company', 'printer_%']});
  my $label;
  my $command;
  for (keys %defaults) {
    if ($_ =~ /printer_/) {
      ($label, $command) = split /=/, $defaults{$_};
      $form->{"${label}_printer"} = $command;
    } else {
      $form->{$_} = $defaults{$_};
    }
  }

  my @sf = qw(partnumber description);

  my $query;
  
  my $curr = substr($form->get_currencies($dbh, $myconfig),0,3);
  
  my $flds = qq|p.id, p.partnumber, p.description, p.onhand, p.unit,
                p.bin, p.sellprice, p.listprice, p.lastcost, p.rop,
		p.avgcost,
		p.weight, p.priceupdate, p.image, p.drawing, p.microfiche,
		p.assembly, pg.partsgroup, pg.code AS partsgroupcode,
		'$curr' AS curr,
		c1.accno AS inventory, c2.accno AS income, c3.accno AS expense,
		p.notes, p.toolnumber, p.countryorigin, p.tariff_hscode,
		p.barcode
		$makemodelflds $assemblyflds $costflds
		|;

  if ($form->{l_cost}) {
    $flds =~ s/p.onhand/(i.qty + i.allocated) * -1 AS onhand/;
  }

  $query = qq|SELECT $flds
	      FROM parts p
	      LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
	      LEFT JOIN chart c1 ON (c1.id = p.inventory_accno_id)
	      LEFT JOIN chart c2 ON (c2.id = p.income_accno_id)
	      LEFT JOIN chart c3 ON (c3.id = p.expense_accno_id)
	      $makemodeljoin
	      $invoicejoin
  	      WHERE $where|;

  # redo query for components report
  if ($form->{searchitems} eq 'component') {
    
    $flds =~ s/p.onhand/a.qty AS onhand/;
    
    $query = qq|SELECT $flds
		FROM assembly a
		JOIN parts p ON (a.parts_id = p.id)
		JOIN parts p1 ON (a.aid = p1.id)
		LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
		LEFT JOIN chart c1 ON (c1.id = p.inventory_accno_id)
		LEFT JOIN chart c2 ON (c2.id = p.income_accno_id)
		LEFT JOIN chart c3 ON (c3.id = p.expense_accno_id)
		$makemodeljoin
  	        WHERE $where
	        ORDER BY $sortorder|;
  }

  # rebuild query for bought and sold items
  if ($form->{bought} || $form->{sold} || $form->{onorder} || $form->{ordered} || $form->{rfq} || $form->{quoted}) {

    $form->sort_order();
    @sf = qw(partnumber description curr employee name serialnumber id);
    push @sf, "invnumber" if ($form->{bought} || $form->{sold});
    push @sf, "ordnumber" if ($form->{onorder} || $form->{ordered});
    push @sf, "quonumber" if ($form->{rfq} || $form->{quoted});

    my $union = "";
    $query = "";
  
    if ($form->{bought} || $form->{sold}) {
      
      my $invwhere = "$where";
      my $transdate = ($form->{method} eq 'accrual') ? "transdate" : "datepaid";
      
      $invwhere .= " AND i.assemblyitem = '0'";
      $invwhere .= " AND a.$transdate >= '$form->{transdatefrom}'" if $form->{transdatefrom};
      $invwhere .= " AND a.$transdate <= '$form->{transdateto}'" if $form->{transdateto};

      if ($form->{description} ne "") {
	$var = $form->like(lc $form->{description});
	$invwhere .= " AND lower(i.description) LIKE '$var'";
      }

      if ($form->{open} || $form->{closed}) {
	if ($form->{open} && $form->{closed}) {
	  if ($form->{method} eq 'cash') {
	    $invwhere .= " AND a.amount = a.paid";
	  }
	} else {
	  if ($form->{open}) {
	    if ($form->{method} eq 'cash') {
	      $invwhere .= " AND a.id = 0";
	    } else {
	      $invwhere .= " AND NOT a.amount = a.paid";
	    }
	  } else {
	    $invwhere .= " AND a.amount = a.paid";
	  }
	}
      } else {
	$invwhere .= " AND a.id = 0";
      }

      my $flds = qq|p.id, p.partnumber, i.description, i.serialnumber,
                    i.qty AS onhand, i.unit, p.bin, i.sellprice,
		    p.listprice, p.lastcost, p.rop, p.weight,
		    p.avgcost,
		    p.priceupdate, p.image, p.drawing, p.microfiche,
		    p.assembly,
		    pg.partsgroup, pg.code AS partsgroupcode,
		    a.invnumber, a.ordnumber, a.quonumber,
		    i.trans_id, ct.name, e.name AS employee,
		    a.curr, a.till, p.notes, p.toolnumber,
		    p.countryorigin, p.tariff_hscode, p.barcode
		    $makemodelflds $costflds|;

      my $rflds;
      
      if ($form->{bought}) {
	
	$rflds = $flds;

	if ($form->{l_cost}) {
	  $rflds =~ s/i.sellprice/p.sellprice/;
	  $rflds =~ s/i.qty AS onhand/(i.qty + i.allocated) * -1 AS onhand/;
	} else {
	  $rflds =~ s/i.qty AS onhand/i.qty * -1 AS onhand/;
	}

	$query = qq|
	            SELECT $rflds, 'ir' AS module, '' AS type,
		    (SELECT exchangerate FROM exchangerate ex
		     WHERE ex.curr = a.curr
		     AND ex.transdate = a.$transdate) AS exchangerate,
		     i.discount, ct.id AS vc_id, 'vendor' as vc
		    FROM invoice i
		    JOIN parts p ON (p.id = i.parts_id)
		    JOIN ap a ON (a.id = i.trans_id)
		    JOIN vendor ct ON (a.vendor_id = ct.id)
		    LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
		    LEFT JOIN employee e ON (a.employee_id = e.id)
		    $makemodeljoin
		    WHERE $invwhere|;
	$union = "
	          UNION ALL";
      }

      if ($form->{sold}) {
	
	$query .= qq|$union
                     SELECT $flds, 'is' AS module, '' AS type,
		    (SELECT exchangerate FROM exchangerate ex
		     WHERE ex.curr = a.curr
		     AND ex.transdate = a.$transdate) AS exchangerate,
		     i.discount, ct.id AS vc_id, 'customer' as vc
		     FROM invoice i
		     JOIN parts p ON (p.id = i.parts_id)
		     JOIN ar a ON (a.id = i.trans_id)
		     JOIN customer ct ON (a.customer_id = ct.id)
		     LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
		     LEFT JOIN employee e ON (a.employee_id = e.id)
		     $makemodeljoin
		     WHERE $invwhere|;
	$union = "
	          UNION ALL";
      }
    }

    if (! $form->{l_cost}) {
      if ($form->{onorder} || $form->{ordered}) {
	my $ordwhere = "$where
		       AND a.quotation = '0'";
	$ordwhere .= " AND a.transdate >= '$form->{transdatefrom}'" if $form->{transdatefrom};
	$ordwhere .= " AND a.transdate <= '$form->{transdateto}'" if $form->{transdateto};

	if ($form->{description} ne "") {
	  $var = $form->like(lc $form->{description});
	  $ordwhere .= " AND lower(i.description) LIKE '$var'";
	}
	
	if ($form->{open} || $form->{closed}) {
	  unless ($form->{open} && $form->{closed}) {
	    $ordwhere .= " AND a.closed = '0'" if $form->{open};
	    $ordwhere .= " AND a.closed = '1'" if $form->{closed};
	  }
	} else {
	  $ordwhere .= " AND a.id = 0";
	}

	$flds = qq|p.id, p.partnumber, i.description, i.serialnumber,
		   i.qty AS onhand, i.unit, p.bin, i.sellprice,
		   p.listprice, p.lastcost, p.rop, p.weight,
		   p.avgcost,
		   p.priceupdate, p.image, p.drawing, p.microfiche,
		   p.assembly,
		   pg.partsgroup, pg.code AS partsgroupcode,
		   '' AS invnumber, a.ordnumber, a.quonumber,
		   i.trans_id, ct.name, e.name AS employee,
		   a.curr, '0' AS till, p.notes, p.toolnumber,
		   p.countryorigin, p.tariff_hscode, p.barcode
		   $makemodelflds|;

	if ($form->{ordered}) {
	  $query .= qq|$union
		       SELECT $flds, 'oe' AS module, 'sales_order' AS type,
		      (SELECT exchangerate FROM exchangerate ex
		       WHERE ex.curr = a.curr
		       AND ex.transdate = a.transdate) AS exchangerate,
		       i.discount, ct.id AS vc_id, 'customer' as vc
		       FROM orderitems i
		       JOIN parts p ON (i.parts_id = p.id)
		       JOIN oe a ON (i.trans_id = a.id)
		       JOIN customer ct ON (a.customer_id = ct.id)
		       LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
		       LEFT JOIN employee e ON (a.employee_id = e.id)
		       $makemodeljoin
		       WHERE $ordwhere
		       AND a.customer_id > 0|;
	  $union = "
		    UNION ALL";
	}
	
	if ($form->{onorder}) {
	  $flds = qq|p.id, p.partnumber, i.description, i.serialnumber,
		     i.qty AS onhand, i.unit, p.bin, i.sellprice,
		     p.listprice, p.lastcost, p.rop, p.weight,
		     p.avgcost,
		     p.priceupdate, p.image, p.drawing, p.microfiche,
		     p.assembly,
		     pg.partsgroup, pg.code AS partsgroupcode,
		     '' AS invnumber, a.ordnumber, a.quonumber,
		     i.trans_id, ct.name, e.name AS employee,
		     a.curr, '0' AS till, p.notes, p.toolnumber,
		     p.countryorigin, p.tariff_hscode, p.barcode
		     $makemodelflds|;
		     
	  $query .= qq|$union
		      SELECT $flds, 'oe' AS module, 'purchase_order' AS type,
		      (SELECT exchangerate FROM exchangerate ex
		       WHERE ex.curr = a.curr
		       AND ex.transdate = a.transdate) AS exchangerate,
		       i.discount, ct.id AS vc_id, 'vendor' as vc
		      FROM orderitems i
		      JOIN parts p ON (i.parts_id = p.id)
		      JOIN oe a ON (i.trans_id = a.id)
		      JOIN vendor ct ON (a.vendor_id = ct.id)
		      LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
		      LEFT JOIN employee e ON (a.employee_id = e.id)
		      $makemodeljoin
		      WHERE $ordwhere
		      AND a.vendor_id > 0|;
	  $union = "
		    UNION ALL";
	}
      
      }
	
      if ($form->{rfq} || $form->{quoted}) {
	my $quowhere = "$where
		       AND a.quotation = '1'";
	$quowhere .= " AND a.transdate >= '$form->{transdatefrom}'" if $form->{transdatefrom};
	$quowhere .= " AND a.transdate <= '$form->{transdateto}'" if $form->{transdateto};

	if ($form->{description} ne "") {
	  $var = $form->like(lc $form->{description});
	  $quowhere .= " AND lower(i.description) LIKE '$var'";
	}
	
	if ($form->{open} || $form->{closed}) {
	  unless ($form->{open} && $form->{closed}) {
	    $ordwhere .= " AND a.closed = '0'" if $form->{open};
	    $ordwhere .= " AND a.closed = '1'" if $form->{closed};
	  }
	} else {
	  $ordwhere .= " AND a.id = 0";
	}

	$flds = qq|p.id, p.partnumber, i.description, i.serialnumber,
		   i.qty AS onhand, i.unit, p.bin, i.sellprice,
		   p.listprice, p.lastcost, p.rop, p.weight,
		   p.avgcost,
		   p.priceupdate, p.image, p.drawing, p.microfiche,
		   p.assembly,
		   pg.partsgroup, pg.code AS partsgroupcode,
		   '' AS invnumber, a.ordnumber, a.quonumber,
		   i.trans_id, ct.name, e.name AS employee,
		   a.curr, '0' AS till, p.notes, p.toolnumber,
		   p.countryorigin, p.tariff_hscode, p.barcode
		   $makemodelflds|;

	if ($form->{quoted}) {
	  $query .= qq|$union
		       SELECT $flds, 'oe' AS module, 'sales_quotation' AS type,
		      (SELECT exchangerate FROM exchangerate ex
		       WHERE ex.curr = a.curr
		       AND ex.transdate = a.transdate) AS exchangerate,
		       i.discount, ct.id AS vc_id, 'customer' as vc
		       FROM orderitems i
		       JOIN parts p ON (i.parts_id = p.id)
		       JOIN oe a ON (i.trans_id = a.id)
		       JOIN customer ct ON (a.customer_id = ct.id)
		       LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
		       LEFT JOIN employee e ON (a.employee_id = e.id)
		       $makemodeljoin
		       WHERE $quowhere
		       AND a.customer_id > 0|;
	  $union = "
		    UNION ALL";
	}
	
	if ($form->{rfq}) {
	  $flds = qq|p.id, p.partnumber, i.description, i.serialnumber,
		     i.qty AS onhand, i.unit, p.bin, i.sellprice,
		     p.listprice, p.lastcost, p.rop, p.weight,
		     p.avgcost,
		     p.priceupdate, p.image, p.drawing, p.microfiche,
		     p.assembly,
		     pg.partsgroup, pg.code AS partsgroupcode,
		     '' AS invnumber, a.ordnumber, a.quonumber,
		     i.trans_id, ct.name, e.name AS employee,
		     a.curr, '0' AS till, p.notes, p.toolnumber,
		     p.countryorigin, p.tariff_hscode, p.barcode
		     $makemodelflds|;

	  $query .= qq|$union
		      SELECT $flds, 'oe' AS module, 'request_quotation' AS type,
		      (SELECT exchangerate FROM exchangerate ex
		       WHERE ex.curr = a.curr
		       AND ex.transdate = a.transdate) AS exchangerate,
		       i.discount, ct.id AS vc_id, 'vendor' as vc
		      FROM orderitems i
		      JOIN parts p ON (i.parts_id = p.id)
		      JOIN oe a ON (i.trans_id = a.id)
		      JOIN vendor ct ON (a.vendor_id = ct.id)
		      LEFT JOIN partsgroup pg ON (p.partsgroup_id = pg.id)
		      LEFT JOIN employee e ON (a.employee_id = e.id)
		      $makemodeljoin
		      WHERE $quowhere
		      AND a.vendor_id > 0|;
	  $union = "
		    UNION ALL";
	}

      }
    }
  }

  my %ordinal = $form->ordinal_order($dbh, $query);
  $query .= qq| ORDER BY | .$form->sort_order(\@sf, \%ordinal);

  my $sth = $dbh->prepare($query);
  $sth->execute || $form->dberror($query);

  $query = qq|SELECT c.accno
              FROM chart c
	      JOIN partstax pt ON (pt.chart_id = c.id)
	      WHERE pt.parts_id = ?
	      ORDER BY c.accno|;
  my $pth = $dbh->prepare($query) || $form->dberror($query);
  
  while ($ref = $sth->fetchrow_hashref(NAME_lc)) {
    $pth->execute($ref->{id});
    while (($accno) = $pth->fetchrow_array) {
      $ref->{tax} .= "$accno ";
    }
    $pth->finish;
    
    push @{ $form->{parts} }, $ref;
  }
  $sth->finish;

  my @li = ();
  
  # include individual items for assembly
  if (($form->{searchitems} =~ /assembly/) && $form->{individual}) {

    if ($form->{sold} || $form->{ordered} || $form->{quoted}) {
      $flds = qq|p.id, p.partnumber, p.description, p.onhand AS perassembly, p.unit,
                 p.bin, p.sellprice, p.listprice, p.lastcost, p.rop,
		 p.avgcost,
 		 p.weight, p.priceupdate, p.image, p.drawing, p.microfiche,
		 p.assembly, pg.partsgroup, pg.code AS partsgroupcode,
		 p.notes, p.toolnumber, p.barcode
		 $makemodelflds $assemblyflds
		 |;
    } else {
      # replace p.onhand with a.qty AS onhand
      $flds =~ s/p.onhand/a.qty AS perassembly/;
    }
	
    for (@{ $form->{parts} }) {
      push @li, $_;
      $_->{perassembly} = 1;
      $flds =~ s/p\.onhand*AS perassembly/p\.onhand, a\.qty AS perassembly/;
      push @li, &include_assembly($dbh, $myconfig, $form, $_->{id}, $flds, $makemodeljoin);
      push @li, {id => $_->{id}, assemblyitem => 1};  # this is just for
                                                     # adding a blank line
    }

    # copy assemblies to $form->{parts}
    @{ $form->{parts} } = @li;
    
  }
    
  
  @li = ();
  if (($form->{warehouse} ne "") || $form->{l_warehouse}) {
    
    if ($form->{warehouse} ne "") {
      ($null, $var) = split /--/, $form->{warehouse};
      $var *= 1;
      $query = qq|SELECT SUM(qty) AS onhand, '$null' AS description
                  FROM inventory
		  WHERE warehouse_id = $var
                  AND parts_id = ?|;
    } else {
      $query = qq|SELECT SUM(i.qty) AS onhand, w.description AS warehouse
                  FROM inventory i
		  JOIN warehouse w ON (w.id = i.warehouse_id)
                  WHERE i.parts_id = ?
		  GROUP BY w.description|;
    }

    $sth = $dbh->prepare($query) || $form->dberror($query);

    for (@{ $form->{parts} }) {

      $sth->execute($_->{id}) || $form->dberror($query);
      
      if ($form->{warehouse} ne "") {
	
	$ref = $sth->fetchrow_hashref(NAME_lc);
	if ($ref->{onhand} != 0) {
	  $_->{onhand} = $ref->{onhand};
	  push @li, $_;
	}

      } else {

	push @li, $_;
	
	while ($ref = $sth->fetchrow_hashref(NAME_lc)) {
          if ($ref->{onhand} > 0) {
	    push @li, $ref;
	  }
	}
      }
      
      $sth->finish;
    }

    @{ $form->{parts} } = @li;

  }
  
  $form->get_peripherals($dbh);

  $form->all_languages($myconfig, $dbh);

  $dbh->disconnect;

}


sub include_assembly {
  my ($dbh, $myconfig, $form, $id, $flds, $makemodeljoin) = @_;
  
  $form->{stagger}++;
  if ($form->{stagger} > $form->{pncol}) {
    $form->{pncol} = $form->{stagger};
  }
 
  $form->{$id} = 1;

  my @sf = qw(partnumber description bin);
  if ($form->{sort} eq 'partnumber') {
    $sortorder = "a.id";
  } else {
    @sf = grep !/$form->{sort}/, @sf;
    $sortorder = "p.$form->{sort} $form->{direction}, ". join ',p.', @sf;
  }
  
  @sf = ();
  my $query = qq|SELECT $flds
		 FROM parts p
		 JOIN assembly a ON (a.parts_id = p.id)
		 LEFT JOIN partsgroup pg ON (pg.id = p.id)
 		 LEFT JOIN chart c1 ON (c1.id = p.inventory_accno_id)
		 LEFT JOIN chart c2 ON (c2.id = p.income_accno_id)
		 LEFT JOIN chart c3 ON (c3.id = p.expense_accno_id)
		 $makemodeljoin
		 WHERE a.aid = $id
		 ORDER BY $sortorder|;
  my $sth = $dbh->prepare($query);
  $sth->execute || $form->dberror($query);
  
  while ($ref = $sth->fetchrow_hashref(NAME_lc)) {
    $ref->{assemblyitem} = 1;
    $ref->{stagger} = $form->{stagger};
    
    push @sf, $ref;
    if ($ref->{assembly} && !$form->{$ref->{id}}) {
      push @sf, &include_assembly($dbh, $myconfig, $form, $ref->{id}, $flds, $makemodeljoin);
      if ($form->{stagger} > $form->{pncol}) {
	$form->{pncol} = $form->{stagger};
      }
    }
  }
  $sth->finish;

  $form->{$id} = 0;
  $form->{stagger}--;

  @sf;

}


sub requirements {
  my ($self, $myconfig, $form) = @_;

  my $null;
  my $var;
  my $ref;
  
  my $where = qq|p.obsolete = '0'|;
  my $dwhere;

  for (qw(partnumber description)) {
    if ($form->{$_} ne "") {
      $var = $form->like(lc $form->{$_});
      $where .= qq| AND lower(p.$_) LIKE '$var'|;
    }
  }
  
  if ($form->{partsgroup} ne "") {
    ($null, $var) = split /--/, $form->{partsgroup};
    $where .= qq| AND p.partsgroup_id = $var|;
  }

  # connect to database
  my $dbh = $form->dbconnect($myconfig);

  my ($transdatefrom, $transdateto);
  if ($form->{year}) {
    ($transdatefrom, $transdateto) = $form->from_to($form->{year}, '01', 12);
    
    $dwhere = qq| AND a.transdate >= '$transdatefrom'
 		  AND a.transdate <= '$transdateto'|;
  }
    
  $query = qq|SELECT p.id, p.partnumber, p.description,
              sum(i.qty) AS qty, p.onhand,
	      extract(MONTH FROM a.transdate) AS month,
	      '0' AS so, '0' AS po
	      FROM invoice i
	      JOIN parts p ON (p.id = i.parts_id)
	      JOIN ar a ON (a.id = i.trans_id)
	      WHERE $where
	      $dwhere
	      AND p.inventory_accno_id > 0
	      GROUP BY p.id, p.partnumber, p.description, p.onhand,
	      extract(MONTH FROM a.transdate)|;
  my $sth = $dbh->prepare($query);
  $sth->execute || $form->dberror($query);

  my %parts;
  while ($ref = $sth->fetchrow_hashref(NAME_lc)) {
    if (exists $parts{$ref->{id}}) {
      $parts{$ref->{id}}->{$ref->{month}} = $ref->{qty};
      $parts{$ref->{id}}->{qty} += $ref->{qty};
    } else {
      $ref->{$ref->{month}} = $ref->{qty};
      $parts{$ref->{id}} = $ref;
    }
  }
  $sth->finish;

  my %ofld = ( customer => so,
               vendor => po );
  
  for (qw(customer vendor)) {
    $query = qq|SELECT p.id, p.partnumber, p.description,
		sum(qty) - sum(ship) AS $ofld{$_}, p.onhand,
		0 AS month
		FROM orderitems i
		JOIN parts p ON (p.id = i.parts_id)
		JOIN oe a ON (a.id = i.trans_id)
		WHERE $where
		AND p.inventory_accno_id > 0
		AND p.assembly = '0'
		AND a.closed = '0'
		AND a.quotation = '0'
		AND a.${_}_id > 0
		GROUP BY p.id, p.partnumber, p.description, p.onhand,
		month|;
    $sth = $dbh->prepare($query);
    $sth->execute || $form->dberror($query);

    while ($ref = $sth->fetchrow_hashref(NAME_lc)) {
      if (exists $parts{$ref->{id}}) {
	$parts{$ref->{id}}->{$ofld{$_}} += $ref->{$ofld{$_}};
      } else {
	$parts{$ref->{id}} = $ref;
      }
    }
    $sth->finish;
  }

  # add assemblies from open sales orders
  $query = qq|SELECT p.id, SUM(i.qty) - SUM(i.ship) AS qty, p.onhand
              FROM orderitems i
	      JOIN parts p ON (p.id = i.parts_id)
	      JOIN oe a ON (a.id = i.trans_id)
	      WHERE $where
	      AND p.assembly = '1'
	      AND a.closed = '0'
	      GROUP BY p.id, p.onhand|;
  $sth = $dbh->prepare($query);
  $sth->execute || $form->dberror($query);

  while ($ref = $sth->fetchrow_hashref(NAME_lc)) {
    $ref->{qty} -= $ref->{onhand};
    &requirements_assembly($dbh, $form, \%parts, $ref->{id}, $ref->{qty}, $where) if $ref->{qty};
  }
  $sth->finish;

  $dbh->disconnect;

  for (sort { $parts{$a}->{$form->{sort}} cmp $parts{$b}->{$form->{sort}} } keys %parts) {
    push @{ $form->{parts} }, $parts{$_};
  }
  
}


sub requirements_assembly {
  my ($dbh, $form, $parts, $id, $qty, $where) = @_;

  # assemblies
  my $query = qq|SELECT p.id, p.partnumber, p.description,
                 a.qty * $qty AS so, p.onhand, p.assembly,
	         p.partsgroup_id
	         FROM assembly a
	         JOIN parts p ON (p.id = a.parts_id)
 	         WHERE $where
		 AND a.aid = $id
	         AND p.inventory_accno_id > 0
		 
		 UNION
	  
	         SELECT p.id, p.partnumber, p.description,
                 a.qty * $qty AS so, p.onhand, p.assembly,
	         p.partsgroup_id
	         FROM assembly a
	         JOIN parts p ON (p.id = a.parts_id)
 	         WHERE a.aid = $id
		 AND p.assembly = '1'|;

  my $sth = $dbh->prepare($query);
  $sth->execute || $form->dberror($query);

  while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
    if ($ref->{assembly}) {
      &requirements_assembly($dbh, $form, $parts, $ref->{id}, $ref->{so}, $where);
      next;
    }

    if (exists $parts->{$ref->{id}}) {
      $parts->{$ref->{id}}{so} += $ref->{so};
    } else {
      $parts->{$ref->{id}} = $ref;
    }
  }
  $sth->finish;
    
}


sub create_links {
  my ($self, $module, $myconfig, $form) = @_;

  # connect to database
  my $dbh = $form->dbconnect($myconfig);
  
  my $ref;

  my $query = qq|SELECT c.accno, c.description, c.link,
                 l.description AS translation
                 FROM chart c
		 LEFT JOIN translation l ON (l.trans_id = c.id AND l.language_code = '$myconfig->{countrycode}')
		 WHERE c.link LIKE '%$module%'
		 ORDER BY c.accno|;
  my $sth = $dbh->prepare($query);
  $sth->execute || $form->dberror($query);

  while ($ref = $sth->fetchrow_hashref(NAME_lc)) {
    foreach my $key (split /:/, $ref->{link}) {
      if ($key =~ /$module/) {
	$ref->{description} = $ref->{translation} if $ref->{translation};

	push @{ $form->{"${module}_links"}{$key} }, { accno => $ref->{accno},
				      description => $ref->{description} };
      }
    }
  }
  $sth->finish;

  if ($form->{item} ne 'assembly') {
    $query = qq|SELECT count(*) FROM vendor|;
    my ($count) = $dbh->selectrow_array($query);

    if ($count < $myconfig->{vclimit}) {
      $query = qq|SELECT id, name
		  FROM vendor
		  ORDER BY name|;
      $sth = $dbh->prepare($query);
      $sth->execute || $form->dberror($query);

      while ($ref = $sth->fetchrow_hashref(NAME_lc)) {
	push @{ $form->{all_vendor} }, $ref;
      }
      $sth->finish;
    }
  }

  # pricegroups, customers
  $query = qq|SELECT count(*) FROM customer|;
  ($count) = $dbh->selectrow_array($query);

  if ($count < $myconfig->{vclimit}) {
    $query = qq|SELECT id, name
		FROM customer
		ORDER BY name|;
    $sth = $dbh->prepare($query);
    $sth->execute || $form->dberror($query);

    while ($ref = $sth->fetchrow_hashref(NAME_lc)) {
      push @{ $form->{all_customer} }, $ref;
    }
    $sth->finish;
  }

  $query = qq|SELECT id, pricegroup
              FROM pricegroup
	      ORDER BY pricegroup|;
  $sth = $dbh->prepare($query);
  $sth->execute || $form->dberror($query);

  while ($ref = $sth->fetchrow_hashref(NAME_lc)) {
    push @{ $form->{all_pricegroup} }, $ref;
  }
  $sth->finish;


  if ($form->{id}) {
    my %defaults = $form->get_defaults($dbh, \@{[qw(weightunit precision)]});
    for (keys %defaults) { $form->{$_} = $defaults{$_} }

  } else {
    $form->{priceupdate} = $form->current_date($myconfig);
    
    my %defaults = $form->get_defaults($dbh, \@{['weightunit', '%_accno_id', 'precision']});
    for (qw(weightunit precision)) { $form->{$_} = $defaults{$_} }

    for (qw(inventory income expense)) {
      $query = qq|SELECT c.accno, c.description,
                  l.description AS translation
                  FROM chart c
		  LEFT JOIN translation l ON (l.trans_id = c.id AND l.language_code = '$myconfig->{countrycode}')
		  WHERE c.id = '$defaults{"${_}_accno_id"}'|;
      ($form->{"${_}_accno"}, $form->{"${_}_description"}, $form->{"${_}_translation"}) = $dbh->selectrow_array($query);
      $form->{"${_}_description"} = $form->{"${_}_translation"} if $form->{"${_}_translation"};
      $form->{amount}{"IC_$_"} = { accno => $form->{"${_}_accno"}, description => $form->{"${_}_description"} };
      
    }
    
  }

  $form->{currencies} = $form->get_currencies($dbh, $myconfig);
  
  $form->get_partsgroup($myconfig, {all => 1}, $dbh);
  
  $dbh->disconnect;

}


sub get_warehouses {
  my ($self, $myconfig, $form) = @_;

  my $dbh = $form->dbconnect($myconfig);

  my $query = qq|SELECT id, description
                 FROM warehouse|;

  my $sth = $dbh->prepare($query);
  $sth->execute || $form->dberror($query);

  if ($form->{searchitems} !~ /(service|labor)/) {
    while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
      push @{ $form->{all_warehouse} }, $ref;
    }
  }
  $sth->finish;

  $form->get_partsgroup($myconfig, { searchitems => $form->{searchitems}, subgroup => 1 }, $dbh);

  $dbh->disconnect;

}


sub get_vc {
  my ($self, $myconfig, $form) = @_;

  my $dbh = $form->dbconnect($myconfig);

  my $query = qq|SELECT count(*)
                 FROM $form->{vc} c
		 JOIN oe o ON (o.$form->{vc}_id = c.id)
		 WHERE o.closed = '0'|;
  my ($count) = $dbh->selectrow_array($query);
  
  if ($count) {
    if ($myconfig->{vclimit} *= 1) {
      $query = qq|SELECT DISTINCT c.id, c.name
		  FROM $form->{vc} c
		  JOIN oe o ON (o.$form->{vc}_id = c.id)
		  WHERE o.closed = '0'
		  ORDER BY c.name|;

      my $sth = $dbh->prepare($query);
      $sth->execute || $form->dberror($query);

      while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
	push @{ $form->{"all_$form->{vc}"} }, $ref;
      }
      $sth->finish;
    }
  }

  $dbh->disconnect;

  $count;

}


sub so_requirements {
  my ($self, $myconfig, $form) = @_;

  my $dbh = $form->dbconnect($myconfig);

  my %defaults = $form->get_defaults($dbh, \@{['company']});
  for (keys %defaults) { $form->{$_} = $defaults{$_} }

  my $var;
  my $where = "o.closed = '0'";
  
  if ($form->{searchitems} eq 'part') {
    $where .= " AND p.inventory_accno_id > 0 AND p.income_accno_id > 0";
  }
  if ($form->{searchitems} eq 'assembly') {
    $where .= " AND p.assembly = '1'";
  }
  if ($form->{searchitems} eq 'service') {
    $where .= " AND p.assembly = '0' AND p.inventory_accno_id IS NULL";
  }
  if ($form->{searchitems} eq 'labor') {
    $where .= " AND p.inventory_accno_id > 0 AND p.income_accno_id IS NULL";
  }

  if ($form->{partnumber}) {
    $var = $form->like(lc $form->{partnumber});
    $where .= " AND lower(p.partnumber) LIKE '$var'";
  }
  if ($form->{description}) {
    $var = $form->like(lc $form->{description});
    $where .= " AND lower(p.description) LIKE '$var'";
  }
  if ($form->{$form->{vc}}) {
    $var = $form->like(lc $form->{$form->{vc}});
    $where .= " AND lower(c.name) LIKE '$var'";
  }
  if ($form->{"$form->{vc}number"}) {
    $var = $form->like(lc $form->{"$form->{vc}number"});
    $where .= " AND lower(c.$form->{vc}number) LIKE '$var'";
  }

  ($form->{reqdatefrom}, $form->{reqdateto}) = $form->from_to($form->{year}, $form->{month}, $form->{interval}) if $form->{year} && $form->{month};
  $where .= " AND o.reqdate >= '$form->{reqdatefrom}'" if $form->{reqdatefrom};
  $where .= " AND o.reqdate <= '$form->{reqdateto}'" if $form->{reqdateto};
  
  my $query = qq|SELECT p.partnumber, p.id as parts_id,
                 c.id AS $form->{vc}_id, c.name, c.$form->{vc}number,
		 o.id, o.ordnumber, o.reqdate,
		 oi.qty, oi.description
                 FROM oe o
		 JOIN orderitems oi ON (oi.trans_id = o.id)
		 JOIN parts p ON (p.id = oi.parts_id)
		 JOIN $form->{vc} c ON (o.$form->{vc}_id = c.id)
		 WHERE $where|;

  my @sf = qw(partnumber ordnumber reqdate);
  my %ordinal = $form->ordinal_order($dbh, $query);
  $query .= qq| ORDER BY | .$form->sort_order(\@sf, \%ordinal);

  my $sth = $dbh->prepare($query);
  $sth->execute || $form->dberror($query);

  while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
    push @{ $form->{all_parts} }, $ref;
  }
  $sth->finish;

  $dbh->disconnect;

}


1;