feat(db): phase 4 group 4 — CAPA routes to Drizzle
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
+94
-47
@@ -1,9 +1,11 @@
|
||||
export const dynamic = 'force-dynamic'
|
||||
|
||||
import { NextRequest, NextResponse } from 'next/server'
|
||||
import { createClient } from '@/lib/supabase/server'
|
||||
import { createAdminClient } from '@/lib/supabase/admin'
|
||||
import { getSession } from '@/lib/auth/get-session'
|
||||
import { withUser, asAdmin } from '@/lib/db/with-user'
|
||||
import { writeAuditLog } from '@/lib/db/audit'
|
||||
import { capaActions, incidents, users } from '@/lib/db/schema'
|
||||
import { aliasedTable, eq } from 'drizzle-orm'
|
||||
|
||||
export async function GET(
|
||||
_: NextRequest,
|
||||
@@ -13,31 +15,66 @@ export async function GET(
|
||||
const session = await getSession()
|
||||
if (!session) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
|
||||
|
||||
const supabase = await createClient()
|
||||
const ownerAlias = aliasedTable(users, 'owner')
|
||||
|
||||
const { data, error } = await supabase
|
||||
.from('capa_actions')
|
||||
.select(`
|
||||
id, incident_id, root_cause_ref, description, owner_user_id, department,
|
||||
due_date, priority, status, completed_at, verified_by, verified_at, created_at,
|
||||
owner_notes,
|
||||
incidents (reference_no, incident_type),
|
||||
owner:users!owner_user_id (name, email)
|
||||
`)
|
||||
.eq('id', id)
|
||||
.single()
|
||||
const [row] = await withUser(session.sub, async tx =>
|
||||
tx
|
||||
.select({
|
||||
id: capaActions.id,
|
||||
incidentId: capaActions.incidentId,
|
||||
rootCauseRef: capaActions.rootCauseRef,
|
||||
description: capaActions.description,
|
||||
ownerUserId: capaActions.ownerUserId,
|
||||
department: capaActions.department,
|
||||
dueDate: capaActions.dueDate,
|
||||
priority: capaActions.priority,
|
||||
status: capaActions.status,
|
||||
completedAt: capaActions.completedAt,
|
||||
verifiedBy: capaActions.verifiedBy,
|
||||
verifiedAt: capaActions.verifiedAt,
|
||||
createdAt: capaActions.createdAt,
|
||||
ownerNotes: capaActions.ownerNotes,
|
||||
incidentReferenceNo: incidents.referenceNo,
|
||||
incidentType: incidents.incidentType,
|
||||
ownerName: ownerAlias.name,
|
||||
ownerEmail: ownerAlias.email,
|
||||
})
|
||||
.from(capaActions)
|
||||
.leftJoin(ownerAlias, eq(capaActions.ownerUserId, ownerAlias.id))
|
||||
.leftJoin(incidents, eq(capaActions.incidentId, incidents.id))
|
||||
.where(eq(capaActions.id, id))
|
||||
.limit(1)
|
||||
)
|
||||
|
||||
if (error || !data) return NextResponse.json({ error: 'Not found' }, { status: 404 })
|
||||
if (!row) return NextResponse.json({ error: 'Not found' }, { status: 404 })
|
||||
|
||||
const role = session.role
|
||||
const isOwner = data.owner_user_id === session.sub
|
||||
const isOwner = row.ownerUserId === session.sub
|
||||
const canRead = ['hse', 'admin', 'supervisor'].includes(role) || isOwner
|
||||
if (!canRead) return NextResponse.json({ error: 'Forbidden' }, { status: 403 })
|
||||
|
||||
// Strip owner email for non-privileged roles — only name needed
|
||||
const result = ['hse', 'admin'].includes(role)
|
||||
? data
|
||||
: { ...data, owner: { name: (data.owner as unknown as { name: string } | null)?.name ?? '' } }
|
||||
const ownerField = ['hse', 'admin'].includes(role)
|
||||
? { name: row.ownerName, email: row.ownerEmail }
|
||||
: { name: row.ownerName ?? '' }
|
||||
|
||||
const result = {
|
||||
id: row.id,
|
||||
incident_id: row.incidentId,
|
||||
root_cause_ref: row.rootCauseRef,
|
||||
description: row.description,
|
||||
owner_user_id: row.ownerUserId,
|
||||
department: row.department,
|
||||
due_date: row.dueDate,
|
||||
priority: row.priority,
|
||||
status: row.status,
|
||||
completed_at: row.completedAt,
|
||||
verified_by: row.verifiedBy,
|
||||
verified_at: row.verifiedAt,
|
||||
created_at: row.createdAt,
|
||||
owner_notes: row.ownerNotes,
|
||||
incidents: { reference_no: row.incidentReferenceNo, incident_type: row.incidentType },
|
||||
owner: ownerField,
|
||||
}
|
||||
|
||||
return NextResponse.json(result)
|
||||
}
|
||||
@@ -50,11 +87,14 @@ export async function PATCH(
|
||||
const session = await getSession()
|
||||
if (!session) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
|
||||
|
||||
const supabase = await createClient()
|
||||
const role = session.role
|
||||
|
||||
const { data: capa } = await supabase.from('capa_actions').select('owner_user_id, status').eq('id', id).single()
|
||||
const isOwner = capa?.owner_user_id === session.sub
|
||||
const [capa] = await withUser(session.sub, async tx =>
|
||||
tx.select({ ownerUserId: capaActions.ownerUserId, status: capaActions.status })
|
||||
.from(capaActions).where(eq(capaActions.id, id)).limit(1)
|
||||
)
|
||||
|
||||
const isOwner = capa?.ownerUserId === session.sub
|
||||
const canEdit = ['hse', 'admin'].includes(role) || isOwner
|
||||
if (!canEdit) return NextResponse.json({ error: 'Forbidden' }, { status: 403 })
|
||||
|
||||
@@ -65,7 +105,6 @@ export async function PATCH(
|
||||
|
||||
const body = await request.json()
|
||||
|
||||
// Only hse/admin can set privileged statuses
|
||||
const privilegedStatuses = ['verified', 'reopened', 'closed']
|
||||
if (body.status && privilegedStatuses.includes(body.status) && !['hse', 'admin'].includes(role)) {
|
||||
return NextResponse.json({ error: 'Forbidden' }, { status: 403 })
|
||||
@@ -74,36 +113,44 @@ export async function PATCH(
|
||||
const allowed = ['hse', 'admin'].includes(role)
|
||||
? ['description', 'due_date', 'priority', 'status', 'department', 'root_cause_ref', 'owner_notes']
|
||||
: ['status', 'owner_notes']
|
||||
const update: Record<string, unknown> = {}
|
||||
for (const key of allowed) {
|
||||
if (key in body) update[key] = body[key]
|
||||
}
|
||||
|
||||
if (body.status === 'pending_verification') {
|
||||
update.completed_at = new Date().toISOString()
|
||||
}
|
||||
const updateSet: Partial<typeof capaActions.$inferInsert> = {}
|
||||
if ('description' in body && allowed.includes('description')) updateSet.description = body.description
|
||||
if ('due_date' in body && allowed.includes('due_date')) updateSet.dueDate = body.due_date
|
||||
if ('priority' in body && allowed.includes('priority')) updateSet.priority = body.priority
|
||||
if ('status' in body && allowed.includes('status')) updateSet.status = body.status
|
||||
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()
|
||||
|
||||
let oldNotes: string | null = null
|
||||
if ('owner_notes' in update) {
|
||||
const { data: current } = await supabase.from('capa_actions').select('owner_notes').eq('id', id).single()
|
||||
oldNotes = (current as { owner_notes: string | null } | null)?.owner_notes ?? null
|
||||
if ('owner_notes' in body && allowed.includes('owner_notes')) {
|
||||
const [current] = await withUser(session.sub, async tx =>
|
||||
tx.select({ ownerNotes: capaActions.ownerNotes }).from(capaActions).where(eq(capaActions.id, id)).limit(1)
|
||||
)
|
||||
oldNotes = current?.ownerNotes ?? null
|
||||
}
|
||||
|
||||
const admin = createAdminClient()
|
||||
const { error } = await admin
|
||||
.from('capa_actions')
|
||||
.update(update)
|
||||
.eq('id', id)
|
||||
await asAdmin(db => db.update(capaActions).set(updateSet).where(eq(capaActions.id, id)))
|
||||
|
||||
if (error) return NextResponse.json({ error: 'Update failed' }, { status: 500 })
|
||||
// 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 supabase.rpc('write_audit_log', {
|
||||
p_table_name: 'capa_actions',
|
||||
p_record_id: id,
|
||||
p_action: 'updated',
|
||||
p_old_value: oldNotes !== null ? { owner_notes: oldNotes } : undefined,
|
||||
p_new_value: update as Record<string, unknown>,
|
||||
})
|
||||
await withUser(session.sub, async tx =>
|
||||
writeAuditLog(
|
||||
tx,
|
||||
'capa_actions',
|
||||
id,
|
||||
'updated',
|
||||
auditNew,
|
||||
oldNotes !== null ? { owner_notes: oldNotes } : undefined,
|
||||
)
|
||||
)
|
||||
|
||||
return NextResponse.json({ ok: true })
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user