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:
+79
-42
@@ -1,33 +1,71 @@
|
||||
export const dynamic = 'force-dynamic'
|
||||
|
||||
import { NextRequest, NextResponse } from 'next/server'
|
||||
import { createClient } from '@/lib/supabase/server'
|
||||
import { getSession } from '@/lib/auth/get-session'
|
||||
import { withUser } from '@/lib/db/with-user'
|
||||
import { writeAuditLog } from '@/lib/db/audit'
|
||||
import { capaActions, incidents, users } from '@/lib/db/schema'
|
||||
import { aliasedTable, eq, asc } from 'drizzle-orm'
|
||||
import { createInAppNotifications } from '@/lib/notifications/in-app'
|
||||
|
||||
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')
|
||||
|
||||
let query = 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,
|
||||
incidents (reference_no, incident_type),
|
||||
owner:users!owner_user_id (name, email)
|
||||
`)
|
||||
.order('due_date', { ascending: true })
|
||||
const rows = await withUser(session.sub, async tx => {
|
||||
let q = 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,
|
||||
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))
|
||||
.orderBy(asc(capaActions.dueDate))
|
||||
|
||||
if (session.role === 'supervisor' || session.role === 'worker') {
|
||||
query = query.eq('owner_user_id', session.sub)
|
||||
}
|
||||
if (session.role === 'supervisor' || session.role === 'worker') {
|
||||
q = q.where(eq(capaActions.ownerUserId, session.sub)) as typeof q
|
||||
}
|
||||
|
||||
const { data, error } = await query
|
||||
if (error) return NextResponse.json({ error: 'Fetch failed' }, { status: 500 })
|
||||
return NextResponse.json(data ?? [])
|
||||
return q
|
||||
})
|
||||
|
||||
const data = rows.map(r => ({
|
||||
id: r.id,
|
||||
incident_id: r.incidentId,
|
||||
root_cause_ref: r.rootCauseRef,
|
||||
description: r.description,
|
||||
owner_user_id: r.ownerUserId,
|
||||
department: r.department,
|
||||
due_date: r.dueDate,
|
||||
priority: r.priority,
|
||||
status: r.status,
|
||||
completed_at: r.completedAt,
|
||||
verified_by: r.verifiedBy,
|
||||
verified_at: r.verifiedAt,
|
||||
created_at: r.createdAt,
|
||||
incidents: { reference_no: r.incidentReferenceNo, incident_type: r.incidentType },
|
||||
owner: { name: r.ownerName, email: r.ownerEmail },
|
||||
}))
|
||||
|
||||
return NextResponse.json(data)
|
||||
}
|
||||
|
||||
export async function POST(request: NextRequest) {
|
||||
@@ -36,44 +74,43 @@ export async function POST(request: NextRequest) {
|
||||
if (!['hse', 'admin'].includes(session.role))
|
||||
return NextResponse.json({ error: 'Forbidden' }, { status: 403 })
|
||||
|
||||
const supabase = await createClient()
|
||||
|
||||
const body = await request.json()
|
||||
const { incident_id, description, owner_user_id, department, due_date, priority, root_cause_ref } = body
|
||||
|
||||
if (!incident_id || !description || !owner_user_id || !due_date)
|
||||
return NextResponse.json({ error: 'Missing required fields' }, { status: 422 })
|
||||
|
||||
const { data: capa, error } = await supabase
|
||||
.from('capa_actions')
|
||||
.insert({
|
||||
incident_id,
|
||||
description,
|
||||
owner_user_id,
|
||||
department: department || '',
|
||||
due_date,
|
||||
priority: priority ?? 'med',
|
||||
root_cause_ref: root_cause_ref ?? null,
|
||||
let capaId!: string
|
||||
|
||||
await withUser(session.sub, async tx => {
|
||||
const [capa] = await tx
|
||||
.insert(capaActions)
|
||||
.values({
|
||||
incidentId: incident_id,
|
||||
description,
|
||||
ownerUserId: owner_user_id,
|
||||
department: department || '',
|
||||
dueDate: due_date,
|
||||
priority: priority ?? 'med',
|
||||
rootCauseRef: root_cause_ref ?? null,
|
||||
})
|
||||
.returning({ id: capaActions.id })
|
||||
|
||||
if (!capa) throw new Error('Insert failed')
|
||||
capaId = capa.id
|
||||
|
||||
await writeAuditLog(tx, 'capa_actions', capa.id, 'created', {
|
||||
incident_id, description, owner_user_id, department, due_date,
|
||||
})
|
||||
.select('id')
|
||||
.single()
|
||||
|
||||
if (error || !capa) return NextResponse.json({ error: 'Insert failed' }, { status: 500 })
|
||||
|
||||
await supabase.rpc('write_audit_log', {
|
||||
p_table_name: 'capa_actions',
|
||||
p_record_id: capa.id,
|
||||
p_action: 'created',
|
||||
p_new_value: { incident_id, description, owner_user_id, department, due_date },
|
||||
})
|
||||
|
||||
await createInAppNotifications([{
|
||||
userId: owner_user_id,
|
||||
title: `CAPA assigned to you, due ${due_date}`,
|
||||
link: `/hse/capa/${capa.id}`,
|
||||
link: `/hse/capa/${capaId}`,
|
||||
incidentId: incident_id,
|
||||
capaId: capa.id,
|
||||
capaId,
|
||||
}])
|
||||
|
||||
return NextResponse.json({ id: capa.id }, { status: 201 })
|
||||
return NextResponse.json({ id: capaId }, { status: 201 })
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user