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) {
|
||||
|
||||
@@ -51,6 +51,25 @@ const US_STATES = [
|
||||
"SD", "TN", "TX", "UT", "VA", "WA", "WI", "WV", "WY",
|
||||
];
|
||||
|
||||
const INSURANCE_OPTIONS: { value: string; label: string }[] = [
|
||||
{ value: "MassHealth", label: "MassHealth" },
|
||||
{ value: "CCA", label: "CCA" },
|
||||
{ value: "DDMA", label: "DDMA" },
|
||||
{ value: "DeltaIns", label: "Delta Ins" },
|
||||
{ value: "Delta Dental Indiv", label: "Delta Indiv" },
|
||||
{ value: "TuftsSCO", label: "Tufts SCO" },
|
||||
{ value: "UnitedSCO", label: "United SCO" },
|
||||
{ value: "BCBS", label: "BCBS" },
|
||||
{ value: "UnitedAAPR", label: "United AAPR" },
|
||||
{ value: "Aetna", label: "Aetna" },
|
||||
{ value: "Altus", label: "Altus" },
|
||||
{ value: "MetlifeDental", label: "Metlife Dental" },
|
||||
{ value: "Cigna", label: "Cigna" },
|
||||
{ value: "DeltaWA", label: "Delta WA" },
|
||||
{ value: "DeltaIL", label: "Delta IL" },
|
||||
{ value: "Others", label: "Others" },
|
||||
];
|
||||
|
||||
interface PatientFormProps {
|
||||
patient?: Patient;
|
||||
extractedInfo?: {
|
||||
@@ -135,6 +154,8 @@ export const PatientForm = forwardRef<PatientFormRef, PatientFormProps>(
|
||||
policyHolder: "",
|
||||
policyHolderPatientId: null,
|
||||
policyHolderRelationship: "SELF",
|
||||
secondaryInsuranceProvider: "",
|
||||
secondaryInsuranceId: "",
|
||||
allergies: "",
|
||||
medicalConditions: "",
|
||||
preferredLanguage: "English",
|
||||
@@ -502,22 +523,9 @@ export const PatientForm = forwardRef<PatientFormRef, PatientFormProps>(
|
||||
</SelectTrigger>
|
||||
</FormControl>
|
||||
<SelectContent>
|
||||
<SelectItem value="MassHealth">MassHealth</SelectItem>
|
||||
<SelectItem value="CCA">CCA</SelectItem>
|
||||
<SelectItem value="DDMA">DDMA</SelectItem>
|
||||
<SelectItem value="DeltaIns">Delta Ins</SelectItem>
|
||||
<SelectItem value="Delta Dental Indiv">Delta Indiv</SelectItem>
|
||||
<SelectItem value="TuftsSCO">Tufts SCO</SelectItem>
|
||||
<SelectItem value="UnitedSCO">United SCO</SelectItem>
|
||||
<SelectItem value="BCBS">BCBS</SelectItem>
|
||||
<SelectItem value="UnitedAAPR">United AAPR</SelectItem>
|
||||
<SelectItem value="Aetna">Aetna</SelectItem>
|
||||
<SelectItem value="Altus">Altus</SelectItem>
|
||||
<SelectItem value="MetlifeDental">Metlife Dental</SelectItem>
|
||||
<SelectItem value="Cigna">Cigna</SelectItem>
|
||||
<SelectItem value="DeltaWA">Delta WA</SelectItem>
|
||||
<SelectItem value="DeltaIL">Delta IL</SelectItem>
|
||||
<SelectItem value="Others">Others</SelectItem>
|
||||
{INSURANCE_OPTIONS.map((o) => (
|
||||
<SelectItem key={o.value} value={o.value}>{o.label}</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
<FormMessage />
|
||||
@@ -634,6 +642,55 @@ export const PatientForm = forwardRef<PatientFormRef, PatientFormProps>(
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Secondary Insurance — e.g. MassHealth ID of a United SCO member, or MassHealth behind a commercial plan */}
|
||||
<div>
|
||||
<h4 className="text-md font-medium text-gray-700 mb-3">
|
||||
Secondary Insurance
|
||||
</h4>
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
|
||||
<FormField
|
||||
control={form.control}
|
||||
name={"secondaryInsuranceProvider" as any}
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>Secondary Insurance Type</FormLabel>
|
||||
<Select
|
||||
onValueChange={(v) => field.onChange(v === "__none__" ? "" : v)}
|
||||
value={(field.value as string) || ""}
|
||||
>
|
||||
<FormControl>
|
||||
<SelectTrigger>
|
||||
<SelectValue placeholder="None" />
|
||||
</SelectTrigger>
|
||||
</FormControl>
|
||||
<SelectContent>
|
||||
<SelectItem value="__none__">None</SelectItem>
|
||||
{INSURANCE_OPTIONS.map((o) => (
|
||||
<SelectItem key={o.value} value={o.value}>{o.label}</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
|
||||
<FormField
|
||||
control={form.control}
|
||||
name={"secondaryInsuranceId" as any}
|
||||
render={({ field }) => (
|
||||
<FormItem>
|
||||
<FormLabel>Secondary Insurance ID</FormLabel>
|
||||
<FormControl>
|
||||
<Input {...field} value={(field.value as string) || ""} />
|
||||
</FormControl>
|
||||
<FormMessage />
|
||||
</FormItem>
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Hidden submit button for form validation */}
|
||||
<button type="submit" className="hidden" aria-hidden="true"></button>
|
||||
</form>
|
||||
|
||||
@@ -1403,6 +1403,18 @@ export function PatientTable({
|
||||
] ?? currentPatient.policyHolderRelationship}
|
||||
</p>
|
||||
)}
|
||||
{(currentPatient.secondaryInsuranceProvider || currentPatient.secondaryInsuranceId) && (
|
||||
<>
|
||||
<p>
|
||||
<span className="text-gray-500">Secondary Provider:</span>{" "}
|
||||
{currentPatient.secondaryInsuranceProvider || "N/A"}
|
||||
</p>
|
||||
<p>
|
||||
<span className="text-gray-500">Secondary ID:</span>{" "}
|
||||
{currentPatient.secondaryInsuranceId || "N/A"}
|
||||
</p>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -1463,7 +1475,7 @@ export function PatientTable({
|
||||
<p className="mt-2 text-gray-500">Loading...</p>
|
||||
) : serviceHistory.length === 0 ? (
|
||||
<p className="mt-2 text-gray-500">
|
||||
No service history on file. It is saved when MH or Tufts SCO eligibility is checked.
|
||||
No service history on file. It is saved when MH, DentaQuest, Tufts SCO or United SCO eligibility is checked.
|
||||
</p>
|
||||
) : (
|
||||
<Table className="mt-2">
|
||||
|
||||
@@ -0,0 +1,158 @@
|
||||
import os
|
||||
import re
|
||||
import time
|
||||
|
||||
from selenium.webdriver.common.by import By
|
||||
|
||||
from dentaquest_service_history import parse_page_text, parse_row_cells
|
||||
|
||||
# Service History on the Dental Hub (United SCO) Selected Patient page. It sits next to
|
||||
# the "Eligibility" and "Benefit Summary" buttons. The column order isn't known for sure,
|
||||
# so columns are mapped by header name when the table has headers; otherwise rows are
|
||||
# read like DentaQuest's (code cell, then description / tooth / place).
|
||||
_CLICK_JS = """
|
||||
const btn = document.getElementById('service-history-link') ||
|
||||
Array.from(document.querySelectorAll('button, a, [role="tab"]'))
|
||||
.find(el => /^\\s*Service History\\s*$/i.test(el.textContent || ''));
|
||||
if (!btn) return false;
|
||||
btn.scrollIntoView({block: 'center'});
|
||||
btn.click();
|
||||
return true;
|
||||
"""
|
||||
|
||||
_TABLES_JS = """
|
||||
const cellText = (el) => (el.innerText || el.textContent || '').replace(/\\s+/g, ' ').trim();
|
||||
const out = [];
|
||||
for (const table of document.querySelectorAll('table, [role="table"], [role="grid"]')) {
|
||||
const headers = Array.from(table.querySelectorAll('th, [role="columnheader"]')).map(cellText);
|
||||
const rows = [];
|
||||
for (const row of table.querySelectorAll('tr, [role="row"]')) {
|
||||
const cells = Array.from(row.querySelectorAll('td, [role="cell"], [role="gridcell"]')).map(cellText);
|
||||
if (cells.some(t => /^D\\d{4}$/.test(t))) rows.push(cells);
|
||||
}
|
||||
if (rows.length) out.push({headers, rows});
|
||||
}
|
||||
return out;
|
||||
"""
|
||||
|
||||
_DATE_RE = re.compile(r"^\d{1,2}/\d{1,2}/\d{4}$")
|
||||
|
||||
_HEADER_KEYS = [
|
||||
# (field, header must contain one of these, checked in this order)
|
||||
("serviceDate", ("date",)),
|
||||
("description", ("description", "desc")),
|
||||
("procedureCode", ("procedure", "code", "cdt")),
|
||||
("toothQuadArchSurface", ("tooth", "surface", "quad", "arch", "area")),
|
||||
("placeOfService", ("place", "location", "pos")),
|
||||
]
|
||||
|
||||
|
||||
def _map_headers(headers):
|
||||
"""Column index per field from header names, or None when the headers don't fit."""
|
||||
cols = {}
|
||||
for i, h in enumerate(h.lower() for h in headers):
|
||||
for field, keys in _HEADER_KEYS:
|
||||
if field not in cols and any(k in h for k in keys):
|
||||
cols[field] = i
|
||||
break
|
||||
return cols if "procedureCode" in cols else None
|
||||
|
||||
|
||||
def parse_tables(tables):
|
||||
result = []
|
||||
for t in tables:
|
||||
cols = _map_headers(t.get("headers") or [])
|
||||
if not cols:
|
||||
result.extend(parse_row_cells(t["rows"]))
|
||||
continue
|
||||
for cells in t["rows"]:
|
||||
get = lambda f: cells[cols[f]] if f in cols and cols[f] < len(cells) else ""
|
||||
code = get("procedureCode")
|
||||
if not re.match(r"^D\d{4}$", code):
|
||||
continue
|
||||
date = get("serviceDate")
|
||||
if not _DATE_RE.match(date):
|
||||
date = next((c for c in cells if _DATE_RE.match(c)), date)
|
||||
result.append({
|
||||
"procedureCode": code,
|
||||
"description": get("description"),
|
||||
"toothQuadArchSurface": get("toothQuadArchSurface"),
|
||||
"placeOfService": get("placeOfService"),
|
||||
"serviceDate": date,
|
||||
})
|
||||
return result
|
||||
|
||||
|
||||
def _dedupe(rows):
|
||||
seen, out = set(), []
|
||||
for r in rows:
|
||||
key = tuple(r.get(k, "") for k in
|
||||
("procedureCode", "description", "toothQuadArchSurface", "placeOfService", "serviceDate"))
|
||||
if key not in seen:
|
||||
seen.add(key)
|
||||
out.append(r)
|
||||
return out
|
||||
|
||||
|
||||
def _dump_page(driver, debug_dir):
|
||||
"""Save the page so the reader can be fixed when it finds nothing."""
|
||||
try:
|
||||
os.makedirs(debug_dir, exist_ok=True)
|
||||
stamp = int(time.time())
|
||||
with open(os.path.join(debug_dir, f"dentalhub_service_history_{stamp}.html"), "w") as f:
|
||||
f.write(driver.page_source or "")
|
||||
print(f"[dentalhub service history] nothing found; page saved to {debug_dir}")
|
||||
except Exception as e:
|
||||
print(f"[dentalhub service history] saving debug page failed: {e}")
|
||||
|
||||
|
||||
def read_service_history(driver, debug_dir, timeout=15):
|
||||
"""Click "Service History" on the Selected Patient page and read its rows.
|
||||
|
||||
Returns [] when nothing was found — that can't tell "no history" from "the page was
|
||||
slow", so callers must not treat it as "no history". Never raises.
|
||||
"""
|
||||
original = driver.current_window_handle
|
||||
before = set(driver.window_handles)
|
||||
try:
|
||||
if not driver.execute_script(_CLICK_JS):
|
||||
print("[dentalhub service history] 'Service History' button not found")
|
||||
_dump_page(driver, debug_dir)
|
||||
return []
|
||||
except Exception as e:
|
||||
print(f"[dentalhub service history] click failed: {e}")
|
||||
return []
|
||||
|
||||
time.sleep(2)
|
||||
new_tabs = list(set(driver.window_handles) - before)
|
||||
if new_tabs:
|
||||
driver.switch_to.window(new_tabs[0])
|
||||
|
||||
history = []
|
||||
deadline = time.time() + timeout
|
||||
try:
|
||||
while True:
|
||||
try:
|
||||
history = parse_tables(driver.execute_script(_TABLES_JS) or [])
|
||||
if not history:
|
||||
text = driver.find_element(By.TAG_NAME, "body").get_attribute("innerText") or ""
|
||||
history = parse_page_text(text)
|
||||
if history:
|
||||
break
|
||||
except Exception as e:
|
||||
print(f"[dentalhub service history] reading page failed: {e}")
|
||||
if time.time() >= deadline:
|
||||
_dump_page(driver, debug_dir)
|
||||
break
|
||||
time.sleep(1)
|
||||
finally:
|
||||
if new_tabs:
|
||||
try:
|
||||
driver.close()
|
||||
except Exception:
|
||||
pass
|
||||
driver.switch_to.window(original)
|
||||
|
||||
history = _dedupe(history)
|
||||
print(f"[dentalhub service history] {len(history)} row(s)")
|
||||
return history
|
||||
@@ -12,6 +12,7 @@ import re
|
||||
import base64
|
||||
|
||||
from unitedsco_browser_manager import get_browser_manager
|
||||
from dentalhub_service_history import read_service_history
|
||||
|
||||
class AutomationUnitedSCOEligibilityCheck:
|
||||
def __init__(self, data):
|
||||
@@ -1135,6 +1136,15 @@ class AutomationUnitedSCOEligibilityCheck:
|
||||
|
||||
print(f"[UnitedSCO step2] PDF saved: {pdf_path}")
|
||||
|
||||
# 4) Service History (button next to "Eligibility") — never fails the check
|
||||
service_history = []
|
||||
try:
|
||||
service_history = read_service_history(
|
||||
self.driver, os.path.join(self.download_dir, "debug_service_history")
|
||||
)
|
||||
except Exception as e:
|
||||
print(f"[UnitedSCO step2] Service history read failed: {e}")
|
||||
|
||||
# Hide browser window after completion
|
||||
self._hide_browser()
|
||||
|
||||
@@ -1146,7 +1156,8 @@ class AutomationUnitedSCOEligibilityCheck:
|
||||
"ss_path": pdf_path,
|
||||
"pdf_path": pdf_path,
|
||||
"patientName": patientName,
|
||||
"memberId": foundMemberId
|
||||
"memberId": foundMemberId,
|
||||
"service_history": service_history,
|
||||
}
|
||||
|
||||
except Exception as e:
|
||||
|
||||
Reference in New Issue
Block a user