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'
|
export const dynamic = 'force-dynamic'
|
||||||
|
|
||||||
import { NextRequest, NextResponse } from 'next/server'
|
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 { getSession } from '@/lib/auth/get-session'
|
||||||
import { withUser } from '@/lib/db/with-user'
|
import { withUser } from '@/lib/db/with-user'
|
||||||
import { writeAuditLog } from '@/lib/db/audit'
|
import { writeAuditLog } from '@/lib/db/audit'
|
||||||
@@ -9,6 +9,8 @@ import { capaActions, evidenceFiles } from '@/lib/db/schema'
|
|||||||
import { uploadEvidenceFile } from '@/lib/storage/evidence'
|
import { uploadEvidenceFile } from '@/lib/storage/evidence'
|
||||||
import { validateCapaSubmission } from '@/lib/capa/submit-validation'
|
import { validateCapaSubmission } from '@/lib/capa/submit-validation'
|
||||||
|
|
||||||
|
class StatusConflict extends Error {}
|
||||||
|
|
||||||
export async function POST(
|
export async function POST(
|
||||||
request: NextRequest,
|
request: NextRequest,
|
||||||
{ params }: { params: Promise<{ id: string }> }
|
{ params }: { params: Promise<{ id: string }> }
|
||||||
@@ -53,36 +55,44 @@ export async function POST(
|
|||||||
}
|
}
|
||||||
|
|
||||||
const completedAt = new Date()
|
const completedAt = new Date()
|
||||||
await withUser(session.sub, async tx => {
|
try {
|
||||||
const rows = await tx.insert(evidenceFiles).values(
|
await withUser(session.sub, async tx => {
|
||||||
uploaded.map(u => ({
|
const updated = await tx.update(capaActions).set({
|
||||||
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',
|
status: 'pending_verification',
|
||||||
owner_notes: check.note,
|
ownerNotes: check.note,
|
||||||
completed_at: completedAt.toISOString(),
|
completedAt,
|
||||||
evidence_file_ids: rows.map(r => r.id),
|
}).where(and(eq(capaActions.id, id), eq(capaActions.status, 'in_progress')))
|
||||||
},
|
.returning({ id: capaActions.id })
|
||||||
{ status: 'in_progress' },
|
if (updated.length === 0) throw new StatusConflict()
|
||||||
)
|
|
||||||
})
|
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 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' },
|
||||||
|
)
|
||||||
|
})
|
||||||
|
} catch (err) {
|
||||||
|
if (err instanceof StatusConflict)
|
||||||
|
return NextResponse.json({ error: 'CAPA must be in_progress' }, { status: 409 })
|
||||||
|
throw err
|
||||||
|
}
|
||||||
|
|
||||||
return NextResponse.json({ ok: true })
|
return NextResponse.json({ ok: true })
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -6,6 +6,7 @@ const h = vi.hoisted(() => ({
|
|||||||
capa: null as null | { incidentId: string; ownerUserId: string; status: string },
|
capa: null as null | { incidentId: string; ownerUserId: string; status: string },
|
||||||
updates: [] as unknown[],
|
updates: [] as unknown[],
|
||||||
inserts: [] as unknown[],
|
inserts: [] as unknown[],
|
||||||
|
updateRows: [{ id: 'capa-1' }] as unknown[],
|
||||||
}))
|
}))
|
||||||
|
|
||||||
vi.mock('@/lib/auth/get-session', () => ({ getSession: async () => h.session }))
|
vi.mock('@/lib/auth/get-session', () => ({ getSession: async () => h.session }))
|
||||||
@@ -18,13 +19,14 @@ vi.mock('@/lib/db/with-user', () => ({
|
|||||||
const tx = {
|
const tx = {
|
||||||
select: () => ({ from: () => ({ where: () => ({ limit: async () => (h.capa ? [h.capa] : []) }) }) }),
|
select: () => ({ from: () => ({ where: () => ({ limit: async () => (h.capa ? [h.capa] : []) }) }) }),
|
||||||
insert: () => ({ values: (v: unknown) => { h.inserts.push(v); return { returning: async () => [{ id: 'ev-1' }] } } }),
|
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)
|
return fn(tx)
|
||||||
},
|
},
|
||||||
}))
|
}))
|
||||||
|
|
||||||
import { writeAuditLog } from '@/lib/db/audit'
|
import { writeAuditLog } from '@/lib/db/audit'
|
||||||
|
import { uploadEvidenceFile } from '@/lib/storage/evidence'
|
||||||
import { POST } from '@/app/api/capa/[id]/submit/route'
|
import { POST } from '@/app/api/capa/[id]/submit/route'
|
||||||
|
|
||||||
function req(note: string | null, fileCount: number) {
|
function req(note: string | null, fileCount: number) {
|
||||||
@@ -40,6 +42,7 @@ beforeEach(() => {
|
|||||||
h.capa = { incidentId: 'inc-1', ownerUserId: 'owner-1', status: 'in_progress' }
|
h.capa = { incidentId: 'inc-1', ownerUserId: 'owner-1', status: 'in_progress' }
|
||||||
h.updates = []
|
h.updates = []
|
||||||
h.inserts = []
|
h.inserts = []
|
||||||
|
h.updateRows = [{ id: 'capa-1' }]
|
||||||
vi.mocked(writeAuditLog).mockClear()
|
vi.mocked(writeAuditLog).mockClear()
|
||||||
})
|
})
|
||||||
|
|
||||||
@@ -84,4 +87,31 @@ describe('POST /api/capa/[id]/submit', () => {
|
|||||||
expect.objectContaining({ status: 'in_progress' }),
|
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