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:
2026-10-14 11:11:10 +08:00
co-authored by Claude Sonnet 5.5
parent 51986b7ae5
commit de7fb298f7
2 changed files with 71 additions and 31 deletions
+31 -1
View File
@@ -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')
})
})