Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01FFDuBhMKvoWjrWT3ZnGmmr
65 lines
2.3 KiB
TypeScript
65 lines
2.3 KiB
TypeScript
export const dynamic = 'force-dynamic'
|
|
|
|
import { NextRequest, NextResponse } from 'next/server'
|
|
import { createClient } from '@/lib/supabase/server'
|
|
|
|
export async function POST(
|
|
request: NextRequest,
|
|
{ params }: { params: Promise<{ id: string }> }
|
|
) {
|
|
const { id } = await params
|
|
const supabase = await createClient()
|
|
|
|
const { data: { user }, error: authError } = await supabase.auth.getUser()
|
|
if (authError || !user) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
|
|
|
|
const { data: profile } = await supabase
|
|
.from('users').select('role').eq('id', user.id).single()
|
|
if (!profile || !['hse', 'admin'].includes(profile.role))
|
|
return NextResponse.json({ error: 'Forbidden' }, { status: 403 })
|
|
|
|
const { data: capa } = await supabase
|
|
.from('capa_actions').select('status, incident_id').eq('id', id).single()
|
|
if (!capa) return NextResponse.json({ error: 'Not found' }, { status: 404 })
|
|
if (capa.status !== 'pending_verification')
|
|
return NextResponse.json({ error: 'CAPA must be pending_verification' }, { status: 409 })
|
|
|
|
const body: { verdict: 'verified' | 'reopened'; reopen_reason?: string } = await request.json()
|
|
if (body.verdict !== 'verified' && body.verdict !== 'reopened')
|
|
return NextResponse.json({ error: 'verdict must be verified or reopened' }, { status: 422 })
|
|
|
|
const update: Record<string, unknown> = {
|
|
status: body.verdict,
|
|
verified_by: user.id,
|
|
verified_at: new Date().toISOString(),
|
|
}
|
|
|
|
const { error } = await supabase
|
|
.from('capa_actions').update(update).eq('id', id)
|
|
|
|
if (error) return NextResponse.json({ error: 'Update failed' }, { status: 500 })
|
|
|
|
await supabase.rpc('write_audit_log', {
|
|
p_table_name: 'capa_actions',
|
|
p_record_id: id,
|
|
p_action: body.verdict === 'verified' ? 'verified' : 'reopened',
|
|
p_new_value: { ...update, reopen_reason: body.reopen_reason ?? null },
|
|
})
|
|
|
|
// Check if all CAPAs for this incident are verified — if so, transition incident to verification
|
|
const { data: openCapas } = await supabase
|
|
.from('capa_actions')
|
|
.select('id')
|
|
.eq('incident_id', capa.incident_id)
|
|
.not('status', 'in', '(verified,closed)')
|
|
|
|
if (!openCapas || openCapas.length === 0) {
|
|
await supabase
|
|
.from('incidents')
|
|
.update({ status: 'verification' })
|
|
.eq('id', capa.incident_id)
|
|
}
|
|
|
|
return NextResponse.json({ ok: true })
|
|
}
|