# Feature Spec: Inventory and Materials

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

---

## Overview

The Inventory and Materials module tracks cultivation supplies (nutrients, pots, IPM products, PPE, CO₂ tanks, filters, soil/media, packaging) with quantity tracking, min/max thresholds, restock prompts, and optional lot/serial linkage to batches for recall support.

---

## User Stories

### As a Head Grower

- I want to track current inventory levels so I know what's in stock
- I want to set min/max thresholds so I'm alerted when supplies are low
- I want to link material lots to batches so I can trace issues back to specific inputs
- I want to see material usage trends so I can optimize ordering

### As a Staff Member

- I want to quickly check if we have enough nutrients for today's feed so I don't run out mid-task
- I want to log material usage so inventory stays accurate

### As an Owner

- I want to see material costs per batch so I can calculate profitability
- I want to track supplier performance (quality, delivery time)

### As a Compliance Manager

- I want to link material lots to batches so I can support recall investigations

---

## Requirements

### Functional Requirements

#### Item Catalog

- **Item types**:
  - Nutrients (base, additives, supplements)
  - Growing media (soil, coco, rockwool)
  - Pots and containers
  - IPM products (pesticides, beneficial insects)
  - PPE (gloves, masks, suits)
  - CO₂ tanks and regulators
  - Filters (carbon, HEPA)
  - Packaging (jars, bags, labels)
  - Tools and equipment
- **Item properties**:
  - Name and SKU
  - Category
  - Unit (gallon, pound, each, etc.)
  - Current quantity
  - Min/max thresholds
  - Location (room, shelf)
  - Supplier
  - Lot/serial number (optional)
  - Expiration date (optional)
  - Cost per unit
  - Notes

#### Inventory Tracking

- **Add stock**: Log new deliveries with quantity, lot, and cost
- **Use stock**: Log material usage with quantity, batch, and user
- **Adjust stock**: Manual adjustments with reason and approval
- **Transfer stock**: Move items between locations
- **Automatic updates**: Deduct stock when linked to task completion (future)

#### Restock Alerts

- **Min threshold alerts**: Notify when quantity falls below minimum
- **Expiration alerts**: Notify when items approach expiration
- **Restock suggestions**: Based on usage trends

#### Lot/Serial Tracking

- **Link lots to batches**: Associate material lots with batches for traceability
- **Recall support**: Query which batches used a specific lot
- **Supplier traceability**: Track materials back to supplier and purchase order

#### Reporting

- **Current inventory**: List of all items with quantities
- **Low stock report**: Items below min threshold
- **Usage report**: Material usage by item, batch, period
- **Cost report**: Material costs per batch
- **Expiration report**: Items expiring soon

### Non-Functional Requirements

- **Performance**: Inventory list loads in < 500ms
- **Data integrity**: Stock adjustments require reason and approval
- **Accessibility**: WCAG 2.1 AA compliant
- **Mobile-first**: Stock usage logging optimized for tablet

---

## Out of Scope (v1)

- Automated reordering (integration with suppliers)
- Barcode/QR code scanning
- Multi-location inventory (single facility only in v1)
- Integration with accounting systems for purchase orders

---

## Acceptance Criteria

### Item Catalog

- [ ] Items can be created with all required properties
- [ ] Items can be categorized by type
- [ ] Items can be searched and filtered
- [ ] Min/max thresholds can be set per item

### Inventory Tracking

- [ ] Stock can be added with lot and cost
- [ ] Stock can be used with batch linkage
- [ ] Stock adjustments require reason and approval
- [ ] Stock transfers are logged with user and timestamp

### Restock Alerts

- [ ] Alerts are generated when quantity falls below min threshold
- [ ] Alerts are generated for items expiring within 30 days
- [ ] Alerts can be dismissed or actioned

### Lot/Serial Tracking

- [ ] Lots can be linked to batches
- [ ] Recall query returns all batches using a specific lot
- [ ] Lot history is immutable

### Reporting

- [ ] Current inventory report displays all items with quantities
- [ ] Low stock report displays items below min threshold
- [ ] Usage report displays material usage by batch
- [ ] Cost report displays material costs per batch

---

## Technical Notes

### Data Model (Prisma Schema)

