# ShopDB Quick Reference Guide

**For:** New team members and quick lookups
**See Also:** ASP_DEVELOPMENT_GUIDE.md (development), STANDARDS.md (coding standards), API.md (REST API)

---

## Quick Access URLs

- **Production:** http://your-production-server/
- **Beta/Staging:** http://your-production-server/v2/
- **Dev Environment:** http://192.168.122.151:8080

---

## Database Quick Facts

| Item | Count | Notes |
|------|-------|-------|
| **Tables** | 35 | Base tables (actual data) |
| **Views** | 26 | Computed/joined data |
| **PCs** | 242 | Active PCs in inventory |
| **Machines** | 256 | CNC machines and locations |
| **Printers** | 40 | Network printers |
| **Applications** | 44 | Shopfloor software |
| **KB Articles** | 196 | Troubleshooting docs |
| **Network IFs** | 705 | Network interfaces tracked |
| **Total Size** | ~3.5 MB | Small but mighty! |

---

## Core Tables Cheat Sheet

### Unified Machines Table (Phase 2 Schema)
```sql
-- ALL PCs, Equipment, and Network Devices are in one table
machines (machineid, hostname, serialnumber, alias, machinenumber,
          machinetypeid, pctypeid, modelnumberid, osid, printerid,
          loggedinuser, machinenotes, isactive, maptop, mapleft, lastupdated)

-- Identify record type:
--   PCs:             pctypeid IS NOT NULL (machinetypeid 33+)
--   Equipment:       pctypeid IS NULL AND machinetypeid NOT IN (16,17,18,19,20) AND machinetypeid < 33
--   Network Devices: machinetypeid IN (16,17,18,19,20)
-- Equipment types: 1-15, 21-25 (e.g., Lathe, Mill, CMM, Hobbing Machine, etc.)
```

### PC-Related Tables
```sql
-- PC Types
pctype (pctypeid, typename)
-- Values: Standard, Engineer, Shopfloor, CMM, Wax Trace, etc.

-- Communication Config (serial ports for equipment)
commconfig (configid, machineid, configtype, portid, baud, databits, parity, ipaddress)

-- DNC Config
dncconfig (dncid, machineid, site, cnc, ncif, dualpath_enabled, path1_name, path2_name)

-- PC-to-Equipment Relationships
machinerelationships (relationshipid, machineid, related_machineid, relationshiptypeid)
-- relationshiptypeid 3 = "Controls" (PC controls equipment)
```

### Network & Communications
```sql
-- All network interfaces
communications (comid, machineid, comstypeid, address, macaddress,
                subnetmask, defaultgateway, interfacename, isprimary, isactive)
-- comstypeid 1 = Network Interface
-- NOTE: Column is 'address' not 'ipaddress'

-- Subnets
subnets (subnetid, address, subnet, vlan, gateway, subnettypeid)
```

### Equipment & Machine Types
```sql
-- Machine Types (machinetypeid ranges)
machinetypes (machinetypeid, machinetype)
--   1-15:  Equipment (Vertical Lathe, Mill, CMM, etc.)
--   16-20: Network Devices (16=AP, 17=IDF, 18=Camera, 19=Switch, 20=Server)
--   33-35: PC Types (Desktop, Laptop, Workstation)

-- Installed Apps on Equipment
installedapps (machineid, applicationid)
```

### Applications & KB
```sql
-- Applications
applications (applicationid, applicationname, appdescription, supportteamid)

-- Knowledge Base
knowledgebase (linkid, shortdescription, keywords, applicationid, linkurl, clicks)
```

### Infrastructure
```sql
-- Printers (separate table, not in machines)
printers (printerid, printercsfname, modelid, serialnumber, ipaddress, fqdn, isactive)
-- NOTE: Printers use 'ipaddress' (unlike communications which uses 'address')

-- Notifications
notifications (notificationid, notification, starttime, endtime, isactive, notificationtypeid)

-- Warranties
warranties (warrantyid, machineid, enddate, servicelevel, status, daysremaining)
```

### Reference Data
```sql
-- Core reference tables
models (modelnumberid, modelnumber, vendorid)
vendors (vendorid, vendor)
operatingsystems (osid, osname)
supportteams (supportteamid, supportteam)
relationshiptypes (relationshiptypeid, relationshiptype)

-- Additional lookup tables
machinestatus (machinestatusid, machinestatus)      -- TBD, In Use, Returned, etc.
notificationtypes (notificationtypeid, typename)    -- Awareness, Change, Incident
comstypes (comstypeid, typename)                    -- IP, Serial, Network_Interface
subnettypes (subnettypeid, subnettypename)          -- Subnet type classifications
topics (topicid, topic)                             -- KB topic categories
appowners (appownerid, appowner)                    -- Application ownership
appversions (appversionid, applicationid, version)  -- Application version tracking
businessunits (businessunitid, businessunit)        -- Business unit classifications
```

