ca-grow-ops-manager/docs/architecture.md
fullsizemalt da7729d6e4
Some checks failed
Deploy to Production / deploy (push) Failing after 0s
Test / backend-test (push) Failing after 0s
Test / frontend-test (push) Failing after 0s
Initial commit: Spec Kit foundation complete
- Constitution and project spec (spec.yml)
- 7 comprehensive feature specs (tasks, batches, labor, compliance, inventory, integrations, comms)
- Phase 1 implementation plan (6-week roadmap)
- Week 1 task breakdown (15 concrete tasks)
- Architecture and compliance documentation
- Backend and frontend setup guides
- Deployment guide for nexus-vector
- CI/CD workflows (Forgejo Actions)
- Quick start guide for developers

Project is ready for implementation with:
- Automated testing on every push
- Automatic deployment to nexus-vector on push to main
- Database migrations handled automatically
- Health checks and monitoring

Stack: TypeScript, Fastify, React, Vite, PostgreSQL, Prisma, Docker
2025-12-08 23:54:12 -08:00

14 KiB

CA Grow Ops Manager — Architecture

Version: 0.1.0
Last Updated: 2025-12-08


Overview

CA Grow Ops Manager is a web + mobile application designed to reduce cognitive load for teams managing licensed California cannabis cultivation facilities. The platform centralizes grow operations, labor tracking, compliance recordkeeping, scheduling, and team communication.


System Architecture

High-Level Architecture

┌─────────────────────────────────────────────────────────────┐
│                         Clients                              │
├─────────────────────────────────────────────────────────────┤
│  Web App (React + Vite)  │  Mobile App (React Native/PWA)   │
└─────────────────┬───────────────────────────────────────────┘
                  │
                  │ HTTPS / JSON
                  │
┌─────────────────▼───────────────────────────────────────────┐
│                    API Gateway / Load Balancer               │
└─────────────────┬───────────────────────────────────────────┘
                  │
                  │
┌─────────────────▼───────────────────────────────────────────┐
│                  Backend (Node.js + Express/Fastify)         │
├─────────────────────────────────────────────────────────────┤
│  ┌──────────────┐  ┌──────────────┐  ┌──────────────┐      │
│  │ CultivationOps│  │  Compliance  │  │    Labor     │      │
│  └──────────────┘  └──────────────┘  └──────────────┘      │
│  ┌──────────────┐  ┌──────────────┐  ┌──────────────┐      │
│  │  Inventory   │  │ Integrations │  │    Comms     │      │
│  └──────────────┘  └──────────────┘  └──────────────┘      │
│  ┌──────────────┐  ┌──────────────┐                        │
│  │     Auth     │  │  Audit Log   │                        │
│  └──────────────┘  └──────────────┘                        │
└─────────────────┬───────────────────────────────────────────┘
                  │
                  │ Prisma ORM
                  │
┌─────────────────▼───────────────────────────────────────────┐
│                    PostgreSQL Database                       │
└─────────────────────────────────────────────────────────────┘

┌─────────────────────────────────────────────────────────────┐
│                    External Integrations                     │
├─────────────────────────────────────────────────────────────┤
│  METRC API  │  Environmental Monitors  │  Email Service     │
└─────────────────────────────────────────────────────────────┘

Domain Architecture

The backend is organized into feature-first modules with clear domain boundaries:

1. CultivationOps

  • Responsibilities: Tasks, batches, rooms, cultivation workflows
  • Key Entities: Task, TaskTemplate, Batch, Room, WeightLog
  • APIs: /api/tasks, /api/batches, /api/rooms

2. Compliance

  • Responsibilities: Document storage, audit packets, METRC mapping
  • Key Entities: ComplianceDocument, AuditLog, MetrcSync
  • APIs: /api/compliance/documents, /api/compliance/audit-packet

3. Labor

  • Responsibilities: Timeclock, hours tracking, labor cost analysis
  • Key Entities: TimeEntry, Role, WageRate
  • APIs: /api/labor/clock-in, /api/labor/reports

4. Inventory

  • Responsibilities: Materials tracking, lot/serial, restock alerts
  • Key Entities: InventoryItem, InventoryLot, InventoryTransaction
  • APIs: /api/inventory/items, /api/inventory/transactions

5. Integrations

  • Responsibilities: External system connections, environmental monitoring
  • Key Entities: IntegrationConfig, EnvironmentalReading, MetrcSync
  • APIs: /api/integrations/environmental, /api/integrations/metrc

6. Communications

  • Responsibilities: Task comments, announcements, notifications
  • Key Entities: TaskComment, Announcement, Notification
  • APIs: /api/communications/comments, /api/communications/announcements

7. Auth

  • Responsibilities: Authentication, authorization, RBAC
  • Key Entities: User, Role, Permission, Session
  • APIs: /api/auth/login, /api/auth/register

Data Flow

Example: Clock In Workflow

1. User opens mobile app
2. User taps "Clock In" button
3. Frontend sends POST /api/labor/clock-in with { roomId, notes }
4. Backend validates user session (Auth module)
5. Backend creates TimeEntry record (Labor module)
6. Backend returns TimeEntry with timestamp
7. Frontend displays confirmation and current shift duration

Example: Complete Task Workflow

