From ff79cd16436a83c72c62e2c33eb198499fb95f31 Mon Sep 17 00:00:00 2001 From: Gitead Date: Mon, 3 Aug 2026 00:56:05 -0400 Subject: [PATCH] fix: earliest patient record wins when duplicates share a phone (inbound SMS/voice) Co-Authored-By: Claude Fable 5 --- apps/Backend/src/routes/twilio-webhooks.ts | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/apps/Backend/src/routes/twilio-webhooks.ts b/apps/Backend/src/routes/twilio-webhooks.ts index 2db50ff3..451565f4 100644 --- a/apps/Backend/src/routes/twilio-webhooks.ts +++ b/apps/Backend/src/routes/twilio-webhooks.ts @@ -193,8 +193,11 @@ router.post("/webhook/sms", async (req: Request, res: Response): Promise => const { From, To, Body, MessageSid } = req.body; const normalizedFrom = (From || "").replace(/\D/g, ""); + // Ordered by id so that when duplicate patients share a phone number + // (one record per insurance), the earliest-created record is the default. const allPatients = await db.patient.findMany({ select: { id: true, phone: true, userId: true, preferredLanguage: true }, + orderBy: { id: "asc" }, }); const patient = allPatients.find( (p) => p.phone && p.phone.replace(/\D/g, "") === normalizedFrom @@ -635,7 +638,8 @@ router.post("/webhook/voice", async (req: Request, res: Response): Promise const { From, CallSid } = req.body; const normalizedFrom = (From || "").replace(/\D/g, ""); - const allPatients = await db.patient.findMany({ select: { id: true, phone: true, userId: true } }); + // Ordered by id — earliest-created record wins when duplicates share a phone. + const allPatients = await db.patient.findMany({ select: { id: true, phone: true, userId: true }, orderBy: { id: "asc" } }); const patient = allPatients.find( (p: { id: number; phone: string | null; userId: number }) => p.phone && p.phone.replace(/\D/g, "") === normalizedFrom );