---

## File Structure Map

```
shopdb/
├── *.asp                   # Main pages
│   ├── default.asp         # Dashboard
│   ├── api.asp             # REST API endpoint
│   ├── search.asp          # Unified search
│   ├── display*.asp        # View pages
│   ├── add*.asp            # Create forms
│   ├── edit*.asp           # Update forms
│   └── printerlookup.asp   # Zabbix printer lookup
│
├── includes/               # Shared code
│   ├── sql.asp             # DB connection
│   ├── header.asp          # HTML head
│   ├── leftsidebar.asp     # Navigation
│   └── topbarheader.asp    # Top bar
│
├── assets/                 # Frontend resources
│   ├── css/                # Stylesheets
│   ├── js/                 # JavaScript
│   ├── images/             # Icons, logos
│   └── plugins/            # Third-party libs
│
├── sql/                    # Database scripts
│   ├── view_consolidation.sql  # All database views
│   └── archive/                # Historical migrations
│
└── docs/                   # Documentation
    ├── API.md                    # REST API docs
    ├── ASP_DEVELOPMENT_GUIDE.md  # Dev setup
    ├── STANDARDS.md              # Coding standards
    ├── QUICK_REFERENCE.md        # This file
    └── archive/                  # Historical docs
```

---

## Common Tasks

### Start Development Environment
```bash
cd ~/projects/windows/shopdb
~/start-dev-env.sh  # Starts Docker + Windows VM
# Wait ~30 seconds for IIS to start
curl http://192.168.122.151:8080  # Test
```

### Database Access
```bash
# Connect to MySQL
docker exec -it dev-mysql mysql -u root -prootpassword shopdb

# Backup database
docker exec dev-mysql mysqldump -u root -prootpassword shopdb > backup.sql

# Restore database
docker exec -i dev-mysql mysql -u root -prootpassword shopdb < backup.sql

# Check table counts
docker exec dev-mysql mysql -u root -prootpassword shopdb \
  -e "SELECT table_name, table_rows FROM information_schema.tables WHERE table_schema='shopdb' ORDER BY table_rows DESC;"
```

### Code Development
```bash
# Edit files (auto-syncs to Windows via Samba)
code ~/projects/windows/shopdb/

# Check syntax (if you have a validator)
# ASP doesn't have great linters, test by loading in browser

# View logs (Windows VM)
# C:\inetpub\logs\LogFiles\
```

