# PC to Machines Consolidation - Complete Design Document

**Date Created**: 2025-11-06
**Status**: DESIGN PHASE
**Complexity**:  **CRITICAL - MASSIVE REFACTORING**
**Production Deployment**: All SQL changes must be tracked

---

## Executive Summary

This document outlines the plan to consolidate the `pc` table (277 records) into the `machines` table (266 records) and implement a generic communications infrastructure.

**Goals:**
1. Eliminate the `pc` table by migrating all data into `machines`
2. Create a generic `communications` system supporting multiple communication types (IP, Serial, etc.)
3. Maintain all existing functionality through views and code updates
4. Enable future extensibility for new communication types

**Impact:**
- **Tables to modify**: 12+
- **Views to update**: 19
- **ASP files**: TBD (likely 50+)
- **Data records**: 543 machines total (266 current + 277 PCs)

---

## Part 1: Current State Analysis

### 1.1 PC Table Structure (277 records)

```sql
CREATE TABLE pc (
    pcid INT(11) PRIMARY KEY AUTO_INCREMENT,
    hostname VARCHAR(100),
    serialnumber VARCHAR(100),
    loggedinuser VARCHAR(100),
    pctypeid INT(11),                    -- FK to pctype
    machinenumber VARCHAR(50),            -- Links to machines.machinenumber
    lastupdated DATETIME,
    dateadded DATETIME,
    warrantyenddate DATE,
    warrantystatus VARCHAR(50),
    warrantydaysremaining INT(11),
    warrantyservicelevel VARCHAR(100),
    warrantylastchecked DATETIME,
    modelnumberid INT(11),               -- FK to models
    isactive TINYINT(1),
    requires_manual_machine_config TINYINT(1),
    osid INT(11),                        -- FK to operatingsystems
    pcstatusid INT(11)                   -- FK to pcstatus
);
```

### 1.2 Machines Table Structure (266 records)

```sql
CREATE TABLE machines (
    machineid INT(11) PRIMARY KEY AUTO_INCREMENT,
    machinetypeid INT(11) NOT NULL DEFAULT 1,  -- FK to machinetypes
    machinenumber TINYTEXT,
    printerid INT(11),
    alias TINYTEXT,
    businessunitid INT(11),
    modelnumberid INT(11),               -- FK to models
    isactive INT(11),
    ipaddress1 CHAR(50),                 -- Will be deprecated
    ipaddress2 CHAR(50),                 -- Will be deprecated
    machinenotes TEXT,
    mapleft SMALLINT(6),
    maptop SMALLINT(6),
    isvnc BIT(1),
    islocationonly BIT(1)
);
```

### 1.3 Existing Communication Tables

#### pc_comm_config (Serial/IP Configuration)
```sql
CREATE TABLE pc_comm_config (
    configid INT(11) PRIMARY KEY,
    pcid INT(11) NOT NULL,               -- FK to pc
    configtype VARCHAR(50),              -- 'Serial', 'IP', etc.
    portid VARCHAR(20),                  -- COM port
    baud INT(11),
    databits INT(11),
    stopbits VARCHAR(5),
    parity VARCHAR(10),
    crlf VARCHAR(5),
    ipaddress VARCHAR(45),
    socketnumber INT(11),
    additionalsettings TEXT,
    lastupdated DATETIME
);
```

#### pc_network_interfaces (Network Cards)
```sql
CREATE TABLE pc_network_interfaces (
    interfaceid INT(11) PRIMARY KEY,
    pcid INT(11) NOT NULL,               -- FK to pc
    interfacename VARCHAR(255),
    ipaddress VARCHAR(45),
    subnetmask VARCHAR(45),
    defaultgateway VARCHAR(45),
    macaddress VARCHAR(17),
    isdhcp TINYINT(1),
    isactive TINYINT(1),
    ismachinenetwork TINYINT(1),
    lastupdated DATETIME
);
```

