# 777 Wolfpack - Complete Product Roadmap

## 📍 Current Status (December 2024)

### ✅ Completed Phases

| Phase | Description | Status |
|-------|-------------|--------|
| **Phase 1** | Core Infrastructure - Auth, Rooms, Batches, Touch Points | ✅ Complete |
| **Phase 2** | Tasks & SOPs - Task management, templates, assignments | ✅ Complete |
| **Phase 3** | Supplies & Inventory - Stock tracking, usage logs | ✅ Complete |
| **Phase 4** | Timeclock - Clock in/out, hour tracking | ✅ Complete |
| **Phase 5** | IPM & Plant Health - Scouting, treatments, health history | ✅ Complete |
| **Phase 6** | Reporting & Analytics - Dashboards, yield reports | ✅ Complete |
| **Polish** | UI/UX - Toasts, offline, PWA, mobile gestures, undo | ✅ Complete |

---

## 🚀 Phase 7: Facility Layout Designer & Plant Addressing

> **⚠️ CRITICAL** - Required for METRC integration and plant-level tracking

### Goal

Create a Figma-like visual layout editor for designing facility layouts. Every plant gets a unique, hierarchical address: `PROPERTY.BUILDING.ROOM.SECTION.ROW.COLUMN.POSITION`

> **Detailed spec**: See `LAYOUT-DESIGNER-SPEC.md`

### Sprint 1: Data Model & API (1 week) [COMPLETED]

- **Backend**:
  - `Property` → `Building` → `Room` → `Section` → `Row` → `Position` hierarchy
  - `Plant` model with addressable position
  - `PlantLocationHistory` for move tracking
  - CRUD endpoints for layout management
  - Bulk plant placement endpoints

### Sprint 2: Layout Editor (2 weeks) [COMPLETED]

- **Frontend**:
  - Canvas editor (react-konva or tldraw)
  - Add/edit buildings, rooms, sections
  - Grid generator for grow tables/racks
  - Drag & drop, resize, snap-to-grid
  - Templates (veg table, flower bed, dry rack)

### Sprint 3: Plant Placement (1 week) [COMPLETED]

- **Frontend**:
  - Room grid view showing positions ✅
  - Place plants in positions ✅
  - Move plants (with history) ✅
  - Bulk placement tool ✅
  - Color coding by batch/stage/health ✅

### Sprint 4: METRC Sync (2 weeks) [IN PROGRESS]

- Address format mapping to METRC ✅
- Location sync on plant create/move ✅ (placeholder - needs API credentials)
- Audit report generation ✅
- Discrepancy detection ✅
- CSV export for manual upload ✅

## 🚀 Phase 8: Visitor Management & Access Control

### Goal

Track all visitors, contractors, and inspectors entering/exiting the facility. Generate nametags/badges. Maintain audit trail for compliance.

### Sprint 1: Visitor Registration [COMPLETED]

- **Backend**: ✅
  - `Visitor` model: name, company, purpose, contact, photo, signature
  - `VisitorLog` model: entryTime, exitTime, escortedBy, areasAccessed
  - Endpoints: `POST /visitors`, `POST /visitors/:id/check-in`, `POST /visitors/:id/check-out`
  
