# Implementation Plan: Phase 1 — Foundation

**Version**: 0.1.0  
**Status**: Planning  
**Created**: 2025-12-08  
**Target Completion**: TBD

---

## Overview

Phase 1 establishes the foundational infrastructure and core features for CA Grow Ops Manager. This phase focuses on:

1. Project setup and infrastructure
2. Authentication and RBAC
3. Core data models (Users, Roles, Batches, Rooms, Tasks)
4. Basic CRUD operations for each domain
5. Minimal viable UI for each feature

**Success Criteria**: A working application where users can authenticate, create batches/rooms, schedule tasks, clock in/out, and upload compliance documents.

---

## Architecture Decisions

### Backend Framework: **Fastify**

**Rationale**:

- 2-3x faster than Express
- Built-in TypeScript support
- Better schema validation (JSON Schema)
- Modern async/await patterns
- Still lightweight and flexible

### Frontend Framework: **Vite + React**

**Rationale**:

- Faster dev server and builds than Next.js
- Simpler for v1 (no SSR needed yet)
- Better HMR experience
- Easier to migrate to Next.js later if needed

### Component Library: **shadcn/ui (Radix + Tailwind)**

**Rationale**:

- Copy-paste components (no npm bloat)
- Built on Radix (accessible primitives)
- Tailwind for styling (mobile-first)
- Highly customizable

### Database: **PostgreSQL 15 + Prisma**

**Rationale**:

- ACID compliance for compliance data
- JSON support for flexible metadata
- Prisma provides type-safe queries
- Easy migrations

---

## Implementation Phases

### Phase 1A: Infrastructure Setup (Week 1)

**Goal**: Set up development environment and CI/CD

#### Tasks

1. **Backend Setup**
   - [ ] Initialize Node.js project with TypeScript
   - [ ] Configure Fastify with TypeScript
   - [ ] Set up Prisma with PostgreSQL
   - [ ] Configure ESLint + Prettier
   - [ ] Set up Jest for testing
   - [ ] Create Docker Compose for local dev
   - [ ] Configure environment variables

2. **Frontend Setup**
   - [ ] Initialize Vite + React + TypeScript
   - [ ] Install and configure Tailwind CSS
   - [ ] Set up shadcn/ui components
   - [ ] Configure React Router
   - [ ] Set up Vitest + React Testing Library
   - [ ] Configure ESLint + Prettier

3. **Infrastructure**
   - [ ] Create Git repository
   - [ ] Set up .gitignore files
   - [ ] Create README files
   - [ ] Set up Docker Compose (backend, frontend, db, redis)
   - [ ] Configure VS Code workspace settings

**Deliverables**:

- Working dev environment with hot reload
- Docker Compose setup for local development
- Basic project structure for backend and frontend

---

### Phase 1B: Authentication & RBAC (Week 2)

**Goal**: Implement secure authentication and role-based access control

#### Tasks

1. **Database Schema**
   - [ ] Create User model (Prisma schema)
   - [ ] Create Role model
   - [ ] Create Session model (optional, if not using Redis)
   - [ ] Run migrations

2. **Backend Auth**
   - [ ] Implement password hashing (bcrypt)
   - [ ] Implement JWT generation (access + refresh tokens)
   - [ ] Create auth routes (`/api/auth/register`, `/api/auth/login`, `/api/auth/refresh`, `/api/auth/logout`)
   - [ ] Create auth middleware (verify JWT)
   - [ ] Create RBAC middleware (check roles/permissions)
   - [ ] Write unit tests for auth service
   - [ ] Write integration tests for auth endpoints

3. **Frontend Auth**
   - [ ] Create AuthContext and useAuth hook
   - [ ] Create Login page
   - [ ] Create Register page (admin-only for v1)
   - [ ] Implement token storage (httpOnly cookies + localStorage)
   - [ ] Implement token refresh logic
   - [ ] Create ProtectedRoute component
   - [ ] Create role-based UI rendering

