# Feature Spec: Integrations and Hardware

**Domain**: Integrations  
**Status**: Draft  
**Version**: 0.1.0  
**Last Updated**: 2025-12-08

---

## Overview

The Integrations and Hardware module connects CA Grow Ops Manager to external systems and environmental monitoring hardware. Phase 1 (v1) focuses on read-only environmental dashboards and manual status widgets. Phase 2 (future) adds METRC connector and advanced hardware integrations.

---

## User Stories

### As a Head Grower

- I want to see real-time environmental data (temp, humidity, VPD) for each room so I can identify issues quickly
- I want to see lighting schedule status so I know if lights are on/off as expected
- I want to receive alerts when environmental conditions go out of range

### As a Staff Member

- I want to see current room conditions on my tablet so I can verify everything is normal

### As a Compliance Manager

- I want to export environmental data for audit purposes
- I want to sync METRC data (future) so internal records align with the state system

### As an Owner

- I want to integrate with METRC (future) so we reduce duplicate data entry
- I want to see environmental trends over time so I can optimize growing conditions

---

## Requirements

### Functional Requirements (Phase 1 - v1)

#### Environmental Dashboards

- **Data sources**:
  - CSV uploads (manual)
  - API polling (if available from monitoring systems)
  - Manual entry (fallback)
- **Metrics per room**:
  - Temperature (°F or °C)
  - Humidity (%)
  - VPD (kPa)
  - CO₂ (ppm) (optional)
- **Display**:
  - Current values
  - Target ranges (from room settings)
  - Status indicators (in range, warning, critical)
  - Historical charts (24h, 7d, 30d)
- **Alerts**:
  - Out-of-range notifications
  - Sensor offline alerts

#### Lighting Schedule Widgets

- **Data sources**:
  - Manual entry (on/off times, photoperiod)
  - API polling (if available from controllers like Trollmaster, Growers Choice)
- **Display**:
  - Current status (on/off)
  - Schedule (on/off times)
  - Photoperiod (18/6, 12/12, etc.)
  - Next state change countdown

### Functional Requirements (Phase 2 - Future)

#### METRC Connector

- **Configuration**:
  - API key management
  - Rate limiting settings
  - Explicit user confirmation before writes
- **Read operations**:
  - Sync METRC plant/batch tags
  - Sync inventory data
  - Sync transfer data
- **Write operations** (with user confirmation):
  - Create plant tags
  - Update plant stages
  - Log harvests
  - Create packages
- **Error handling**:
  - Retry logic with exponential backoff
  - Clear error messages
  - Rollback on failure

#### Advanced Hardware Integrations

- **Adapter framework**:
  - Plugin architecture for new hardware
  - Standardized data models
  - Polling intervals and caching
- **Supported systems** (examples):
  - Trollmaster environmental controllers
  - Growers Choice lighting systems
  - Pulse environmental monitors
  - Aroya crop steering systems
- **Graceful degradation**:
  - Manual fallback for all automated inputs
  - Clear offline/error states

### Non-Functional Requirements

- **Performance**: Environmental data updates every 5-15 minutes
- **Reliability**: Graceful degradation when integrations are unavailable
- **Security**: API keys encrypted at rest; least privilege access
- **Auditability**: All METRC writes logged with user confirmation

---

## Out of Scope (v1)

- METRC write integration (read-only mapping only)
- Automated environmental control (read-only dashboards only)
- Predictive analytics based on environmental data
- Integration with irrigation systems

---

## Acceptance Criteria (Phase 1 - v1)

### Environmental Dashboards

- [ ] Environmental data can be uploaded via CSV
- [ ] Environmental data can be polled from API (if available)
- [ ] Current temp, humidity, VPD displayed per room
- [ ] Status indicators show in-range, warning, critical
- [ ] Historical charts display 24h, 7d, 30d data
- [ ] Alerts generated when conditions go out of range

### Lighting Schedule Widgets

- [ ] Lighting schedules can be entered manually
- [ ] Current on/off status displayed
- [ ] Next state change countdown displayed
- [ ] Photoperiod displayed (18/6, 12/12, etc.)

### Integration Framework

- [ ] Adapter pattern supports multiple data sources
- [ ] Manual fallback available for all automated inputs
- [ ] Clear error handling and offline states

---

## Acceptance Criteria (Phase 2 - Future)

### METRC Connector

- [ ] API keys can be configured and encrypted
- [ ] METRC tags can be synced (read-only)
- [ ] User confirmation required before any write operation
- [ ] All METRC writes logged with user and timestamp
- [ ] Error handling with retry logic and clear messages

### Advanced Hardware

- [ ] Plugin architecture supports new hardware adapters
- [ ] Polling intervals configurable per adapter
- [ ] Data cached to reduce API calls
- [ ] Graceful degradation when hardware is offline

---

## Technical Notes

### Data Model (Prisma Schema)