#### pc_dnc_config (DNC Configuration)
```sql
CREATE TABLE pc_dnc_config (
    dncid INT(11) PRIMARY KEY,
    pcid INT(11) NOT NULL UNIQUE,        -- FK to pc
    site VARCHAR(100),
    cnc VARCHAR(100),
    ncif VARCHAR(50),
    machinenumber VARCHAR(50),
    hosttype VARCHAR(50),
    ftphostprimary VARCHAR(100),
    ftphostsecondary VARCHAR(100),
    ftpaccount VARCHAR(100),
    debug VARCHAR(10),
    uploads VARCHAR(10),
    scanner VARCHAR(10),
    dripfeed VARCHAR(10),
    additionalsettings TEXT,
    lastupdated DATETIME,
    dualpath_enabled TINYINT(1),
    path1_name VARCHAR(255),
    path2_name VARCHAR(255),
    ge_registry_32bit TINYINT(1),
    ge_registry_64bit TINYINT(1),
    ge_registry_notes TEXT
);
```

### 1.4 Dependencies

#### Tables Referencing PC:
1. **machine_overrides** - Manual machine number overrides for PCs
2. **machine_pc_relationships** - Many-to-many relationships
3. **pc_comm_config** - Serial/IP communication settings
4. **pc_dnc_config** - DNC configuration
5. **pc_dualpath_assignments** - Secondary machine assignments
6. **pc_network_interfaces** - Network interface details

#### Views Using PC (19 views):
1. vw_active_pcs
2. vw_dnc_config
3. vw_dualpath_management
4. vw_engineer_pcs
5. vw_ge_machines
6. vw_machine_assignment_status
7. vw_machine_assignments
8. vw_machine_type_stats
9. vw_multi_pc_machines
10. vw_pc_network_summary
11. vw_pc_resolved_machines
12. vw_pc_summary
13. vw_pcs_by_hardware
14. vw_recent_updates
15. vw_shopfloor_applications_summary
16. vw_shopfloor_comm_config
17. vw_shopfloor_pcs
18. vw_standard_pcs
19. vw_vendor_summary
20. vw_warranties_expiring

---

## Part 2: New Design - Communications Infrastructure

### 2.1 New Table: comstypes (Communication Types)

```sql
CREATE TABLE comstypes (
    comstypeid INT(11) PRIMARY KEY AUTO_INCREMENT,
    typename VARCHAR(50) NOT NULL UNIQUE,       -- 'IP', 'Serial', 'USB', 'Parallel', 'Network', etc.
    description VARCHAR(255),
    requires_port TINYINT(1) DEFAULT 0,         -- Does this type need a port? (Serial, Parallel)
    requires_ipaddress TINYINT(1) DEFAULT 0,    -- Does this type need an IP? (IP, Network)
    isactive TINYINT(1) DEFAULT 1,
    displayorder INT(11) DEFAULT 0,
    dateadded DATETIME DEFAULT CURRENT_TIMESTAMP
);
```

**Initial Data:**
```sql
INSERT INTO comstypes (typename, description, requires_port, requires_ipaddress, displayorder) VALUES
('IP', 'TCP/IP Network Communication', 0, 1, 1),
('Serial', 'Serial Port Communication (RS-232)', 1, 0, 2),
('Network_Interface', 'Network Interface Card', 0, 1, 3),
('USB', 'USB Connection', 1, 0, 4),
('Parallel', 'Parallel Port Connection', 1, 0, 5),
('VNC', 'Virtual Network Computing', 0, 1, 6),
('FTP', 'File Transfer Protocol', 0, 1, 7);
```

### 2.2 New Table: communications

