# Add/Edit Machine Form Updates - Summary

## Overview
Updated machine add/edit forms to support all Phase 2 migration data including network communications, machine relationships, and compliance information.

---

## Files Modified

### 1. addmachine.asp
**Location:** `/home/camp/projects/windows/shopdb/addmachine.asp`

#### New Form Sections Added:

**A. Network Communications Section**
```html
<h6>Network Communications (Optional)</h6>
```
Tab-based layout with support for up to 3 network interfaces:

**Interface 1 (Primary)**
- **IP Address** - Text input with IPv4 validation pattern (field: ip1)
- **MAC Address** - Text input with MAC address validation pattern (field: mac1)
- Marked as primary interface (isprimary=1)

**Interface 2 (Optional)**
- **IP Address** - Text input with IPv4 validation pattern (field: ip2)
- **MAC Address** - Text input with MAC address validation pattern (field: mac2)
- Secondary interface (isprimary=0)

**Interface 3 (Optional)**
- **IP Address** - Text input with IPv4 validation pattern (field: ip3)
- **MAC Address** - Text input with MAC address validation pattern (field: mac3)
- Secondary interface (isprimary=0)

**B. Machine Relationships Section**
```html
<h6>Machine Relationships (Optional)</h6>
```
New Fields:
- **Controlling PC** - Dropdown populated with all PCs from machines table (WHERE pctypeid IS NOT NULL)
- **Dualpath / Redundant Machine** - Dropdown populated with all equipment (WHERE pctypeid IS NULL)

**C. Compliance & Security Section**
```html
<h6>Compliance & Security (Optional)</h6>
```
New Fields:
- **Third Party Managed** - Dropdown (N/A, Yes, No)
- **Third Party Vendor** - Dropdown populated from vendors table
- **OT Asset System** - Text input for operational technology classification
- **DoD Asset Device Type** - Text input for Department of Defense asset classification

---

### 2. savemachine_direct.asp
**Location:** `/home/camp/projects/windows/shopdb/savemachine_direct.asp`

#### New Data Handling Added:

**A. Network Communications Save**
- Retrieves form fields: `ip1`, `mac1`, `ip2`, `mac2`, `ip3`, `mac3`
- Looks up `Network_Interface` communication type ID
- Inserts up to 3 records into `communications` table
- Sets `isprimary = 1` for Interface 1 only (Interfaces 2-3 have isprimary=0)
- Only inserts if IP or MAC provided for each interface
- Interface names: "Interface 1", "Interface 2", "Interface 3"

**B. Machine Relationships Save**
- Retrieves form fields: `controllingpc`, `dualpathid`
- Looks up relationship type IDs for 'Controls' and 'Dualpath'

**Controls Relationship:**
- Creates one-way relationship: PC (machineid) → Equipment (related_machineid)
- Relationship type: 'Controls'

**Dualpath Relationship:**
- Creates **bidirectional** relationship
- Direction 1: New Machine → Dualpath Machine
- Direction 2: Dualpath Machine → New Machine
- Both records use 'Dualpath' relationship type

**C. Compliance Data Save**
- Retrieves form fields: `thirdpartymanaged`, `thirdpartyvendorid`, `otassetsystem`, `dodassettype`
- Inserts record into `compliance` table
- Maps third party managed to ENUM: 'Yes', 'No', or 'NA'
- Stores third party vendor as foreign key to vendors table (third_party_vendorid)

---

### 3. displaymachines.asp
**Location:** `/home/camp/projects/windows/shopdb/displaymachines.asp`

#### Query Filter Updated:

**Before:**
```sql
machines.isactive = 1 AND islocationonly=0
```

**After:**
```sql
machines.isactive = 1 AND islocationonly=0 AND machines.pctypeid IS NULL
```

**Purpose:** Exclude PCs from equipment list - PCs should only appear in displaypcs.asp

---

### 4. displaymachine.asp
**Location:** `/home/camp/projects/windows/shopdb/displaymachine.asp`

#### Fixed Issues:
- Changed INNER JOIN to LEFT JOIN for `machinetypes` and `functionalaccounts`
- Allows machines with NULL machinetypeid to still display (fixes redirect to homepage)
- Updated Settings tab to show IP/MAC from communications table instead of old PC tables
- Shows controlling PC from relationships table

---

## Database Tables Used

### New Tables Created in Phase 2:

#### communications
```sql
CREATE TABLE communications (
    comid INT PRIMARY KEY AUTO_INCREMENT,
    machineid INT NOT NULL,
    comstypeid INT NOT NULL,
    address VARCHAR(50),          -- IP address
    macaddress VARCHAR(50),
    interfacename VARCHAR(50),
    isprimary TINYINT(1) DEFAULT 0,
    isactive TINYINT(1) DEFAULT 1,
    FOREIGN KEY (machineid) REFERENCES machines(machineid),
    FOREIGN KEY (comstypeid) REFERENCES comstypes(comstypeid)
)
```