4. **Seed Data**
   - [ ] Create seed script for default roles (Owner, Compliance Manager, Head Grower, Staff, Accountant)
   - [ ] Create seed script for test users

**Deliverables**:

- Working login/logout flow
- JWT-based authentication
- RBAC middleware protecting routes
- Seed data for testing

**API Endpoints**:

- `POST /api/auth/register` - Register new user (admin-only)
- `POST /api/auth/login` - Login with email/password
- `POST /api/auth/refresh` - Refresh access token
- `POST /api/auth/logout` - Logout and invalidate tokens
- `GET /api/auth/me` - Get current user

---

### Phase 1C: Core Data Models (Week 3)

**Goal**: Implement core domain models and CRUD operations

#### Tasks

1. **Batches & Rooms Module**
   - [ ] Create Prisma schemas (Batch, Room, BatchNote, BatchPhoto, WeightLog)
   - [ ] Run migrations
   - [ ] Implement batch service (CRUD operations)
   - [ ] Implement room service (CRUD operations)
   - [ ] Create batch routes (`/api/batches`)
   - [ ] Create room routes (`/api/rooms`)
   - [ ] Write unit tests
   - [ ] Write integration tests

2. **Tasks Module**
   - [ ] Create Prisma schemas (Task, TaskTemplate)
   - [ ] Run migrations
   - [ ] Implement task service (CRUD operations)
   - [ ] Implement task template service
   - [ ] Create task routes (`/api/tasks`, `/api/tasks/templates`)
   - [ ] Write unit tests
   - [ ] Write integration tests

3. **Labor Module**
   - [ ] Create Prisma schemas (TimeEntry, WageRate)
   - [ ] Run migrations
   - [ ] Implement timeclock service (clock in/out logic)
   - [ ] Create labor routes (`/api/labor/clock-in`, `/api/labor/clock-out`, `/api/labor/time-entries`)
   - [ ] Write unit tests
   - [ ] Write integration tests

4. **Compliance Module**
   - [ ] Create Prisma schema (ComplianceDocument, AuditLog)
   - [ ] Run migrations
   - [ ] Implement document storage (local filesystem or S3-compatible)
   - [ ] Implement document service (upload, download, delete)
   - [ ] Create compliance routes (`/api/compliance/documents`)
   - [ ] Write unit tests
   - [ ] Write integration tests

**Deliverables**:

- Working CRUD APIs for all core entities
- Database migrations applied
- Unit and integration tests passing
- Postman/Insomnia collection for testing

**API Endpoints Summary**:

- Batches: `GET/POST/PATCH/DELETE /api/batches`, `POST /api/batches/:id/weights`
- Rooms: `GET/POST/PATCH/DELETE /api/rooms`
- Tasks: `GET/POST/PATCH/DELETE /api/tasks`, `POST /api/tasks/:id/complete`
- Labor: `POST /api/labor/clock-in`, `POST /api/labor/clock-out`, `GET /api/labor/time-entries`
- Compliance: `GET/POST/PATCH/DELETE /api/compliance/documents`, `GET /api/compliance/documents/:id/download`

---

### Phase 1D: Frontend UI (Week 4-5)

**Goal**: Build minimal viable UI for each feature

#### Tasks

1. **Design System**
   - [ ] Set up Tailwind config with design tokens (colors, spacing, fonts)
   - [ ] Create base UI components (Button, Input, Card, Badge, Dialog, Dropdown)
   - [ ] Create layout components (Header, Sidebar, Footer)
   - [ ] Implement dark mode toggle
   - [ ] Create responsive breakpoints

2. **Dashboard & Navigation**
   - [ ] Create Dashboard page (overview widgets)
   - [ ] Create Sidebar navigation
   - [ ] Create Header with user menu
   - [ ] Implement routing (React Router)

3. **Batches & Rooms UI**
   - [ ] Create BatchList page
   - [ ] Create BatchDetail page
   - [ ] Create BatchForm (create/edit)
   - [ ] Create RoomList page
   - [ ] Create RoomDetail page
   - [ ] Create RoomForm (create/edit)
   - [ ] Create WeightLogForm component