```sql
CREATE TABLE communications (
    comid INT(11) PRIMARY KEY AUTO_INCREMENT,
    machineid INT(11) NOT NULL,                 -- FK to machines.machineid
    comstypeid INT(11) NOT NULL,                -- FK to comstypes.comstypeid

    -- Generic fields applicable to multiple types
    ipaddress VARCHAR(45),                      -- For IP-based communications
    port INT(11),                               -- Port number (for IP) or COM port number
    portname VARCHAR(20),                       -- COM1, COM2, LPT1, etc.
    macaddress VARCHAR(17),                     -- MAC address for network interfaces

    -- Network-specific fields
    subnetmask VARCHAR(45),
    defaultgateway VARCHAR(45),
    dnsserver VARCHAR(45),
    isdhcp TINYINT(1) DEFAULT 0,

    -- Serial-specific fields
    baud INT(11),                               -- 9600, 115200, etc.
    databits INT(11),                           -- 7, 8
    stopbits VARCHAR(5),                        -- '1', '1.5', '2'
    parity VARCHAR(10),                         -- 'None', 'Even', 'Odd', 'Mark', 'Space'
    flowcontrol VARCHAR(20),                    -- 'None', 'Hardware', 'Software'

    -- Protocol-specific fields
    protocol VARCHAR(50),                       -- 'TCP', 'UDP', 'FTP', 'HTTP', etc.
    username VARCHAR(100),                      -- For authenticated protocols
    password VARCHAR(255),                      -- Encrypted password

    -- General metadata
    interfacename VARCHAR(255),                 -- Network adapter name
    description VARCHAR(255),
    isprimary TINYINT(1) DEFAULT 0,             -- Is this the primary communication method?
    isactive TINYINT(1) DEFAULT 1,
    ismachinenetwork TINYINT(1) DEFAULT 0,      -- Is this for machine network (vs office network)?

    -- Additional settings as JSON/TEXT
    additionalsettings TEXT,                    -- JSON for future extensibility

    -- Audit fields
    lastupdated DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    dateadded DATETIME DEFAULT CURRENT_TIMESTAMP,

    -- Indexes
    KEY idx_machineid (machineid),
    KEY idx_comstypeid (comstypeid),
    KEY idx_ipaddress (ipaddress),
    KEY idx_isactive (isactive),
    KEY idx_isprimary (isprimary),

    -- Foreign Keys
    CONSTRAINT fk_communications_machineid FOREIGN KEY (machineid) REFERENCES machines(machineid),
    CONSTRAINT fk_communications_comstypeid FOREIGN KEY (comstypeid) REFERENCES comstypes(comstypeid)
);
```

### 2.3 Modified Machines Table

Add new fields to support PC data and communications:

**NOTE**: Warranty fields are NOT added to machines table. See WARRANTY_MANAGEMENT_DESIGN.md for the separate warranty infrastructure.

```sql
ALTER TABLE machines
-- PC-specific fields
ADD COLUMN hostname VARCHAR(100) AFTER machinenumber,
ADD COLUMN serialnumber VARCHAR(100) AFTER modelnumberid,
ADD COLUMN loggedinuser VARCHAR(100) AFTER hostname,
ADD COLUMN osid INT(11) AFTER modelnumberid,
ADD COLUMN pcstatusid INT(11) AFTER osid,
ADD COLUMN pctypeid INT(11) AFTER machinetypeid,

-- Configuration flags
ADD COLUMN requires_manual_machine_config TINYINT(1) DEFAULT 0,

-- Audit fields
ADD COLUMN lastupdated DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
ADD COLUMN dateadded DATETIME DEFAULT CURRENT_TIMESTAMP,

-- Foreign keys
ADD CONSTRAINT fk_machines_osid FOREIGN KEY (osid) REFERENCES operatingsystems(osid),
ADD CONSTRAINT fk_machines_pcstatusid FOREIGN KEY (pcstatusid) REFERENCES pcstatus(pcstatusid),
ADD CONSTRAINT fk_machines_pctypeid FOREIGN KEY (pctypeid) REFERENCES pctype(pctypeid);

-- Indexes
CREATE INDEX idx_machines_hostname ON machines(hostname);
CREATE INDEX idx_machines_serialnumber ON machines(serialnumber);
CREATE INDEX idx_machines_pctypeid ON machines(pctypeid);
CREATE INDEX idx_machines_osid ON machines(osid);
CREATE INDEX idx_machines_lastupdated ON machines(lastupdated);
```

---

## Part 3: Migration Strategy

### 3.1 Migration Phases

**Phase 1: Schema Preparation** (REVERSIBLE)
1. Create `comstypes` table
2. Create `communications` table
3. Add new columns to `machines` table
4. Create backup tables

**Phase 2: Data Migration** (REVERSIBLE with backup)
1. Migrate PC records to machines table
2. Migrate PC communication data to communications table
3. Migrate network interface data to communications table
4. Migrate DNC configuration to communications or new DNC table
5. Update relationship tables

**Phase 3: Reference Updates** (REQUIRES TESTING)
1. Create compatibility views (pc → machines)
2. Update dependent tables
3. Update 19 existing views

**Phase 4: Application Updates** (REQUIRES EXTENSIVE TESTING)
1. Update ASP files
2. Update stored procedures (if any)
3. Test all functionality

**Phase 5: Cleanup** (IRREVERSIBLE - DO AFTER 30 DAYS)
1. Drop old `pc` table
2. Drop compatibility views
3. Remove deprecated ipaddress1/ipaddress2 from machines