### Testing Changes
1. Save file on Linux (auto-syncs to Z:\shopdb\ on Windows)
2. Refresh browser (http://192.168.122.151:8080/yourfile.asp)
3. Check browser console for JS errors
4. Check IIS Express console for ASP errors
5. Check database for data changes

---

## Search System Quick Guide

### Search Syntax
- **Exact match:** `"exact phrase"` (not yet implemented)
- **Multiple words:** `word1 word2` (finds both)
- **Short words:** < 4 characters use LIKE fallback automatically

### What's Searchable?
- **Applications:** Name
- **Knowledge Base:** Title, keywords, application name
- **Notifications:** Notification text
- **Machines:** Number, alias, type, vendor, notes
- **Printers:** CSF name, model, serial number

### Smart Redirects
- **Printer serial (exact):** → Printer detail page
- **Printer FQDN (exact):** → Printer detail page
- **Machine number (exact):** → Machine detail page

---

## Key VBScript Patterns

### Include Required Files
```vbscript
<!--#include file="./includes/sql.asp"-->
<!--#include file="./includes/error_handler.asp"-->
<!--#include file="./includes/validation.asp"-->
<!--#include file="./includes/db_helpers.asp"-->
```

### Safe Database Query
```vbscript
<%
' Get and validate input
Dim machineId
machineId = GetSafeInteger("QS", "machineid", 0, 1, 999999)

If machineId = 0 Then
    Response.Redirect("error.asp?code=INVALID_ID")
    Response.End
End If

' Parameterized query
strSQL = "SELECT * FROM machines WHERE machineid = ? AND isactive = 1"
Set rs = ExecuteParameterizedQuery(objConn, strSQL, Array(machineId))

' Use results
If Not rs.EOF Then
    Response.Write Server.HTMLEncode(rs("machinenumber"))
End If

' Cleanup
rs.Close
Set rs = Nothing
Call CleanupResources()
%>
```

### Display a List
```vbscript
<%
strSQL = "SELECT machineid, machinenumber, alias FROM machines WHERE isactive=1 ORDER BY machinenumber"
Set rs = objConn.Execute(strSQL)

Do While Not rs.EOF
%>
    <tr>
        <td><%=Server.HTMLEncode(rs("machinenumber"))%></td>
        <td><%=Server.HTMLEncode(rs("alias"))%></td>
        <td><a href="displaymachine.asp?machineid=<%=rs("machineid")%>">View</a></td>
    </tr>
<%
    rs.MoveNext
Loop

rs.Close
Set rs = Nothing
%>
```

### Form Handling
```vbscript
<%
If Request.ServerVariables("REQUEST_METHOD") = "POST" Then
    ' Validate input
    Dim machineName
    machineName = GetSafeString("FORM", "machinename", "", 1, 50, "^[A-Za-z0-9\s\-]+$")

    If machineName = "" Then
        Call HandleValidationError("addmachine.asp", "REQUIRED_FIELD")
    End If

    ' Insert into database
    strSQL = "INSERT INTO machines (machinenumber) VALUES (?)"
    Set rs = ExecuteParameterizedQuery(objConn, strSQL, Array(machineName))

    Call CleanupResources()
    Response.Redirect("displaymachines.asp")
    Response.End
End If
%>
<!-- Show form -->
<form method="post">
    <input type="text" name="machinename" required>
    <button type="submit">Save</button>
</form>
```

---

## Important Views to Know

All views defined in `sql/view_consolidation.sql`

### Display Page Views
- `vw_equipment_list` - Equipment for displaymachines.asp
- `vw_pc_list` - PCs for displaypcs.asp
- `vw_printer_list` - Printers for displayprinters.asp
- `vw_machine_detail` - Full details for detail pages
- `vw_network_devices` - Network devices (APs, switches, etc.)

### Map Views
- `vw_map_equipment` - Equipment with map positions
- `vw_map_printers` - Printers with map positions
- `vw_map_network_devices` - Network devices on map
- `vw_network_map_devices` - Combined printers + network devices

### Relationship Views
- `vw_equipment_pc_relationships` - PC-to-equipment links

### Summary Views
- `vw_warranty_status` - Warranty tracking
- `vw_warranty_summary` - Warranty stats by status
- `vw_pctype_summary` - Counts by PC type
- `vw_equipment_type_summary` - Counts by equipment type

### Notification Views
- `vw_active_notifications` - Current/recent notifications
- `vw_upcoming_notifications` - Scheduled notifications

### Application Views
- `vw_applications_list` - Apps with KB counts
- `vw_knowledge_base` - KB articles with app info
- `vw_kb_by_application` - KB grouped by application
- `vw_installed_apps_summary` - App installation stats
- `vw_installed_apps_by_machine` - Apps per machine
- `vw_pc_app_stats` - PC application statistics

### Reports/Charts Views
- `vw_downtime_by_type` - Downtime stats by notification type
- `vw_incident_durations` - Notification duration tracking

### Other Views
- `vw_subnet_list` - Network subnets
- `vw_usb_checkout_history` - USB device checkout tracking

---

## Database Credentials

**Development Database:**
- Host: 192.168.122.1 (from Windows VM)
- Port: 3306
- Database: shopdb
- User: root
- Password: rootpassword

**Production Database:**
- See production server documentation (credentials secured)

---

## Troubleshooting

### "Page Cannot Be Displayed"
1. Check IIS Express is running (Windows Task Manager)
2. Check Windows VM is running: `virsh list --all`
3. Check network: `ping 192.168.122.151`
4. Restart: `~/stop-dev-env.sh && ~/start-dev-env.sh`

### "Database Connection Failed"
1. Check MySQL container: `docker ps | grep mysql`
2. Check credentials in sql.asp
3. Test connection: `docker exec -it dev-mysql mysql -u 570005354 -p570005354 shopdb`
4. Check firewall: MySQL port 3306 must be open

### "ODBC Driver Not Found" (Windows)
1. Install MySQL ODBC 8.0 Driver on Windows VM
2. Verify in Control Panel → ODBC Data Sources
3. Restart IIS Express

### "Changes Not Appearing"
1. Hard refresh: Ctrl+F5
2. Check file actually saved: `ls -la ~/projects/windows/shopdb/filename.asp`
3. Check Samba: `sudo systemctl status smbd`
4. Check Windows can see Z: drive

### "SQL Injection Error"
1. You're using unsafe query patterns!
2. Use `ExecuteParameterizedQuery()` from db_helpers.asp
3. Review STANDARDS.md for correct patterns

---

## Security Checklist

Before deploying code, verify:

- [ ] All SQL queries use parameterization
- [ ] All user input validated (validation.asp)
- [ ] All output encoded (Server.HTMLEncode)
- [ ] Error messages don't expose internals
- [ ] No hard-coded credentials
- [ ] Resources cleaned up (Call CleanupResources())
- [ ] Tested on dev environment first
- [ ] Peer reviewed (if possible)

---

## Useful SQL Queries

### Get All PCs
```sql
SELECT m.machineid, m.hostname, m.serialnumber, pt.typename AS pctype
FROM machines m
JOIN pctype pt ON m.pctypeid = pt.pctypeid
WHERE m.pctypeid IS NOT NULL AND m.isactive = 1
ORDER BY m.hostname;
```

### Get All Equipment
```sql
SELECT m.machineid, m.machinenumber, m.alias, mt.machinetype
FROM machines m
JOIN machinetypes mt ON m.machinetypeid = mt.machinetypeid
WHERE m.pctypeid IS NULL AND m.machinetypeid < 16 AND m.isactive = 1
ORDER BY m.machinenumber;
```

### Get Network Devices
```sql
SELECT m.machineid, m.alias, mt.machinetype, c.address
FROM machines m
JOIN machinetypes mt ON m.machinetypeid = mt.machinetypeid
LEFT JOIN communications c ON m.machineid = c.machineid AND c.isprimary = 1
WHERE m.machinetypeid IN (16,17,18,19,20) AND m.isactive = 1;
```

### Find PC by Hostname with IP
```sql
SELECT m.hostname, m.serialnumber, c.address AS ipaddress, pt.typename
FROM machines m
JOIN pctype pt ON m.pctypeid = pt.pctypeid
LEFT JOIN communications c ON m.machineid = c.machineid AND c.isprimary = 1
WHERE m.hostname = 'PC-NAME' AND m.pctypeid IS NOT NULL;
```

### Equipment with Controlling PCs
```sql
SELECT
    equipment.machinenumber AS equipment,
    equipment.alias,
    pc.hostname AS controlling_pc
FROM machinerelationships mr
JOIN machines equipment ON mr.machineid = equipment.machineid
JOIN machines pc ON mr.related_machineid = pc.machineid
WHERE mr.relationshiptypeid = 3 AND mr.isactive = 1;
```

### Most Clicked KB Articles
```sql
SELECT k.shortdescription, a.applicationname, k.clicks, k.linkurl
FROM knowledgebase k
JOIN applications a ON k.applicationid = a.applicationid
WHERE k.isactive = 1
ORDER BY k.clicks DESC
LIMIT 20;
```

### DualPath PCs
```sql
SELECT m.hostname, dnc.dualpath_enabled, dnc.path1_name, dnc.path2_name
FROM machines m
JOIN dncconfig dnc ON m.machineid = dnc.machineid
WHERE dnc.dualpath_enabled = 1 AND m.pctypeid IS NOT NULL;
```

---

## Resources

### Documentation
- **REST API:** docs/API.md
- **Development Setup:** docs/ASP_DEVELOPMENT_GUIDE.md
- **Coding Standards:** docs/STANDARDS.md
- **Project Context:** CLAUDE.md

### External Links
- **Classic ASP Reference:** https://learn.microsoft.com/en-us/previous-versions/iis/6.0-sdk/ms525334(v=vs.90)
- **VBScript Reference:** https://learn.microsoft.com/en-us/previous-versions//d1wf56tt(v=vs.85)
- **MySQL 5.6 Docs:** https://dev.mysql.com/doc/refman/5.6/en/
- **Bootstrap 4 Docs:** https://getbootstrap.com/docs/4.6/getting-started/introduction/

### Tools
- **Database Management:** phpMyAdmin (http://localhost:8081)
- **API Testing:** Postman or curl
- **Code Editor:** VSCode with ASP/VBScript extensions

---

## Common Gotchas

1. **VBScript uses & for concatenation**, not +
2. **Comparison is = not ==**
3. **All Dim declarations must be at function/procedure top**
4. **Always close recordsets and connections**
5. **FULLTEXT requires words ≥ 4 characters** (we have LIKE fallback)
6. **bit(1) fields need CBool() conversion** to use in IF statements
7. **Request.QueryString/Form always returns strings** - validate/cast!
8. **Server.HTMLEncode() all output** to prevent XSS
9. **objConn is global** - don't redeclare, just use it
10. **File paths in Windows use backslash** \, Linux forward /

---

## Keyboard Shortcuts

### Browser
- **Ctrl+F5** - Hard refresh (bypass cache)
- **F12** - Open developer tools
- **Ctrl+Shift+I** - Open inspector

### VSCode
- **Ctrl+P** - Quick file open
- **Ctrl+Shift+F** - Search across all files
- **Ctrl+/** - Toggle comment
- **Alt+Up/Down** - Move line up/down

---

## Contact & Support

**Team Lead:** [Your name here]
**Documentation:** ~/projects/windows/shopdb/docs/
**Issues:** Create GitHub issue (once repo setup)
**Emergency:** [Contact info]

---

**Last Updated:** 2025-12-11
**Maintained By:** Development Team
**Schema:** Phase 2 (unified machines table)
