# Feature Spec: Compliance and Documentation

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

---

## Overview

The Compliance and Documentation module helps California cannabis cultivation facilities maintain audit-ready records for DCC (Department of Cannabis Control) compliance. It tracks key compliance-adjacent records (taxes, utilities, invoices, payroll references), provides compliance views by month/quarter, and generates "audit packet" exports. **METRC remains the system of record for track-and-trace; this module supports adjacent recordkeeping.**

---

## User Stories

### As a Compliance Manager

- I want to upload and categorize compliance documents (PDFs, images) so they're organized and searchable
- I want to see a monthly/quarterly compliance checklist so I know what's missing
- I want to generate an audit packet (ZIP with all docs and indexes) so I'm ready for inspections
- I want to track METRC tag mappings for batches so I can cross-reference with the state system

### As an Owner

- I want to see compliance status at a glance so I know we're audit-ready
- I want to delegate compliance tasks to the Compliance Manager
- I want to ensure all financial records (taxes, invoices, payroll) are properly documented

### As an Accountant

- I want to upload invoices and bills with structured metadata so they're easy to find
- I want to export compliance records for tax preparation

---

## Requirements

### Functional Requirements

#### Document Management

- **Document types**:
  - Monthly taxes (excise, sales, cultivation)
  - Utility bills (SMUD, PG&E, water, gas)
  - Rent/lease agreements
  - CO₂ and greenhouse supply invoices
  - Nutrient and material invoices
  - Bills of sale
  - Payroll summaries (references only, not full payroll data)
  - Hours tracking exports (from Labor module)
  - Licenses and permits
  - Inspection reports
  - SOPs (Standard Operating Procedures)
- **Document upload**:
  - Drag-and-drop or file picker
  - PDF, image (JPG, PNG), and CSV supported
  - Automatic OCR for searchability (future enhancement)
- **Structured metadata**:
  - Document type
  - Date (invoice date, bill date, etc.)
  - Vendor/supplier
  - Amount (if applicable)
  - Period covered (month/quarter)
  - Tags (custom labels)
  - Notes

#### Compliance Views

- **Monthly view**:
  - Checklist of required documents for the month
  - Status: complete, missing, pending
  - Quick upload for missing items
- **Quarterly view**:
  - Aggregated checklist for the quarter
  - DCC-aligned categories
- **Annual view**:
  - Year-end compliance summary
  - License renewal reminders

#### Audit Packet Generation

- **Export format**: ZIP file containing:
  - All documents for the selected period
  - CSV index with metadata (filename, type, date, vendor, amount)
  - JSON index for programmatic access
  - README with export details
- **Filters**:
  - By date range
  - By document type
  - By vendor
- **Encryption** (optional): Password-protected ZIP

#### METRC Tag Mapping

- **Batch-to-METRC mapping**:
  - Store METRC tag IDs for each batch
  - Display mapping in batch detail view
  - Export mapping as CSV
- **Read-only in v1**: No direct METRC sync

### Non-Functional Requirements

- **Security**: Documents encrypted at rest
- **Access control**: Only Compliance Manager and Owner can view/edit
- **Audit trail**: All document uploads and deletions logged
- **Performance**: Document list loads in < 1 second
- **Storage**: Configurable retention policy (e.g., 7 years for tax records)

---

## Out of Scope (v1)

- Direct METRC integration (read/write)
- Automated compliance alerts based on METRC data
- OCR and automatic metadata extraction
- E-signature for documents
- Integration with accounting systems (QuickBooks, Xero)

---

## Acceptance Criteria

### Document Management

- [ ] Compliance Manager can upload documents with metadata
- [ ] Documents are categorized by type
- [ ] Documents can be searched by metadata (type, date, vendor)
- [ ] Documents can be previewed in-app (PDF, images)
- [ ] Documents can be downloaded individually

### Compliance Views

- [ ] Monthly view displays checklist of required documents
- [ ] Missing documents are highlighted
- [ ] Quick upload button for missing documents
- [ ] Quarterly and annual views aggregate monthly data

### Audit Packet

- [ ] Audit packet can be generated for a date range
- [ ] ZIP contains all documents and indexes (CSV, JSON)
- [ ] Export includes README with metadata
- [ ] Password protection is optional

### METRC Mapping

- [ ] METRC tags can be associated with batches
- [ ] Mapping is displayed in batch detail view
- [ ] Mapping can be exported as CSV

### Audit Trail