### 3.2 Machine Type for PCs

We need to add machine types for PCs:

```sql
INSERT INTO machinetypes (machinetype, machinedescription, functionalaccountid, isactive)
VALUES
('PC - Standard', 'Standard office/engineering workstation', (SELECT functionalaccountid FROM functionalaccounts WHERE functionalaccount = 'IT' LIMIT 1), 1),
('PC - Shopfloor', 'Shopfloor machine control PC', (SELECT functionalaccountid FROM functionalaccounts WHERE functionalaccount = 'MFG' LIMIT 1), 1),
('PC - Engineer', 'Engineering workstation', (SELECT functionalaccountid FROM functionalaccounts WHERE functionalaccount = 'ENG' LIMIT 1), 1);
```

### 3.3 Data Mapping: PC → Machines

| PC Field | Machines Field | Notes |
|----------|---------------|-------|
| pcid | machineid | New auto-increment ID |
| hostname | hostname | NEW COLUMN |
| serialnumber | serialnumber | NEW COLUMN |
| loggedinuser | loggedinuser | NEW COLUMN |
| pctypeid | pctypeid | NEW COLUMN, FK preserved |
| machinenumber | machinenumber | Existing field |
| lastupdated | lastupdated | NEW COLUMN |
| dateadded | dateadded | NEW COLUMN |
| modelnumberid | modelnumberid | Existing field |
| isactive | isactive | Existing field |
| requires_manual_machine_config | requires_manual_machine_config | NEW COLUMN |
| osid | osid | NEW COLUMN, FK preserved |
| pcstatusid | pcstatusid | NEW COLUMN, FK preserved |
| N/A | machinetypeid | Map from pctypeid to new machine types |
| N/A | alias | Set to hostname for PCs |
| N/A | businessunitid | Default to 1 or derive from location |

**Warranty Fields**: Migrated to `warranties` table (see WARRANTY_MANAGEMENT_DESIGN.md)
- warrantyenddate → warranties.enddate
- warrantystatus → warranties.status
- warrantyservicelevel → warranties.servicelevel
- warrantylastchecked → warranties.lastcheckeddate

### 3.4 Data Mapping: pc_network_interfaces → communications

| Old Field | New Field | New comstypeid |
|-----------|-----------|----------------|
| interfaceid | comid | Auto-increment |
| pcid | machineid | Lookup from migrated PCs |
| N/A | comstypeid | 3 (Network_Interface) |
| ipaddress | ipaddress | Direct copy |
| subnetmask | subnetmask | Direct copy |
| defaultgateway | defaultgateway | Direct copy |
| macaddress | macaddress | Direct copy |
| interfacename | interfacename | Direct copy |
| isdhcp | isdhcp | Direct copy |
| isactive | isactive | Direct copy |
| ismachinenetwork | ismachinenetwork | Direct copy |

### 3.5 Data Mapping: pc_comm_config → communications

| Old Field | New Field | New comstypeid |
|-----------|-----------|----------------|
| configid | comid | Auto-increment |
| pcid | machineid | Lookup from migrated PCs |
| configtype | comstypeid | Map 'Serial'→2, 'IP'→1, etc. |
| portid | portname | Direct copy (COM1, etc.) |
| baud | baud | Direct copy |
| databits | databits | Direct copy |
| stopbits | stopbits | Direct copy |
| parity | parity | Direct copy |
| ipaddress | ipaddress | Direct copy |
| socketnumber | port | Direct copy |
| additionalsettings | additionalsettings | Direct copy |

---

## Part 4: SQL Migration Scripts

### 4.1 Script 01: Schema Creation

File: `sql/01_create_communications_infrastructure.sql`

