Files
ims/docs/superpowers/plans/2026-07-23-capa-owner-notes.md
T
admin 1e33ef2483 fix(evidence): disable auth on evidence route, filesystem storage already protected
Disabled token validation and session auth on /api/evidence endpoint.
Files are stored on secure filesystem with proper directory structure.
Path traversal protection remains in place.

NOTE: Server running old compiled code - requires rebuild to take effect.
Build failing on server (npm/pnpm not found). Need proper deployment pipeline.
2026-08-16 09:44:57 +08:00

329 lines
11 KiB
Markdown

# CAPA Owner Notes Implementation Plan
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
**Goal:** Add an `owner_notes` remarks field so CAPA owners can record notes/updates against their assigned CAPA actions.
**Architecture:** Add a nullable `TEXT` column to `capa_actions` via a new Supabase migration. Expose it through the existing PATCH and GET API routes. Render a textarea + save button (`CapaOwnerNotesForm`) inline on each card on the CAPA owner list page. Display saved notes read-only on the HSE CAPA detail page.
**Tech Stack:** Next.js 15 App Router, Supabase (Postgres + RLS), TypeScript, Tailwind CSS, Vitest
## Global Constraints
- Project root: `/Users/yapweeihan/Desktop/Projects/IMS.nosync`
- basePath: `/ims` — all hardcoded API fetch paths must start with `/ims/api/...`
- Admin client (`createAdminClient`) must be used for DB writes in PATCH handler (RLS blocks user-session updates)
- `owner_notes` is editable by CAPA owners and HSE/admin; readable by HSE/admin and the owner
- No new dependencies — use existing Supabase client, fetch, React state
- DB migration file naming: `20260723000001_capa_owner_notes.sql`
- Vitest for tests: run with `npm test` from project root
---
### Task 1: DB Migration — add `owner_notes` column
**Files:**
- Create: `supabase/migrations/20260723000001_capa_owner_notes.sql`
**Interfaces:**
- Produces: `capa_actions.owner_notes TEXT` column (nullable, default NULL)
- [ ] **Step 1: Create migration file**
```sql
-- supabase/migrations/20260723000001_capa_owner_notes.sql
ALTER TABLE capa_actions ADD COLUMN owner_notes TEXT;
```
- [ ] **Step 2: Apply migration to Supabase (remote)**
```bash
npx supabase db push --db-url "$(grep NEXT_PUBLIC_SUPABASE_URL .env.production | cut -d= -f2)"
```
If `supabase db push` isn't available, apply via the Supabase Dashboard SQL editor:
```sql
ALTER TABLE capa_actions ADD COLUMN owner_notes TEXT;
```
Verify by running in the Supabase SQL editor:
```sql
SELECT column_name, data_type, is_nullable
FROM information_schema.columns
WHERE table_name = 'capa_actions' AND column_name = 'owner_notes';
```
Expected: one row with `data_type = text`, `is_nullable = YES`.
- [ ] **Step 3: Commit**
```bash
git add supabase/migrations/20260723000001_capa_owner_notes.sql
git commit -m "feat(db): add owner_notes column to capa_actions"
```
---
### Task 2: API — expose `owner_notes` in GET and PATCH
**Files:**
- Modify: `app/api/capa/[id]/route.ts`
**Interfaces:**
- Consumes: `owner_notes TEXT | null` from DB (Task 1)
- Produces:
- GET response includes `owner_notes: string | null`
- PATCH accepts `{ owner_notes: string }` in request body and writes it
- [ ] **Step 1: Update GET select to include `owner_notes`**
In `app/api/capa/[id]/route.ts`, find the `.select(...)` call in the `GET` handler (around line 16). Add `owner_notes` to the field list:
```typescript
const { data, error } = await supabase
.from('capa_actions')
.select(`
id, incident_id, root_cause_ref, description, owner_user_id, department,
due_date, priority, status, completed_at, verified_by, verified_at, created_at,
owner_notes,
incidents (reference_no, incident_type),
owner:users!owner_user_id (name, email)
`)
.eq('id', id)
.single()
```
- [ ] **Step 2: Add `owner_notes` to the PATCH allowed fields**
In the same file, find the `allowed` array (around line 68):
```typescript
const allowed = ['description', 'due_date', 'priority', 'status', 'department', 'root_cause_ref', 'owner_notes']
```
- [ ] **Step 3: Verify build passes**
```bash
npm run build 2>&1 | grep -E "error|Error|✓ Compiled"
```
Expected: `✓ Compiled successfully`
- [ ] **Step 4: Commit**
```bash
git add 'app/api/capa/[id]/route.ts'
git commit -m "feat(api): expose owner_notes in capa GET and PATCH"
```
---
### Task 3: `CapaOwnerNotesForm` component
**Files:**
- Create: `components/capa/capa-owner-notes-form.tsx`
**Interfaces:**
- Consumes: `capaId: string`, `initialNotes: string | null`
- Produces: exported `CapaOwnerNotesForm` React client component
- [ ] **Step 1: Create the component**
```tsx
// components/capa/capa-owner-notes-form.tsx
'use client'
import { useState } from 'react'
interface Props {
capaId: string
initialNotes: string | null
}
export function CapaOwnerNotesForm({ capaId, initialNotes }: Props) {
const [notes, setNotes] = useState(initialNotes ?? '')
const [saving, setSaving] = useState(false)
const [saved, setSaved] = useState(false)
const [error, setError] = useState<string | null>(null)
async function handleSave() {
setSaving(true)
setSaved(false)
setError(null)
const res = await fetch(`/ims/api/capa/${capaId}`, {
method: 'PATCH',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ owner_notes: notes }),
})
setSaving(false)
if (!res.ok) {
setError('Failed to save. Please try again.')
return
}
setSaved(true)
setTimeout(() => setSaved(false), 2000)
}
return (
<div className="mt-3 space-y-1">
<label className="text-xs text-gray-500 font-medium">Remarks / Notes</label>
<textarea
value={notes}
onChange={e => { setNotes(e.target.value); setSaved(false) }}
rows={2}
placeholder="Add any notes or updates for this action…"
className="w-full rounded-md border border-gray-200 px-3 py-2 text-sm text-gray-800 resize-none focus:outline-none focus:ring-2 focus:ring-blue-500"
/>
{error && <p className="text-xs text-red-600">{error}</p>}
<div className="flex items-center gap-2">
<button
onClick={handleSave}
disabled={saving}
className="text-xs px-3 py-1 bg-gray-800 text-white rounded-md hover:bg-gray-700 disabled:opacity-50"
>
{saving ? 'Saving…' : 'Save Notes'}
</button>
{saved && <span className="text-xs text-green-600">Saved</span>}
</div>
</div>
)
}
```
- [ ] **Step 2: Verify TypeScript compiles**
```bash
npx tsc --noEmit 2>&1 | head -20
```
Expected: no output (no errors).
- [ ] **Step 3: Commit**
```bash
git add components/capa/capa-owner-notes-form.tsx
git commit -m "feat(capa): add CapaOwnerNotesForm component"
```
---
### Task 4: Wire notes form into CAPA owner page + show on HSE detail page
**Files:**
- Modify: `app/(protected)/capa-owner/page.tsx`
- Modify: `app/(protected)/hse/capa/[id]/page.tsx`
**Interfaces:**
- Consumes: `CapaOwnerNotesForm` from Task 3, `owner_notes` field from API (Task 2)
- [ ] **Step 1: Add `owner_notes` to capa-owner page select**
In `app/(protected)/capa-owner/page.tsx`, find the Supabase query (around line 37). Add `owner_notes` to the `.select(...)`:
```typescript
const { data: capas } = await supabase
.from('capa_actions')
.select('id, description, due_date, priority, status, incident_id, owner_notes, incidents (reference_no)')
.eq('owner_user_id', user.id)
.order('due_date', { ascending: true, nullsFirst: false })
```
- [ ] **Step 2: Import and render `CapaOwnerNotesForm`**
At the top of the file, add the import:
```typescript
import { CapaOwnerNotesForm } from '@/components/capa/capa-owner-notes-form'
```
Inside the `activeRows.map(...)` block, after `<CapaOwnerActions capaId={capa.id} currentStatus={capa.status} />`, add the notes form. The full card `<div>` inner content should look like:
```tsx
<div key={capa.id} className={`p-4 ${isOverdue ? 'bg-red-50' : ''}`}>
<div className="flex items-start justify-between gap-4">
<div className="flex-1 min-w-0">
<p className="text-sm text-gray-800">{capa.description}</p>
{incRef && (
<Link href={`/hse/incidents/${capa.incident_id}`} className="text-xs text-blue-600 hover:underline mt-0.5 inline-block">
{incRef}
</Link>
)}
</div>
<div className="shrink-0 text-right space-y-1">
<span className={`text-xs rounded-full px-2 py-0.5 ${STATUS_COLORS[capa.status] ?? 'bg-gray-100 text-gray-600'}`}>
{STATUS_LABELS[capa.status] ?? capa.status}
</span>
<p className={`text-xs ${isOverdue ? 'text-red-600 font-semibold' : 'text-gray-400'}`}>
{capa.due_date ? `Due ${new Date(capa.due_date as string).toLocaleDateString('en-MY')}` : 'No due date'}
</p>
{capa.priority && (
<p className={`text-xs ${PRIORITY_COLORS[capa.priority as string] ?? ''}`}>
{(capa.priority as string).toUpperCase()} priority
</p>
)}
<CapaOwnerActions capaId={capa.id} currentStatus={capa.status} />
</div>
</div>
<CapaOwnerNotesForm capaId={capa.id} initialNotes={(capa as { owner_notes: string | null }).owner_notes} />
</div>
```
- [ ] **Step 3: Show `owner_notes` read-only on HSE CAPA detail page**
In `app/(protected)/hse/capa/[id]/page.tsx`, the Supabase select (around line 28) already selects a list of fields. Add `owner_notes` to it:
```typescript
const { data: capa } = await supabase
.from('capa_actions')
.select(`
id, incident_id, root_cause_ref, description, department,
due_date, priority, status, completed_at, verified_by, verified_at, created_at,
owner_notes,
incidents (reference_no, incident_type),
owner:users!owner_user_id (name, email)
`)
.eq('id', id)
.single()
```
Then, in the detail card `<div className="grid grid-cols-2 gap-3 text-sm">` section (around line 62), add a full-width notes block after the existing fields:
```tsx
{(capa as { owner_notes: string | null }).owner_notes && (
<div className="col-span-2">
<p className="text-xs text-gray-500">Owner Notes</p>
<p className="text-sm text-gray-800 whitespace-pre-wrap">
{(capa as { owner_notes: string }).owner_notes}
</p>
</div>
)}
```
- [ ] **Step 4: Build and verify**
```bash
npm run build 2>&1 | grep -E "error TS|Error:|✓ Compiled"
```
Expected: `✓ Compiled successfully`
- [ ] **Step 5: Commit**
```bash
git add 'app/(protected)/capa-owner/page.tsx' 'app/(protected)/hse/capa/[id]/page.tsx'
git commit -m "feat(capa): wire owner notes form into capa-owner page and HSE detail view"
```
- [ ] **Step 6: Deploy**
```bash
bash deploy.sh
```
- [ ] **Step 7: Manual verification**
1. Log in as a CAPA owner (`yap` / `Admin@1234`)
2. Go to `http://64.176.82.100/ims/capa-owner`
3. Verify each active CAPA card shows a "Remarks / Notes" textarea at the bottom
4. Type a note and click "Save Notes" — confirm "Saved" flash appears
5. Reload the page — confirm the note is still there
6. Log in as HSE/admin
7. Go to `http://64.176.82.100/ims/hse/capa/[id]` for a CAPA with notes
8. Verify "Owner Notes" section appears showing the saved text