- **Frontend**: ✅
  - **Kiosk Mode**: Tablet-friendly check-in screen at reception
  - NDA acknowledgement, badge number generation
  - Real-time visitor list (who's in the building now)

### Sprint 2: Badge & Nametag Printing [COMPLETED]

- **Integration**: ✅
  - Generate printable badges (browser print with thermal/standard sizes)
  - QR code linking to visitor record
  - Temporary badge expiration (visual indicator + void overlay)
  
- **Frontend**: ✅
  - Enhanced VisitorBadge component with templates
  - Badge templates (Visitor, Contractor, Inspector, Vendor, Delivery)
  - BadgePrintQueue component for bulk printing
  - Size selector (Standard 3.5x5, Large 3.5x6, Thermal 2.25x3.5)

### Sprint 3: Access Zones & Escort Requirements [COMPLETED]

- **Backend**: ✅
  - `AccessZone` model: lobbyOnly, escortRequired, restrictedAreas
  - Link visitors to permitted zones
  - Zone occupancy tracking
  
- **Frontend**: ✅
  - Zone management UI
  - Escort assignment on check-in
  - Zone access logging

---

## 🚀 Phase 9: Messaging & Mass Communication

### Goal

Enable facility-wide announcements, team messaging, shift handoffs, and emergency alerts. Ensure message acknowledgement for compliance.

### Sprint 1: Announcements & Broadcasts [COMPLETED]

- **Backend**: ✅
  - `Announcement` model: title, body, priority, expiresAt, targetRoles
  - `AnnouncementAck` model: userId, readAt, acknowledged
  - REST API for announcements and acknowledgements

- **Frontend**: ✅
  - **Announcement Banner**: Critical messages at top of screen
  - Expandable announcement list with read/unread status
  - "I acknowledge" button for required messages

### Sprint 2: Acknowledgement System [COMPLETED]

- **Backend**: ✅
  - Acknowledgement tracking per user per announcement
  - Pending acknowledgement endpoint
  - Admin endpoint for acknowledgement status
  
- **Frontend**: ✅
  - Acknowledge button in banner
  - Acknowledgement status display

### Sprint 3: Team Messaging [COMPLETED]

- **Backend**: ✅
  - `ShiftNote` model: roomId, batchId, content, importance
  - CRUD endpoints for shift notes
  - Read tracking per user
  
- **Frontend**: ✅
  - ShiftNotesWidget component (`components/messaging/ShiftNotesWidget.tsx`)
  - Embeddable in Room/Batch pages with importance levels

---

## 🚀 Phase 10: Compliance & Audit Trail

### Goal

Zero-friction compliance reporting. Every action logged, every document versioned, instant report generation for inspectors.

### Sprint 1: Comprehensive Audit Log [COMPLETED]

- **Backend**: ✅
  - `AuditLog` model: userId, action, entity, entityId, before, after, timestamp, ipAddress
  - Helper function for audit logging from any route
  - Immutable storage (append-only)

- **Frontend**: ✅
  - AuditLogPage with filterable table, summary cards, detail modal
  - CSV export and pagination
  - Route: `/compliance/audit`

### Sprint 2: Compliance Reports [COMPLETED]

- **Backend**: ✅
  - Audit log query with filters
  - Summary statistics endpoint
  - CSV export for audit logs

- **Frontend**: ✅
  - Integrated in AuditLogPage
  - Filter by entity, action, date range

### Sprint 3: Document Version Control [COMPLETED]

- **Backend**: ✅
  - `Document` model with version tracking
  - `DocumentVersion` for history
  - Approval workflow endpoints
  - Acknowledgement tracking
  
- **Frontend**: ✅
  - DocumentsPage with card grid, category grouping, search/filters
  - Document viewer modal with version history sidebar
  - Pending acknowledgement banner
  - Route: `/compliance/documents`

---

## 🚀 Phase 11: Accessibility & Internationalization

### Goal

Make the application accessible to all users regardless of ability or language. WCAG 2.1 AA compliance.

### Sprint 1: Accessibility (a11y) [COMPLETED]

- **Implementation**: ✅
  - Screen reader support (sr-only class, ARIA labels, live regions)
  - Keyboard navigation (focus management, skip links)
  - High contrast mode (CSS media queries)
  - Reduced motion preference (prefers-reduced-motion)
  - Font size adjustment (normal/large/xlarge settings)
  - Accessibility hooks (useFocusTrap, useAnnounce, useRovingTabIndex)

- **Testing**: TODO
  - Automated a11y testing (axe-core)
  - Manual testing with VoiceOver/NVDA

### Sprint 2: Internationalization (i18n) [COMPLETED]

- **Implementation**: ✅
  - react-i18next integration
  - Comprehensive translation files (en, es)
  - Language detection from browser
  
- **Frontend**: ✅
  - Language selector in Settings
  - Date/number formatting by locale

### Sprint 3: User Preferences [COMPLETED]

- **Settings**: ✅
  - Theme (light/dark/system)
  - Language (English/Spanish)
  - Accessibility options (high contrast, font size, reduced motion)
  - Sound and notification preferences
  
- **Sync**: ✅
  - Persist to localStorage
  - Apply on page load

---

## 🚀 Phase 12: Hardware Integration

### Goal

Integrate physical hardware throughout facility: NFC badges, QR scanners, e-ink displays for real-time status boards.

> **Detailed spec**: See `HARDWARE-SPEC.md`

### Sprint 1: QR Code System [COMPLETED]

- **Implementation**: ✅
  - QR code generation library (qrcode.ts)
  - Batch, plant, visitor, room QR generators
  - QRCodeGenerator component with download/copy/print
  - Visitor badge component with printable format
  - Printable label generation

### Sprint 2: NFC Badges [TODO]

- Provision NFC badges for employees
- Tap-to-clock-in at time stations
- Zone access logging

### Sprint 3: E-Ink Display Network [TODO]

- Pilot: One room entrance display
- Room status boards (7.5")
- Task overview boards (6")
- Batch row tags (2.13")
- ESP32 + MQTT update protocol

---

## 🚀 Phase 13: Advanced Features

### Sprint 1: Environmental Monitoring [COMPLETED]

- **Backend**: ✅
  - `Sensor` model with type, thresholds, room assignment
  - `SensorReading` model for time-series data
  - `EnvironmentAlert` with severity and resolution tracking
  - `EnvironmentProfile` for target ranges per stage
  - Automatic threshold alerts on readings

- **Frontend**: ✅
  - Environment Dashboard with real-time readings
  - Alert display with acknowledge/resolve
  - Sensor list with latest values
  - Profile display with targets

### Sprint 2: Financial Tracking [COMPLETED]

- **Backend**: ✅
  - `FinancialTransaction` model (expense/revenue)
  - `BatchCost` aggregation with cost-per-gram
  - `Sale` records with revenue tracking
  - Profit/loss reports by period
  - Category breakdown analysis

- **Frontend**: ✅
  - Financial Dashboard with summary cards
  - Expense category breakdown chart
  - Monthly trend visualization
  - Recent transactions list

### Sprint 3: AI/ML Insights [COMPLETED]

- **Backend**: ✅
  - `YieldPrediction` model with factors
  - `AnomalyDetection` model for tracking
  - Yield prediction algorithm (strain, environment factors)
  - Anomaly detection using statistical analysis (z-scores)
  - Insights dashboard endpoint

- **Frontend**: ✅
  - AI Insights Dashboard
  - Prediction accuracy tracking
  - Anomaly list with resolve function
  - Batch performance rankings

### Future Enhancements

- **METRC Direct Integration**: API sync with CA track & trace
- **Mobile Native Apps**: iOS/Android with offline-first
- **Real ML Models**: TensorFlow/PyTorch integration
- **Predictive Maintenance**: Equipment failure prediction

## 🚀 Phase 14: Facility Monitoring & Security Integration

### Goal

Integrate physical security and monitoring systems (RTSP/ONVIF cameras) directly into the dashboard for real-time facility oversight.

### Sprint 1: Streaming Infrastructure [COMPLETED]

- **Infrastructure**: ✅
  - Depoy `go2rtc` media server
  - Configure Traefik routing `/monitor`
  - Demo stream verification

### Sprint 2: Integration [ROADMAP]

- **Backend**:
  - `Camera` model: RTSP URL, location, auth
  - Proxy authentication for secure stream access
  - Snapshot generation for thumbnails

- **Frontend**:
  - WebRTC Video Player component
  - "Security Overview" dashboard widget
  - Map integration (cameras on Layout Designer)

## 🚀 Phase 15: 3D Facility Visualization (The "Cool Views")

### Goal

Deliver the "SketchUp-like" experience by rendering the facility layout in an immersive 3D view.

### Sprint 1: 3D Viewer [ROADMAP]

- **Tech Stack**: `react-three-fiber` (Three.js)
- **Features**:
  - Render buildings, floors, rooms as 3D volumes
  - Render tables/racks with correct tier stacking
  - First-person "Walking" mode
  - "God View" (Orbit controls)
  - Visualizing plant health/status as colored blocks

---

## 📊 Roadmap Timeline (Proposed)

| Phase | Duration | Priority |
|-------|----------|----------|
| Phase 7: Layout Designer | In Progress | 🔴 Critical |
| Phase 8: Visitor Management | 2-3 weeks | 🔴 High (Compliance) |
| Phase 9: Messaging & Acknowledgements | 2-3 weeks | 🔴 High (Compliance) |
| Phase 10: Audit & Reporting | 2-3 weeks | 🔴 High (Compliance) |
| Phase 11: Accessibility & i18n | 1-2 weeks | 🟡 Medium |
| Phase 12: Hardware Integration | 2-4 weeks | 🟡 Medium |
| Phase 13: Advanced Features | Ongoing | 🟢 Future |
| Phase 14: Facility Monitoring | Roadmapped | 🟢 Future |
| Phase 15: 3D Visualization | Roadmapped | 🟢 Future |

---

## 📋 Database Models Needed

```prisma
// Phase 8: Visitors
model Visitor {
  id          String   @id @default(uuid())
  name        String
  company     String?
  email       String?
  phone       String?
  photoUrl    String?
  purpose     String
  logs        VisitorLog[]
  createdAt   DateTime @default(now())
}

model VisitorLog {
  id          String   @id @default(uuid())
  visitor     Visitor  @relation(fields: [visitorId], references: [id])
  visitorId   String
  entryTime   DateTime @default(now())
  exitTime    DateTime?
  escortedBy  User?    @relation(fields: [escortId], references: [id])
  escortId    String?
  badgeNumber String?
  zones       String[] // Areas accessed
  signature   String?  // Base64 or URL
  notes       String?
}

// Phase 9: Messaging
model Announcement {
  id          String   @id @default(uuid())
  title       String
  body        String
  priority    String   // INFO, WARNING, CRITICAL
  requiresAck Boolean  @default(false)
  targetRoles String[] // Which roles see this
  expiresAt   DateTime?
  createdBy   User     @relation(fields: [createdById], references: [id])
  createdById String
  createdAt   DateTime @default(now())
  acks        AnnouncementAck[]
}

model AnnouncementAck {
  id            String   @id @default(uuid())
  announcement  Announcement @relation(fields: [announcementId], references: [id])
  announcementId String
  user          User     @relation(fields: [userId], references: [id])
  userId        String
  readAt        DateTime?
  acknowledgedAt DateTime?
}

// Phase 10: Audit
model AuditLog {
  id          String   @id @default(uuid())
  userId      String?
  action      String   // CREATE, UPDATE, DELETE
  entity      String   // Batch, Task, etc.
  entityId    String
  before      Json?
  after       Json?
  ipAddress   String?
  userAgent   String?
  timestamp   DateTime @default(now())
}
```

---

## ✅ Next Steps

1. **Review this roadmap** - Prioritize what to build first
2. **Continue Phase 7** - Finish Layout Designer (Plant Placement & METRC Sync)
3. **Start Phase 8** - Visitor management is often required for compliance
3. **Parallel development** - i18n can be done alongside other features
4. **Compliance audit** - Before building, validate requirements with legal/compliance team