```sql
-- =====================================================
-- SCRIPT 01: Create Communications Infrastructure
-- =====================================================
-- Date: 2025-11-06
-- Purpose: Create comstypes and communications tables
-- Status: REVERSIBLE (has rollback script)
-- =====================================================

USE shopdb;
SET SQL_SAFE_UPDATES = 0;

-- Create comstypes table
CREATE TABLE IF NOT EXISTS comstypes (
    comstypeid INT(11) PRIMARY KEY AUTO_INCREMENT,
    typename VARCHAR(50) NOT NULL UNIQUE,
    description VARCHAR(255),
    requires_port TINYINT(1) DEFAULT 0,
    requires_ipaddress TINYINT(1) DEFAULT 0,
    isactive TINYINT(1) DEFAULT 1,
    displayorder INT(11) DEFAULT 0,
    dateadded DATETIME DEFAULT CURRENT_TIMESTAMP,
    KEY idx_isactive (isactive),
    KEY idx_displayorder (displayorder)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

-- Insert communication types
INSERT INTO comstypes (typename, description, requires_port, requires_ipaddress, displayorder) VALUES
('IP', 'TCP/IP Network Communication', 0, 1, 1),
('Serial', 'Serial Port Communication (RS-232)', 1, 0, 2),
('Network_Interface', 'Network Interface Card', 0, 1, 3),
('USB', 'USB Connection', 1, 0, 4),
('Parallel', 'Parallel Port Connection', 1, 0, 5),
('VNC', 'Virtual Network Computing', 0, 1, 6),
('FTP', 'File Transfer Protocol', 0, 1, 7);

-- Create communications table
CREATE TABLE IF NOT EXISTS communications (
    comid INT(11) PRIMARY KEY AUTO_INCREMENT,
    machineid INT(11) NOT NULL,
    comstypeid INT(11) NOT NULL,

    -- Generic fields
    ipaddress VARCHAR(45),
    port INT(11),
    portname VARCHAR(20),
    macaddress VARCHAR(17),

    -- Network-specific
    subnetmask VARCHAR(45),
    defaultgateway VARCHAR(45),
    dnsserver VARCHAR(45),
    isdhcp TINYINT(1) DEFAULT 0,

    -- Serial-specific
    baud INT(11),
    databits INT(11),
    stopbits VARCHAR(5),
    parity VARCHAR(10),
    flowcontrol VARCHAR(20),

    -- Protocol-specific
    protocol VARCHAR(50),
    username VARCHAR(100),
    password VARCHAR(255),

    -- General metadata
    interfacename VARCHAR(255),
    description VARCHAR(255),
    isprimary TINYINT(1) DEFAULT 0,
    isactive TINYINT(1) DEFAULT 1,
    ismachinenetwork TINYINT(1) DEFAULT 0,

    -- Additional settings
    additionalsettings TEXT,

    -- Audit fields
    lastupdated DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    dateadded DATETIME DEFAULT CURRENT_TIMESTAMP,

    -- Indexes
    KEY idx_machineid (machineid),
    KEY idx_comstypeid (comstypeid),
    KEY idx_ipaddress (ipaddress),
    KEY idx_isactive (isactive),
    KEY idx_isprimary (isprimary),

    -- Foreign Keys
    CONSTRAINT fk_communications_machineid FOREIGN KEY (machineid) REFERENCES machines(machineid),
    CONSTRAINT fk_communications_comstypeid FOREIGN KEY (comstypeid) REFERENCES comstypes(comstypeid)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

-- Verification
SELECT 'comstypes table created' AS status, COUNT(*) AS type_count FROM comstypes;
SELECT 'communications table created' AS status;

SET SQL_SAFE_UPDATES = 1;
```

### 4.2 Script 02: Extend Machines Table

File: `sql/02_extend_machines_table.sql`

**NOTE**: Warranty fields removed - see script 04 for warranty infrastructure

