# Feature Spec: Audit Trail & Document Management

**Priority**: 🔴 Critical (Compliance)  
**Phase**: 10  
**Status**: ✅ Implemented

---

## Overview

Zero-friction compliance reporting. Every action logged, every document versioned, instant report generation for inspectors.

---

## Audit Log

### Model: AuditLog

- `id`: UUID
- `userId`: FK to User
- `action`: string (CREATE, UPDATE, DELETE, VIEW, LOGIN, etc.)
- `entityType`: string (Batch, Room, Plant, etc.)
- `entityId`: string
- `beforeData`: JSON (state before change)
- `afterData`: JSON (state after change)
- `ipAddress`: string
- `userAgent`: string
- `timestamp`: datetime
- `metadata`: JSON (additional context)

### API Endpoints

- `GET /api/audit/logs` - Query logs with filters
- `GET /api/audit/logs/:entityType/:entityId` - Entity history
- `GET /api/audit/summary` - Dashboard statistics
- `GET /api/audit/export` - CSV/JSON export

### Implementation Notes

- Immutable storage (append-only, no deletions)
- Automatic logging via middleware
- 7-year retention for compliance
- Indexes on entityType, entityId, timestamp

---

## Document Management

### Model: Document

- `id`: UUID
- `title`: string
- `type`: enum (SOP, POLICY, FORM, CERTIFICATE, LICENSE, OTHER)
- `category`: string
- `content`: string (markdown) OR fileUrl
- `currentVersion`: number
- `status`: enum (DRAFT, PENDING_APPROVAL, APPROVED)
- `requiresAck`: boolean
- `createdById`: FK
- `approvedById`: FK (optional)
- `approvedAt`: datetime (optional)

### Model: DocumentVersion

- `id`: UUID
- `documentId`: FK
- `version`: number
- `content`: string OR fileUrl
- `changeNotes`: string
- `createdById`: FK
- `createdAt`: datetime

### Model: DocumentAck

- `id`: UUID
- `documentId`: FK
- `userId`: FK
- `version`: number
- `acknowledgedAt`: datetime

### API Endpoints

- `GET /api/documents` - List documents
- `POST /api/documents` - Create document
- `GET /api/documents/:id` - Get with versions
- `PUT /api/documents/:id` - Update (creates new version)
- `POST /api/documents/:id/approve` - Approve document
- `POST /api/documents/:id/acknowledge` - Ack document
- `GET /api/documents/:id/ack-status` - Who has acked
- `GET /api/documents/:id/versions` - Version history

---

## Compliance Reports

### Available Reports

1. **Audit Summary** - Actions by type, user, time period
2. **Document Compliance** - Ack rates, pending reviews
3. **User Activity** - Login history, action counts
4. **Entity History** - Full change log for any entity

### Export Formats

- CSV (for spreadsheets)
- JSON (for integrations)
- PDF (for auditors)
