init-source
This commit is contained in:
@@ -0,0 +1,78 @@
|
||||
import type { NextApiRequest, NextApiResponse } from 'next'
|
||||
import { prisma } from '@/lib/prisma'
|
||||
import { requireAuth, logAction } from '@/lib/auth'
|
||||
import { notifySolutionConfirmed } from '@/lib/email'
|
||||
import { NCRSeverity, NCRStatus } from '@prisma/client'
|
||||
|
||||
export default async function handler(req: NextApiRequest, res: NextApiResponse) {
|
||||
const user = await requireAuth(req, res, ['ADMIN', 'QC'])
|
||||
if (!user) return
|
||||
|
||||
const { id } = req.query as { id: string }
|
||||
|
||||
const ncr = await prisma.nCR.findUnique({
|
||||
where: { id },
|
||||
include: { raisedBy: { select: { id: true, name: true, email: true } }, capa: { select: { ref: true } } },
|
||||
})
|
||||
if (!ncr) return res.status(404).json({ error: 'NCR not found' })
|
||||
|
||||
if (req.method === 'GET') {
|
||||
return res.json({ data: ncr })
|
||||
}
|
||||
|
||||
if (req.method === 'PATCH') {
|
||||
const before = { ...ncr }
|
||||
const { severity, status, resolution, category, confirmNotify } = req.body as {
|
||||
severity?: NCRSeverity
|
||||
status?: NCRStatus
|
||||
resolution?: string
|
||||
category?: string
|
||||
confirmNotify?: boolean
|
||||
}
|
||||
|
||||
const updateData: any = {}
|
||||
|
||||
if (severity !== undefined) updateData.severity = severity
|
||||
|
||||
if (status !== undefined) updateData.status = status
|
||||
|
||||
if (resolution !== undefined && category !== undefined) {
|
||||
// Resolving — requires both resolution notes and a category, files to library
|
||||
updateData.resolution = resolution
|
||||
updateData.category = category
|
||||
updateData.status = 'RESOLVED'
|
||||
updateData.resolvedAt = new Date()
|
||||
}
|
||||
|
||||
if (confirmNotify) {
|
||||
updateData.notified = true
|
||||
updateData.notifiedAt = new Date()
|
||||
}
|
||||
|
||||
const updated = await prisma.nCR.update({
|
||||
where: { id },
|
||||
data: updateData,
|
||||
include: { raisedBy: { select: { id: true, name: true, email: true } }, capa: { select: { ref: true } } },
|
||||
})
|
||||
|
||||
// File to resolutions library
|
||||
if (resolution !== undefined && category !== undefined) {
|
||||
await prisma.resolution.create({
|
||||
data: {
|
||||
title: ncr.description.length > 80 ? ncr.description.slice(0, 80) + '…' : ncr.description,
|
||||
category, resolution, linkedRef: ncr.ref,
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// Confirm-and-notify: emails/notifies whoever raised the NCR
|
||||
if (confirmNotify && ncr.raisedBy) {
|
||||
await notifySolutionConfirmed(ncr.ref, ncr.description, ncr.raisedBy.email, ncr.raisedBy.id)
|
||||
}
|
||||
|
||||
await logAction(user.id, 'UPDATE', 'NCR', id, before, updated)
|
||||
return res.json({ data: updated })
|
||||
}
|
||||
|
||||
res.status(405).end()
|
||||
}
|
||||
Reference in New Issue
Block a user