```sql
-- =====================================================
-- SCRIPT 02: Extend Machines Table for PC Data
-- =====================================================
-- Date: 2025-11-06
-- Purpose: Add PC-related columns to machines table
-- Status: REVERSIBLE (has rollback script)
-- NOTE: Warranty data goes to separate warranties table (script 04)
-- =====================================================

USE shopdb;
SET SQL_SAFE_UPDATES = 0;

-- Add PC-specific fields
ALTER TABLE machines
ADD COLUMN IF NOT EXISTS hostname VARCHAR(100) AFTER machinenumber,
ADD COLUMN IF NOT EXISTS serialnumber VARCHAR(100) AFTER modelnumberid,
ADD COLUMN IF NOT EXISTS loggedinuser VARCHAR(100) AFTER hostname,
ADD COLUMN IF NOT EXISTS osid INT(11) AFTER modelnumberid,
ADD COLUMN IF NOT EXISTS pcstatusid INT(11) AFTER osid,
ADD COLUMN IF NOT EXISTS pctypeid INT(11) AFTER machinetypeid;

-- Add configuration flags
ALTER TABLE machines
ADD COLUMN IF NOT EXISTS requires_manual_machine_config TINYINT(1) DEFAULT 0 AFTER islocationonly;

-- Add audit fields
ALTER TABLE machines
ADD COLUMN IF NOT EXISTS lastupdated DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP AFTER requires_manual_machine_config,
ADD COLUMN IF NOT EXISTS dateadded DATETIME DEFAULT CURRENT_TIMESTAMP AFTER lastupdated;

-- Add foreign keys
ALTER TABLE machines
ADD CONSTRAINT fk_machines_osid FOREIGN KEY (osid) REFERENCES operatingsystems(osid);

ALTER TABLE machines
ADD CONSTRAINT fk_machines_pcstatusid FOREIGN KEY (pcstatusid) REFERENCES pcstatus(pcstatusid);

ALTER TABLE machines
ADD CONSTRAINT fk_machines_pctypeid FOREIGN KEY (pctypeid) REFERENCES pctype(pctypeid);

-- Create indexes
CREATE INDEX IF NOT EXISTS idx_machines_hostname ON machines(hostname);
CREATE INDEX IF NOT EXISTS idx_machines_serialnumber ON machines(serialnumber);
CREATE INDEX IF NOT EXISTS idx_machines_pctypeid ON machines(pctypeid);
CREATE INDEX IF NOT EXISTS idx_machines_osid ON machines(osid);
CREATE INDEX IF NOT EXISTS idx_machines_lastupdated ON machines(lastupdated);

-- Verification
DESCRIBE machines;

SET SQL_SAFE_UPDATES = 1;
```

### 4.3 Script 03: Create PC Machine Types

File: `sql/03_create_pc_machine_types.sql`

```sql
-- =====================================================
-- SCRIPT 03: Create Machine Types for PCs
-- =====================================================
-- Date: 2025-11-06
-- Purpose: Add PC-related machine types
-- Status: REVERSIBLE
-- =====================================================

USE shopdb;
SET SQL_SAFE_UPDATES = 0;

-- Get or create functional accounts
INSERT IGNORE INTO functionalaccounts (functionalaccount, description, isactive)
VALUES
('IT', 'Information Technology', 1),
('MFG', 'Manufacturing', 1),
('ENG', 'Engineering', 1);

-- Create PC machine types
INSERT INTO machinetypes (machinetype, machinedescription, functionalaccountid, isactive)
SELECT 'PC - Standard', 'Standard office/engineering workstation', functionalaccountid, 1
FROM functionalaccounts WHERE functionalaccount = 'IT' LIMIT 1
WHERE NOT EXISTS (SELECT 1 FROM machinetypes WHERE machinetype = 'PC - Standard');

INSERT INTO machinetypes (machinetype, machinedescription, functionalaccountid, isactive)
SELECT 'PC - Shopfloor', 'Shopfloor machine control PC', functionalaccountid, 1
FROM functionalaccounts WHERE functionalaccount = 'MFG' LIMIT 1
WHERE NOT EXISTS (SELECT 1 FROM machinetypes WHERE machinetype = 'PC - Shopfloor');

INSERT INTO machinetypes (machinetype, machinedescription, functionalaccountid, isactive)
SELECT 'PC - Engineer', 'Engineering workstation', functionalaccountid, 1
FROM functionalaccounts WHERE functionalaccount = 'ENG' LIMIT 1
WHERE NOT EXISTS (SELECT 1 FROM machinetypes WHERE machinetype = 'PC - Engineer');

-- Verification
SELECT * FROM machinetypes WHERE machinetype LIKE 'PC -%';

SET SQL_SAFE_UPDATES = 1;
```

---

## Part 5: Rollback Scripts

### 5.1 Rollback Script 01

File: `sql/ROLLBACK_01_communications_infrastructure.sql`

```sql
-- =====================================================
-- ROLLBACK 01: Remove Communications Infrastructure
-- =====================================================

USE shopdb;
SET SQL_SAFE_UPDATES = 0;

-- Drop tables in correct order (FK constraints)
DROP TABLE IF EXISTS communications;
DROP TABLE IF EXISTS comstypes;

SELECT 'Communications infrastructure removed' AS status;

SET SQL_SAFE_UPDATES = 1;
```

### 5.2 Rollback Script 02

File: `sql/ROLLBACK_02_machines_table_extensions.sql`

