Files
ims/app/api/incidents/[id]/close/route.ts
T
adminandClaude Sonnet 4.6 25f923f530 feat(db): phase 4 group 1 — lib/ settings + notifications to Drizzle
Convert lib/settings.ts, lib/notifications/{in-app,email,capa-escalation,
effectiveness-recheck}.ts from Supabase PostgREST to Drizzle asAdmin queries.
Drop supabase arg from all call sites in app/api/ and cron routes. Rewrite
notification unit tests to mock @/lib/db/with-user instead of SupabaseClient.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-07-23 16:37:51 +08:00

64 lines
2.2 KiB
TypeScript

export const dynamic = 'force-dynamic'
import { NextRequest, NextResponse } from 'next/server'
import { createClient } from '@/lib/supabase/server'
import { getSession } from '@/lib/auth/get-session'
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 supabase = await createClient()
const { data: incident } = await supabase
.from('incidents')
.select('status, reference_no, reported_by')
.eq('id', id)
.single()
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 { data: openCapas } = await supabase
.from('capa_actions')
.select('id')
.eq('incident_id', id)
.not('status', 'in', '(verified,closed)')
if (openCapas && openCapas.length > 0)
return NextResponse.json({ error: 'All CAPA actions must be verified before closure' }, { status: 409 })
const closedAt = new Date().toISOString()
const { error } = await supabase
.from('incidents')
.update({ status: 'closed', closed_at: closedAt })
.eq('id', id)
if (error) return NextResponse.json({ error: 'Update failed' }, { status: 500 })
await supabase.rpc('write_audit_log', {
p_table_name: 'incidents',
p_record_id: id,
p_action: 'closed',
p_new_value: { status: 'closed', closed_at: closedAt, closed_by: session.sub },
})
if (incident.reported_by) {
await createInAppNotifications([{
userId: incident.reported_by,
title: `Your incident report ${incident.reference_no ?? ''} has been closed`,
link: '/reporter',
incidentId: id,
}])
}
return NextResponse.json({ ok: true, closed_at: closedAt })
}