From de995de2ad6fcfb5f48ccd4678e7e208e3df1c89 Mon Sep 17 00:00:00 2001 From: ff Date: Sun, 17 May 2026 23:06:36 -0400 Subject: [PATCH] fix: allow deleting users by reassigning their records to admin first Deleting users with patients/appointments/claims was blocked by FK constraints. Now reassigns those records to the requesting admin before deletion, and cleans up user-specific data (backups, cloud files). Co-Authored-By: Claude Sonnet 4.6 --- apps/Backend/src/routes/users.ts | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/apps/Backend/src/routes/users.ts b/apps/Backend/src/routes/users.ts index 3e0f3a32..4097700c 100755 --- a/apps/Backend/src/routes/users.ts +++ b/apps/Backend/src/routes/users.ts @@ -137,6 +137,22 @@ router.delete("/:id", async (req: Request, res: Response):Promise => { const id = parseInt(idParam); if (isNaN(id)) return res.status(400).send("Invalid user ID"); + if (id === req.user!.id) return res.status(400).json({ error: "Cannot delete your own account" }); + + const adminId = req.user!.id; + + // Reassign all records owned by this user to the requesting admin + // before deletion to satisfy foreign key constraints. + const { prisma } = await import("@repo/db/client"); + await prisma.$transaction([ + prisma.patient.updateMany({ where: { userId: id }, data: { userId: adminId } }), + prisma.appointment.updateMany({ where: { userId: id }, data: { userId: adminId } }), + prisma.claim.updateMany({ where: { userId: id }, data: { userId: adminId } }), + prisma.backupDestination.deleteMany({ where: { userId: id } }), + prisma.cloudFile.deleteMany({ where: { userId: id } }), + prisma.cloudFolder.deleteMany({ where: { userId: id } }), + ]); + const success = await storage.deleteUser(id); if (!success) return res.status(404).send("User not found");