feat: allow company deletion by detaching dependents

This commit is contained in:
Esdras Renan 2025-10-16 22:28:12 -03:00
parent 2980885bf8
commit 7951bc25a3
3 changed files with 32 additions and 21 deletions

View file

@ -77,23 +77,20 @@ export async function DELETE(_: Request, { params }: { params: Promise<{ id: str
}
try {
// Préchecagem para evitar 500 por FK: conta vínculos antes
const [usersCount, ticketsCount] = await Promise.all([
prisma.user.count({ where: { companyId: company.id } }),
prisma.ticket.count({ where: { companyId: company.id } }),
])
if (usersCount > 0 || ticketsCount > 0) {
return NextResponse.json(
{
error: "Não é possível remover esta empresa pois existem registros vinculados.",
details: { users: usersCount, tickets: ticketsCount },
},
{ status: 409 }
)
}
const result = await prisma.$transaction(async (tx) => {
const users = await tx.user.updateMany({
where: { companyId: company.id, tenantId: company.tenantId },
data: { companyId: null },
})
const tickets = await tx.ticket.updateMany({
where: { companyId: company.id, tenantId: company.tenantId },
data: { companyId: null },
})
await tx.company.delete({ where: { id: company.id } })
return { detachedUsers: users.count, detachedTickets: tickets.count }
})
await prisma.company.delete({ where: { id: company.id } })
return NextResponse.json({ ok: true })
return NextResponse.json({ ok: true, ...result })
} catch (error) {
if (error instanceof PrismaClientKnownRequestError && error.code === "P2003") {
return NextResponse.json(