feat: secondary insurance; SCO primary + MassHealth secondary rule; United SCO service history
- Patient: new secondaryInsuranceProvider / secondaryInsuranceId (form section, Patient Details, merge fill) - MassHealth check on an SCO patient (Tufts SCO / United SCO primary), matched by MassHealth ID on file as secondary or by the single SCO patient with the same DOB (name must share a word when the portal returns one): MassHealth saved as secondary, primary plan/ID/status unchanged, MassHealth history not imported, PDF still saved to Eligibility documents. Prevents the name+DOB fallback from overwriting the SCO ID - United SCO check: a MassHealth patient moved to United SCO keeps the old MassHealth ID as secondary; reads Dental Hub Service History and saves it - Service history saves drop duplicate identical lines - Chatbot: bare 100… member ID + DOB with no patient/insurance defaults to MassHealth Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -462,11 +462,14 @@ async function handleEligibilityById(
|
||||
};
|
||||
}
|
||||
|
||||
// Determine siteKey (defaults to DDMA when no payer is specified)
|
||||
// Determine siteKey (defaults to DDMA when no payer is specified, except MassHealth-style
|
||||
// IDs "100…" — e.g. the MassHealth ID of an SCO patient, whose record holds the SCO ID)
|
||||
const siteKey =
|
||||
patient?.insuranceProvider || c.insuranceHint
|
||||
? resolveSiteKey(patient?.insuranceProvider ?? null, c.insuranceHint ?? null)
|
||||
: "DDMA";
|
||||
: /^100\d{6,}$/.test(memberId)
|
||||
? "MH"
|
||||
: "DDMA";
|
||||
|
||||
const label = patient
|
||||
? `${patient.firstName ?? ""} ${patient.lastName ?? ""}`.trim()
|
||||
|
||||
@@ -218,3 +218,65 @@ export async function createOrUpdatePatientByInsuranceId(options: {
|
||||
? storage.getPatientByInsuranceIdAndDob(normalizedId, dobDate)
|
||||
: storage.getPatientByInsuranceId(normalizedId);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// SCO + MassHealth: an SCO plan (Tufts SCO / United SCO) is the primary insurance
|
||||
// and MassHealth is kept as the secondary.
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
export const isScoProvider = (provider?: string | null): boolean =>
|
||||
!!provider && /(tufts|united).*sco/i.test(provider);
|
||||
|
||||
/** "1948-08-23", "08/23/1948" or a Date → midnight UTC of that day. */
|
||||
export function dobToUtcDay(dob: string | Date | null | undefined): Date | null {
|
||||
if (!dob) return null;
|
||||
if (dob instanceof Date) {
|
||||
return isNaN(dob.getTime())
|
||||
? null
|
||||
: new Date(Date.UTC(dob.getUTCFullYear(), dob.getUTCMonth(), dob.getUTCDate()));
|
||||
}
|
||||
const s = dob.trim();
|
||||
let m = s.match(/^(\d{4})-(\d{1,2})-(\d{1,2})/);
|
||||
if (m) return new Date(Date.UTC(+m[1]!, +m[2]! - 1, +m[3]!));
|
||||
m = s.match(/^(\d{1,2})\/(\d{1,2})\/(\d{4})$/);
|
||||
if (m) return new Date(Date.UTC(+m[3]!, +m[1]! - 1, +m[2]!));
|
||||
return null;
|
||||
}
|
||||
|
||||
const nameTokens = (s: string) =>
|
||||
s.toUpperCase().split(/[^A-Z]+/).filter((t) => t.length > 1);
|
||||
|
||||
/**
|
||||
* The SCO patient a MassHealth check belongs to, or null for the normal MassHealth flow.
|
||||
* 1. A patient whose primary ID is this MassHealth ID → normal flow (null)
|
||||
* 2. An SCO patient that already has this MassHealth ID as secondary
|
||||
* 3. The only SCO patient with the same DOB (and, when the MassHealth portal
|
||||
* returned a name, sharing at least one name word with it)
|
||||
*/
|
||||
export async function findScoPatientForMassHealth(opts: {
|
||||
mhId: string;
|
||||
dob?: string | Date | null;
|
||||
firstName?: string | null;
|
||||
lastName?: string | null;
|
||||
}) {
|
||||
const mhId = opts.mhId.replace(/\s+/g, "");
|
||||
if (await storage.getPatientByInsuranceId(mhId)) return null;
|
||||
|
||||
const bySecondary = await storage.getPatientBySecondaryInsuranceId(mhId);
|
||||
if (bySecondary && isScoProvider(bySecondary.insuranceProvider)) return bySecondary;
|
||||
|
||||
const day = dobToUtcDay(opts.dob);
|
||||
if (!day) return null;
|
||||
const incoming = nameTokens(`${opts.firstName ?? ""} ${opts.lastName ?? ""}`);
|
||||
const candidates = (await storage.getPatientsByDobDay(day)).filter((p) => {
|
||||
if (!isScoProvider(p.insuranceProvider)) return false;
|
||||
if (incoming.length === 0) return true;
|
||||
const theirs = new Set(nameTokens(`${p.firstName ?? ""} ${p.lastName ?? ""}`));
|
||||
return incoming.some((t) => theirs.has(t));
|
||||
});
|
||||
if (candidates.length === 1) return candidates[0]!;
|
||||
if (candidates.length > 1) {
|
||||
console.log(`[findScoPatientForMassHealth] ${candidates.length} SCO patients share DOB ${day.toISOString().slice(0, 10)}; not guessing`);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
@@ -16,6 +16,7 @@ import {
|
||||
createOrUpdatePatientByInsuranceId,
|
||||
imageToPdfBuffer,
|
||||
memberDetailDemographics,
|
||||
findScoPatientForMassHealth,
|
||||
} from "./_shared";
|
||||
import { io } from "../../socket";
|
||||
|
||||
@@ -79,15 +80,27 @@ async function processMHResult(
|
||||
? splitName(rawName)
|
||||
: { firstName: formFirstName ?? "", lastName: formLastName ?? "" };
|
||||
|
||||
await createOrUpdatePatientByInsuranceId({
|
||||
insuranceId,
|
||||
// SCO member (Tufts SCO / United SCO primary): MassHealth is only the secondary
|
||||
// insurance. Keep the SCO plan, member ID and status; don't import MassHealth
|
||||
// service history. The eligibility PDF is still saved to the patient's documents.
|
||||
const scoPatient = await findScoPatientForMassHealth({
|
||||
mhId: insuranceId,
|
||||
dob: formDob,
|
||||
firstName,
|
||||
lastName,
|
||||
dob: formDob,
|
||||
userId,
|
||||
});
|
||||
|
||||
const patient = await storage.getPatientByInsuranceId(insuranceId);
|
||||
if (!scoPatient) {
|
||||
await createOrUpdatePatientByInsuranceId({
|
||||
insuranceId,
|
||||
firstName,
|
||||
lastName,
|
||||
dob: formDob,
|
||||
userId,
|
||||
});
|
||||
}
|
||||
|
||||
const patient = scoPatient ?? (await storage.getPatientByInsuranceId(insuranceId));
|
||||
if (!patient?.id) {
|
||||
output.patientUpdateStatus = "Patient not found; no update performed";
|
||||
return output;
|
||||
@@ -114,23 +127,36 @@ async function processMHResult(
|
||||
? seleniumResult.remainingBenefit.trim()
|
||||
: "";
|
||||
|
||||
await storage.updatePatient(patient.id, {
|
||||
status: newStatus,
|
||||
insuranceProvider: /masshealth/i.test(planName) ? planName : "MassHealth",
|
||||
...(remainingBenefit ? { remainingBenefit } : {}),
|
||||
...memberDetailDemographics(seleniumResult, patient.phone),
|
||||
});
|
||||
// Only replace when rows came back — an empty read may just mean the portal
|
||||
// was slow, and shouldn't wipe history saved by an earlier check.
|
||||
if (Array.isArray(seleniumResult?.service_history) && seleniumResult.service_history.length > 0) {
|
||||
try {
|
||||
await storage.replacePatientServiceHistory(patient.id, seleniumResult.service_history);
|
||||
} catch (e: any) {
|
||||
console.error("[mh-processor] saving service history failed:", e.message);
|
||||
if (scoPatient) {
|
||||
await storage.updatePatient(patient.id, {
|
||||
secondaryInsuranceProvider: "MassHealth",
|
||||
secondaryInsuranceId: insuranceId.replace(/\s+/g, ""),
|
||||
} as any);
|
||||
log("mh-processor", "SCO patient: MassHealth saved as secondary", {
|
||||
patientId: patient.id,
|
||||
primary: patient.insuranceProvider,
|
||||
});
|
||||
output.patientUpdateStatus =
|
||||
`MassHealth ${newStatus} — saved as secondary insurance; primary (${patient.insuranceProvider}) unchanged`;
|
||||
} else {
|
||||
await storage.updatePatient(patient.id, {
|
||||
status: newStatus,
|
||||
insuranceProvider: /masshealth/i.test(planName) ? planName : "MassHealth",
|
||||
...(remainingBenefit ? { remainingBenefit } : {}),
|
||||
...memberDetailDemographics(seleniumResult, patient.phone),
|
||||
});
|
||||
// Only replace when rows came back — an empty read may just mean the portal
|
||||
// was slow, and shouldn't wipe history saved by an earlier check.
|
||||
if (Array.isArray(seleniumResult?.service_history) && seleniumResult.service_history.length > 0) {
|
||||
try {
|
||||
await storage.replacePatientServiceHistory(patient.id, seleniumResult.service_history);
|
||||
} catch (e: any) {
|
||||
console.error("[mh-processor] saving service history failed:", e.message);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
output.patientUpdateStatus = `Patient status updated to ${newStatus}`;
|
||||
output.patientUpdateStatus = `Patient status updated to ${newStatus}`;
|
||||
}
|
||||
|
||||
let pdfBuffer: Buffer | null = null;
|
||||
let pdfFilename: string | null = null;
|
||||
|
||||
@@ -86,6 +86,15 @@ async function processUnitedSCOResult(
|
||||
? splitName(rawName)
|
||||
: { firstName: formFirstName ?? "", lastName: formLastName ?? "" };
|
||||
|
||||
// A MassHealth patient who joined United SCO is matched by name+DOB below and moved
|
||||
// to the SCO ID — remember their MassHealth ID so it's kept as the secondary insurance.
|
||||
const dobForLookup = formDob ? new Date(formDob) : null;
|
||||
const before =
|
||||
(await storage.getPatientByInsuranceId(insuranceId)) ??
|
||||
(dobForLookup && !isNaN(dobForLookup.getTime()) && firstName && lastName
|
||||
? await storage.getPatientByNameAndDob(firstName, lastName, dobForLookup)
|
||||
: null);
|
||||
|
||||
// 2) Create / update patient
|
||||
await createOrUpdatePatientByInsuranceId({
|
||||
insuranceId,
|
||||
@@ -111,6 +120,21 @@ async function processUnitedSCOResult(
|
||||
const statusUpdates: any = { insuranceProvider: "United Healthcare SCO" };
|
||||
if (newStatus) statusUpdates.status = newStatus;
|
||||
|
||||
if (
|
||||
before?.id === patient.id &&
|
||||
/masshealth/i.test(before.insuranceProvider ?? "") &&
|
||||
before.insuranceId &&
|
||||
before.insuranceId !== insuranceId &&
|
||||
!(patient as any).secondaryInsuranceId
|
||||
) {
|
||||
statusUpdates.secondaryInsuranceProvider = "MassHealth";
|
||||
statusUpdates.secondaryInsuranceId = before.insuranceId;
|
||||
log("unitedsco-processor", "MassHealth patient moved to United SCO; MassHealth kept as secondary", {
|
||||
patientId: patient.id,
|
||||
massHealthId: before.insuranceId,
|
||||
});
|
||||
}
|
||||
|
||||
// The eligibility page can report a different (updated) Member ID than the
|
||||
// one we searched with — e.g. UHC MA reissues IDs. Overwrite the patient's
|
||||
// stored insuranceId so future lookups use the current one.
|
||||
@@ -128,6 +152,15 @@ async function processUnitedSCOResult(
|
||||
}
|
||||
|
||||
await storage.updatePatient(patient.id, statusUpdates);
|
||||
// Service History from Dental Hub. Only replace when rows came back — an empty read
|
||||
// may just mean the portal was slow, and shouldn't wipe history saved earlier.
|
||||
if (Array.isArray(seleniumResult?.service_history) && seleniumResult.service_history.length > 0) {
|
||||
try {
|
||||
await storage.replacePatientServiceHistory(patient.id, seleniumResult.service_history);
|
||||
} catch (e: any) {
|
||||
console.error("[unitedsco-processor] saving service history failed:", e.message);
|
||||
}
|
||||
}
|
||||
output.patientUpdateStatus = newStatus
|
||||
? `Patient status updated to ${newStatus}`
|
||||
: `Eligibility unknown — status not changed`;
|
||||
|
||||
@@ -28,6 +28,8 @@ export interface IStorage {
|
||||
getPatientByInsuranceIdAndDob(insuranceId: string, dob: Date): Promise<Patient | null>;
|
||||
getPatientByInsuranceIdNoDob(insuranceId: string): Promise<Patient | null>;
|
||||
getPatientByNameAndDob(firstName: string, lastName: string, dob: Date): Promise<Patient | null>;
|
||||
getPatientsByDobDay(dayUtc: Date): Promise<Patient[]>;
|
||||
getPatientBySecondaryInsuranceId(insuranceId: string): Promise<Patient | null>;
|
||||
getAllPatients(): Promise<Patient[]>;
|
||||
getRecentPatients(limit: number, offset: number): Promise<Patient[]>;
|
||||
getPatientsByIds(ids: number[]): Promise<Patient[]>;
|
||||
@@ -131,6 +133,19 @@ export const patientsStorage: IStorage = {
|
||||
});
|
||||
},
|
||||
|
||||
// dayUtc = midnight UTC of the birth date (how @db.Date values come back)
|
||||
async getPatientsByDobDay(dayUtc: Date): Promise<Patient[]> {
|
||||
const next = new Date(dayUtc.getTime() + 24 * 60 * 60 * 1000);
|
||||
return db.patient.findMany({ where: { dateOfBirth: { gte: dayUtc, lt: next } } });
|
||||
},
|
||||
|
||||
async getPatientBySecondaryInsuranceId(insuranceId: string): Promise<Patient | null> {
|
||||
return db.patient.findFirst({
|
||||
where: { secondaryInsuranceId: insuranceId },
|
||||
orderBy: { updatedAt: "desc" },
|
||||
});
|
||||
},
|
||||
|
||||
async getRecentPatients(limit: number, offset: number): Promise<Patient[]> {
|
||||
return db.patient.findMany({
|
||||
skip: offset,
|
||||
@@ -195,10 +210,21 @@ export const patientsStorage: IStorage = {
|
||||
},
|
||||
|
||||
async replacePatientServiceHistory(patientId: number, rows: ServiceHistoryRow[]) {
|
||||
// Portals can list the same table twice; keep one copy of identical lines
|
||||
const seen = new Set<string>();
|
||||
const unique = rows.filter((row) => {
|
||||
const key = JSON.stringify([
|
||||
row.procedureCode, row.description ?? "", row.toothQuadArchSurface ?? "",
|
||||
row.placeOfService ?? "", row.serviceDate ?? "",
|
||||
]);
|
||||
if (seen.has(key)) return false;
|
||||
seen.add(key);
|
||||
return true;
|
||||
});
|
||||
await db.$transaction([
|
||||
db.patientServiceHistory.deleteMany({ where: { patientId } }),
|
||||
db.patientServiceHistory.createMany({
|
||||
data: rows.map((row) => ({
|
||||
data: unique.map((row) => ({
|
||||
patientId,
|
||||
procedureCode: row.procedureCode,
|
||||
description: row.description ?? null,
|
||||
@@ -263,7 +289,7 @@ export const patientsStorage: IStorage = {
|
||||
"gender", "phone", "email", "address", "city", "state", "zipCode", "insuranceProvider",
|
||||
"insuranceId", "groupNumber", "policyHolder", "policyHolderPatientId",
|
||||
"policyHolderRelationship", "allergies", "medicalConditions", "remainingBenefit",
|
||||
"thirdPartyInsurance",
|
||||
"thirdPartyInsurance", "secondaryInsuranceProvider", "secondaryInsuranceId",
|
||||
] as const;
|
||||
const fill: Record<string, unknown> = {};
|
||||
for (const field of fillable) {
|
||||
|
||||
Reference in New Issue
Block a user