Files
ims/app/api/incidents/[id]/close/route.ts
T
Weei HanandClaude Sonnet 5.5 813395700f feat(auth): merge reporter, supervisor, capa_owner into ssa role
Add Site Safety Assistant (ssa) role replacing reporter, supervisor and
capa_owner. Portals move under /ssa (overview, my-reports, incidents,
capas). Update RLS, schema, API role checks, notification recipients,
nav and tests. Add db/ops/2026-11-06-merge-roles-into-ssa.sql (not yet
applied; needs owner go-ahead and a pg_dump first).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-06 21:34:10 +08:00

61 lines
2.4 KiB
TypeScript

export const dynamic = 'force-dynamic'
import { NextRequest, NextResponse } from 'next/server'
import { getSession } from '@/lib/auth/get-session'
import { withUser } from '@/lib/db/with-user'
import { writeAuditLog } from '@/lib/db/audit'
import { incidents, capaActions } from '@/lib/db/schema'
import { eq, and, not, inArray } from 'drizzle-orm'
import { createInAppNotifications } from '@/lib/notifications/in-app'
export async function POST(
_request: 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 [incident] = await withUser(session.sub, async tx =>
tx.select({ status: incidents.status, referenceNo: incidents.referenceNo, reportedBy: incidents.reportedBy })
.from(incidents).where(eq(incidents.id, id)).limit(1)
)
if (!incident) return NextResponse.json({ error: 'Not found' }, { status: 404 })
if (incident.status === 'closed')
return NextResponse.json({ error: 'Already closed' }, { status: 409 })
if (incident.status !== 'verification')
return NextResponse.json({ error: 'Incident must be in verification status' }, { status: 409 })
const openCapas = await withUser(session.sub, async tx =>
tx.select({ id: capaActions.id })
.from(capaActions)
.where(and(
eq(capaActions.incidentId, id),
not(inArray(capaActions.status, ['verified', 'closed'])),
))
)
if (openCapas.length > 0)
return NextResponse.json({ error: 'All CAPA actions must be verified before closure' }, { status: 409 })
const closedAt = new Date()
await withUser(session.sub, async tx => {
await tx.update(incidents).set({ status: 'closed', closedAt }).where(eq(incidents.id, id))
await writeAuditLog(tx, 'incidents', id, 'closed', {
status: 'closed', closed_at: closedAt.toISOString(), closed_by: session.sub,
})
})
if (incident.reportedBy) {
await createInAppNotifications([{
userId: incident.reportedBy,
title: `Your incident report ${incident.referenceNo ?? ''} has been closed`,
link: '/ssa/my-reports',
incidentId: id,
}])
}
return NextResponse.json({ ok: true, closed_at: closedAt.toISOString() })
}