fix(capa): atomic in_progress guard on submit, add behavioural tests
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -1,7 +1,7 @@
|
||||
export const dynamic = 'force-dynamic'
|
||||
|
||||
import { NextRequest, NextResponse } from 'next/server'
|
||||
import { eq } from 'drizzle-orm'
|
||||
import { and, eq } from 'drizzle-orm'
|
||||
import { getSession } from '@/lib/auth/get-session'
|
||||
import { withUser } from '@/lib/db/with-user'
|
||||
import { writeAuditLog } from '@/lib/db/audit'
|
||||
@@ -9,6 +9,8 @@ import { capaActions, evidenceFiles } from '@/lib/db/schema'
|
||||
import { uploadEvidenceFile } from '@/lib/storage/evidence'
|
||||
import { validateCapaSubmission } from '@/lib/capa/submit-validation'
|
||||
|
||||
class StatusConflict extends Error {}
|
||||
|
||||
export async function POST(
|
||||
request: NextRequest,
|
||||
{ params }: { params: Promise<{ id: string }> }
|
||||
@@ -53,7 +55,16 @@ export async function POST(
|
||||
}
|
||||
|
||||
const completedAt = new Date()
|
||||
try {
|
||||
await withUser(session.sub, async tx => {
|
||||
const updated = await tx.update(capaActions).set({
|
||||
status: 'pending_verification',
|
||||
ownerNotes: check.note,
|
||||
completedAt,
|
||||
}).where(and(eq(capaActions.id, id), eq(capaActions.status, 'in_progress')))
|
||||
.returning({ id: capaActions.id })
|
||||
if (updated.length === 0) throw new StatusConflict()
|
||||
|
||||
const rows = await tx.insert(evidenceFiles).values(
|
||||
uploaded.map(u => ({
|
||||
incidentId: capa.incidentId,
|
||||
@@ -66,12 +77,6 @@ export async function POST(
|
||||
}))
|
||||
).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',
|
||||
{
|
||||
@@ -83,6 +88,11 @@ export async function POST(
|
||||
{ status: 'in_progress' },
|
||||
)
|
||||
})
|
||||
} catch (err) {
|
||||
if (err instanceof StatusConflict)
|
||||
return NextResponse.json({ error: 'CAPA must be in_progress' }, { status: 409 })
|
||||
throw err
|
||||
}
|
||||
|
||||
return NextResponse.json({ ok: true })
|
||||
}
|
||||
|
||||
@@ -6,6 +6,7 @@ const h = vi.hoisted(() => ({
|
||||
capa: null as null | { incidentId: string; ownerUserId: string; status: string },
|
||||
updates: [] as unknown[],
|
||||
inserts: [] as unknown[],
|
||||
updateRows: [{ id: 'capa-1' }] as unknown[],
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/auth/get-session', () => ({ getSession: async () => h.session }))
|
||||
@@ -18,13 +19,14 @@ vi.mock('@/lib/db/with-user', () => ({
|
||||
const tx = {
|
||||
select: () => ({ from: () => ({ where: () => ({ limit: async () => (h.capa ? [h.capa] : []) }) }) }),
|
||||
insert: () => ({ values: (v: unknown) => { h.inserts.push(v); return { returning: async () => [{ id: 'ev-1' }] } } }),
|
||||
update: () => ({ set: (v: unknown) => { h.updates.push(v); return { where: async () => undefined } } }),
|
||||
update: () => ({ set: (v: unknown) => { h.updates.push(v); return { where: () => ({ returning: async () => h.updateRows }) } } }),
|
||||
}
|
||||
return fn(tx)
|
||||
},
|
||||
}))
|
||||
|
||||
import { writeAuditLog } from '@/lib/db/audit'
|
||||
import { uploadEvidenceFile } from '@/lib/storage/evidence'
|
||||
import { POST } from '@/app/api/capa/[id]/submit/route'
|
||||
|
||||
function req(note: string | null, fileCount: number) {
|
||||
@@ -40,6 +42,7 @@ beforeEach(() => {
|
||||
h.capa = { incidentId: 'inc-1', ownerUserId: 'owner-1', status: 'in_progress' }
|
||||
h.updates = []
|
||||
h.inserts = []
|
||||
h.updateRows = [{ id: 'capa-1' }]
|
||||
vi.mocked(writeAuditLog).mockClear()
|
||||
})
|
||||
|
||||
@@ -84,4 +87,31 @@ describe('POST /api/capa/[id]/submit', () => {
|
||||
expect.objectContaining({ status: 'in_progress' }),
|
||||
)
|
||||
})
|
||||
it('409 on a lost race: no evidence insert, no audit', async () => {
|
||||
h.updateRows = []
|
||||
const res = await POST(req('done', 1) as never, ctx)
|
||||
expect(res.status).toBe(409)
|
||||
expect(h.inserts).toHaveLength(0)
|
||||
expect(writeAuditLog).not.toHaveBeenCalled()
|
||||
})
|
||||
it('422 with details and no DB writes when upload fails', async () => {
|
||||
vi.mocked(uploadEvidenceFile).mockRejectedValueOnce(new Error('disk full'))
|
||||
const res = await POST(req('done', 1) as never, ctx)
|
||||
expect(res.status).toBe(422)
|
||||
expect((await res.json()).details).toContain('disk full')
|
||||
expect(h.inserts).toHaveLength(0)
|
||||
expect(h.updates).toHaveLength(0)
|
||||
expect(writeAuditLog).not.toHaveBeenCalled()
|
||||
})
|
||||
it('200 for an hse non-owner, evidence uploadedBy is the hse user', async () => {
|
||||
h.session = { sub: 'hse-1', role: 'hse' }
|
||||
const res = await POST(req('done', 1) as never, ctx)
|
||||
expect(res.status).toBe(200)
|
||||
expect(h.inserts[0]).toEqual([expect.objectContaining({ uploadedBy: 'hse-1' })])
|
||||
})
|
||||
it('422 for 6 files at route level', async () => {
|
||||
const res = await POST(req('done', 6) as never, ctx)
|
||||
expect(res.status).toBe(422)
|
||||
expect((await res.json()).details).toContain('At most 5 photos are allowed')
|
||||
})
|
||||
})
|
||||
|
||||
Reference in New Issue
Block a user