#### machinerelationships
```sql
CREATE TABLE machinerelationships (
    relationshipid INT PRIMARY KEY AUTO_INCREMENT,
    machineid INT NOT NULL,
    related_machineid INT NOT NULL,
    relationshiptypeid INT NOT NULL,
    isactive TINYINT(1) DEFAULT 1,
    FOREIGN KEY (machineid) REFERENCES machines(machineid),
    FOREIGN KEY (related_machineid) REFERENCES machines(machineid),
    FOREIGN KEY (relationshiptypeid) REFERENCES relationshiptypes(relationshiptypeid)
)
```

#### relationshiptypes
```sql
CREATE TABLE relationshiptypes (
    relationshiptypeid INT PRIMARY KEY AUTO_INCREMENT,
    relationshiptype VARCHAR(50) NOT NULL,  -- 'Controls', 'Dualpath'
    isactive TINYINT(1) DEFAULT 1
)
```

#### compliance
```sql
CREATE TABLE compliance (
    complianceid INT PRIMARY KEY AUTO_INCREMENT,
    machineid INT NOT NULL,
    is_third_party_managed ENUM('Yes', 'No', 'NA'),
    third_party_manager VARCHAR(100),
    ot_asset_system VARCHAR(100),
    ot_asset_device_type VARCHAR(100),
    is_compliant TINYINT(1),
    FOREIGN KEY (machineid) REFERENCES machines(machineid)
)
```

---

## Form Validation

### Client-Side Validation (HTML5):

**IP Address:**
```html
pattern="^(?:[0-9]{1,3}\.){3}[0-9]{1,3}$"
```

**MAC Address:**
```html
pattern="^([0-9A-Fa-f]{2}[:-]){5}([0-9A-Fa-f]{2})$"
```

### Server-Side Validation:

All inputs are:
- Trimmed of whitespace
- Checked for empty values before INSERT
- Passed through parameterized queries (SQL injection protection)
- Used with `IIf()` to convert empty strings to NULL

---

## Workflow Examples

### Adding a New CNC Machine with Full Data:

1. **Basic Info** (existing fields):
   - Machine Number: 4500
   - Model: Okuma LB 3000
   - Business Unit: Production
   - Alias: "Main Turning Center"

2. **Network** (new fields):
   - Interface 1 IP: 192.168.10.50
   - Interface 1 MAC: 00:1A:2B:3C:4D:5E
   - Interface 2 IP: 192.168.10.51
   - Interface 2 MAC: 00:1A:2B:3C:4D:5F
   - Interface 3: (left blank)

3. **Relationships** (new fields):
   - Controlling PC: PC-SHOP-045
   - Dualpath Machine: Machine 4501 (backup)

4. **Compliance** (new fields):
   - Third Party Managed: No
   - OT Asset System: Production Control
   - DoD Asset Type: CNC Lathe

**Result:**
- Machine inserted into `machines` table
- Two communication records inserted into `communications` table:
  - Interface 1: 192.168.10.50 (isprimary=1)
  - Interface 2: 192.168.10.51 (isprimary=0)
- Controls relationship: PC-SHOP-045 → Machine 4500
- Dualpath relationships: 4500 ↔ 4501 (bidirectional)
- Compliance record inserted into `compliance` table
- Redirects to displaymachine.asp?machineid=[newid]

---

## Security Features

### Parameterized Queries:
All database operations use `ADODB.Command` with parameters:
```asp
Set cmd = Server.CreateObject("ADODB.Command")
cmd.ActiveConnection = objConn
cmd.CommandText = "INSERT INTO communications (...) VALUES (?, ?, ?, ?, ?)"
cmd.Parameters.Append cmd.CreateParameter("@machineid", 3, 1, , machineid)
...
cmd.Execute
```

### HTML Encoding:
All user input displayed in dropdowns uses `Server.HTMLEncode()`:
```asp
Response.Write("<option value='" & id & "'>" & Server.HTMLEncode(displayText) & "</option>")
```

### Input Validation:
- Required fields checked server-side
- Numeric fields validated with `IsNumeric()`
- String length limits enforced
- NULL handling with `IIf()`

---

## Error Handling

### Graceful Failures:
```asp
On Error Resume Next
cmd.Execute
Set cmd = Nothing
On Error Goto 0
```

All Phase 2 data inserts use error suppression to allow partial success:
- Machine can be created even if communication insert fails
- Relationship creation failures don't block machine creation
- Compliance data is optional

