feat(capa): require note and photos via /submit, block PATCH bypass
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -105,6 +105,13 @@ export async function PATCH(
|
||||
|
||||
const body = await request.json()
|
||||
|
||||
if (body.status === 'pending_verification') {
|
||||
return NextResponse.json(
|
||||
{ error: 'Use POST /api/capa/[id]/submit to submit for verification' },
|
||||
{ status: 403 },
|
||||
)
|
||||
}
|
||||
|
||||
const privilegedStatuses = ['verified', 'reopened', 'closed']
|
||||
if (body.status && privilegedStatuses.includes(body.status) && !['hse', 'admin'].includes(role)) {
|
||||
return NextResponse.json({ error: 'Forbidden' }, { status: 403 })
|
||||
@@ -122,14 +129,12 @@ export async function PATCH(
|
||||
if ('department' in body && allowed.includes('department')) updateSet.department = body.department
|
||||
if ('root_cause_ref' in body && allowed.includes('root_cause_ref')) updateSet.rootCauseRef = body.root_cause_ref
|
||||
if ('owner_notes' in body && allowed.includes('owner_notes')) updateSet.ownerNotes = body.owner_notes
|
||||
if (body.status === 'pending_verification') updateSet.completedAt = new Date()
|
||||
|
||||
// Build audit new/old value from original snake_case body keys for consistency
|
||||
const auditNew: Record<string, unknown> = {}
|
||||
for (const key of allowed) {
|
||||
if (key in body) auditNew[key] = body[key]
|
||||
}
|
||||
if (body.status === 'pending_verification') auditNew.completed_at = updateSet.completedAt?.toISOString()
|
||||
|
||||
await withUser(session.sub, async tx => {
|
||||
let oldNotes: string | null = null
|
||||
|
||||
@@ -0,0 +1,88 @@
|
||||
export const dynamic = 'force-dynamic'
|
||||
|
||||
import { NextRequest, NextResponse } from 'next/server'
|
||||
import { eq } from 'drizzle-orm'
|
||||
import { getSession } from '@/lib/auth/get-session'
|
||||
import { withUser } from '@/lib/db/with-user'
|
||||
import { writeAuditLog } from '@/lib/db/audit'
|
||||
import { capaActions, evidenceFiles } from '@/lib/db/schema'
|
||||
import { uploadEvidenceFile } from '@/lib/storage/evidence'
|
||||
import { validateCapaSubmission } from '@/lib/capa/submit-validation'
|
||||
|
||||
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 })
|
||||
|
||||
const [capa] = await withUser(session.sub, async tx =>
|
||||
tx.select({
|
||||
incidentId: capaActions.incidentId,
|
||||
ownerUserId: capaActions.ownerUserId,
|
||||
status: capaActions.status,
|
||||
}).from(capaActions).where(eq(capaActions.id, id)).limit(1)
|
||||
)
|
||||
if (!capa) return NextResponse.json({ error: 'Not found' }, { status: 404 })
|
||||
|
||||
const isElevated = ['hse', 'admin'].includes(session.role)
|
||||
if (capa.ownerUserId !== session.sub && !isElevated)
|
||||
return NextResponse.json({ error: 'Forbidden' }, { status: 403 })
|
||||
|
||||
if (capa.status !== 'in_progress')
|
||||
return NextResponse.json({ error: 'CAPA must be in_progress' }, { status: 409 })
|
||||
|
||||
const form = await request.formData()
|
||||
const files = form.getAll('files').filter((f): f is File => f instanceof File)
|
||||
const check = validateCapaSubmission(String(form.get('note') ?? ''), files)
|
||||
if (!check.ok)
|
||||
return NextResponse.json({ error: 'Validation failed', details: check.errors }, { status: 422 })
|
||||
|
||||
const uploaded: Array<{ publicUrl: string; hash: string; type: string }> = []
|
||||
try {
|
||||
for (const file of files) {
|
||||
const { publicUrl, hash } = await uploadEvidenceFile(file, capa.incidentId, 'capa', session.sub)
|
||||
uploaded.push({ publicUrl, hash, type: file.type })
|
||||
}
|
||||
} catch (err) {
|
||||
return NextResponse.json(
|
||||
{ error: 'Photo upload failed', details: [err instanceof Error ? err.message : 'unknown error'] },
|
||||
{ status: 422 },
|
||||
)
|
||||
}
|
||||
|
||||
const completedAt = new Date()
|
||||
await withUser(session.sub, async tx => {
|
||||
const rows = await tx.insert(evidenceFiles).values(
|
||||
uploaded.map(u => ({
|
||||
incidentId: capa.incidentId,
|
||||
capaId: id,
|
||||
stage: 'capa' as const,
|
||||
fileUrl: u.publicUrl,
|
||||
fileType: u.type,
|
||||
fileHash: u.hash,
|
||||
uploadedBy: session.sub,
|
||||
}))
|
||||
).returning({ id: evidenceFiles.id })
|
||||
|
||||
await tx.update(capaActions).set({
|
||||
status: 'pending_verification',
|
||||
ownerNotes: check.note,
|
||||
completedAt,
|
||||
}).where(eq(capaActions.id, id))
|
||||
|
||||
await writeAuditLog(
|
||||
tx, 'capa_actions', id, 'submitted_for_verification',
|
||||
{
|
||||
status: 'pending_verification',
|
||||
owner_notes: check.note,
|
||||
completed_at: completedAt.toISOString(),
|
||||
evidence_file_ids: rows.map(r => r.id),
|
||||
},
|
||||
{ status: 'in_progress' },
|
||||
)
|
||||
})
|
||||
|
||||
return NextResponse.json({ ok: true })
|
||||
}
|
||||
Reference in New Issue
Block a user