docs: Phase 3 design spec — AI features + dashboard upgrade

This commit is contained in:
2026-07-11 17:39:18 +08:00
parent 3297198179
commit a07c9f0910
@@ -0,0 +1,175 @@
# Phase 3 — AI Features & Dashboard Upgrade
**Date:** 2026-07-11
**Status:** Approved
---
## Scope
Phase 3 adds AI-assisted capabilities via the Claude API and upgrades all role dashboards from placeholders to functional views. Similar-incident retrieval (pgvector) is deferred to Phase 4.
**Deliverables:**
1. Upgraded dashboards for all 5 roles
2. Report quality check (AI)
3. Severity/category suggestion at triage (AI)
4. RCA/CAPA drafting assistant (AI)
---
## 1. Dashboard Upgrades
### Approach
Replace placeholder home pages for each role with data-driven dashboards scoped to what that role needs to act on. All dashboards are server-rendered (Next.js App Router, `force-dynamic`). Site/zone heatmap is a plain HTML table with Tailwind bg-opacity intensity — no canvas library.
### Role Dashboards
**HSE Officer**`/hse/dashboard` (upgrade existing)
- Leading vs lagging split: near_miss + hazard = leading indicators; injury + lti = lagging
- Site/zone heatmap: incident count per site × zone, color-coded by intensity
- CAPA on-time completion rate: `(verified CAPAs where completed_at <= due_date) / total verified * 100`
- Top 3 incident categories by count (current month)
- Top 3 root causes from `investigations.root_cause_summary` (simple text frequency, no NLP)
- DOSH-reportable filing status: counts of `dosh_reports` rows by status (not_required / pending / submitted)
- CSV export endpoint: `GET /api/dashboard/export?role=hse` — all incidents with key fields
**Management**`/management` (upgrade placeholder)
- This month vs last month incident count (delta + arrow)
- LTI count (incidents where `medical_status = 'lti'`)
- Severity distribution bar (count per severity 1-5)
- Leading/lagging split (same calc as HSE)
- CAPA overdue count (status = 'overdue')
- Site comparison table: incident count per site, sorted descending
- CSV export: `GET /api/dashboard/export?role=management`
**Supervisor**`/supervisor` (upgrade placeholder)
- Scoped to `user.site_id` — only their site's data
- Open incidents count + list (status != closed), linked to incident detail
- CAPA status summary for their site: open / in_progress / overdue counts
- Overdue CAPAs: list with owner name + due date
**CAPA Owner**`/capa-owner` (upgrade placeholder)
- Scoped to `capa_actions.owner_user_id = current_user`
- My open CAPAs: list with incident ref, description, due date, status
- Overdue count highlighted in red
- No export needed
**Reporter**`/reporter` (upgrade placeholder)
- Scoped to `incidents.reported_by = current_user`
- My submissions: list with reference_no, date, type, current status
- Status shown as colored badge (reported / triaged / investigating / capa_pending / verification / closed)
- No export needed
---
## 2. AI Features
### Architecture
- All Claude API calls: server-side only, `/app/api/...` routes
- Model: `claude-sonnet-4-6`
- API key: `ANTHROPIC_API_KEY` env var (never client-side)
- Every AI suggestion logged to `audit_log` with: table=`ai_suggestion`, action=`suggested`, old_value=null, new_value=JSON of suggestion, changed_by=current user
### 2a. Report Quality Check
**Trigger:** Incident report form submit — before DB write, client POSTs to quality-check route first.
**API route:** `POST /api/incidents/quality-check`
**Request payload:**
```json
{
"description": "string",
"incident_type": "injury | near_miss | ...",
"injury_involved": true,
"evidence_count": 0
}
```
**Claude prompt strategy:** Send incident fields; ask Claude to return a JSON array of short warning strings covering: vague description (< 20 words), injury with no photo, no location detail, missing witness info for serious incidents.
**Response:**
```json
{ "warnings": ["Description too vague — add what happened and where", "Injury reported but no photo attached"] }
```
**UI:** If warnings exist, show yellow warning panel above the submit button listing each warning. "Submit anyway" button still present — user is never blocked, only informed.
**Audit log:** Not logged (no human decision to record — warnings are informational only).
### 2b. Severity/Category Suggestion (Triage)
**Trigger:** "Get AI suggestion" button in existing triage panel at `/hse/incidents/[id]/triage`.
**API route:** `POST /api/incidents/[id]/ai-triage`
**Claude prompt strategy:** Send description, incident_type, injury_involved, lost_days. Ask Claude to return suggested severity 1-5 with confidence (high/medium/low) and one-sentence reasoning. Return as JSON.
**Response:**
```json
{
"suggested_severity": 3,
"confidence": "medium",
"reasoning": "Injury involved with medical treatment but no LTI reported — consistent with severity 3."
}
```
**UI:** Suggestion card appears below the severity input in the triage form. "Accept" pre-fills the severity field. HSE can ignore and type their own value. Card shows confidence label and reasoning text.
**Audit log:** On triage form save, log: suggested_severity, confidence, human's final severity value. `record_id` = incident id.
### 2c. RCA/CAPA Drafting Assistant
**Trigger:** "Generate suggestions" button in investigation workspace at `/hse/incidents/[id]/investigation`.
**API route:** `POST /api/incidents/[id]/ai-rca`
**Claude prompt strategy:** Send incident description, investigation findings_text, root_cause_summary. Ask Claude to return: 2-3 root cause categories (from standard EHS taxonomy: Human Factors, Equipment Failure, Procedure, Environment, Management System) + 2-3 draft CAPA action descriptions as JSON array.
**Response:**
```json
{
"root_causes": [
{ "category": "Procedure", "explanation": "No documented SOP for forklift loading at Dock A" }
],
"capa_drafts": [
"Develop and implement SOP for forklift loading operations at all dock areas within 14 days",
"Conduct refresher training for all forklift operators on LOTO procedure by end of month"
]
}
```
**UI:** Collapsible "AI Suggestions" panel below the RCA form fields. Each root cause has a "Use this" button that appends text to `root_cause_summary`. Each CAPA draft has a "Create CAPA" button that opens the CAPA creation form pre-filled with that description.
**Audit log:** Log on button click: which suggestion index was used, full suggestions array as old_value context. `record_id` = incident id.
---
## 3. Data & Schema
No new DB tables required. Existing `audit_log` table handles AI suggestion logging via `action = 'ai_suggested'`.
CSV export routes query existing tables — no new schema.
---
## 4. Implementation Order
1. Dashboard — HSE (upgrade existing, most complex)
2. Dashboard — Management
3. Dashboard — Supervisor
4. Dashboard — CAPA Owner
5. Dashboard — Reporter
6. CSV export endpoint (shared, covers HSE + management)
7. Report quality check (AI)
8. Severity suggestion at triage (AI)
9. RCA/CAPA drafting assistant (AI)
---
## 5. Out of Scope (Phase 3)
- Similar-incident retrieval via pgvector — Phase 4
- WhatsApp notifications — Phase 4
- Multi-language UI — Phase 4
- CAPA effectiveness re-check automation — Phase 4
- Risk heatmap / predictive analytics — Phase 4