1. User views task in "Today" view
2. User taps "Complete" and adds notes + photo
3. Frontend sends POST /api/tasks/:id/complete with { notes, photo }
4. Backend validates user is assignee (Auth + Tasks modules)
5. Backend updates task status to COMPLETE (Tasks module)
6. Backend creates audit log entry (Audit module)
7. Backend triggers notification to Head Grower (Comms module)
8. Frontend displays success and removes task from "Today" view

Trust Boundaries

Authentication & Authorization

  • Authentication: JWT-based with refresh tokens
  • Authorization: Role-Based Access Control (RBAC)
  • Roles:
    • Owner: Full access to all features
    • Compliance Manager: Full access to compliance, read-only for operations
    • Head Grower: Full access to cultivation ops, read-only for compliance
    • Staff: Limited access to tasks, timeclock, and assigned batches
    • Accountant: Read-only access to labor and compliance reports

Data Access Patterns

Role CultivationOps Compliance Labor Inventory Integrations Comms
Owner Full Full Full Full Full Full
Compliance Manager Read Full Read Read Read Full
Head Grower Full Read Read Full Read Full
Staff Limited None Limited Read Read Limited
Accountant Read Read Read Read None Read

External Integrations

  • METRC: Read-only in v1; write operations (Phase 2) require explicit user confirmation
  • Environmental Monitoring: Read-only; no write operations
  • Email Service: Outbound only (notifications, digests)

Security Architecture

Authentication Flow

1. User submits credentials (email + password)
2. Backend validates credentials against hashed password
3. Backend generates JWT access token (15 min expiry) and refresh token (7 day expiry)
4. Frontend stores tokens in httpOnly cookies (access) and localStorage (refresh)
5. Frontend includes access token in Authorization header for all API requests
6. Backend validates token on each request
7. On access token expiry, frontend uses refresh token to get new access token

Data Encryption

  • At Rest: Database encryption enabled (PostgreSQL TDE)
  • In Transit: HTTPS/TLS 1.3 for all API communication
  • Sensitive Fields: API keys, passwords hashed with bcrypt (cost factor 12)

Audit Logging

All critical operations are logged:

  • User authentication (login, logout, failed attempts)
  • Batch lifecycle transitions
  • Weight logging
  • Compliance document uploads/deletions
  • Time entry edits
  • METRC sync operations

Audit logs are immutable and include:

  • User ID
  • Timestamp
  • Action (create, update, delete)
  • Entity type and ID
  • Metadata (before/after state for updates)

Scalability Considerations

Database

  • Connection Pooling: Prisma connection pool (max 10 connections initially)
  • Indexing: Indexes on frequently queried fields (userId, batchId, roomId, date ranges)
  • Partitioning: Time-series data (environmental readings, audit logs) partitioned by month

Caching

  • Application-Level: Redis for session storage and frequently accessed data
  • CDN: Static assets (images, CSS, JS) served via CDN
  • API Response Caching: Cache GET requests for 5 minutes where appropriate

Horizontal Scaling

  • Stateless Backend: All session state in Redis; backend can scale horizontally
  • Load Balancer: Nginx or cloud load balancer for traffic distribution
  • Database Replication: Read replicas for reporting queries

Deployment Architecture

Environments

  • Local: Docker Compose for development
  • Staging: Cloud-hosted (AWS, GCP, or Azure) with production-like config
  • Production: Cloud-hosted with auto-scaling, monitoring, and backups

Infrastructure

┌─────────────────────────────────────────────────────────────┐
│                         CDN (CloudFlare)                     │
└─────────────────┬───────────────────────────────────────────┘
                  │
┌─────────────────▼───────────────────────────────────────────┐
│                    Load Balancer (Nginx)                     │
└─────────────────┬───────────────────────────────────────────┘
                  │
        ┌─────────┴─────────┐
        │                   │
┌───────▼────────┐  ┌───────▼────────┐
│  Backend (1)   │  │  Backend (2)   │  (Auto-scaling)
└───────┬────────┘  └───────┬────────┘
        │                   │
        └─────────┬─────────┘
                  │
        ┌─────────┴─────────┐
        │                   │
┌───────▼────────┐  ┌───────▼────────┐
│  PostgreSQL    │  │     Redis      │
│  (Primary)     │  │   (Sessions)   │
└────────────────┘  └────────────────┘

Technology Choices

Backend

  • TypeScript: Type safety, better tooling, easier refactoring
  • Node.js: JavaScript ecosystem, async I/O, large community
  • Express/Fastify: Lightweight, flexible, well-documented
  • Prisma: Type-safe ORM, migrations, great DX
  • PostgreSQL: ACID compliance, JSON support, mature ecosystem

Frontend

  • TypeScript: Type safety across frontend and backend
  • React: Component-based, large ecosystem, mobile support (React Native)
  • Vite/Next.js: Fast builds, SSR support (Next.js), great DX
  • Radix UI/shadcn: Accessible primitives, customizable, modern design

Infrastructure

  • Docker: Consistent environments, easy deployment
  • Nginx: Reverse proxy, load balancing, static file serving
  • Redis: Session storage, caching
  • S3-compatible storage: Document and photo storage

Future Enhancements

  • Multi-Tenancy: Support multiple facilities per account
  • Real-Time Updates: WebSockets for live task updates and environmental data
  • Advanced Analytics: Predictive yield modeling, labor optimization
  • Mobile App: Native React Native app for iOS/Android
  • Offline Support: Service workers for offline task completion

References