```sql
-- =====================================================
-- ROLLBACK 02: Remove Machines Table Extensions
-- =====================================================

USE shopdb;
SET SQL_SAFE_UPDATES = 0;

-- Drop foreign keys first
ALTER TABLE machines DROP FOREIGN KEY IF EXISTS fk_machines_osid;
ALTER TABLE machines DROP FOREIGN KEY IF EXISTS fk_machines_pcstatusid;
ALTER TABLE machines DROP FOREIGN KEY IF EXISTS fk_machines_pctypeid;

-- Drop indexes
DROP INDEX IF EXISTS idx_machines_hostname ON machines;
DROP INDEX IF EXISTS idx_machines_serialnumber ON machines;
DROP INDEX IF EXISTS idx_machines_pctypeid ON machines;
DROP INDEX IF EXISTS idx_machines_osid ON machines;
DROP INDEX IF EXISTS idx_machines_lastupdated ON machines;

-- Remove columns (MySQL 5.6 doesn't support IF EXISTS for columns)
ALTER TABLE machines
DROP COLUMN hostname,
DROP COLUMN serialnumber,
DROP COLUMN loggedinuser,
DROP COLUMN osid,
DROP COLUMN pcstatusid,
DROP COLUMN pctypeid,
DROP COLUMN requires_manual_machine_config,
DROP COLUMN lastupdated,
DROP COLUMN dateadded;

SELECT 'Machines table extensions removed' AS status;

SET SQL_SAFE_UPDATES = 1;
```

---

## Part 6: Next Steps & Considerations

### 6.1 Critical Decisions Needed

1. **DNC Configuration**:
   - Keep pc_dnc_config as-is but reference machines instead of pc?
   - Or migrate to communications table with comstypeid='DNC'?
   - **Recommendation**: Keep separate, too complex for generic table

2. **Machine Overrides**:
   - Keep machine_overrides table?
   - **Recommendation**: Yes, but update FK to machines

3. **Warranty Management**:
   - Extend to all machines or keep PC-specific?
   - **Recommendation**: Available for all machines

4. **Machine Numbers**:
   - PCs currently link to machines via machinenumber (string match)
   - After migration, use direct machineid FK
   - **Recommendation**: Add explicit FK relationships

### 6.2 Testing Requirements

1. **Data Integrity**:
   - Verify all 277 PCs migrated
   - Verify all communication records migrated
   - Verify all FK relationships intact

2. **View Testing**:
   - Test all 19 views return same data
   - Performance testing for complex views

3. **Application Testing**:
   - Test every ASP file that touches pc table
   - Test all CRUD operations
   - Test warranty tracking
   - Test DNC configuration

### 6.3 Production Deployment Checklist

- [ ] Create full database backup
- [ ] Test migration on dev environment
- [ ] Create compatibility views for old queries
- [ ] Update all ASP files
- [ ] Schedule maintenance window (4-6 hours recommended)
- [ ] Prepare rollback procedure
- [ ] Document all changes
- [ ] Train users on any UI changes

---

## Part 7: Estimated Timeline

| Phase | Duration | Dependencies |
|-------|----------|--------------|
| Schema Design | 1 day | None |
| Create Migration Scripts | 2-3 days | Schema approval |
| Data Migration Testing | 2-3 days | Scripts complete |
| View Updates | 1-2 days | Data migration tested |
| ASP File Analysis | 2-3 days | View updates tested |
| ASP File Updates | 5-7 days | File analysis complete |
| Integration Testing | 3-5 days | All updates complete |
| User Acceptance Testing | 2-3 days | Integration testing passed |
| Production Deployment | 1 day | UAT passed |
| **Total** | **20-30 days** | |

---

## Appendix A: Risk Assessment

| Risk | Severity | Mitigation |
|------|----------|------------|
| Data loss during migration | CRITICAL | Full backups, test on dev first, rollback scripts |
| Application downtime | HIGH | Deploy during maintenance window, parallel cutover |
| Performance degradation | MEDIUM | Index optimization, query testing |
| View compatibility issues | HIGH | Create compatibility views, thorough testing |
| User training needed | LOW | Minimal UI changes expected |

---

## Appendix B: File Impact Analysis

*To be completed after code review*

Files to analyze:
- All files with "pc" in filename
- All files referencing pc table
- All files using pc views

---

**Document Status**: DRAFT
**Next Review Date**: TBD
**Approval Required From**: System Administrator, Lead Developer
