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 <noreply@anthropic.com>
This commit is contained in:
ff
2026-05-17 23:06:36 -04:00
parent 8cab823d60
commit de995de2ad

View File

@@ -137,6 +137,22 @@ router.delete("/:id", async (req: Request, res: Response):Promise<any> => {
const id = parseInt(idParam); const id = parseInt(idParam);
if (isNaN(id)) return res.status(400).send("Invalid user ID"); 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); const success = await storage.deleteUser(id);
if (!success) return res.status(404).send("User not found"); if (!success) return res.status(404).send("User not found");