4. **Tasks UI**
   - [ ] Create TaskList page (with filters)
   - [ ] Create TodayView page (mobile-optimized)
   - [ ] Create TaskDetail page
   - [ ] Create TaskForm (create/edit)
   - [ ] Create TaskTemplateForm

5. **Labor UI**
   - [ ] Create TimeclockWidget component
   - [ ] Create TimeEntryList page
   - [ ] Create LaborReports page (basic hours report)

6. **Compliance UI**
   - [ ] Create DocumentList page
   - [ ] Create DocumentUploader component
   - [ ] Create DocumentPreview component (PDF/image viewer)

7. **Settings UI**
   - [ ] Create SettingsPage (user preferences, notification settings)
   - [ ] Create UserManagement page (admin-only)

**Deliverables**:

- Fully functional UI for all Phase 1 features
- Mobile-responsive design
- Dark mode support
- Accessible components (WCAG 2.1 AA)

---

### Phase 1E: Testing & Polish (Week 6)

**Goal**: Comprehensive testing and UX polish

#### Tasks

1. **Backend Testing**
   - [ ] Achieve 80%+ code coverage for services
   - [ ] Write integration tests for all API endpoints
   - [ ] Test RBAC permissions for all routes
   - [ ] Test error handling and edge cases

2. **Frontend Testing**
   - [ ] Write component tests for all UI components
   - [ ] Write integration tests for key workflows (login, create batch, clock in)
   - [ ] Test responsive design on mobile/tablet/desktop
   - [ ] Test dark mode

3. **UX Polish**
   - [ ] Optimize mobile tap targets (44×44px minimum)
   - [ ] Add loading states and skeletons
   - [ ] Add error states and retry logic
   - [ ] Add success toasts and confirmations
   - [ ] Optimize form validation and error messages
   - [ ] Add keyboard shortcuts for power users

4. **Performance**
   - [ ] Optimize API response times (< 200ms p95)
   - [ ] Optimize frontend bundle size
   - [ ] Add pagination for large lists
   - [ ] Add caching for frequently accessed data

5. **Documentation**
   - [ ] Write API documentation (OpenAPI/Swagger)
   - [ ] Write user guide for each feature
   - [ ] Write deployment guide
   - [ ] Update README files

**Deliverables**:

- 80%+ test coverage
- Polished UX with loading/error states
- API documentation
- User guide

---

## Technical Specifications

### Database Schema (Prisma)

