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'
|
export const dynamic = 'force-dynamic'
|
||||||
|
|
||||||
import { NextRequest, NextResponse } from 'next/server'
|
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 { 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(
|
export async function GET(
|
||||||
_: NextRequest,
|
_: NextRequest,
|
||||||
@@ -13,31 +15,66 @@ export async function GET(
|
|||||||
const session = await getSession()
|
const session = await getSession()
|
||||||
if (!session) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
|
if (!session) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
|
||||||
|
|
||||||
const supabase = await createClient()
|
const ownerAlias = aliasedTable(users, 'owner')
|
||||||
|
|
||||||
const { data, error } = await supabase
|
const [row] = await withUser(session.sub, async tx =>
|
||||||
.from('capa_actions')
|
tx
|
||||||
.select(`
|
.select({
|
||||||
id, incident_id, root_cause_ref, description, owner_user_id, department,
|
id: capaActions.id,
|
||||||
due_date, priority, status, completed_at, verified_by, verified_at, created_at,
|
incidentId: capaActions.incidentId,
|
||||||
owner_notes,
|
rootCauseRef: capaActions.rootCauseRef,
|
||||||
incidents (reference_no, incident_type),
|
description: capaActions.description,
|
||||||
owner:users!owner_user_id (name, email)
|
ownerUserId: capaActions.ownerUserId,
|
||||||
`)
|
department: capaActions.department,
|
||||||
.eq('id', id)
|
dueDate: capaActions.dueDate,
|
||||||
.single()
|
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 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
|
const canRead = ['hse', 'admin', 'supervisor'].includes(role) || isOwner
|
||||||
if (!canRead) return NextResponse.json({ error: 'Forbidden' }, { status: 403 })
|
if (!canRead) return NextResponse.json({ error: 'Forbidden' }, { status: 403 })
|
||||||
|
|
||||||
// Strip owner email for non-privileged roles — only name needed
|
const ownerField = ['hse', 'admin'].includes(role)
|
||||||
const result = ['hse', 'admin'].includes(role)
|
? { name: row.ownerName, email: row.ownerEmail }
|
||||||
? data
|
: { name: row.ownerName ?? '' }
|
||||||
: { ...data, owner: { name: (data.owner as unknown as { name: string } | null)?.name ?? '' } }
|
|
||||||
|
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)
|
return NextResponse.json(result)
|
||||||
}
|
}
|
||||||
@@ -50,11 +87,14 @@ export async function PATCH(
|
|||||||
const session = await getSession()
|
const session = await getSession()
|
||||||
if (!session) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
|
if (!session) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
|
||||||
|
|
||||||
const supabase = await createClient()
|
|
||||||
const role = session.role
|
const role = session.role
|
||||||
|
|
||||||
const { data: capa } = await supabase.from('capa_actions').select('owner_user_id, status').eq('id', id).single()
|
const [capa] = await withUser(session.sub, async tx =>
|
||||||
const isOwner = capa?.owner_user_id === session.sub
|
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
|
const canEdit = ['hse', 'admin'].includes(role) || isOwner
|
||||||
if (!canEdit) return NextResponse.json({ error: 'Forbidden' }, { status: 403 })
|
if (!canEdit) return NextResponse.json({ error: 'Forbidden' }, { status: 403 })
|
||||||
|
|
||||||
@@ -65,7 +105,6 @@ export async function PATCH(
|
|||||||
|
|
||||||
const body = await request.json()
|
const body = await request.json()
|
||||||
|
|
||||||
// Only hse/admin can set privileged statuses
|
|
||||||
const privilegedStatuses = ['verified', 'reopened', 'closed']
|
const privilegedStatuses = ['verified', 'reopened', 'closed']
|
||||||
if (body.status && privilegedStatuses.includes(body.status) && !['hse', 'admin'].includes(role)) {
|
if (body.status && privilegedStatuses.includes(body.status) && !['hse', 'admin'].includes(role)) {
|
||||||
return NextResponse.json({ error: 'Forbidden' }, { status: 403 })
|
return NextResponse.json({ error: 'Forbidden' }, { status: 403 })
|
||||||
@@ -74,36 +113,44 @@ export async function PATCH(
|
|||||||
const allowed = ['hse', 'admin'].includes(role)
|
const allowed = ['hse', 'admin'].includes(role)
|
||||||
? ['description', 'due_date', 'priority', 'status', 'department', 'root_cause_ref', 'owner_notes']
|
? ['description', 'due_date', 'priority', 'status', 'department', 'root_cause_ref', 'owner_notes']
|
||||||
: ['status', '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') {
|
const updateSet: Partial<typeof capaActions.$inferInsert> = {}
|
||||||
update.completed_at = new Date().toISOString()
|
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
|
let oldNotes: string | null = null
|
||||||
if ('owner_notes' in update) {
|
if ('owner_notes' in body && allowed.includes('owner_notes')) {
|
||||||
const { data: current } = await supabase.from('capa_actions').select('owner_notes').eq('id', id).single()
|
const [current] = await withUser(session.sub, async tx =>
|
||||||
oldNotes = (current as { owner_notes: string | null } | null)?.owner_notes ?? null
|
tx.select({ ownerNotes: capaActions.ownerNotes }).from(capaActions).where(eq(capaActions.id, id)).limit(1)
|
||||||
|
)
|
||||||
|
oldNotes = current?.ownerNotes ?? null
|
||||||
}
|
}
|
||||||
|
|
||||||
const admin = createAdminClient()
|
await asAdmin(db => db.update(capaActions).set(updateSet).where(eq(capaActions.id, id)))
|
||||||
const { error } = await admin
|
|
||||||
.from('capa_actions')
|
|
||||||
.update(update)
|
|
||||||
.eq('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', {
|
await withUser(session.sub, async tx =>
|
||||||
p_table_name: 'capa_actions',
|
writeAuditLog(
|
||||||
p_record_id: id,
|
tx,
|
||||||
p_action: 'updated',
|
'capa_actions',
|
||||||
p_old_value: oldNotes !== null ? { owner_notes: oldNotes } : undefined,
|
id,
|
||||||
p_new_value: update as Record<string, unknown>,
|
'updated',
|
||||||
})
|
auditNew,
|
||||||
|
oldNotes !== null ? { owner_notes: oldNotes } : undefined,
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
return NextResponse.json({ ok: true })
|
return NextResponse.json({ ok: true })
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,8 +1,11 @@
|
|||||||
export const dynamic = 'force-dynamic'
|
export const dynamic = 'force-dynamic'
|
||||||
|
|
||||||
import { NextRequest, NextResponse } from 'next/server'
|
import { NextRequest, NextResponse } from 'next/server'
|
||||||
import { createClient } from '@/lib/supabase/server'
|
|
||||||
import { getSession } from '@/lib/auth/get-session'
|
import { getSession } from '@/lib/auth/get-session'
|
||||||
|
import { withUser } from '@/lib/db/with-user'
|
||||||
|
import { writeAuditLog } from '@/lib/db/audit'
|
||||||
|
import { capaActions, incidents } from '@/lib/db/schema'
|
||||||
|
import { eq, and, not, inArray } from 'drizzle-orm'
|
||||||
import { createInAppNotifications } from '@/lib/notifications/in-app'
|
import { createInAppNotifications } from '@/lib/notifications/in-app'
|
||||||
|
|
||||||
export async function POST(
|
export async function POST(
|
||||||
@@ -15,10 +18,10 @@ export async function POST(
|
|||||||
if (!['hse', 'admin'].includes(session.role))
|
if (!['hse', 'admin'].includes(session.role))
|
||||||
return NextResponse.json({ error: 'Forbidden' }, { status: 403 })
|
return NextResponse.json({ error: 'Forbidden' }, { status: 403 })
|
||||||
|
|
||||||
const supabase = await createClient()
|
const [capa] = await withUser(session.sub, async tx =>
|
||||||
|
tx.select({ status: capaActions.status, incidentId: capaActions.incidentId, ownerUserId: capaActions.ownerUserId })
|
||||||
const { data: capa } = await supabase
|
.from(capaActions).where(eq(capaActions.id, id)).limit(1)
|
||||||
.from('capa_actions').select('status, incident_id, owner_user_id').eq('id', id).single()
|
)
|
||||||
if (!capa) return NextResponse.json({ error: 'Not found' }, { status: 404 })
|
if (!capa) return NextResponse.json({ error: 'Not found' }, { status: 404 })
|
||||||
if (capa.status !== 'pending_verification')
|
if (capa.status !== 'pending_verification')
|
||||||
return NextResponse.json({ error: 'CAPA must be pending_verification' }, { status: 409 })
|
return NextResponse.json({ error: 'CAPA must be pending_verification' }, { status: 409 })
|
||||||
@@ -31,54 +34,47 @@ export async function POST(
|
|||||||
const recheckDate = new Date(verifiedAt)
|
const recheckDate = new Date(verifiedAt)
|
||||||
recheckDate.setUTCDate(recheckDate.getUTCDate() + 30)
|
recheckDate.setUTCDate(recheckDate.getUTCDate() + 30)
|
||||||
|
|
||||||
const update: Record<string, unknown> = {
|
await withUser(session.sub, async tx => {
|
||||||
status: body.verdict,
|
await tx.update(capaActions).set({
|
||||||
verified_by: session.sub,
|
status: body.verdict,
|
||||||
verified_at: verifiedAt.toISOString(),
|
verifiedBy: session.sub,
|
||||||
...(body.verdict === 'verified'
|
verifiedAt,
|
||||||
? {
|
...(body.verdict === 'verified' ? {
|
||||||
effectiveness_recheck_date: recheckDate.toISOString().split('T')[0],
|
effectivenessRecheckDate: recheckDate.toISOString().split('T')[0],
|
||||||
effectiveness_recheck_round: 0,
|
effectivenessRecheckRound: 0,
|
||||||
}
|
} : {}),
|
||||||
: {}),
|
}).where(eq(capaActions.id, id))
|
||||||
}
|
|
||||||
|
|
||||||
const { error } = await supabase
|
await writeAuditLog(tx, 'capa_actions', id, body.verdict === 'verified' ? 'verified' : 'reopened', {
|
||||||
.from('capa_actions').update(update).eq('id', id)
|
status: body.verdict, reopen_reason: body.reopen_reason ?? null,
|
||||||
|
})
|
||||||
if (error) return NextResponse.json({ error: 'Update failed' }, { status: 500 })
|
|
||||||
|
|
||||||
await supabase.rpc('write_audit_log', {
|
|
||||||
p_table_name: 'capa_actions',
|
|
||||||
p_record_id: id,
|
|
||||||
p_action: body.verdict === 'verified' ? 'verified' : 'reopened',
|
|
||||||
p_new_value: { ...update, reopen_reason: body.reopen_reason ?? null },
|
|
||||||
})
|
})
|
||||||
|
|
||||||
if (capa.owner_user_id) {
|
if (capa.ownerUserId) {
|
||||||
await createInAppNotifications([{
|
await createInAppNotifications([{
|
||||||
userId: capa.owner_user_id,
|
userId: capa.ownerUserId,
|
||||||
title: body.verdict === 'verified'
|
title: body.verdict === 'verified'
|
||||||
? 'Your CAPA action was verified'
|
? 'Your CAPA action was verified'
|
||||||
: `Your CAPA action was reopened${body.reopen_reason ? `: ${body.reopen_reason}` : ''}`,
|
: `Your CAPA action was reopened${body.reopen_reason ? `: ${body.reopen_reason}` : ''}`,
|
||||||
link: `/hse/capa/${id}`,
|
link: `/hse/capa/${id}`,
|
||||||
incidentId: capa.incident_id,
|
incidentId: capa.incidentId,
|
||||||
capaId: id,
|
capaId: id,
|
||||||
}])
|
}])
|
||||||
}
|
}
|
||||||
|
|
||||||
// Check if all CAPAs for this incident are verified — if so, transition incident to verification
|
const openCapas = await withUser(session.sub, async tx =>
|
||||||
const { data: openCapas } = await supabase
|
tx.select({ id: capaActions.id }).from(capaActions)
|
||||||
.from('capa_actions')
|
.where(and(
|
||||||
.select('id')
|
eq(capaActions.incidentId, capa.incidentId),
|
||||||
.eq('incident_id', capa.incident_id)
|
not(inArray(capaActions.status, ['verified', 'closed'])),
|
||||||
.not('status', 'in', '(verified,closed)')
|
))
|
||||||
|
)
|
||||||
|
|
||||||
if (!openCapas || openCapas.length === 0) {
|
if (openCapas.length === 0) {
|
||||||
await supabase
|
await withUser(session.sub, async tx => {
|
||||||
.from('incidents')
|
await tx.update(incidents).set({ status: 'verification' }).where(eq(incidents.id, capa.incidentId))
|
||||||
.update({ status: 'verification' })
|
await writeAuditLog(tx, 'incidents', capa.incidentId, 'status_changed', { status: 'verification' })
|
||||||
.eq('id', capa.incident_id)
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
return NextResponse.json({ ok: true })
|
return NextResponse.json({ ok: true })
|
||||||
|
|||||||
+79
-42
@@ -1,33 +1,71 @@
|
|||||||
export const dynamic = 'force-dynamic'
|
export const dynamic = 'force-dynamic'
|
||||||
|
|
||||||
import { NextRequest, NextResponse } from 'next/server'
|
import { NextRequest, NextResponse } from 'next/server'
|
||||||
import { createClient } from '@/lib/supabase/server'
|
|
||||||
import { getSession } from '@/lib/auth/get-session'
|
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'
|
import { createInAppNotifications } from '@/lib/notifications/in-app'
|
||||||
|
|
||||||
export async function GET() {
|
export async function GET() {
|
||||||
const session = await getSession()
|
const session = await getSession()
|
||||||
if (!session) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
|
if (!session) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
|
||||||
|
|
||||||
const supabase = await createClient()
|
const ownerAlias = aliasedTable(users, 'owner')
|
||||||
|
|
||||||
let query = supabase
|
const rows = await withUser(session.sub, async tx => {
|
||||||
.from('capa_actions')
|
let q = tx
|
||||||
.select(`
|
.select({
|
||||||
id, incident_id, root_cause_ref, description, owner_user_id, department,
|
id: capaActions.id,
|
||||||
due_date, priority, status, completed_at, verified_by, verified_at, created_at,
|
incidentId: capaActions.incidentId,
|
||||||
incidents (reference_no, incident_type),
|
rootCauseRef: capaActions.rootCauseRef,
|
||||||
owner:users!owner_user_id (name, email)
|
description: capaActions.description,
|
||||||
`)
|
ownerUserId: capaActions.ownerUserId,
|
||||||
.order('due_date', { ascending: true })
|
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') {
|
if (session.role === 'supervisor' || session.role === 'worker') {
|
||||||
query = query.eq('owner_user_id', session.sub)
|
q = q.where(eq(capaActions.ownerUserId, session.sub)) as typeof q
|
||||||
}
|
}
|
||||||
|
|
||||||
const { data, error } = await query
|
return q
|
||||||
if (error) return NextResponse.json({ error: 'Fetch failed' }, { status: 500 })
|
})
|
||||||
return NextResponse.json(data ?? [])
|
|
||||||
|
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) {
|
export async function POST(request: NextRequest) {
|
||||||
@@ -36,44 +74,43 @@ export async function POST(request: NextRequest) {
|
|||||||
if (!['hse', 'admin'].includes(session.role))
|
if (!['hse', 'admin'].includes(session.role))
|
||||||
return NextResponse.json({ error: 'Forbidden' }, { status: 403 })
|
return NextResponse.json({ error: 'Forbidden' }, { status: 403 })
|
||||||
|
|
||||||
const supabase = await createClient()
|
|
||||||
|
|
||||||
const body = await request.json()
|
const body = await request.json()
|
||||||
const { incident_id, description, owner_user_id, department, due_date, priority, root_cause_ref } = body
|
const { incident_id, description, owner_user_id, department, due_date, priority, root_cause_ref } = body
|
||||||
|
|
||||||
if (!incident_id || !description || !owner_user_id || !due_date)
|
if (!incident_id || !description || !owner_user_id || !due_date)
|
||||||
return NextResponse.json({ error: 'Missing required fields' }, { status: 422 })
|
return NextResponse.json({ error: 'Missing required fields' }, { status: 422 })
|
||||||
|
|
||||||
const { data: capa, error } = await supabase
|
let capaId!: string
|
||||||
.from('capa_actions')
|
|
||||||
.insert({
|
await withUser(session.sub, async tx => {
|
||||||
incident_id,
|
const [capa] = await tx
|
||||||
description,
|
.insert(capaActions)
|
||||||
owner_user_id,
|
.values({
|
||||||
department: department || '',
|
incidentId: incident_id,
|
||||||
due_date,
|
description,
|
||||||
priority: priority ?? 'med',
|
ownerUserId: owner_user_id,
|
||||||
root_cause_ref: root_cause_ref ?? null,
|
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([{
|
await createInAppNotifications([{
|
||||||
userId: owner_user_id,
|
userId: owner_user_id,
|
||||||
title: `CAPA assigned to you, due ${due_date}`,
|
title: `CAPA assigned to you, due ${due_date}`,
|
||||||
link: `/hse/capa/${capa.id}`,
|
link: `/hse/capa/${capaId}`,
|
||||||
incidentId: incident_id,
|
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