- [ ] All document uploads are logged with user and timestamp
- [ ] All document deletions are logged (soft delete)
- [ ] Audit log is exportable

---

## Technical Notes

### Data Model (Prisma Schema)

```prisma
model ComplianceDocument {
  id          String   @id @default(cuid())
  type        DocumentType
  filename    String
  url         String   // S3 or local storage
  date        DateTime // invoice date, bill date, etc.
  vendor      String?
  amount      Float?
  period      String?  // "2025-01" for January 2025
  tags        String[] // custom labels
  notes       String?
  uploadedBy  String
  user        User     @relation(fields: [uploadedBy], references: [id])
  deletedAt   DateTime? // soft delete
  deletedBy   String?
  createdAt   DateTime @default(now())
  updatedAt   DateTime @updatedAt
}

enum DocumentType {
  TAX_MONTHLY
  UTILITY_BILL
  RENT_LEASE
  CO2_INVOICE
  NUTRIENT_INVOICE
  BILL_OF_SALE
  PAYROLL_SUMMARY
  HOURS_EXPORT
  LICENSE_PERMIT
  INSPECTION_REPORT
  SOP
  OTHER
}

model AuditLog {
  id          String   @id @default(cuid())
  action      String   // "upload", "delete", "edit"
  entityType  String   // "ComplianceDocument", "Batch", etc.
  entityId    String
  userId      String
  user        User     @relation(fields: [userId], references: [id])
  metadata    Json?    // additional context
  createdAt   DateTime @default(now())
}
```

### API Endpoints

- `GET /api/compliance/documents` - List documents with filters
- `GET /api/compliance/documents/:id` - Get document detail
- `POST /api/compliance/documents` - Upload document
- `PATCH /api/compliance/documents/:id` - Update document metadata
- `DELETE /api/compliance/documents/:id` - Soft delete document
- `GET /api/compliance/documents/:id/download` - Download document
- `GET /api/compliance/checklist/:period` - Get compliance checklist for period
- `POST /api/compliance/audit-packet` - Generate audit packet
- `GET /api/compliance/metrc-mapping` - Get METRC tag mappings
- `GET /api/compliance/audit-log` - Get audit log

### UI Components

- `DocumentUploader` - Drag-and-drop upload with metadata form
- `DocumentList` - Filterable list of documents
- `DocumentPreview` - In-app PDF/image viewer
- `ComplianceChecklist` - Monthly/quarterly checklist view
- `AuditPacketGenerator` - Export interface with filters
- `MetrcMappingTable` - Batch-to-METRC tag mapping
- `AuditLogViewer` - Audit trail display

---

## Dependencies

- **Batches and Rooms** module (for METRC mapping)
- **Labor** module (for payroll/hours exports)
- **Authentication** (for RBAC and audit trail)

---

## Risks & Mitigations

| Risk | Impact | Mitigation |
|------|--------|------------|
| Document storage costs | Medium | Configurable retention policy; compression |
| Missing documents at audit time | High | Proactive checklists; monthly reminders |
| METRC mapping errors | High | Clear UI; validation; read-only in v1 |
| Data breach (sensitive financial docs) | High | Encryption at rest; strict access control; audit trail |

---

## Compliance Notes (California DCC)

### Key Recordkeeping Requirements

Per California DCC regulations, licensed cannabis businesses must maintain:

- **Financial records**: Invoices, receipts, bank statements, tax filings (7 years)
- **Inventory records**: METRC is the system of record; internal records must align
- **Labor records**: Hours, wages, payroll (4 years minimum)
- **Licenses and permits**: Current and historical
- **Inspection reports**: All DCC and local inspections
- **SOPs**: Current versions and change history

### Audit Preparation

- **Quarterly self-audits** recommended
- **Audit packet** should include:
  - All financial records for the period
  - METRC reconciliation reports
  - Labor and payroll summaries
  - Licenses and permits
  - Inspection reports
  - SOPs

### Resources

- [California DCC Regulations](https://cannabis.ca.gov/cannabis-laws/dcc-regulations/)
- [METRC California Guide](https://www.metrc.com/california)
- [DCC Compliance Checklist](https://cannabis.ca.gov/licensees/compliance-hub/)

---

## Future Enhancements (Post-v1)

- OCR and automatic metadata extraction
- METRC integration (read/write with user confirmation)
- Automated compliance alerts (e.g., "Missing utility bill for March")
- E-signature for SOPs and inspection reports
- Integration with accounting systems (QuickBooks, Xero)
- Automated tax filing reminders
