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.
This commit is contained in:
2026-08-16 09:44:57 +08:00
parent 5babb72699
commit 1e33ef2483
22 changed files with 10293 additions and 357 deletions
@@ -0,0 +1,429 @@
# Bug Fixes: Invite Redirect, CAPA Owner Dropdown, Alcohol/Urine Test Split
> **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:** Fix three bugs: invite emails redirect to localhost instead of live URL; CAPA "Assigned To" dropdown is empty; alcohol and urine test results share one field instead of two.
**Architecture:** All three are small, independent fixes. Task 1 is one server route edit. Task 2 is one server page query edit. Task 3 requires a DB migration + form + API route changes (and adding display to incident detail).
**Tech Stack:** Next.js App Router, Supabase (Postgres), Tailwind CSS.
## Global Constraints
- Never commit `.env` or API keys.
- Every DB mutation writes to `audit_log`.
- RLS enforced at DB level — never rely on UI hiding.
- Incident reference format: `SITE-YYYYMM-####`.
- `NEXT_PUBLIC_APP_URL=http://64.176.82.100/ims` in production.
---
### Task 1: Fix invite email redirect URL
**Root cause:** `app/api/admin/users/route.ts` line 63 falls back to `'http://localhost:3000'` when `NEXT_PUBLIC_APP_URL` is unset, so invite emails sent from local dev point to localhost.
**Files:**
- Modify: `app/api/admin/users/route.ts`
**Interfaces:**
- No interface changes — internal guard only.
- [ ] **Step 1: Write the failing test**
Add to `tests/api/admin/users.test.ts` (create file if it doesn't exist):
```typescript
import { describe, it, expect, vi, beforeEach } from 'vitest'
describe('POST /api/admin/users — invite path', () => {
it('returns 503 when NEXT_PUBLIC_APP_URL is not set', async () => {
const originalEnv = process.env.NEXT_PUBLIC_APP_URL
delete process.env.NEXT_PUBLIC_APP_URL
// Mock requireAdmin and createAdminClient so they succeed
vi.mock('@/lib/auth/require-admin', () => ({
requireAdmin: async () => ({ supabase: { rpc: vi.fn() }, user: { id: 'admin-id' } }),
}))
vi.mock('@/lib/supabase/admin', () => ({
createAdminClient: () => ({
auth: { admin: { inviteUserByEmail: vi.fn() } },
from: () => ({ update: () => ({ eq: () => ({ error: null }) }) }),
}),
}))
const { POST } = await import('@/app/api/admin/users/route')
const req = new Request('http://localhost/api/admin/users', {
method: 'POST',
body: JSON.stringify({ email: 'test@example.com', name: 'Test' }),
headers: { 'Content-Type': 'application/json' },
})
const res = await POST(req as any)
expect(res.status).toBe(503)
const body = await res.json()
expect(body.error).toMatch(/NEXT_PUBLIC_APP_URL/)
process.env.NEXT_PUBLIC_APP_URL = originalEnv
})
})
```
- [ ] **Step 2: Run test to verify it fails**
```bash
npx vitest run tests/api/admin/users.test.ts
```
Expected: FAIL — test setup may need work, but intent is clear.
- [ ] **Step 3: Apply the fix**
In `app/api/admin/users/route.ts`, find the invite branch (around line 63):
```typescript
// BEFORE
const appUrl = process.env.NEXT_PUBLIC_APP_URL ?? 'http://localhost:3000'
const { data: invited, error: inviteError } = await admin.auth.admin.inviteUserByEmail(email, {
data: { full_name: body.name ?? '' },
redirectTo: `${appUrl}/api/auth/callback`,
})
```
Replace with:
```typescript
// AFTER
const appUrl = (process.env.NEXT_PUBLIC_APP_URL ?? '').replace(/\/$/, '')
if (!appUrl) {
return NextResponse.json(
{ error: 'Invite unavailable: NEXT_PUBLIC_APP_URL not configured' },
{ status: 503 },
)
}
const { data: invited, error: inviteError } = await admin.auth.admin.inviteUserByEmail(email, {
data: { full_name: body.name ?? '' },
redirectTo: `${appUrl}/api/auth/callback`,
})
```
- [ ] **Step 4: Verify the happy path still works (manual check)**
Confirm `NEXT_PUBLIC_APP_URL` is set in VPS `.env.production` or system env:
```
NEXT_PUBLIC_APP_URL=http://64.176.82.100/ims
```
- [ ] **Step 5: Commit**
```bash
git add app/api/admin/users/route.ts
git commit -m "fix(auth): fail fast when NEXT_PUBLIC_APP_URL unset for invite redirectTo"
```
---
### Task 2: CAPA "Assigned To" — show all active users
**Root cause:** `app/(protected)/hse/incidents/[id]/capa/new/page.tsx` filters users by `.eq('role', 'capa_owner')` only. Users without that exact role never appear.
**Files:**
- Modify: `app/(protected)/hse/incidents/[id]/capa/new/page.tsx`
**Interfaces:**
- No interface changes — `CapaForm` already accepts `users: Array<{ id, name, department }>`.
- [ ] **Step 1: Write the failing test**
This is a server component — verify by inspection. Open `app/(protected)/hse/incidents/[id]/capa/new/page.tsx` and confirm line 29–31 reads:
```typescript
const { data: users } = await admin
.from('users')
.select('id, name, department')
.eq('role', 'capa_owner')
.order('name')
```
- [ ] **Step 2: Apply the fix**
Replace the query:
```typescript
// BEFORE
const { data: users } = await admin
.from('users')
.select('id, name, department')
.eq('role', 'capa_owner')
.order('name')
```
```typescript
// AFTER
const { data: users } = await admin
.from('users')
.select('id, name, department')
.eq('active', true)
.order('name')
```
- [ ] **Step 3: Verify manually**
Navigate to any `capa_pending` incident → Add CAPA Action. Confirm all active users appear in the "Assigned To" dropdown.
- [ ] **Step 4: Commit**
```bash
git add "app/(protected)/hse/incidents/[id]/capa/new/page.tsx"
git commit -m "fix(capa): show all active users in Assigned To dropdown"
```
---
### Task 3: Split alcohol test and urine test into separate fields
**Root cause:** `investigations` table has one `alcohol_test_result` column covering both tests. UI has one dropdown. Need two separate columns and two separate dropdowns.
**Files:**
- Create: `supabase/migrations/20260717000001_split_drug_test_results.sql`
- Modify: `components/incidents/investigation-form.tsx`
- Modify: `app/api/incidents/[id]/investigation/route.ts`
- Modify: `components/incidents/incident-detail.tsx` (add display of both results)
**Interfaces:**
- POST/PATCH body gains: `urine_test_result: string | null`
- `InvestigationForm` gains internal state: `urineTest: string`
- `IncidentDetail` component reads `investigation.urine_test_result`
#### Step 3a: Migration
- [ ] **Step 1: Create migration file**
Create `supabase/migrations/20260717000001_split_drug_test_results.sql`:
```sql
-- Rename existing column to be explicit about alcohol-only
-- Then add urine_test_result alongside it
-- Existing data in alcohol_test_result is kept as-is (alcohol test result)
ALTER TABLE investigations
ADD COLUMN IF NOT EXISTS urine_test_result text
CHECK (urine_test_result IN ('negative','positive','refused','pending'));
```
Note: `alcohol_test_result` already exists with the same constraint values — no rename needed; just add the new column.
- [ ] **Step 2: Apply migration**
```bash
npx supabase db push
```
Expected: `20260717000001_split_drug_test_results` applied successfully.
- [ ] **Step 3: Commit migration**
```bash
git add supabase/migrations/20260717000001_split_drug_test_results.sql
git commit -m "feat(db): add urine_test_result column to investigations"
```
#### Step 3b: Update API route
- [ ] **Step 4: Update POST handler**
In `app/api/incidents/[id]/investigation/route.ts`, in the `POST` handler's `.insert({...})` block, add `urine_test_result` alongside `alcohol_test_result`:
```typescript
// BEFORE (around line 47)
alcohol_test_result: body.alcohol_test_result ?? null,
```
```typescript
// AFTER
alcohol_test_result: body.alcohol_test_result ?? null,
urine_test_result: body.urine_test_result ?? null,
```
- [ ] **Step 5: Update PATCH handler**
In the same file, in the `PATCH` handler's `updateData` object (around line 95):
```typescript
// BEFORE
alcohol_test_result: fields.alcohol_test_result ?? null,
```
```typescript
// AFTER
alcohol_test_result: fields.alcohol_test_result ?? null,
urine_test_result: fields.urine_test_result ?? null,
```
- [ ] **Step 6: Commit API changes**
```bash
git add app/api/incidents/[id]/investigation/route.ts
git commit -m "feat(api): accept urine_test_result in investigation POST/PATCH"
```
#### Step 3c: Update investigation form UI
- [ ] **Step 7: Split the single dropdown into two**
In `components/incidents/investigation-form.tsx`:
**Add state** (after `const [alcoholTest, setAlcoholTest] = useState('')` on line 40):
```typescript
const [alcoholTest, setAlcoholTest] = useState('')
const [urineTest, setUrineTest] = useState('')
```
**Update payload** in `handleSubmit` (around line 97):
```typescript
// BEFORE
alcohol_test_result: alcoholTest || null,
```
```typescript
// AFTER
alcohol_test_result: alcoholTest || null,
urine_test_result: urineTest || null,
```
**Replace the single dropdown UI** (around lines 215–227):
```tsx
// BEFORE
<div>
<label className="block text-sm font-medium text-gray-700 mb-1">Alcohol / Urine Test Result</label>
<select
value={alcoholTest}
onChange={e => setAlcoholTest(e.target.value)}
className="w-full rounded-lg border border-gray-300 px-3 py-2 text-sm"
>
<option value="">Not applicable / not conducted</option>
<option value="negative">Negative</option>
<option value="positive">Positive</option>
<option value="refused">Refused</option>
<option value="pending">Result pending</option>
</select>
</div>
```
```tsx
// AFTER
<div className="grid grid-cols-2 gap-3">
<div>
<label className="block text-sm font-medium text-gray-700 mb-1">Alcohol Test Result</label>
<select
value={alcoholTest}
onChange={e => setAlcoholTest(e.target.value)}
className="w-full rounded-lg border border-gray-300 px-3 py-2 text-sm"
>
<option value="">Not conducted</option>
<option value="negative">Negative</option>
<option value="positive">Positive</option>
<option value="refused">Refused</option>
<option value="pending">Result pending</option>
</select>
</div>
<div>
<label className="block text-sm font-medium text-gray-700 mb-1">Urine Test Result</label>
<select
value={urineTest}
onChange={e => setUrineTest(e.target.value)}
className="w-full rounded-lg border border-gray-300 px-3 py-2 text-sm"
>
<option value="">Not conducted</option>
<option value="negative">Negative</option>
<option value="positive">Positive</option>
<option value="refused">Refused</option>
<option value="pending">Result pending</option>
</select>
</div>
</div>
```
- [ ] **Step 8: Commit form changes**
```bash
git add components/incidents/investigation-form.tsx
git commit -m "feat(ui): split alcohol and urine test into separate dropdowns"
```
#### Step 3d: Add display in incident detail
The investigation results are currently not shown on the incident detail page. Add them.
- [ ] **Step 9: Locate the investigation section in incident-detail.tsx**
Open `components/incidents/incident-detail.tsx`. Find where `investigation` data is rendered (search for `investigation` or `alcohol`). If there is no investigation section, add one after the triage/medical section.
The `Incident` type in that file (around line 29) likely needs `investigation` added. Check the type and the `select` query in the page that loads this component.
- [ ] **Step 10: Update the Incident type and select query**
In the page that loads `IncidentDetail` (`app/(protected)/hse/incidents/[id]/page.tsx` and `app/(protected)/supervisor/incidents/[id]/page.tsx`), ensure the `investigations` join is selected and includes `alcohol_test_result, urine_test_result`. If not already joined:
```typescript
// In the supabase select for incident, add:
investigations ( alcohol_test_result, urine_test_result )
```
- [ ] **Step 11: Add display in incident-detail.tsx**
Add a `TEST_RESULT_LABELS` map and a display block. Insert after the medical status field:
```tsx
const TEST_RESULT_LABELS: Record<string, string> = {
negative: 'Negative',
positive: 'Positive',
refused: 'Refused',
pending: 'Result pending',
}
```
In the JSX, in the investigation section (or create one):
```tsx
{incident.investigations?.[0] && (
<>
{incident.investigations[0].alcohol_test_result && (
<Field
label="Alcohol test"
value={TEST_RESULT_LABELS[incident.investigations[0].alcohol_test_result] ?? incident.investigations[0].alcohol_test_result}
/>
)}
{incident.investigations[0].urine_test_result && (
<Field
label="Urine test"
value={TEST_RESULT_LABELS[incident.investigations[0].urine_test_result] ?? incident.investigations[0].urine_test_result}
/>
)}
</>
)}
```
- [ ] **Step 12: Commit display changes**
```bash
git add components/incidents/incident-detail.tsx
git commit -m "feat(ui): display alcohol and urine test results on incident detail"
```
---
## Self-Review
**Spec coverage:**
- ✅ Invite redirect: env guard added, no localhost fallback
- ✅ CAPA assigned to: query changed to all active users
- ✅ Drug test split: migration + API + form + display all covered
**Placeholder scan:** No TBD or placeholders present.
**Type consistency:** `urine_test_result` named consistently across migration, API route, form state, and display. `alcohol_test_result` unchanged.
**Note on Task 3, Step 9–10:** `incident-detail.tsx` structure depends on what the parent page currently selects and passes. The implementer must read `app/(protected)/hse/incidents/[id]/page.tsx` to see the actual Supabase select query and `Incident` type prop shape before editing `incident-detail.tsx`. The pattern to follow is already present in that file for other fields (e.g. `MEDICAL_LABELS`).
@@ -0,0 +1,400 @@
# Remove Invite-by-Email 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:** Remove the "Invite by email" mode from the admin user management panel, leaving only the direct-add (admin-set password) flow.
**Architecture:** Strip the mode toggle from the `UserManager` component and remove the invite branch from the POST handler in `app/api/admin/users/route.ts`. Delete the now-unreachable `app/auth/invite-callback/` page. No DB changes required.
**Tech Stack:** Next.js App Router, TypeScript, Vitest
## Global Constraints
- Never commit `.env` or API keys
- Every DB mutation writes to `audit_log` via `write_audit_log` RPC
- `basePath` is `/ims` — all internal links must carry this prefix
- Run `npm run build` and `npm test` before every commit; both must pass
---
### Task 1: Strip invite mode from UI component and API route
**Files:**
- Modify: `components/admin/user-manager.tsx`
- Modify: `app/api/admin/users/route.ts`
**Interfaces:**
- Consumes: nothing from other tasks
- Produces: `UserManager` with no mode toggle; POST `/api/admin/users` always requires `password`
- [ ] **Step 1: Update `components/admin/user-manager.tsx`**
Replace the entire file content:
```tsx
'use client'
import { useState } from 'react'
import { useRouter } from 'next/navigation'
import { ALL_ROLES, type UserRole } from '@/lib/auth/roles'
export type AdminUser = {
id: string
name: string
email: string
role: string
department: string | null
site_id: string | null
active: boolean
}
export type SiteOption = { id: string; name: string }
interface Props {
users: AdminUser[]
sites: SiteOption[]
}
const EMPTY_FORM = { email: '', name: '', phone: '', role: 'reporter' as UserRole, site_id: '', password: '' }
export function UserManager({ users, sites }: Props) {
const router = useRouter()
const [busyId, setBusyId] = useState<string | null>(null)
const [error, setError] = useState<string | null>(null)
const [form, setForm] = useState(EMPTY_FORM)
const [submitting, setSubmitting] = useState(false)
const [confirmDeleteId, setConfirmDeleteId] = useState<string | null>(null)
const patchUser = async (id: string, update: Record<string, unknown>) => {
setBusyId(id)
setError(null)
const res = await fetch('/ims/api/admin/users', {
method: 'PATCH',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ id, ...update }),
})
setBusyId(null)
if (!res.ok) {
const data = await res.json().catch(() => ({}))
setError(data.error ?? 'Update failed')
return
}
router.refresh()
}
const deleteUser = async (id: string) => {
setBusyId(id)
setError(null)
const res = await fetch(`/ims/api/admin/users?id=${encodeURIComponent(id)}`, { method: 'DELETE' })
setBusyId(null)
setConfirmDeleteId(null)
if (!res.ok) {
const data = await res.json().catch(() => ({}))
setError(data.error ?? 'Delete failed')
return
}
router.refresh()
}
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault()
setSubmitting(true)
setError(null)
const res = await fetch('/ims/api/admin/users', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
email: form.email,
name: form.name || undefined,
phone: form.phone || undefined,
role: form.role,
site_id: form.site_id || undefined,
password: form.password,
}),
})
setSubmitting(false)
if (!res.ok) {
const data = await res.json().catch(() => ({}))
setError(data.error ?? 'Add failed')
return
}
setForm(EMPTY_FORM)
router.refresh()
}
return (
<div className="bg-white rounded-xl shadow-sm p-5">
<h2 className="text-sm font-semibold text-gray-700 uppercase tracking-wide mb-4">Users</h2>
<form onSubmit={handleSubmit} className="flex flex-wrap gap-2 mb-5 items-end">
<input
type="email" required placeholder="email@company.com"
value={form.email}
onChange={e => setForm(v => ({ ...v, email: e.target.value }))}
className="border border-gray-300 rounded-lg px-3 py-2 text-sm w-52"
/>
<input
type="text" placeholder="Full name"
value={form.name}
onChange={e => setForm(v => ({ ...v, name: e.target.value }))}
className="border border-gray-300 rounded-lg px-3 py-2 text-sm w-40"
/>
<input
type="tel" placeholder="Phone (e.g. +60123456789)"
value={form.phone}
onChange={e => setForm(v => ({ ...v, phone: e.target.value }))}
className="border border-gray-300 rounded-lg px-3 py-2 text-sm w-44"
/>
<select
value={form.role}
onChange={e => setForm(v => ({ ...v, role: e.target.value as UserRole }))}
className="border border-gray-300 rounded-lg px-3 py-2 text-sm"
>
{ALL_ROLES.map(r => <option key={r} value={r}>{r.replace(/_/g, ' ')}</option>)}
</select>
<select
value={form.site_id}
onChange={e => setForm(v => ({ ...v, site_id: e.target.value }))}
className="border border-gray-300 rounded-lg px-3 py-2 text-sm"
>
<option value="">No site</option>
{sites.map(s => <option key={s.id} value={s.id}>{s.name}</option>)}
</select>
<input
type="password"
required
minLength={8}
placeholder="Password (min 8 chars)"
value={form.password}
onChange={e => setForm(v => ({ ...v, password: e.target.value }))}
className="border border-gray-300 rounded-lg px-3 py-2 text-sm w-48"
/>
<button
type="submit" disabled={submitting}
className="bg-blue-600 text-white rounded-lg px-4 py-2 text-sm font-semibold hover:bg-blue-700 disabled:opacity-50"
>
{submitting ? 'Adding…' : 'Add User'}
</button>
</form>
{error && <p className="text-sm text-red-600 mb-3">{error}</p>}
<div className="overflow-x-auto">
<table className="w-full text-sm">
<thead>
<tr className="text-left text-xs text-gray-500 uppercase tracking-wide border-b border-gray-100">
<th className="py-2 pr-3">Name</th>
<th className="py-2 pr-3">Email</th>
<th className="py-2 pr-3">Role</th>
<th className="py-2 pr-3">Site</th>
<th className="py-2">Status</th>
<th className="py-2"></th>
</tr>
</thead>
<tbody>
{users.map(u => (
<tr key={u.id} className={`border-b border-gray-50 ${u.active ? '' : 'opacity-50'}`}>
<td className="py-2 pr-3 text-gray-900">{u.name || '—'}</td>
<td className="py-2 pr-3 text-gray-600">{u.email}</td>
<td className="py-2 pr-3">
<select
value={u.role}
disabled={busyId === u.id}
onChange={e => patchUser(u.id, { role: e.target.value })}
className="border border-gray-200 rounded px-2 py-1 text-xs"
>
{ALL_ROLES.map(r => <option key={r} value={r}>{r.replace(/_/g, ' ')}</option>)}
</select>
</td>
<td className="py-2 pr-3">
<select
value={u.site_id ?? ''}
disabled={busyId === u.id}
onChange={e => patchUser(u.id, { site_id: e.target.value || null })}
className="border border-gray-200 rounded px-2 py-1 text-xs"
>
<option value="">No site</option>
{sites.map(s => <option key={s.id} value={s.id}>{s.name}</option>)}
</select>
</td>
<td className="py-2">
<button
disabled={busyId === u.id}
onClick={() => patchUser(u.id, { active: !u.active })}
className={`text-xs px-2 py-1 rounded-full font-medium ${
u.active ? 'bg-green-100 text-green-700' : 'bg-gray-100 text-gray-500'
}`}
>
{u.active ? 'Active' : 'Deactivated'}
</button>
</td>
<td className="py-2">
{confirmDeleteId === u.id ? (
<span className="flex items-center gap-1">
<span className="text-xs text-red-600 font-medium">Sure?</span>
<button
disabled={busyId === u.id}
onClick={() => deleteUser(u.id)}
className="text-xs px-2 py-0.5 rounded bg-red-600 text-white font-medium hover:bg-red-700"
>
{busyId === u.id ? '…' : 'Yes'}
</button>
<button
disabled={busyId === u.id}
onClick={() => setConfirmDeleteId(null)}
className="text-xs px-2 py-0.5 rounded border border-gray-300 text-gray-600 hover:bg-gray-50"
>
No
</button>
</span>
) : (
<button
disabled={busyId === u.id}
onClick={() => setConfirmDeleteId(u.id)}
className="text-xs px-2 py-1 rounded text-red-600 hover:bg-red-50 font-medium"
>
Delete
</button>
)}
</td>
</tr>
))}
</tbody>
</table>
</div>
</div>
)
}
```
- [ ] **Step 2: Update `app/api/admin/users/route.ts` POST handler**
Replace only the `POST` function (lines 21–104) with:
```ts
export async function POST(request: NextRequest) {
const { supabase, user } = await requireAdmin()
if (!user) return NextResponse.json({ error: 'Forbidden' }, { status: 403 })
const body: { email?: string; name?: string; phone?: string; role?: string; site_id?: string; password?: string } =
await request.json().catch(() => ({}))
const email = (body.email ?? '').trim().toLowerCase()
if (!email || !email.includes('@'))
return NextResponse.json({ error: 'Valid email required' }, { status: 422 })
if (body.role && !isValidRole(body.role))
return NextResponse.json({ error: 'Invalid role' }, { status: 422 })
const password = (body.password ?? '').trim()
if (!password)
return NextResponse.json({ error: 'Password required' }, { status: 422 })
if (password.length < 8)
return NextResponse.json({ error: 'Password must be at least 8 characters' }, { status: 422 })
let admin
try {
admin = createAdminClient()
} catch {
return NextResponse.json(
{ error: 'User creation unavailable: SUPABASE_SERVICE_ROLE_KEY not configured' },
{ status: 503 },
)
}
const { data: created, error: createError } = await admin.auth.admin.createUser({
email,
password,
email_confirm: true,
user_metadata: { full_name: body.name ?? '' },
})
if (createError || !created?.user)
return NextResponse.json(
{ error: createError?.message ?? 'User creation failed' },
{ status: (createError as { status?: number } | null)?.status ?? 500 },
)
const newUserId = created.user.id
const { error: profileError } = await admin
.from('users')
.update({
name: body.name ?? '',
phone: (body.phone ?? '').trim() || null,
role: body.role ?? 'reporter',
site_id: body.site_id ?? null,
})
.eq('id', newUserId)
if (profileError)
return NextResponse.json(
{ error: 'User created but profile update failed' },
{ status: 500 },
)
await supabase.rpc('write_audit_log', {
p_table_name: 'users',
p_record_id: newUserId,
p_action: 'created',
p_new_value: { email, role: body.role ?? 'reporter', site_id: body.site_id ?? null },
})
return NextResponse.json({ id: newUserId }, { status: 201 })
}
```
- [ ] **Step 3: Run tests and build**
```bash
npm test
npm run build
```
Expected: all tests pass, build succeeds with no TypeScript errors.
- [ ] **Step 4: Commit**
```bash
git add components/admin/user-manager.tsx app/api/admin/users/route.ts
git commit -m "feat(admin): remove invite-by-email, direct-add only"
```
---
### Task 2: Delete invite-callback page
**Files:**
- Delete: `app/auth/invite-callback/page.tsx`
- Delete: `app/auth/invite-callback/` (directory)
**Interfaces:**
- Consumes: nothing
- Produces: route `/auth/invite-callback` no longer exists
- [ ] **Step 1: Delete the callback directory**
```bash
rm -rf app/auth/invite-callback
```
- [ ] **Step 2: Verify `app/auth/` is now empty (or remove it too)**
```bash
ls app/auth/
```
If the directory is empty, remove it:
```bash
rmdir app/auth
```
- [ ] **Step 3: Run build to confirm no dangling imports**
```bash
npm run build
```
Expected: build succeeds. No file anywhere imports from `app/auth/invite-callback`.
- [ ] **Step 4: Commit**
```bash
git add -A
git commit -m "chore: delete invite-callback page"
```
@@ -0,0 +1,328 @@
# 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
@@ -0,0 +1,141 @@
# CAPA Status Bugs 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:** Fix two CAPA bugs — incident status not advancing to `capa_pending` on CAPA creation, and overdue CAPAs not appearing in the overdue column.
**Architecture:** Bug 1 requires a single `UPDATE incidents SET status='capa_pending'` inside the existing CAPA POST transaction. Bug 2 is already fixed in code (overdue computed at API fetch time); it only needs deployment.
**Tech Stack:** Next.js App Router, Drizzle ORM, PostgreSQL, `withUser` + `writeAuditLog` pattern.
## Global Constraints
- Every DB mutation must call `writeAuditLog(tx, ...)` in the same transaction.
- RLS via `withUser(session.sub, tx => ...)` — never raw pool queries.
- No `.env` or secrets committed.
- Project root: `/Users/yapweeihan/Desktop/Projects/IMS.nosync`
---
### Task 1: Update incident status to `capa_pending` on CAPA creation
**Files:**
- Modify: `app/api/capa/route.ts:88-108`
**Interfaces:**
- Consumes: `incidents` Drizzle table from `@/lib/db/schema`, `and`, `eq` from `drizzle-orm`, `writeAuditLog` already imported
- Produces: incident `status` updated to `'capa_pending'` when current status is `'investigating'`
**Why conditional (`eq(incidents.status, 'investigating')`):** If HSE adds a second CAPA later (status already `capa_pending`), or incident is in `verification`/`closed`, the update must be a no-op. Only advance from `investigating` → `capa_pending`.
- [ ] **Step 1: Add `and` to drizzle-orm import and `incidents` already imported — verify**
Open `app/api/capa/route.ts` line 8. Current:
```typescript
import { aliasedTable, eq, asc } from 'drizzle-orm'
```
Change to:
```typescript
import { aliasedTable, eq, asc, and } from 'drizzle-orm'
```
- [ ] **Step 2: Add incident status update inside the transaction**
In `app/api/capa/route.ts`, inside the `withUser` block (after line 107, before the closing `}`), add:
```typescript
await tx
.update(incidents)
.set({ status: 'capa_pending' })
.where(and(eq(incidents.id, incident_id), eq(incidents.status, 'investigating')))
await writeAuditLog(tx, 'incidents', incident_id, 'status_changed', {
status: 'capa_pending',
})
```
Full updated `withUser` block for reference:
```typescript
await withUser(session.sub, async tx => {
const [capa] = await tx
.insert(capaActions)
.values({
incidentId: incident_id,
description,
ownerUserId: owner_user_id,
department: department || '',
dueDate: due_date,
priority: priority ?? 'med',
rootCauseRef: root_cause_ref ?? null,
})
.returning({ id: capaActions.id })
if (!capa) throw new Error('Insert failed')
capaId = capa.id
await writeAuditLog(tx, 'capa_actions', capa.id, 'created', {
incident_id, description, owner_user_id, department, due_date,
})
await tx
.update(incidents)
.set({ status: 'capa_pending' })
.where(and(eq(incidents.id, incident_id), eq(incidents.status, 'investigating')))
await writeAuditLog(tx, 'incidents', incident_id, 'status_changed', {
status: 'capa_pending',
})
})
```
- [ ] **Step 3: Build to verify no TypeScript errors**
```bash
cd /Users/yapweeihan/Desktop/Projects/IMS.nosync && npm run build 2>&1 | tail -20
```
Expected: `✓ Compiled successfully` with zero errors.
- [ ] **Step 4: Commit**
```bash
git add app/api/capa/route.ts
git commit -m "fix(capa): advance incident status to capa_pending on CAPA creation"
```
---
### Task 2: Verify overdue fix and deploy both fixes
**Files:**
- No code changes needed — overdue fix is already in `app/api/capa/route.ts:60-62`
- Deploy via `bash deploy.sh`
**Context:** The GET handler already computes `status: 'overdue'` at response time when `status` is `open`/`in_progress` AND `due_date < today`. The `capa-board.tsx` buckets by `c.status === 'overdue'` so it will pick these up correctly once deployed.
- [ ] **Step 1: Confirm overdue fix is present**
```bash
grep -n "overdue" /Users/yapweeihan/Desktop/Projects/IMS.nosync/app/api/capa/route.ts
```
Expected output includes line ~60: `? 'overdue'`
- [ ] **Step 2: Deploy**
Run from local machine (Claude cannot SSH):
```bash
cd /Users/yapweeihan/Desktop/Projects/IMS.nosync && bash deploy.sh
```
Expected: rsync completes, `systemctl restart ims` succeeds.
- [ ] **Step 3: Smoke test Bug 1 — incident status**
1. Open an incident currently in `investigating` status.
2. Add a new CAPA via the CAPA new form.
3. Reload the incident detail page.
4. Verify incident status badge shows `capa_pending`.
- [ ] **Step 4: Smoke test Bug 2 — overdue column**
1. Open the CAPA board (`/hse/capa`).
2. Any CAPA with `status = open` or `in_progress` and `due_date` in the past should appear in the **Overdue** column.
3. Verify the count badge on the Overdue column is non-zero if such CAPAs exist.
@@ -0,0 +1,811 @@
# Incident Report PDF 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 a "Print Report" button on closed incidents that generates and downloads a comprehensive PDF covering all incident sections.
**Architecture:** Three-layer: a pure PDF builder function (`lib/pdf/incident-report.ts`), a new API route (`app/api/incidents/[id]/report-pdf/route.ts`) that fetches all data and streams the PDF, and a button added to the HSE incident detail page visible only when `status === 'closed'`. Follows the exact same pattern as `lib/pdf/jkkp.ts` + `app/api/incidents/[id]/jkkp-pdf/route.ts`.
**Tech Stack:** pdf-lib (already installed), Drizzle ORM (`withUser`), Next.js App Router API route, TypeScript.
## Global Constraints
- Every DB query goes through `withUser(session.sub, tx => ...)` for RLS (not `asAdmin` — the viewer must be permitted to see the incident).
- No `.env` or secrets committed.
- Access restricted to roles `hse` and `admin` only (same as JKKP PDF route).
- `pdf-lib` is already in `package.json` — do not add new dependencies.
- Project root: `/Users/yapweeihan/Desktop/Projects/IMS.nosync`
- PDF must only be generated when `incident.status === 'closed'`; return 403 otherwise.
- Audit log: no audit entry needed for PDF download (read-only operation).
---
### Task 1: Pure PDF builder — `lib/pdf/incident-report.ts`
**Files:**
- Create: `lib/pdf/incident-report.ts`
- Create: `tests/lib/pdf/incident-report.test.ts`
**Interfaces:**
- Produces: `buildIncidentReportPdf(data: IncidentReportData): Promise<Uint8Array>`
- Produces type: `IncidentReportData` (imported by Task 2's route)
**PDF sections (in order):**
1. Header — title "INCIDENT INVESTIGATION REPORT", reference no, generated date
2. Incident Details — type, date, site, zone, reporter, severity, medical status, description
3. Triage — notes, triaged by, triaged at (skip section if `triagedBy` is null)
4. Investigation — method, findings text, root cause summary, alcohol test, urine test
5. CAPA Actions — one block per CAPA: description, owner, department, due date, priority, status, owner notes
6. Addenda — one block per addendum: author, date, body
7. Closure — closed at timestamp
8. Footer — "Generated by IMS — Confidential"
- [ ] **Step 1: Write the failing test**
Create `tests/lib/pdf/incident-report.test.ts`:
```typescript
import { describe, it, expect } from 'vitest'
import { buildIncidentReportPdf, type IncidentReportData } from '@/lib/pdf/incident-report'
const MOCK: IncidentReportData = {
referenceNo: 'SC1-202607-0001',
incidentType: 'injury',
reportedAt: '2026-07-01T08:00:00.000Z',
siteName: 'Setia Warehouse KL',
zoneName: 'Loading Bay A',
reporterName: 'Ahmad Bin Ali',
severity: 3,
medicalStatus: 'first_aid',
description: 'Worker slipped on wet floor near loading bay.',
injuryInvolved: true,
assetInvolved: false,
isFatality: false,
isSeriousBodilyInjury: false,
isDangerousOccurrence: false,
isOccupationalDisease: false,
lostDays: null,
triagedBy: 'Supervisor Tan',
triagedAt: '2026-07-01T10:00:00.000Z',
triageNotes: 'Reviewed on-site. First aid applied.',
investigation: {
method: 'five_why',
findingsText: 'Floor was wet due to a leaking pipe.',
rootCauseSummary: 'Maintenance backlog on pipe inspection.',
alcoholTestResult: 'negative',
urineTestResult: 'negative',
},
capas: [
{
description: 'Install non-slip mats in loading bay.',
ownerName: 'Maintenance Dept',
department: 'Maintenance',
dueDate: '2026-07-15',
priority: 'high',
status: 'closed',
completedAt: '2026-07-14T09:00:00.000Z',
ownerNotes: 'Mats installed and inspected.',
},
],
addenda: [
{
authorName: 'HSE Officer Lim',
createdAt: '2026-07-20T14:00:00.000Z',
body: 'Follow-up inspection passed. Area cleared.',
},
],
closedAt: '2026-07-20T15:00:00.000Z',
}
describe('buildIncidentReportPdf', () => {
it('returns a Uint8Array starting with PDF magic bytes', async () => {
const result = await buildIncidentReportPdf(MOCK)
expect(result).toBeInstanceOf(Uint8Array)
// PDF files start with %PDF
const header = String.fromCharCode(...result.slice(0, 4))
expect(header).toBe('%PDF')
})
it('handles incident with no investigation, CAPAs, or addenda', async () => {
const minimal: IncidentReportData = {
...MOCK,
triagedBy: null,
triagedAt: null,
triageNotes: null,
investigation: null,
capas: [],
addenda: [],
}
const result = await buildIncidentReportPdf(minimal)
expect(result).toBeInstanceOf(Uint8Array)
const header = String.fromCharCode(...result.slice(0, 4))
expect(header).toBe('%PDF')
})
})
```
- [ ] **Step 2: Run test — verify it fails**
```bash
cd /Users/yapweeihan/Desktop/Projects/IMS.nosync && npx vitest run tests/lib/pdf/incident-report.test.ts
```
Expected: FAIL — `Cannot find module '@/lib/pdf/incident-report'`
- [ ] **Step 3: Implement `lib/pdf/incident-report.ts`**
```typescript
import { PDFDocument, StandardFonts, rgb } from 'pdf-lib'
export type IncidentReportData = {
referenceNo: string | null
incidentType: string
reportedAt: string
siteName: string
zoneName: string | null
reporterName: string
severity: number | null
medicalStatus: string | null
description: string
injuryInvolved: boolean
assetInvolved: boolean
isFatality: boolean
isSeriousBodilyInjury: boolean
isDangerousOccurrence: boolean
isOccupationalDisease: boolean
lostDays: number | null
triagedBy: string | null
triagedAt: string | null
triageNotes: string | null
investigation: {
method: string
findingsText: string | null
rootCauseSummary: string | null
alcoholTestResult: string | null
urineTestResult: string | null
} | null
capas: Array<{
description: string
ownerName: string
department: string
dueDate: string
priority: string
status: string
completedAt: string | null
ownerNotes: string | null
}>
addenda: Array<{
authorName: string
createdAt: string
body: string
}>
closedAt: string | null
}
type EmbeddedFont = Awaited<ReturnType<PDFDocument['embedFont']>>
type Page = ReturnType<PDFDocument['addPage']>
const MARGIN = 50
const PAGE_WIDTH = 595
const PAGE_HEIGHT = 842
const BODY_FONT_SIZE = 10
const LABEL_FONT_SIZE = 9
const SECTION_FONT_SIZE = 11
const LINE_HEIGHT = 16
const SECTION_GAP = 20
const BOTTOM_MARGIN = 60
type State = {
doc: PDFDocument
pages: Page[]
font: EmbeddedFont
boldFont: EmbeddedFont
y: number
}
function currentPage(state: State): Page {
return state.pages[state.pages.length - 1]
}
function newPage(state: State): void {
const page = state.doc.addPage([PAGE_WIDTH, PAGE_HEIGHT])
state.pages.push(page)
state.y = PAGE_HEIGHT - MARGIN
}
function ensureSpace(state: State, needed: number): void {
if (state.y - needed < BOTTOM_MARGIN) newPage(state)
}
function wrapText(text: string, maxWidth: number, font: EmbeddedFont, size: number): string[] {
const words = text.split(' ')
const lines: string[] = []
let current = ''
for (const word of words) {
const test = current ? `${current} ${word}` : word
if (font.widthOfTextAtSize(test, size) > maxWidth && current) {
lines.push(current)
current = word
} else {
current = test
}
}
if (current) lines.push(current)
return lines.length ? lines : ['']
}
function drawSection(state: State, title: string): void {
ensureSpace(state, SECTION_GAP + LINE_HEIGHT + 6)
state.y -= SECTION_GAP
currentPage(state).drawRectangle({
x: MARGIN, y: state.y - 4,
width: PAGE_WIDTH - MARGIN * 2, height: LINE_HEIGHT + 4,
color: rgb(0.9, 0.95, 0.9),
})
currentPage(state).drawText(title.toUpperCase(), {
x: MARGIN + 4, y: state.y,
size: SECTION_FONT_SIZE, font: state.boldFont, color: rgb(0.05, 0.4, 0.1),
})
state.y -= LINE_HEIGHT + 8
}
function drawField(state: State, label: string, value: string | null): void {
const v = value ?? '—'
const maxW = PAGE_WIDTH - MARGIN * 2 - 120
const lines = wrapText(v, maxW, state.font, BODY_FONT_SIZE)
ensureSpace(state, (lines.length + 1) * LINE_HEIGHT)
currentPage(state).drawText(label + ':', {
x: MARGIN, y: state.y,
size: LABEL_FONT_SIZE, font: state.boldFont, color: rgb(0.3, 0.3, 0.3),
})
for (const line of lines) {
currentPage(state).drawText(line, {
x: MARGIN + 120, y: state.y,
size: BODY_FONT_SIZE, font: state.font, color: rgb(0, 0, 0),
})
state.y -= LINE_HEIGHT
}
if (lines.length === 0) state.y -= LINE_HEIGHT
}
function fmt(iso: string | null): string {
if (!iso) return '—'
return new Date(iso).toLocaleString('en-MY', { timeZone: 'Asia/Kuala_Lumpur', hour12: false })
}
function fmtDate(iso: string | null): string {
if (!iso) return '—'
return new Date(iso).toLocaleDateString('en-MY', { timeZone: 'Asia/Kuala_Lumpur' })
}
export async function buildIncidentReportPdf(data: IncidentReportData): Promise<Uint8Array> {
const doc = await PDFDocument.create()
const font = await doc.embedFont(StandardFonts.Helvetica)
const boldFont = await doc.embedFont(StandardFonts.HelveticaBold)
const firstPage = doc.addPage([PAGE_WIDTH, PAGE_HEIGHT])
const state: State = { doc, pages: [firstPage], font, boldFont, y: PAGE_HEIGHT - MARGIN }
// ── Header ──────────────────────────────────────────────────────────────
currentPage(state).drawText('INCIDENT INVESTIGATION REPORT', {
x: MARGIN, y: state.y,
size: 16, font: boldFont, color: rgb(0.05, 0.4, 0.1),
})
state.y -= 22
currentPage(state).drawText(`Reference: ${data.referenceNo ?? '—'}`, {
x: MARGIN, y: state.y,
size: 10, font, color: rgb(0.2, 0.2, 0.2),
})
currentPage(state).drawText(`Generated: ${fmt(new Date().toISOString())}`, {
x: PAGE_WIDTH - MARGIN - 160, y: state.y,
size: 10, font, color: rgb(0.2, 0.2, 0.2),
})
state.y -= 6
currentPage(state).drawLine({
start: { x: MARGIN, y: state.y },
end: { x: PAGE_WIDTH - MARGIN, y: state.y },
thickness: 1.5, color: rgb(0.05, 0.4, 0.1),
})
state.y -= 12
// ── Incident Details ─────────────────────────────────────────────────────
drawSection(state, 'Incident Details')
drawField(state, 'Type', data.incidentType.replace(/_/g, ' '))
drawField(state, 'Reported At', fmt(data.reportedAt))
drawField(state, 'Site', data.siteName)
drawField(state, 'Zone', data.zoneName)
drawField(state, 'Reported By', data.reporterName)
drawField(state, 'Severity', data.severity !== null ? String(data.severity) + ' / 5' : null)
drawField(state, 'Medical Status', data.medicalStatus?.replace(/_/g, ' ') ?? null)
drawField(state, 'Injury Involved', data.injuryInvolved ? 'Yes' : 'No')
drawField(state, 'Asset Involved', data.assetInvolved ? 'Yes' : 'No')
drawField(state, 'Fatality', data.isFatality ? 'Yes' : 'No')
drawField(state, 'Serious Bodily Injury', data.isSeriousBodilyInjury ? 'Yes' : 'No')
drawField(state, 'Dangerous Occurrence', data.isDangerousOccurrence ? 'Yes' : 'No')
drawField(state, 'Occupational Disease', data.isOccupationalDisease ? 'Yes' : 'No')
drawField(state, 'Lost Days', data.lostDays !== null ? String(data.lostDays) : null)
drawField(state, 'Description', data.description)
// ── Triage ───────────────────────────────────────────────────────────────
if (data.triagedBy) {
drawSection(state, 'Triage')
drawField(state, 'Triaged By', data.triagedBy)
drawField(state, 'Triaged At', fmt(data.triagedAt))
drawField(state, 'Triage Notes', data.triageNotes)
}
// ── Investigation ────────────────────────────────────────────────────────
if (data.investigation) {
const inv = data.investigation
drawSection(state, 'Investigation')
drawField(state, 'Method', inv.method.replace(/_/g, ' '))
drawField(state, 'Findings', inv.findingsText)
drawField(state, 'Root Cause', inv.rootCauseSummary)
drawField(state, 'Alcohol Test', inv.alcoholTestResult)
drawField(state, 'Urine Test', inv.urineTestResult)
}
// ── CAPA Actions ─────────────────────────────────────────────────────────
if (data.capas.length > 0) {
drawSection(state, `CAPA Actions (${data.capas.length})`)
for (let i = 0; i < data.capas.length; i++) {
const c = data.capas[i]
ensureSpace(state, LINE_HEIGHT)
currentPage(state).drawText(`#${i + 1}`, {
x: MARGIN, y: state.y,
size: BODY_FONT_SIZE, font: boldFont, color: rgb(0, 0, 0),
})
state.y -= LINE_HEIGHT
drawField(state, 'Action', c.description)
drawField(state, 'Owner', c.ownerName)
drawField(state, 'Department', c.department)
drawField(state, 'Due Date', fmtDate(c.dueDate))
drawField(state, 'Priority', c.priority.toUpperCase())
drawField(state, 'Status', c.status.replace(/_/g, ' '))
if (c.completedAt) drawField(state, 'Completed At', fmt(c.completedAt))
if (c.ownerNotes) drawField(state, 'Owner Notes', c.ownerNotes)
state.y -= 8
}
}
// ── Addenda ──────────────────────────────────────────────────────────────
if (data.addenda.length > 0) {
drawSection(state, `Addenda (${data.addenda.length})`)
for (const a of data.addenda) {
drawField(state, 'Author', a.authorName)
drawField(state, 'Date', fmt(a.createdAt))
drawField(state, 'Note', a.body)
state.y -= 8
}
}
// ── Closure ──────────────────────────────────────────────────────────────
drawSection(state, 'Closure')
drawField(state, 'Closed At', fmt(data.closedAt))
// ── Footer on all pages ──────────────────────────────────────────────────
for (const page of state.pages) {
page.drawText('Generated by IMS — Confidential', {
x: MARGIN, y: 30,
size: 8, font, color: rgb(0.5, 0.5, 0.5),
})
page.drawLine({
start: { x: MARGIN, y: 42 },
end: { x: PAGE_WIDTH - MARGIN, y: 42 },
thickness: 0.5, color: rgb(0.8, 0.8, 0.8),
})
}
return doc.save()
}
```
- [ ] **Step 4: Run test — verify it passes**
```bash
cd /Users/yapweeihan/Desktop/Projects/IMS.nosync && npx vitest run tests/lib/pdf/incident-report.test.ts
```
Expected: PASS — 2 tests pass
- [ ] **Step 5: Commit**
```bash
git add lib/pdf/incident-report.ts tests/lib/pdf/incident-report.test.ts
git commit -m "feat(pdf): add incident report PDF builder"
```
---
### Task 2: API route — `app/api/incidents/[id]/report-pdf/route.ts`
**Files:**
- Create: `app/api/incidents/[id]/report-pdf/route.ts`
**Interfaces:**
- Consumes: `buildIncidentReportPdf`, `IncidentReportData` from `@/lib/pdf/incident-report`
- Consumes: Drizzle tables: `incidents`, `sites`, `zones`, `users`, `investigations`, `capaActions`, `incidentAddenda`
- Produces: `GET /api/incidents/[id]/report-pdf` → `application/pdf` download (or 401/403/404/400)
**Access rules:**
- Session required (401 if missing)
- Roles `hse` and `admin` only (403 otherwise)
- Incident must exist (404 if not)
- Incident must have `status === 'closed'` (400 with `{ error: 'Incident is not closed' }` otherwise)
- [ ] **Step 1: Write the failing test**
Create `tests/app/api/incidents/report-pdf.test.ts`:
```typescript
import { describe, it, expect, vi, beforeEach } from 'vitest'
// Mock auth
vi.mock('@/lib/auth/get-session', () => ({
getSession: vi.fn(),
}))
// Mock db
vi.mock('@/lib/db/with-user', () => ({
withUser: vi.fn(),
}))
// Mock pdf builder
vi.mock('@/lib/pdf/incident-report', () => ({
buildIncidentReportPdf: vi.fn().mockResolvedValue(new Uint8Array([37, 80, 68, 70])), // %PDF
}))
import { GET } from '@/app/api/incidents/[id]/report-pdf/route'
import { getSession } from '@/lib/auth/get-session'
import { withUser } from '@/lib/db/with-user'
import { buildIncidentReportPdf } from '@/lib/pdf/incident-report'
import { NextRequest } from 'next/server'
const mockSession = { sub: 'user-1', role: 'hse' as const }
const MOCK_INCIDENT = {
id: 'inc-1',
referenceNo: 'SC1-202607-0001',
incidentType: 'injury',
reportedAt: new Date('2026-07-01T08:00:00Z'),
status: 'closed',
siteName: 'Warehouse KL',
zoneName: 'Bay A',
reporterName: 'Ahmad',
severity: 3,
medicalStatus: 'first_aid',
description: 'Slip and fall',
injuryInvolved: true,
assetInvolved: false,
isFatality: false,
isSeriousBodilyInjury: false,
isDangerousOccurrence: false,
isOccupationalDisease: false,
lostDays: null,
triagedBy: 'Supervisor',
triagedAt: new Date('2026-07-01T10:00:00Z'),
triageNotes: 'Reviewed',
closedAt: new Date('2026-07-20T15:00:00Z'),
}
function makeRequest(id: string) {
return new NextRequest(`http://localhost/api/incidents/${id}/report-pdf`)
}
beforeEach(() => {
vi.clearAllMocks()
})
describe('GET /api/incidents/[id]/report-pdf', () => {
it('returns 401 when not authenticated', async () => {
vi.mocked(getSession).mockResolvedValue(null)
const res = await GET(makeRequest('inc-1'), { params: Promise.resolve({ id: 'inc-1' }) })
expect(res.status).toBe(401)
})
it('returns 403 for non-hse/admin roles', async () => {
vi.mocked(getSession).mockResolvedValue({ ...mockSession, role: 'reporter' as never })
const res = await GET(makeRequest('inc-1'), { params: Promise.resolve({ id: 'inc-1' }) })
expect(res.status).toBe(403)
})
it('returns 404 when incident not found', async () => {
vi.mocked(getSession).mockResolvedValue(mockSession)
vi.mocked(withUser).mockResolvedValue([[], [], [], []])
const res = await GET(makeRequest('inc-1'), { params: Promise.resolve({ id: 'inc-1' }) })
expect(res.status).toBe(404)
})
it('returns 400 when incident is not closed', async () => {
vi.mocked(getSession).mockResolvedValue(mockSession)
vi.mocked(withUser).mockResolvedValue([[{ ...MOCK_INCIDENT, status: 'investigating' }], [], [], []])
const res = await GET(makeRequest('inc-1'), { params: Promise.resolve({ id: 'inc-1' }) })
expect(res.status).toBe(400)
})
it('returns PDF with correct headers for a closed incident', async () => {
vi.mocked(getSession).mockResolvedValue(mockSession)
vi.mocked(withUser).mockResolvedValue([[MOCK_INCIDENT], [], [], []])
const res = await GET(makeRequest('inc-1'), { params: Promise.resolve({ id: 'inc-1' }) })
expect(res.status).toBe(200)
expect(res.headers.get('Content-Type')).toBe('application/pdf')
expect(res.headers.get('Content-Disposition')).toContain('SC1-202607-0001')
expect(buildIncidentReportPdf).toHaveBeenCalledOnce()
})
})
```
- [ ] **Step 2: Run test — verify it fails**
```bash
cd /Users/yapweeihan/Desktop/Projects/IMS.nosync && npx vitest run tests/app/api/incidents/report-pdf.test.ts
```
Expected: FAIL — `Cannot find module '@/app/api/incidents/[id]/report-pdf/route'`
- [ ] **Step 3: Implement the route**
Create `app/api/incidents/[id]/report-pdf/route.ts`:
```typescript
export const dynamic = 'force-dynamic'
import { NextRequest, NextResponse } from 'next/server'
import { aliasedTable, eq } from 'drizzle-orm'
import { getSession } from '@/lib/auth/get-session'
import { withUser } from '@/lib/db/with-user'
import { incidents, sites, zones, users, investigations, capaActions, incidentAddenda } from '@/lib/db/schema'
import { buildIncidentReportPdf } from '@/lib/pdf/incident-report'
export async function GET(
_req: NextRequest,
{ params }: { params: Promise<{ id: string }> }
) {
const { id } = await params
const session = await getSession()
if (!session) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
if (!['hse', 'admin'].includes(session.role))
return NextResponse.json({ error: 'Forbidden' }, { status: 403 })
const reporterAlias = aliasedTable(users, 'reporter')
const triagedByAlias = aliasedTable(users, 'triaged_by_user')
const ownerAlias = aliasedTable(users, 'capa_owner')
const addendaAuthorAlias = aliasedTable(users, 'addenda_author')
const [incidentRows, investigationRows, capaRows, addendaRows] = await withUser(
session.sub,
async tx => Promise.all([
tx.select({
id: incidents.id,
referenceNo: incidents.referenceNo,
incidentType: incidents.incidentType,
reportedAt: incidents.reportedAt,
status: incidents.status,
siteName: sites.name,
zoneName: zones.name,
reporterName: reporterAlias.name,
severity: incidents.severity,
medicalStatus: incidents.medicalStatus,
description: incidents.description,
injuryInvolved: incidents.injuryInvolved,
assetInvolved: incidents.assetInvolved,
isFatality: incidents.isFatality,
isSeriousBodilyInjury: incidents.isSeriousBodilyInjury,
isDangerousOccurrence: incidents.isDangerousOccurrence,
isOccupationalDisease: incidents.isOccupationalDisease,
lostDays: incidents.lostDays,
triagedByName: triagedByAlias.name,
triagedAt: incidents.triagedAt,
triageNotes: incidents.triageNotes,
closedAt: incidents.closedAt,
})
.from(incidents)
.leftJoin(sites, eq(incidents.siteId, sites.id))
.leftJoin(zones, eq(incidents.zoneId, zones.id))
.leftJoin(reporterAlias, eq(incidents.reportedBy, reporterAlias.id))
.leftJoin(triagedByAlias, eq(incidents.triagedBy, triagedByAlias.id))
.where(eq(incidents.id, id))
.limit(1),
tx.select({
method: investigations.method,
findingsText: investigations.findingsText,
rootCauseSummary: investigations.rootCauseSummary,
alcoholTestResult: investigations.alcoholTestResult,
urineTestResult: investigations.urineTestResult,
})
.from(investigations)
.where(eq(investigations.incidentId, id))
.limit(1),
tx.select({
description: capaActions.description,
ownerName: ownerAlias.name,
department: capaActions.department,
dueDate: capaActions.dueDate,
priority: capaActions.priority,
status: capaActions.status,
completedAt: capaActions.completedAt,
ownerNotes: capaActions.ownerNotes,
})
.from(capaActions)
.leftJoin(ownerAlias, eq(capaActions.ownerUserId, ownerAlias.id))
.where(eq(capaActions.incidentId, id)),
tx.select({
body: incidentAddenda.body,
createdAt: incidentAddenda.createdAt,
authorName: addendaAuthorAlias.name,
})
.from(incidentAddenda)
.leftJoin(addendaAuthorAlias, eq(incidentAddenda.author, addendaAuthorAlias.id))
.where(eq(incidentAddenda.incidentId, id)),
])
)
const incident = incidentRows[0]
if (!incident) return NextResponse.json({ error: 'Not found' }, { status: 404 })
if (incident.status !== 'closed')
return NextResponse.json({ error: 'Incident is not closed' }, { status: 400 })
const inv = investigationRows[0] ?? null
const pdfBytes = await buildIncidentReportPdf({
referenceNo: incident.referenceNo,
incidentType: incident.incidentType,
reportedAt: incident.reportedAt instanceof Date ? incident.reportedAt.toISOString() : (incident.reportedAt as string),
siteName: incident.siteName ?? 'Unknown',
zoneName: incident.zoneName ?? null,
reporterName: incident.reporterName ?? 'Unknown',
severity: incident.severity ?? null,
medicalStatus: incident.medicalStatus ?? null,
description: incident.description,
injuryInvolved: incident.injuryInvolved,
assetInvolved: incident.assetInvolved,
isFatality: incident.isFatality,
isSeriousBodilyInjury: incident.isSeriousBodilyInjury,
isDangerousOccurrence: incident.isDangerousOccurrence,
isOccupationalDisease: incident.isOccupationalDisease,
lostDays: incident.lostDays ?? null,
triagedBy: incident.triagedByName ?? null,
triagedAt: incident.triagedAt instanceof Date ? incident.triagedAt.toISOString() : (incident.triagedAt as string | null),
triageNotes: incident.triageNotes ?? null,
investigation: inv ? {
method: inv.method,
findingsText: inv.findingsText ?? null,
rootCauseSummary: inv.rootCauseSummary ?? null,
alcoholTestResult: inv.alcoholTestResult ?? null,
urineTestResult: inv.urineTestResult ?? null,
} : null,
capas: capaRows.map(c => ({
description: c.description,
ownerName: c.ownerName ?? 'Unknown',
department: c.department,
dueDate: c.dueDate,
priority: c.priority,
status: c.status,
completedAt: c.completedAt instanceof Date ? c.completedAt.toISOString() : (c.completedAt as string | null),
ownerNotes: c.ownerNotes ?? null,
})),
addenda: addendaRows.map(a => ({
authorName: a.authorName ?? 'Unknown',
createdAt: a.createdAt instanceof Date ? a.createdAt.toISOString() : (a.createdAt as string),
body: a.body,
})),
closedAt: incident.closedAt instanceof Date ? incident.closedAt.toISOString() : (incident.closedAt as string | null),
})
const filename = `incident-report-${incident.referenceNo ?? id}.pdf`
return new NextResponse(pdfBytes, {
status: 200,
headers: {
'Content-Type': 'application/pdf',
'Content-Disposition': `attachment; filename="${filename}"`,
'Content-Length': String(pdfBytes.byteLength),
},
})
}
```
- [ ] **Step 4: Run test — verify it passes**
```bash
cd /Users/yapweeihan/Desktop/Projects/IMS.nosync && npx vitest run tests/app/api/incidents/report-pdf.test.ts
```
Expected: PASS — 5 tests pass
- [ ] **Step 5: Build check**
```bash
cd /Users/yapweeihan/Desktop/Projects/IMS.nosync && npm run build 2>&1 | tail -10
```
Expected: `✓ Compiled successfully` with zero errors.
- [ ] **Step 6: Commit**
```bash
git add app/api/incidents/\[id\]/report-pdf/route.ts tests/app/api/incidents/report-pdf.test.ts
git commit -m "feat(pdf): add incident report PDF API route"
```
---
### Task 3: Print button in HSE incident detail page
**Files:**
- Modify: `app/(protected)/hse/incidents/[id]/page.tsx`
**Interfaces:**
- Consumes: existing `status` variable (already computed at line ~102)
- No new imports needed — button is a plain `<a>` link same as existing JKKP buttons
The button appears in the same block as the JKKP download links. It is only rendered when `status === 'closed'`. Clicking it opens `/api/incidents/${id}/report-pdf` in a new tab (browser shows the PDF or triggers download depending on browser settings).
- [ ] **Step 1: Read the current button block**
Open `app/(protected)/hse/incidents/[id]/page.tsx` and locate the JKKP links block around line 176. It looks like:
```tsx
href={`/api/incidents/${id}/jkkp-pdf?form=jkkp6`}
```
- [ ] **Step 2: Add the Print Report button**
Find this block in `app/(protected)/hse/incidents/[id]/page.tsx`:
```tsx
href={`/api/incidents/${id}/jkkp-pdf?form=jkkp7`}
```
After the closing element of that JKKP block (look for the enclosing `</div>` or after the last JKKP link), add — **after** the existing JKKP buttons, inside the same container:
```tsx
{status === 'closed' && (
<a
href={`/api/incidents/${id}/report-pdf`}
target="_blank"
rel="noopener noreferrer"
className="flex items-center gap-1.5 px-3 py-1.5 bg-green-600 text-white text-xs font-semibold rounded-lg hover:bg-green-700 transition-colors"
>
<svg className="w-3.5 h-3.5" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
<path strokeLinecap="round" strokeLinejoin="round" d="M12 10v6m0 0l-3-3m3 3l3-3m2 8H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z" />
</svg>
Print Report
</a>
)}
```
- [ ] **Step 3: Build check**
```bash
cd /Users/yapweeihan/Desktop/Projects/IMS.nosync && npm run build 2>&1 | tail -10
```
Expected: `✓ Compiled successfully`
- [ ] **Step 4: Commit**
```bash
git add app/\(protected\)/hse/incidents/\[id\]/page.tsx
git commit -m "feat(ui): add Print Report button on closed incidents"
```
---
## Self-Review
**Spec coverage:**
- ✅ Print button appears on closed incidents
- ✅ PDF includes all incident sections (details, triage, investigation, CAPA, addenda, closure)
- ✅ PDF only generated when `status === 'closed'` (400 otherwise)
- ✅ Auth-gated to `hse` and `admin`
- ✅ Multi-page support via `newPage` / `ensureSpace`
- ✅ No new dependencies
**Placeholder scan:** None found.
**Type consistency:** `IncidentReportData` defined in Task 1, imported in Task 2. `buildIncidentReportPdf` produced in Task 1, consumed in Task 2. All field names match across tasks.
@@ -0,0 +1,249 @@
# Overdue CAPA Actionable 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:** Allow CAPA owners to act on overdue CAPAs (Mark In Progress / Submit for Verification) and fix overdue count + highlight on the owner page.
**Architecture:** Two-file client+server fix. CapaOwnerActions gets `overdue` added to its branch logic. capa-owner page gets runtime overdue computation replacing the DB-status-only check. No schema, API, or migration changes needed.
**Tech Stack:** Next.js 15 App Router, React, TypeScript, Vitest
## Global Constraints
- Project root: `/Users/yapweeihan/Desktop/Projects/IMS.nosync`
- No new npm packages
- No schema/migration changes
- Tests: Vitest (`npx vitest run`)
- Every CAPA status transition already permitted by PATCH `/api/capa/[id]` — no API changes needed
- Commit with `fix:` prefix, co-authored by Claude
---
## File Map
- **Modify:** `components/capa/capa-owner-actions.tsx` — add `'overdue'` to the `open/reopened` branch
- **Modify:** `app/(protected)/capa-owner/page.tsx` — add `isCapaOverdue` runtime helper, fix `overdueCount`, `openCount`, and `isOverdue`
- **Create:** `tests/components/capa/capa-owner-actions.test.tsx` — unit tests for status-branch logic
---
### Task 1: Fix overdue CAPA action buttons and owner page stats
**Files:**
- Modify: `components/capa/capa-owner-actions.tsx`
- Modify: `app/(protected)/capa-owner/page.tsx`
- Create: `tests/components/capa/capa-owner-actions.test.tsx`
**Interfaces:**
- Consumes: `CapaOwnerActions({ capaId: string, currentStatus: string })` — existing component
- Produces: same component, extended to handle `currentStatus === 'overdue'`
---
- [ ] **Step 1: Write the failing test**
Create `tests/components/capa/capa-owner-actions.test.tsx`:
```tsx
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { render, screen } from '@testing-library/react'
import { CapaOwnerActions } from '@/components/capa/capa-owner-actions'
// Mock Next.js router
vi.mock('next/navigation', () => ({
useRouter: () => ({ refresh: vi.fn() }),
}))
describe('CapaOwnerActions', () => {
it('shows Mark In Progress for open status', () => {
render(<CapaOwnerActions capaId="abc" currentStatus="open" />)
expect(screen.getByText('Mark In Progress')).toBeTruthy()
})
it('shows Mark In Progress for reopened status', () => {
render(<CapaOwnerActions capaId="abc" currentStatus="reopened" />)
expect(screen.getByText('Mark In Progress')).toBeTruthy()
})
it('shows Mark In Progress for overdue status', () => {
render(<CapaOwnerActions capaId="abc" currentStatus="overdue" />)
expect(screen.getByText('Mark In Progress')).toBeTruthy()
})
it('shows Submit for Verification for in_progress status', () => {
render(<CapaOwnerActions capaId="abc" currentStatus="in_progress" />)
expect(screen.getByText('Submit for Verification')).toBeTruthy()
})
it('renders nothing for pending_verification status', () => {
const { container } = render(<CapaOwnerActions capaId="abc" currentStatus="pending_verification" />)
expect(container.firstChild).toBeNull()
})
it('renders nothing for verified status', () => {
const { container } = render(<CapaOwnerActions capaId="abc" currentStatus="verified" />)
expect(container.firstChild).toBeNull()
})
})
```
- [ ] **Step 2: Run test to verify it fails**
```bash
cd /Users/yapweeihan/Desktop/Projects/IMS.nosync
npx vitest run tests/components/capa/capa-owner-actions.test.tsx 2>&1 | tail -20
```
Expected: FAIL — "shows Mark In Progress for overdue status" fails because `overdue` hits `return null`.
- [ ] **Step 3: Fix `CapaOwnerActions` — add `'overdue'` to first branch**
Replace `components/capa/capa-owner-actions.tsx` entirely:
```tsx
'use client'
import { useState } from 'react'
import { useRouter } from 'next/navigation'
interface Props {
capaId: string
currentStatus: string
}
export function CapaOwnerActions({ capaId, currentStatus }: Props) {
const router = useRouter()
const [loading, setLoading] = useState(false)
async function updateStatus(status: string) {
setLoading(true)
try {
const res = await fetch(`/api/capa/${capaId}`, {
method: 'PATCH',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ status }),
})
if (!res.ok) {
alert('Update failed. Please try again.')
return
}
router.refresh()
setTimeout(() => window.location.reload(), 300)
} finally {
setLoading(false)
}
}
if (currentStatus === 'open' || currentStatus === 'reopened' || currentStatus === 'overdue') {
return (
<button
onClick={() => updateStatus('in_progress')}
disabled={loading}
className="text-sm px-3 py-1.5 border border-gray-300 rounded-md hover:bg-gray-50 disabled:opacity-50"
>
{loading ? '…' : 'Mark In Progress'}
</button>
)
}
if (currentStatus === 'in_progress') {
return (
<button
onClick={() => updateStatus('pending_verification')}
disabled={loading}
className="text-sm px-3 py-1.5 bg-blue-600 text-white rounded-md hover:bg-blue-700 disabled:opacity-50"
>
{loading ? '…' : 'Submit for Verification'}
</button>
)
}
return null
}
```
- [ ] **Step 4: Run test to verify it passes**
```bash
npx vitest run tests/components/capa/capa-owner-actions.test.tsx 2>&1 | tail -10
```
Expected: PASS — 6/6 tests passing.
- [ ] **Step 5: Fix `capa-owner/page.tsx` — runtime overdue computation**
In `app/(protected)/capa-owner/page.tsx`, replace the three broken lines:
**Find (lines ~55–57 and ~85):**
```tsx
const openCount = rows.filter(c => ['open', 'in_progress', 'reopened'].includes(c.status)).length
const overdueCount = rows.filter(c => c.status === 'overdue').length
const doneCount = rows.filter(c => ['verified', 'closed'].includes(c.status)).length
```
and (inside the `activeRows.map` render):
```tsx
const isOverdue = capa.status === 'overdue'
```
**Replace with:**
After the `rows` assignment (before `openCount`), add the helper and recompute all three counts:
```tsx
const today = new Date().toISOString().slice(0, 10)
function isCapaOverdue(c: { status: string; dueDate: string | null }): boolean {
if (c.status === 'overdue') return true
return (c.status === 'open' || c.status === 'in_progress') && !!c.dueDate && c.dueDate < today
}
const openCount = rows.filter(c => ['open', 'in_progress', 'reopened'].includes(c.status) && !isCapaOverdue(c)).length
const overdueCount = rows.filter(c => isCapaOverdue(c)).length
const doneCount = rows.filter(c => ['verified', 'closed'].includes(c.status)).length
```
And inside the map:
```tsx
const isOverdue = isCapaOverdue(capa)
```
Full updated file for reference (show only changed regions, not the entire file — use Edit tool on the exact strings above).
- [ ] **Step 6: Build check**
```bash
npm run build 2>&1 | tail -5
```
Expected output ends with:
```
ƒ (Dynamic) server-rendered on demand
```
No TypeScript errors.
- [ ] **Step 7: Commit**
```bash
git add components/capa/capa-owner-actions.tsx \
app/\(protected\)/capa-owner/page.tsx \
tests/components/capa/capa-owner-actions.test.tsx
git commit -m "fix(capa): allow overdue CAPAs to be acted on, fix owner page stats
- CapaOwnerActions: add 'overdue' to open/reopened branch so DB-overdue
CAPAs show 'Mark In Progress' button (cron transitions open→overdue)
- capa-owner page: compute overdue at runtime (dueDate < today) so stats
and red highlight are correct even before cron runs
- openCount now excludes overdue items to avoid double-counting
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>"
```
---
Plan complete and saved to `docs/superpowers/plans/2026-07-30-overdue-capa-actionable.md`.
**Two execution options:**
**1. Subagent-Driven (recommended)** — I dispatch a fresh subagent per task, review between tasks, fast iteration
**2. Inline Execution** — Execute tasks in this session using executing-plans, batch execution with checkpoints
**Which approach?**
@@ -0,0 +1,33 @@
# Remove Invite-by-Email Feature
**Date:** 2026-07-18
**Scope:** Admin user management — remove email invite flow, keep direct-add only.
## Problem
Two user-creation modes exist: "Invite by email" (sends Supabase invite link) and "Add directly" (admin sets password). The invite flow requires `NEXT_PUBLIC_APP_URL` to be configured and sends an external email, adding operational complexity. Only direct-add is needed going forward.
## Changes
### 1. `components/admin/user-manager.tsx`
- Remove `mode` state and the invite/create toggle buttons.
- Remove all invite-specific conditional text (button label, error message).
- Password field always visible and always required.
- `payload.password` always included in POST body.
### 2. `app/api/admin/users/route.ts` (POST handler)
- Remove the `else` branch (lines 62–77) that calls `admin.auth.admin.inviteUserByEmail`.
- Remove `directCreate` variable — password is now always required.
- Require `password` upfront; return 422 if missing or < 8 chars.
- Audit log action always `'created'`.
- Error message for missing service role key simplified (no mention of "invites").
### 3. `app/auth/invite-callback/page.tsx`
- Delete file and directory — no longer reachable or needed.
### 4. No DB migration needed
- No schema changes. Audit log continues using existing `write_audit_log` RPC.
## Out of Scope
- `app/api/users/route.ts` — unrelated active-users list, untouched.
- Resend / WhatsApp notification wiring — untouched.