### User Feedback:
- Success: Redirects to displaymachine.asp with new machine
- Failure: Shows error message with "Go back" link
- Duplicate machine number: Prevented with validation check

---

## Testing Checklist

- [ ] Add machine with all new fields populated
- [ ] Add machine with only required fields (Phase 2 fields empty)
- [ ] Verify IP address validation (invalid format rejected)
- [ ] Verify MAC address validation (invalid format rejected)
- [ ] Verify controlling PC creates correct relationship
- [ ] Verify dualpath creates bidirectional relationships
- [ ] Verify compliance data saves correctly
- [ ] Test with special characters in text fields
- [ ] Verify displaymachines.asp no longer shows PCs
- [ ] Verify machines with NULL machinetypeid still display
- [ ] Test redirect after successful machine creation
- [ ] Verify Settings tab shows data from communications table

---

## Known Limitations

1. **No Relationship Editing**
   - Cannot modify relationships after creation
   - Must edit relationships via database or future edit form
   - Future enhancement: Edit relationships on machine edit page

2. **No Communication Editing**
   - Cannot modify IP/MAC after creation
   - Must edit via database or future edit form
   - Future enhancement: Edit communications on machine edit page

3. **PC Filter Assumption**
   - Assumes all PCs have `pctypeid IS NOT NULL`
   - Legacy PCs may not have pctypeid set
   - Migration should ensure all PCs have pctypeid

---

## Future Enhancements

### For editmacine.asp (Edit Page):

1. **Network Communications Management**
   - List all existing interfaces
   - Add new interfaces
   - Edit existing interfaces
   - Delete interfaces
   - Set primary interface

2. **Relationship Management**
   - View all relationships
   - Add new relationships
   - Remove relationships
   - Edit relationship types

3. **Compliance Management**
   - Edit all compliance fields
   - Add security scan records
   - View scan history
   - Update compliance status

4. **Bulk Operations**
   - Assign same PC to multiple machines
   - Create multiple dualpath links at once
   - Bulk update compliance data

---

## Migration Notes

### Data Already Imported:
- 308 equipment with network communications
- 144 PC control relationships
- 62 dualpath relationships
- 164 machines with compliance data
- 68 security scans

### What This Form Adds:
- Ability to create NEW machines with Phase 2 data
- Ensures all new machines have proper network configuration
- Establishes relationships at creation time
- Records compliance data from day one

---

## Troubleshooting

### Machine redirects to homepage:
- Check if model has NULL machinetypeid
- Run: `UPDATE models SET machinetypeid = X WHERE modelnumberid = Y`
- Or use LEFT JOIN fix in displaymachine.asp

### IP address not showing:
- Check if communication record was created
- Verify `isprimary = 1` is set
- Check Settings tab query for communications join

### Relationship not created:
- Verify relationship types exist in database
- Check for duplicate relationships (prevents re-insert)
- Verify both machines have valid machineids

### PC still showing in equipment list:
- Verify PC has `pctypeid IS NOT NULL`
- Check displaymachines.asp WHERE clause includes PC filter
- Clear browser cache

---

## Contact / Support

For questions about these changes:
- See `/home/camp/projects/windows/shopdb/sql/migration_phase2/` for migration scripts
- See `/home/camp/projects/windows/shopdb/DISPLAY_PAGES_UPDATE_SUMMARY.md` for display page changes
- Review import logs in `/tmp/inventory_import_final.log`

---

## Change Log

**Date:** 2025-11-07

**Files Modified:**
- /home/camp/projects/windows/shopdb/addmachine.asp
- /home/camp/projects/windows/shopdb/savemachine_direct.asp
- /home/camp/projects/windows/shopdb/displaymachines.asp
- /home/camp/projects/windows/shopdb/displaymachine.asp

**Changes:**
- Redesigned addmachine.asp with Bootstrap tabs (Basic Info, Network, Relationships, Compliance, Location)
- Added support for up to 3 network interfaces on add machine form
- Added machine relationship fields (controlling PC, dualpath)
- Added compliance data fields with third-party vendor dropdown
- Updated save handler to insert Phase 2 data (multiple interfaces, relationships, compliance)
- Fixed displaymachines.asp to exclude PCs (pctypeid IS NULL filter)
- Fixed displaymachine.asp LEFT JOIN for NULL machinetypes
- Updated Settings tab to show communications data
- Fixed NULL handling in controlling PC dropdown (Server.HTMLEncode type mismatch)
- Changed third_party_manager from text field to third_party_vendorid foreign key

**Database Impact:**
- New records created in: communications (up to 3 per machine), machinerelationships, compliance
- Added third_party_vendorid column to compliance table
- All changes backward compatible