```prisma
model InventoryItem {
  id          String   @id @default(cuid())
  name        String
  sku         String?  @unique
  category    ItemCategory
  unit        String   // gallon, pound, each, etc.
  quantity    Float
  minThreshold Float?
  maxThreshold Float?
  location    String?
  supplierId  String?
  supplier    Supplier? @relation(fields: [supplierId], references: [id])
  costPerUnit Float?
  notes       String?
  lots        InventoryLot[]
  transactions InventoryTransaction[]
  createdAt   DateTime @default(now())
  updatedAt   DateTime @updatedAt
}

model InventoryLot {
  id          String   @id @default(cuid())
  itemId      String
  item        InventoryItem @relation(fields: [itemId], references: [id])
  lotNumber   String
  serialNumber String?
  quantity    Float
  expirationDate DateTime?
  receivedDate DateTime
  supplierId  String?
  supplier    Supplier? @relation(fields: [supplierId], references: [id])
  batchLinks  BatchMaterialLink[]
  createdAt   DateTime @default(now())
  updatedAt   DateTime @updatedAt
}

model InventoryTransaction {
  id          String   @id @default(cuid())
  itemId      String
  item        InventoryItem @relation(fields: [itemId], references: [id])
  type        TransactionType
  quantity    Float
  lotId       String?
  lot         InventoryLot? @relation(fields: [lotId], references: [id])
  batchId     String?
  batch       Batch?   @relation(fields: [batchId], references: [id])
  userId      String
  user        User     @relation(fields: [userId], references: [id])
  reason      String?
  approvedBy  String?
  approvedAt  DateTime?
  createdAt   DateTime @default(now())
}

model BatchMaterialLink {
  id          String   @id @default(cuid())
  batchId     String
  batch       Batch    @relation(fields: [batchId], references: [id])
  lotId       String
  lot         InventoryLot @relation(fields: [lotId], references: [id])
  quantityUsed Float
  usedAt      DateTime @default(now())
  userId      String
  user        User     @relation(fields: [userId], references: [id])
}

model Supplier {
  id          String   @id @default(cuid())
  name        String
  contact     String?
  email       String?
  phone       String?
  address     String?
  notes       String?
  items       InventoryItem[]
  lots        InventoryLot[]
  createdAt   DateTime @default(now())
  updatedAt   DateTime @updatedAt
}

enum ItemCategory {
  NUTRIENT
  MEDIA
  POT
  IPM
  PPE
  CO2
  FILTER
  PACKAGING
  TOOL
  OTHER
}

enum TransactionType {
  ADD
  USE
  ADJUST
  TRANSFER
}
```

### API Endpoints

- `GET /api/inventory/items` - List items with filters
- `GET /api/inventory/items/:id` - Get item detail
- `POST /api/inventory/items` - Create item
- `PATCH /api/inventory/items/:id` - Update item
- `DELETE /api/inventory/items/:id` - Delete item
- `POST /api/inventory/transactions` - Log transaction (add, use, adjust)
- `GET /api/inventory/transactions` - List transactions
- `GET /api/inventory/lots` - List lots
- `POST /api/inventory/lots` - Create lot
- `GET /api/inventory/lots/:id/batches` - Get batches using a lot (recall query)
- `GET /api/inventory/alerts` - Get restock and expiration alerts
- `GET /api/inventory/reports/current` - Current inventory report
- `GET /api/inventory/reports/low-stock` - Low stock report
- `GET /api/inventory/reports/usage` - Usage report
- `GET /api/inventory/reports/cost` - Cost report
- `GET /api/inventory/suppliers` - List suppliers
- `POST /api/inventory/suppliers` - Create supplier

### UI Components

- `InventoryList` - Filterable list of items
- `InventoryCard` - Item summary card with quantity gauge
- `InventoryDetail` - Full item view with transaction history
- `InventoryForm` - Item creation/editing
- `TransactionForm` - Add/use/adjust stock form
- `LotTracker` - Lot/serial tracking interface
- `RecallQuery` - Recall investigation tool
- `RestockAlerts` - Alert dashboard
- `InventoryReports` - Reporting interface

---

## Dependencies

- **Batches and Rooms** module (for batch linkage)
- **Tasks** module (for automatic stock deduction on task completion)
- **Authentication** (for user attribution and RBAC)

---

## Risks & Mitigations

| Risk | Impact | Mitigation |
|------|--------|------------|
| Inventory drift (physical vs. system) | High | Regular physical counts; adjustment approval workflow |
| Lot tracking errors | Medium | Clear UI; validation; immutable lot history |
| Restock alert fatigue | Medium | Configurable thresholds; smart batching of alerts |

---

## Future Enhancements (Post-v1)

- Barcode/QR code scanning for quick stock updates
- Automated reordering based on usage trends
- Integration with supplier systems for purchase orders
- Multi-location inventory (multiple facilities)
- Predictive restock suggestions based on batch schedules
- Integration with accounting systems (QuickBooks, Xero)
