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 );