# Feature Spec: Batches and Rooms

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

---

## Overview

The Batches and Rooms module manages the lifecycle of cannabis batches from clone to finished product, and tracks the physical rooms where cultivation occurs. It provides internal batch IDs with METRC tag mapping, room lifecycle management, weight logging with automatic yield calculations, and rich batch history with photos and notes.

---

## User Stories

### As a Head Grower

- I want to create batches and track them through each growth stage so I can monitor progress
- I want to map internal batch IDs to METRC tags so I can maintain compliance without duplicating data entry
- I want to log weights at each stage (wet, bucked, final, trim, waste) so I can calculate yields and moisture loss
- I want to attach photos and notes to batches so I can document issues and successes
- I want to see batch history and task completion so I can review what worked

### As a Staff Member

- I want to see which batches are in which rooms so I know where to focus my work
- I want to log harvest weights quickly on a tablet so I don't slow down the workflow
- I want to add photos of issues (pests, deficiencies) so the Head Grower can review

### As a Compliance Manager

- I want to see METRC tag mappings for each batch so I can cross-reference with the state system
- I want to export batch data with weights and dates for audit purposes

### As an Owner

- I want to see yield reports per batch so I can identify top-performing genetics and methods
- I want to see labor costs per batch so I can calculate profitability

---

## Requirements

### Functional Requirements

#### Batch Management

- **Create batches** with:
  - Internal batch ID (auto-generated or custom)
  - Strain/genetics
  - Source (clone, seed)
  - Start date
  - Initial plant count
  - METRC tag(s) (stored, not synced in v1)
- **Batch lifecycle stages**:
  - Clone In
  - Vegetative
  - Flowering
  - Harvest
  - Drying
  - Curing
  - Finished
- **Batch transitions**:
  - Move batch between stages
  - Move batch between rooms
  - Split batch (e.g., cull underperformers)
  - Merge batches (if allowed by compliance)

#### Room Management

- **Room types**: Veg, Flower, Dry, Facility
- **Room properties**:
  - Name/number
  - Type
  - Capacity (plant count or sq ft)
  - Current batches
  - Environmental setpoints (target temp, humidity, VPD)
- **Room lifecycle**:
  - Active (in use)
  - Cleaning (between batches)
  - Maintenance (offline)

#### Weight Logging

- **Weight types**:
  - Wet weight (at harvest)
  - Bucked weight (after initial trim)
  - Final dry weight
  - Trim weight
  - Waste weight
- **Automatic calculations**:
  - Moisture loss % (wet → dry)
  - Yield per plant
  - Trim ratio
  - Total yield per batch
- **Weight entry**:
  - Quick entry form (mobile-optimized)
  - Bulk entry (CSV upload)
  - Photo attachment for verification

#### Batch History & Documentation

- **Attach to batches**:
  - Photos (timestamped)
  - Notes (markdown-supported)
  - Task completion history
  - Weight logs
  - Room transitions
- **Timeline view** of all batch events
- **Export** batch report (PDF or CSV)

### Non-Functional Requirements

- **Performance**: Batch list loads in < 500ms
- **Data integrity**: Weight logs are immutable once saved
- **Accessibility**: WCAG 2.1 AA compliant
- **Mobile-first**: Weight logging optimized for tablet use

---

## Out of Scope (v1)

- Direct METRC sync (read/write)
- Automated batch transitions based on environmental data
- Predictive yield modeling
- Genetic lineage tracking (family trees)

---

## Acceptance Criteria

### Batch Lifecycle

- [ ] Head Grower can create a new batch with all required fields
- [ ] Batches can be transitioned through lifecycle stages
- [ ] Batch transitions are logged with timestamp and user
- [ ] Batches can be moved between rooms
- [ ] Batch history displays all events in chronological order

### METRC Mapping

- [ ] METRC tags can be associated with batches
- [ ] Multiple METRC tags can be linked to a single internal batch
- [ ] METRC tags are stored but not synced in v1

### Weight Logging

- [ ] Staff can log weights for each weight type
- [ ] Weight logs are timestamped and attributed to user
- [ ] Automatic calculations (moisture loss, yield) are displayed
- [ ] Photos can be attached to weight logs
- [ ] Weight logs are immutable after save

### Room Management

- [ ] Rooms can be created with type and capacity
- [ ] Current batches in each room are displayed
- [ ] Room status (active, cleaning, maintenance) can be updated
- [ ] Room capacity warnings when exceeded

### Batch Documentation

- [ ] Photos can be attached to batches with timestamps
- [ ] Notes can be added to batches (markdown-supported)
- [ ] Batch timeline displays all events
- [ ] Batch report can be exported (PDF or CSV)

