# ShopDB Quick Reference Guide

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

---

## 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** | 29 | Base tables (actual data) |
| **Views** | 23 | 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

### PC Management
```sql
-- Main PC table
pc (pcid, hostname, serialnumber, pctypeid, machinenumber, modelnumberid, osid)

-- PC Types
pctype (Standard, Engineer, Shopfloor, Server, Laptop, VM)

-- PC Status
pcstatus (In Use, Spare, Retired, Broken, Unknown)

-- Network
pc_network_interfaces (pcid, ipaddress, subnetmask, macaddress, isdhcp)

-- Communication
pc_comm_config (pcid, configtype, portid, baud, databits, ipaddress)

-- DNC
pc_dnc_config (pcid, site, cnc, ncif, dualpath_enabled, path1_name, path2_name)
```

### Machine Management
```sql
-- Machines
machines (machineid, machinenumber, alias, machinetypeid, printerid, ipaddress1/2)

-- Machine Types
machinetypes (Vertical Lathe, Horizontal Lathe, 5-Axis Mill, CMM, Part Washer, etc.)

-- Installed Apps
installedapps (appid, machineid) -- Junction table
```

### Applications & KB
```sql
-- Applications
applications (appid, appname, appdescription, supportteamid, isinstallable)

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

### Infrastructure
```sql
-- Printers
printers (printerid, printercsfname, modelid, serialnumber, ipaddress, fqdn, machineid)

-- Subnets
subnets (subnetid, ipaddress, subnet, vlan, gateway, subnettypeid)

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

### Reference Data
```sql
models (modelnumberid, modelnumber, vendorid)
vendors (vendorid, vendor)
operatingsystems (osid, operatingsystem)
supportteams (supportteamid, supportteam)
```

---

## File Structure Map

```
shopdb/
├── *.asp                   # Main pages (91 files)
│   ├── default.asp         # Dashboard
│   ├── search.asp          # Unified search
│   ├── calendar.asp        # Notification calendar
│   ├── display*.asp        # View pages
│   ├── add*.asp            # Create forms
│   ├── edit*.asp           # Update forms
│   ├── save*.asp           # Backend processors
│   └── api_*.asp           # JSON APIs
│
├── includes/               # Shared code
│   ├── sql.asp             # DB connection
│   ├── header.asp          # HTML head
│   ├── leftsidebar.asp     # Navigation
│   ├── topbarheader.asp    # Top bar
│   ├── error_handler.asp   # Error handling
│   ├── validation.asp      # Input validation
│   ├── db_helpers.asp      # DB utilities
│   └── data_cache.asp      # Caching system
│
├── assets/                 # Frontend resources
│   ├── css/                # Stylesheets
│   ├── js/                 # JavaScript
│   ├── images/             # Icons, logos
│   └── plugins/            # Third-party libs
│
├── images/                 # Dashboard images
│   └── 1-9.jpg             # Rotating images
│
├── sql/                    # Database scripts
│   └── database_updates_for_production.sql
│
└── docs/                   # Documentation
    ├── DEEP_DIVE_REPORT.md       # Comprehensive guide
    ├── ASP_DEVELOPMENT_GUIDE.md  # Dev setup
    ├── STANDARDS.md              # Coding standards
    ├── NESTED_ENTITY_CREATION.md # Complex forms
    └── QUICK_REFERENCE.md        # This file
```

---

## 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 570005354 -p570005354 shopdb

# Backup database
docker exec dev-mysql mysqldump -u 570005354 -p570005354 shopdb > backup.sql

# Restore database
docker exec -i dev-mysql mysql -u 570005354 -p570005354 shopdb < backup.sql

# Check table counts
docker exec dev-mysql mysql -u 570005354 -p570005354 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

### PC-Related Views
- `vw_shopfloor_pcs` - Shopfloor PCs with machine assignments
- `vw_active_pcs` - PCs updated in last 30 days
- `vw_pc_summary` - Overall PC inventory
- `vw_pc_network_summary` - Network configuration overview
- `vw_warranty_status` - Warranty tracking
- `vw_warranties_expiring` - Expiring in next 90 days

### Machine-Related Views
- `vw_machine_assignments` - PC-to-machine relationships
- `vw_machine_type_stats` - Counts by machine type
- `vw_multi_pc_machines` - Machines with multiple PCs
- `vw_unmapped_machines` - Missing map coordinates
- `vw_dualpath_management` - DualPath CNCs

### Reporting Views
- `vw_vendor_summary` - PC counts by manufacturer
- `vw_pcs_by_hardware` - Hardware distribution
- `vw_pctype_config` - Configuration by PC type
- `vw_recent_updates` - Recent changes

---

## Database Credentials

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

**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

### Find PCs by Machine Number
```sql
SELECT p.hostname, p.serialnumber, p.machinenumber, pt.typename
FROM pc p
JOIN pctype pt ON p.pctypeid = pt.pctypeid
WHERE p.machinenumber = '3104'
  AND p.isactive = 1;
```

### Machines Without Assigned PCs
```sql
SELECT m.machinenumber, m.alias, mt.machinetype
FROM machines m
LEFT JOIN pc p ON p.machinenumber = m.machinenumber AND p.isactive = 1
JOIN machinetypes mt ON m.machinetypeid = mt.machinetypeid
WHERE p.pcid IS NULL
  AND m.isactive = 1
  AND m.islocationonly = 0;
```

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

### Warranties Expiring This Month
```sql
SELECT hostname, serialnumber, warrantyenddate, warrantydaysremaining
FROM vw_warranties_expiring
WHERE warrantyenddate BETWEEN CURDATE() AND DATE_ADD(CURDATE(), INTERVAL 30 DAY)
ORDER BY warrantyenddate;
```

### DualPath PCs
```sql
SELECT p.hostname, d.primary_machine, d.secondary_machine, dnc.dualpath_enabled
FROM pc p
JOIN pc_dualpath_assignments d ON p.pcid = d.pcid
JOIN pc_dnc_config dnc ON p.pcid = dnc.pcid
WHERE dnc.dualpath_enabled = 1;
```

---

## Resources

### Documentation
- **Comprehensive Guide:** docs/DEEP_DIVE_REPORT.md
- **Development Setup:** docs/ASP_DEVELOPMENT_GUIDE.md
- **Coding Standards:** docs/STANDARDS.md
- **Complex Forms:** docs/NESTED_ENTITY_CREATION.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-10-20
**Maintained By:** Development Team
**Review:** Update when major changes occur
