# ScanLook - Deployment & Testing Guide

## 📦 Phase 1 (MVP) - What's Been Built

### ✅ Complete Features

1. **User Authentication System**
   - 3 role levels: Owner, Admin, Staff
   - Secure password hashing
   - Session management
   - Default test accounts created

2. **Session Management**
   - Admin can create count sessions
   - Session types: Cycle Count, Full Physical
   - Active session tracking

3. **MASTER Baseline Upload**
   - CSV import from NetSuite
   - Validation of required columns
   - Storage in BaselineInventory_Master table
   - Never changes during session

4. **Scanning Interface**
   - Mobile-optimized, high-contrast design
   - Location scanning workflow
   - Lot scanning with immediate validation
   - Weight entry modal
   - Real-time status feedback

5. **Variance Detection**
   - ✅ MATCH: Lot in correct location
   - ⚠️ WRONG LOCATION: Lot exists elsewhere
   - ❌ GHOST LOT: Not in system

6. **Real-Time Dashboard**
   - Admin view: All sessions, statistics
   - Staff view: Active session selection
   - Session detail with progress tracking
   - Active counter monitoring

7. **Mobile-First Design**
   - Dark theme for warehouse environment
   - Large touch targets (44px+)
   - Scanner-optimized inputs
   - Autofocus on scan fields
   - Color-coded status indicators

---

## 🧪 Testing the Application

### Step 1: Start the Server

```bash
cd /home/claude/scanlook
./start.sh
```

Or manually:
```bash
python app.py
```

The server will start on `http://localhost:5000`

### Step 2: Admin Workflow Test

1. **Login as Admin**
   - Username: `admin`
   - Password: `admin123`

2. **Create a Count Session**
   - Click "New Session"
   - Session name: "Test Session - January 17 2026"
   - Type: Cycle Count
   - Click "Create Session"

3. **Upload MASTER Baseline**
   - In session detail, find "MASTER Baseline" section
   - Click "Choose File" → select `sample_baseline.csv`
   - Click "Upload MASTER"
   - Verify: "✅ MASTER baseline uploaded: 16 records"

4. **Monitor Dashboard**
   - View real-time statistics (all zeros initially)
   - Check baseline status shows uploaded timestamp

### Step 3: Staff Workflow Test

1. **Logout** (top right) and **Login as Staff**
   - Username: `staff1`
   - Password: `staff123`

2. **Select Active Session**
   - Click on "Test Session - January 17 2026"

3. **Start Counting a Location**
   - Type or scan: `R903B`
   - Click "START"
   - You're now counting location R903B

4. **Scan First Lot**
   - Lot input: `20260108-132620-PO25146`
   - Press Enter (or click submit)
   - Weight modal appears
   - Enter weight: `2030`
   - Click "Save"
   - Result: ✅ **MATCH** (green badge)

5. **Scan Second Lot (Same Location)**
   - Lot input: `20260108-132700-PO25146`
   - Enter weight: `2030`
   - Result: ✅ **MATCH**

6. **Scan Third Lot (Wrong Location)**
   - Lot input: `20260106-150649-PO24949`
   - Enter weight: `2065`
   - Result: ⚠️ **WRONG LOCATION** (yellow badge)
   - Shows expected: R905C

7. **Scan Ghost Lot (Not in System)**
   - Lot input: `GHOST-LOT-999`
   - Enter weight: `1500`
   - Result: ❌ **GHOST LOT** (red badge)

8. **View Your Scans**
   - Scroll down to see all scanned lots
   - Each shows:
     - Lot number
     - Weight
     - Item description
     - Status badge
     - Timestamp

9. **Finish Location**
   - Click "✓ Finish Location"
   - Confirm
   - Returns to location selection

10. **Count Another Location**
    - Try location: `R810D`
    - Scan lots: `20260110-084530-PO25200`, `20260110-091215-PO25200`

### Step 4: Admin Monitoring Test

1. **Login as Admin** again
2. **View Session Detail**
   - See statistics updated:
     - Matched: X lots
     - Wrong Location: Y lots
     - Ghost Lots: Z lots
3. **Check Active Counters**
   - Shows "John Doe" at location (if still in progress)
4. **View Location Progress**
   - Table shows:
     - R903B: ✓ Done
     - R810D: ⏳ Counting (or ✓ Done)

---

## 📊 Understanding the Data Flow

### MASTER Baseline Flow:

```
1. Admin uploads CSV
   ↓
2. System parses and validates
   ↓
3. Inserts into BaselineInventory_Master
   ↓
4. Updates session.master_baseline_timestamp
   ↓
5. Staff can now scan and validate against this
```

### Scanning Flow:

```
1. Staff scans location → Creates LocationCount record
   ↓
2. Staff scans lot → System looks up in MASTER baseline
   ↓
3. Validates:
   - Exists? → Check location
     - Correct? → MATCH
     - Wrong? → WRONG_LOCATION
   - Doesn't exist? → GHOST_LOT
   ↓
4. Staff enters weight
   ↓
5. Insert into ScanEntries with status
   ↓
6. Update LocationCount.lots_found counter
   ↓
7. Dashboard auto-updates via page refresh
```

---

## 🔍 Database Inspection

Check what's in the database:

```bash
cd /home/claude/scanlook
sqlite3 database/scanlook.db
```

Useful queries:

```sql
-- View all users
SELECT * FROM Users;

-- View all sessions
SELECT * FROM CountSessions;

-- View MASTER baseline
SELECT * FROM BaselineInventory_Master LIMIT 10;

-- View all scans
SELECT 
    lot_number, 
    scanned_location, 
    actual_weight, 
    master_status 
FROM ScanEntries 
ORDER BY scan_timestamp DESC;

-- View location counts
SELECT * FROM LocationCounts;

-- Exit
.quit
```

---

## 🐛 Troubleshooting

### Issue: Can't connect from scanner device

**Solution:**
1. Check server is running on `0.0.0.0` (it is by default)
2. Find server IP: `hostname -I`
3. Ensure scanner and server on same network
4. Disable firewall or allow port 5000

### Issue: CSV upload fails

**Solution:**
1. Verify CSV has exact column names (case-sensitive):
   - Item, Description, Lot Number, Location, Bin Number, On Hand
2. Check for special characters or encoding issues
3. Use the `sample_baseline.csv` as template

### Issue: Scans not showing status

**Solution:**
1. Verify MASTER baseline was uploaded first
2. Check lot numbers match exactly (case-sensitive)
3. Look at browser console for JavaScript errors

### Issue: Can't log in

**Solution:**
1. Verify database was initialized: `ls database/scanlook.db`
2. Re-run: `python database/init_db.py`
3. Use exact credentials (case-sensitive):
   - admin / admin123

---

## 🔒 Security Notes (For Production)

### Before Deploying to Production:

1. **Change Secret Key**
   ```python
   # In app.py, line 12
   app.secret_key = 'your-unique-random-secret-key-here'
   ```

2. **Change Default Passwords**
   - Delete default users from database
   - Create new users with strong passwords

3. **Enable HTTPS**
   - Use reverse proxy (nginx/Apache)
   - Get SSL certificate (Let's Encrypt)

4. **Restrict Network Access**
   - Firewall rules
   - VPN or internal network only

5. **Backup Database**
   - Regular automated backups
   - Test restore procedures

6. **Set Proper File Permissions**
   ```bash
   chmod 600 database/scanlook.db
   ```

---

## 📈 Next Steps: Phase 2

### CURRENT Baseline Refresh (Next to Build)

**What it does:**
- Admin uploads new CSV anytime during session
- Soft deletes old CURRENT baseline
- Inserts new version with incremented version number
- Recalculates CURRENT status for all existing scans
- Shows what moved/changed after count

**New statuses:**
- `still_there`: Still in same location
- `moved_after_count`: Lot moved after we counted it
- `removed_from_system`: No longer in system
- `still_wrong`: Still in wrong location

**Benefits:**
- Proves count was correct
- Shows operational changes during count
- Distinguishes real variances from movement

---

## 🎯 Production Deployment Checklist

- [ ] Change app.secret_key
- [ ] Change all default passwords
- [ ] Set up HTTPS/reverse proxy
- [ ] Configure firewall rules
- [ ] Set up database backups
- [ ] Test on actual scanner devices
- [ ] Train staff on interface
- [ ] Create support documentation
- [ ] Set up monitoring/logging
- [ ] Plan data retention policy

---

## 📝 Sample Test Scenarios

### Scenario 1: Perfect Count
- All lots scanned in correct locations
- Weights match exactly
- Result: 100% accuracy, no variances

### Scenario 2: Location Errors
- Some lots in wrong bins
- System flags immediately
- Admin can investigate

### Scenario 3: Ghost Inventory
- Physical lots not in system
- Identifies data quality issues
- Needs system update

### Scenario 4: Missing Lots
- System expects lots not found
- Possible theft, damage, or location error
- Flagged for investigation

---

## 💻 Development Notes

### File Structure:
```
scanlook/
├── app.py                 # Main application (500+ lines)
├── database/
│   ├── init_db.py         # DB schema & initialization
│   └── scanlook.db        # SQLite database
├── static/
│   ├── css/style.css      # ~1000 lines of custom CSS
│   └── js/main.js         # Client-side utilities
├── templates/             # 8 HTML templates
├── sample_baseline.csv    # Test data
├── start.sh              # Startup script
├── requirements.txt      # Python dependencies
└── README.md             # User documentation
```

### Code Quality:
- Parameterized SQL queries (injection prevention)
- Password hashing (Werkzeug)
- Session management (Flask)
- Role-based access control
- Soft deletes (audit trail)
- Mobile-first responsive design
- High-contrast warehouse theme

---

## 🎨 Design Philosophy

**Why this design?**

1. **Dark Theme**: Better for warehouse lighting conditions
2. **High Contrast**: Easy to read at a glance
3. **Large Inputs**: Scanner-friendly, touch-optimized
4. **Minimal Typing**: Scan everything possible
5. **Instant Feedback**: Color-coded status immediately
6. **Autofocus**: Scanner workflow optimization
7. **Bold Typography**: Legibility in fast-paced environment

**Color Meanings:**
- **Cyan (#00d4ff)**: Primary actions, matches
- **Green (#00ff88)**: Success, correct scans
- **Yellow (#ffaa00)**: Warnings, wrong location
- **Red (#ff3366)**: Errors, ghost lots, missing

---

## 🚀 Ready to Deploy?

Once testing is complete and you're satisfied with Phase 1:

1. Copy entire `scanlook` folder to production server
2. Follow Production Deployment Checklist above
3. Train users on the workflow
4. Start with pilot (small session)
5. Gather feedback
6. Scale up to full operations

**Remember:** This replaces 5 days of work with a weekend. You're about to be a hero at your workplace! 🎉

---

*Built January 2026 • ScanLook v1.0 (Phase 1)*