```prisma
model EnvironmentalReading {
  id          String   @id @default(cuid())
  roomId      String
  room        Room     @relation(fields: [roomId], references: [id])
  temperature Float?   // °F or °C
  humidity    Float?   // %
  vpd         Float?   // kPa
  co2         Float?   // ppm
  timestamp   DateTime
  source      String   // "manual", "csv", "api:pulse", etc.
  createdAt   DateTime @default(now())
}

model IntegrationConfig {
  id          String   @id @default(cuid())
  type        IntegrationType
  name        String
  apiKey      String?  // encrypted
  apiUrl      String?
  pollingInterval Int? // minutes
  enabled     Boolean  @default(true)
  settings    Json?    // integration-specific settings
  createdAt   DateTime @default(now())
  updatedAt   DateTime @updatedAt
}

model MetrcSync {
  id          String   @id @default(cuid())
  batchId     String?
  batch       Batch?   @relation(fields: [batchId], references: [id])
  metrcTag    String
  operation   String   // "read", "write"
  action      String   // "sync_tags", "create_plant", "log_harvest", etc.
  status      SyncStatus
  requestData Json?
  responseData Json?
  error       String?
  userId      String?
  user        User?    @relation(fields: [userId], references: [id])
  confirmedAt DateTime?
  createdAt   DateTime @default(now())
}

enum IntegrationType {
  METRC
  ENVIRONMENTAL
  LIGHTING
  IRRIGATION
  OTHER
}

enum SyncStatus {
  PENDING
  CONFIRMED
  SUCCESS
  FAILED
}
```

### API Endpoints (Phase 1)

- `GET /api/integrations/environmental/:roomId` - Get environmental data for room
- `POST /api/integrations/environmental/upload` - Upload CSV environmental data
- `GET /api/integrations/environmental/:roomId/chart` - Get historical chart data
- `GET /api/integrations/lighting/:roomId` - Get lighting schedule for room
- `POST /api/integrations/lighting/:roomId` - Update lighting schedule
- `GET /api/integrations/config` - List integration configs
- `POST /api/integrations/config` - Create integration config
- `PATCH /api/integrations/config/:id` - Update integration config

### API Endpoints (Phase 2)

- `POST /api/integrations/metrc/sync-tags` - Sync METRC tags (read-only)
- `POST /api/integrations/metrc/create-plant` - Create plant in METRC (with confirmation)
- `POST /api/integrations/metrc/log-harvest` - Log harvest in METRC (with confirmation)
- `GET /api/integrations/metrc/sync-history` - Get METRC sync history

### UI Components

- `EnvironmentalDashboard` - Room environmental data display
- `EnvironmentalChart` - Historical chart (24h, 7d, 30d)
- `LightingWidget` - Lighting schedule and status
- `IntegrationConfig` - Integration setup and management
- `MetrcConnector` - METRC sync interface (Phase 2)
- `MetrcConfirmation` - User confirmation dialog for METRC writes (Phase 2)

---

## Dependencies

- **Batches and Rooms** module (for room context)
- **Authentication** (for RBAC and audit trail)

---

## Risks & Mitigations

| Risk | Impact | Mitigation |
|------|--------|------------|
| METRC API downtime | High | Graceful degradation; manual fallback; clear error messages |
| METRC write errors (data loss) | Critical | User confirmation; rollback on failure; audit trail |
| Hardware API changes | Medium | Adapter pattern; versioning; clear deprecation notices |
| API rate limits | Medium | Caching; configurable polling intervals; exponential backoff |

---

## Integration Strategy

### Adapter Pattern

Each integration implements a standard adapter interface:

```typescript
interface IntegrationAdapter {
  name: string;
  type: IntegrationType;
  connect(config: IntegrationConfig): Promise<void>;
  disconnect(): Promise<void>;
  poll(): Promise<any>;
  write?(data: any): Promise<any>;
  healthCheck(): Promise<boolean>;
}
```

### Polling and Caching

- **Polling intervals**: Configurable per integration (default: 5-15 minutes)
- **Caching**: Cache data for 5 minutes to reduce API calls
- **Error handling**: Exponential backoff on failures; max 3 retries

### User Confirmation for Writes

- **METRC writes**: Require explicit user confirmation with preview of changes
- **Audit trail**: Log all write operations with user, timestamp, and result
- **Rollback**: Attempt rollback on failure; flag for manual review if rollback fails

---

## Compliance Notes (METRC)

- **METRC is the system of record** for California cannabis track-and-trace
- **Read-only in v1**: Internal batch IDs map to METRC tags but no writes
- **Phase 2 writes**: Require explicit user confirmation and robust error handling
- **Audit trail**: All METRC operations logged for compliance

---

## Future Enhancements (Post-v1)

- METRC connector with read/write (Phase 2)
- Advanced hardware integrations (Trollmaster, Aroya, etc.)
- Automated environmental control (set points, alerts)
- Predictive analytics based on environmental data
- Integration with irrigation systems
- Mobile app for environmental monitoring