```prisma
// User & Auth
model User {
  id          String   @id @default(cuid())
  email       String   @unique
  password    String   // bcrypt hashed
  name        String
  roleId      String
  role        Role     @relation(fields: [roleId], references: [id])
  createdAt   DateTime @default(now())
  updatedAt   DateTime @updatedAt
}

model Role {
  id          String   @id @default(cuid())
  name        String   @unique
  description String?
  users       User[]
  wageRates   WageRate[]
}

// Batches & Rooms
model Batch {
  id          String   @id @default(cuid())
  batchNumber String   @unique
  strain      String
  stage       BatchStage @default(CLONE_IN)
  plantCount  Int
  startDate   DateTime
  roomId      String?
  room        Room?    @relation(fields: [roomId], references: [id])
  metrcTags   String[]
  createdAt   DateTime @default(now())
  updatedAt   DateTime @updatedAt
}

model Room {
  id          String   @id @default(cuid())
  name        String
  type        RoomType
  capacity    Int?
  status      RoomStatus @default(ACTIVE)
  batches     Batch[]
  createdAt   DateTime @default(now())
  updatedAt   DateTime @updatedAt
}

// Tasks
model Task {
  id          String   @id @default(cuid())
  name        String
  status      TaskStatus @default(PENDING)
  dueDate     DateTime
  assigneeId  String?
  assignee    User?    @relation(fields: [assigneeId], references: [id])
  roomId      String?
  room        Room?    @relation(fields: [roomId], references: [id])
  batchId     String?
  batch       Batch?   @relation(fields: [batchId], references: [id])
  completedAt DateTime?
  createdAt   DateTime @default(now())
  updatedAt   DateTime @updatedAt
}

// Labor
model TimeEntry {
  id          String   @id @default(cuid())
  userId      String
  user        User     @relation(fields: [userId], references: [id])
  clockIn     DateTime
  clockOut    DateTime?
  duration    Int?
  roomId      String?
  room        Room?    @relation(fields: [roomId], references: [id])
  createdAt   DateTime @default(now())
}

model WageRate {
  id          String   @id @default(cuid())
  roleId      String
  role        Role     @relation(fields: [roleId], references: [id])
  hourlyRate  Float
  effectiveDate DateTime
  createdAt   DateTime @default(now())
}

// Compliance
model ComplianceDocument {
  id          String   @id @default(cuid())
  type        DocumentType
  filename    String
  url         String
  date        DateTime
  uploadedBy  String
  user        User     @relation(fields: [uploadedBy], references: [id])
  createdAt   DateTime @default(now())
}

// Enums
enum BatchStage {
  CLONE_IN
  VEGETATIVE
  FLOWERING
  HARVEST
  DRYING
  CURING
  FINISHED
}

enum RoomType {
  VEG
  FLOWER
  DRY
  FACILITY
}

enum RoomStatus {
  ACTIVE
  CLEANING
  MAINTENANCE
}

enum TaskStatus {
  PENDING
  IN_PROGRESS
  COMPLETE
  OVERDUE
}

enum DocumentType {
  TAX_MONTHLY
  UTILITY_BILL
  RENT_LEASE
  INVOICE
  LICENSE_PERMIT
  OTHER
}
```

---

## Risk Management

| Risk | Impact | Mitigation | Owner |
|------|--------|------------|-------|
| Scope creep in Phase 1 | High | Strict adherence to Phase 1 spec; defer enhancements to Phase 2 | PM |
| Database schema changes | Medium | Use Prisma migrations; test migrations thoroughly | Backend Lead |
| Mobile UX issues | High | Test on real devices early; prioritize tablet testing | Frontend Lead |
| Authentication vulnerabilities | Critical | Security audit of auth code; use established libraries (bcrypt, jsonwebtoken) | Backend Lead |
| Performance issues with large datasets | Medium | Implement pagination early; add database indexes | Backend Lead |

---

## Success Metrics

### Phase 1 Completion Criteria

- [ ] All Phase 1 features implemented and tested
- [ ] 80%+ test coverage (backend and frontend)
- [ ] All API endpoints documented
- [ ] User guide written
- [ ] Deployment guide written
- [ ] Application deployed to staging environment
- [ ] Demo completed with stakeholders

### Performance Targets

- [ ] API response time < 200ms (p95)
- [ ] Page load time < 2s on 3G
- [ ] Time to interactive < 3s on 3G
- [ ] Lighthouse score > 90 (Performance, Accessibility)

### Quality Targets

- [ ] Zero critical security vulnerabilities
- [ ] Zero high-priority bugs
- [ ] WCAG 2.1 AA compliance
- [ ] Mobile-responsive on all pages

---

## Timeline

**Total Duration**: 6 weeks

- **Week 1**: Infrastructure Setup
- **Week 2**: Authentication & RBAC
- **Week 3**: Core Data Models
- **Week 4-5**: Frontend UI
- **Week 6**: Testing & Polish

**Milestones**:

- End of Week 2: Working auth system
- End of Week 3: All APIs functional
- End of Week 5: All UI complete
- End of Week 6: Phase 1 complete and deployed

---

## Next Steps

1. **Review this plan** with the team
2. **Break down into tasks** using `/speckit.tasks`
3. **Assign tasks** to team members
4. **Set up project tracking** (GitHub Projects, Linear, etc.)
5. **Begin Week 1**: Infrastructure Setup