---

## Technical Notes

### Data Model (Prisma Schema)

```prisma
model Batch {
  id          String   @id @default(cuid())
  batchNumber String   @unique
  strain      String
  source      BatchSource
  stage       BatchStage @default(CLONE_IN)
  plantCount  Int
  startDate   DateTime
  harvestDate DateTime?
  finishDate  DateTime?
  roomId      String?
  room        Room?    @relation(fields: [roomId], references: [id])
  metrcTags   String[] // array of METRC tag IDs
  notes       BatchNote[]
  photos      BatchPhoto[]
  weights     WeightLog[]
  tasks       Task[]
  createdAt   DateTime @default(now())
  updatedAt   DateTime @updatedAt
}

model Room {
  id          String   @id @default(cuid())
  name        String
  type        RoomType
  capacity    Int?     // plant count or sq ft
  status      RoomStatus @default(ACTIVE)
  targetTemp  Float?
  targetHumidity Float?
  targetVPD   Float?
  batches     Batch[]
  tasks       Task[]
  createdAt   DateTime @default(now())
  updatedAt   DateTime @updatedAt
}

model WeightLog {
  id          String   @id @default(cuid())
  batchId     String
  batch       Batch    @relation(fields: [batchId], references: [id])
  weightType  WeightType
  weight      Float    // grams
  unit        String   @default("g")
  notes       String?
  photos      String[] // URLs
  loggedBy    String
  user        User     @relation(fields: [loggedBy], references: [id])
  createdAt   DateTime @default(now())
}

model BatchNote {
  id        String   @id @default(cuid())
  batchId   String
  batch     Batch    @relation(fields: [batchId], references: [id])
  content   String   // markdown
  authorId  String
  author    User     @relation(fields: [authorId], references: [id])
  createdAt DateTime @default(now())
}

model BatchPhoto {
  id        String   @id @default(cuid())
  batchId   String
  batch     Batch    @relation(fields: [batchId], references: [id])
  url       String
  caption   String?
  uploadedBy String
  user      User     @relation(fields: [uploadedBy], references: [id])
  createdAt DateTime @default(now())
}

enum BatchSource {
  CLONE
  SEED
}

enum BatchStage {
  CLONE_IN
  VEGETATIVE
  FLOWERING
  HARVEST
  DRYING
  CURING
  FINISHED
}

enum RoomType {
  VEG
  FLOWER
  DRY
  FACILITY
}

enum RoomStatus {
  ACTIVE
  CLEANING
  MAINTENANCE
}

enum WeightType {
  WET
  BUCKED
  FINAL_DRY
  TRIM
  WASTE
}
```

### API Endpoints

- `GET /api/batches` - List batches with filters
- `GET /api/batches/:id` - Get batch detail
- `POST /api/batches` - Create batch
- `PATCH /api/batches/:id` - Update batch
- `POST /api/batches/:id/transition` - Transition batch stage
- `POST /api/batches/:id/weights` - Log weight
- `POST /api/batches/:id/notes` - Add note
- `POST /api/batches/:id/photos` - Upload photo
- `GET /api/batches/:id/timeline` - Get batch timeline
- `GET /api/batches/:id/export` - Export batch report
- `GET /api/rooms` - List rooms
- `POST /api/rooms` - Create room
- `PATCH /api/rooms/:id` - Update room

### UI Components

- `BatchList` - Filterable batch list
- `BatchCard` - Batch summary card
- `BatchDetail` - Full batch view with timeline
- `BatchForm` - Batch creation/editing
- `WeightLogForm` - Quick weight entry (mobile-optimized)
- `RoomBoard` - Kanban-style room view with batches
- `RoomDetail` - Room view with current batches and environmental data
- `BatchTimeline` - Chronological event history

---

## Dependencies

- **Tasks** module (for task history)
- **Labor** module (for cost per batch)
- **Integrations** module (for environmental data)
- **Authentication** (for user attribution)

---

## Risks & Mitigations

| Risk | Impact | Mitigation |
|------|--------|------------|
| METRC tag mapping errors | High | Clear UI for tag entry; validation; read-only in v1 |
| Weight logging errors (typos) | Medium | Confirmation step; edit window; audit trail |
| Photo storage costs | Medium | Image compression; configurable retention policy |

---

## Future Enhancements (Post-v1)

- METRC sync (read/write)
- Automated batch transitions based on environmental triggers
- Predictive yield modeling based on historical data
- Genetic lineage tracking
- QR code batch labels for quick lookup
