feat: Tufts SCO service/preauth history, chat clear archives history, labeled ID/DOB detection

- AI chat Clear empties the chat box but archives the conversation in the per-user JSON file
- Chat bot detects Member ID/DOB pasted with labels ("Date of Birth ... Member ID ...")
- Tufts SCO (DentaQuest) eligibility saves the member's service history
- Tufts SCO Check PreAuth saves procedure lines (code, tooth, plan payment, status) to a
  new PatientPreauthHistory table, shown as Preauth History in Patient Details

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-09 22:34:27 -05:00
co-authored by Claude Opus 5.5
parent 2352922089
commit 6c98f7f985
182 changed files with 4254 additions and 141 deletions
+5 -1
View File
@@ -275,8 +275,12 @@ export function restoreCodeToothLists(message: string, names: string[]): string[
return kept;
}
// Field labels copied along with the values, e.g. "Date of Birth 05/03/1952\nMember ID S01057721".
const ID_DOB_LABEL_RE =
/(?<![A-Za-z0-9])(?:date\s+of\s+birth|birth\s*date|d\.?o\.?b\.?|member\s*(?:id|number|no\.?)|subscriber\s*id|insurance\s*id|id)(?![A-Za-z0-9])\s*[:#]?/gi;
function parseBareIdDob(message: string): { memberId: string; dob: string } | null {
const text = message.trim();
const text = message.replace(ID_DOB_LABEL_RE, " ").replace(/\s+/g, " ").trim();
const dobPattern = /(\d{1,2}[\/\-]\d{1,2}[\/\-]\d{4})/;
const idThenDob = text.match(new RegExp(`^([A-Za-z0-9]{3,})[\\s,]+${dobPattern.source}$`));
if (idThenDob) return { memberId: idThenDob[1]!, dob: idThenDob[2]!.replace(/-/g, "/") };
@@ -101,6 +101,16 @@ async function processDentaQuestResult(
insuranceProvider: "DentaQuest",
...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("[dentaquest-processor] saving service history failed:", e.message);
}
}
output.patientUpdateStatus = `Patient status updated to ${newStatus}`;
let pdfBuffer: Buffer | null = null;
@@ -108,6 +108,17 @@ async function saveApprovalPdf(userId: number, claimId: number | undefined, pdfP
return true;
}
// Procedure lines of the pre-auth, shown in the patient's Preauth History
async function savePreauthHistory(claimId: number | undefined, preAuthNumber: string, procedures: any[]) {
const claim = claimId ? await storage.getClaim(claimId) : undefined;
if (!claim?.patientId) {
log("preauth history not saved: claim/patient not found", { claimId });
return;
}
await storage.replacePatientPreauthHistory(claim.patientId, preAuthNumber, procedures);
log("preauth history saved", { claimId, patientId: claim.patientId, rows: procedures.length });
}
export async function runPreAuthCheckProcessor(
input: {
siteKey: PreAuthCheckSiteKey;
@@ -143,6 +154,13 @@ export async function runPreAuthCheckProcessor(
const saved = await saveApprovalPdf(userId, claimId, result.approval_pdf_path);
message += saved ? " Saved to the patient's Approval folder." : "";
}
if (Array.isArray(result.procedures) && result.procedures.length > 0 && result.preAuthNumber) {
try {
await savePreauthHistory(claimId, String(result.preAuthNumber), result.procedures);
} catch (e: any) {
log("saving preauth history failed", { claimId, error: e?.message });
}
}
} finally {
await removeDownloadedFiles(result);
}
+34 -8
View File
@@ -470,15 +470,34 @@ router.post("/create-appointment-today", async (req: Request, res: Response): Pr
});
// ─── Chat history persistence (JSON file per user) ──────────────────────────
// File shape: { messages, archived }. `messages` is the conversation shown in the chat box;
// "Clear" moves it into `archived` (never deleted) so the full history stays on disk.
interface ChatHistoryFile {
messages: any[];
archived: { clearedAt: string; messages: any[] }[];
}
function readChatHistory(userId: number): ChatHistoryFile {
const filePath = getChatHistoryPath(userId);
if (!fs.existsSync(filePath)) return { messages: [], archived: [] };
const data = JSON.parse(fs.readFileSync(filePath, "utf-8"));
return {
messages: Array.isArray(data.messages) ? data.messages : [],
archived: Array.isArray(data.archived) ? data.archived : [],
};
}
function writeChatHistory(userId: number, data: ChatHistoryFile) {
if (!fs.existsSync(CHAT_HISTORY_DIR)) fs.mkdirSync(CHAT_HISTORY_DIR, { recursive: true });
fs.writeFileSync(getChatHistoryPath(userId), JSON.stringify(data, null, 2));
}
router.get("/chat-history", async (req: Request, res: Response): Promise<any> => {
try {
const userId = req.user?.id;
if (!userId) return res.status(401).json({ message: "Unauthorized" });
const filePath = getChatHistoryPath(userId);
if (!fs.existsSync(filePath)) return res.status(200).json({ messages: [] });
const raw = fs.readFileSync(filePath, "utf-8");
return res.status(200).json(JSON.parse(raw));
return res.status(200).json({ messages: readChatHistory(userId).messages });
} catch (err) {
return res.status(500).json({ error: "Failed to load chat history", details: String(err) });
}
@@ -490,20 +509,27 @@ router.put("/chat-history", async (req: Request, res: Response): Promise<any> =>
if (!userId) return res.status(401).json({ message: "Unauthorized" });
const { messages } = req.body;
if (!Array.isArray(messages)) return res.status(400).json({ message: "messages array is required" });
if (!fs.existsSync(CHAT_HISTORY_DIR)) fs.mkdirSync(CHAT_HISTORY_DIR, { recursive: true });
fs.writeFileSync(getChatHistoryPath(userId), JSON.stringify({ messages }, null, 2));
const data = readChatHistory(userId);
writeChatHistory(userId, { ...data, messages });
return res.status(200).json({ ok: true });
} catch (err) {
return res.status(500).json({ error: "Failed to save chat history", details: String(err) });
}
});
// Clears the visible conversation but keeps it in `archived`. The client sends its current
// messages so anything not yet flushed by the debounced PUT is archived too.
router.delete("/chat-history", async (req: Request, res: Response): Promise<any> => {
try {
const userId = req.user?.id;
if (!userId) return res.status(401).json({ message: "Unauthorized" });
const filePath = getChatHistoryPath(userId);
if (fs.existsSync(filePath)) fs.unlinkSync(filePath);
const data = readChatHistory(userId);
const toArchive = Array.isArray(req.body?.messages) ? req.body.messages : data.messages;
// Skip a conversation that is only the bot's welcome message
if (toArchive.some((m: any) => m?.role === "user")) {
data.archived.push({ clearedAt: new Date().toISOString(), messages: toArchive });
}
writeChatHistory(userId, { messages: [], archived: data.archived });
return res.status(200).json({ ok: true });
} catch (err) {
return res.status(500).json({ error: "Failed to clear chat history", details: String(err) });
+13
View File
@@ -461,4 +461,17 @@ router.get("/:id/service-history", async (req: Request, res: Response): Promise<
}
});
// GET /api/patients/:id/preauth-history
router.get("/:id/preauth-history", async (req: Request, res: Response): Promise<any> => {
try {
const patientId = parseInt(req.params.id);
if (isNaN(patientId)) return res.status(400).json({ message: "Invalid patient ID" });
const history = await storage.getPatientPreauthHistory(patientId);
return res.status(200).json(history);
} catch (err) {
return res.status(500).json({ error: "Failed to fetch preauth history", details: String(err) });
}
});
export default router;
@@ -14,6 +14,13 @@ export type ServiceHistoryRow = {
serviceDate?: string | null;
};
export type PreauthHistoryRow = {
submittedCode: string;
toothQuadArchSurface?: string | null;
paidAmount?: string | null;
status?: string | null;
};
export interface IStorage {
// Patient methods
getPatient(id: number): Promise<Patient | undefined>;
@@ -63,6 +70,14 @@ export interface IStorage {
patientId: number,
rows: ServiceHistoryRow[]
): Promise<void>;
getPatientPreauthHistory(
patientId: number
): Promise<(PreauthHistoryRow & { id: number; preAuthNumber: string; createdAt: Date })[]>;
replacePatientPreauthHistory(
patientId: number,
preAuthNumber: string,
rows: PreauthHistoryRow[]
): Promise<void>;
}
export const patientsStorage: IStorage = {
@@ -195,6 +210,30 @@ export const patientsStorage: IStorage = {
]);
},
// Most recently checked pre-auth first, lines in the portal's order
async getPatientPreauthHistory(patientId: number) {
return db.patientPreauthHistory.findMany({
where: { patientId },
orderBy: [{ createdAt: "desc" }, { id: "asc" }],
});
},
async replacePatientPreauthHistory(patientId: number, preAuthNumber: string, rows: PreauthHistoryRow[]) {
await db.$transaction([
db.patientPreauthHistory.deleteMany({ where: { patientId, preAuthNumber } }),
db.patientPreauthHistory.createMany({
data: rows.map((row) => ({
patientId,
preAuthNumber,
submittedCode: row.submittedCode,
toothQuadArchSurface: row.toothQuadArchSurface ?? null,
paidAmount: row.paidAmount ?? null,
status: row.status ?? null,
})),
}),
]);
},
async deletePatient(id: number): Promise<void> {
try {
await db.patient.delete({ where: { id } });
@@ -154,9 +154,14 @@ function getAutoCheck(_dobISO: string): "mh" {
return "mh";
}
// Field labels copied along with the values, e.g. "Date of Birth 05/03/1952\nMember ID S01057721".
const ID_DOB_LABEL_RE =
/(?<![A-Za-z0-9])(?:date\s+of\s+birth|birth\s*date|d\.?o\.?b\.?|member\s*(?:id|number|no\.?)|subscriber\s*id|insurance\s*id|id)(?![A-Za-z0-9])\s*[:#]?/gi;
function parseEligibilityInput(
raw: string
input: string
): { memberId: string; display: string; iso: string } | null {
const raw = input.replace(ID_DOB_LABEL_RE, " ");
const dateMatch = raw.match(/\b(\d{1,2})[\/\-](\d{1,2})[\/\-](\d{4})\b/);
if (!dateMatch) return null;
const m = dateMatch[1];
@@ -217,10 +222,13 @@ function saveChatHistoryToServer(msgs: Message[]) {
}, 500);
}
function clearChatHistoryOnServer() {
// Server archives the cleared conversation in the JSON file rather than deleting it
function clearChatHistoryOnServer(msgs: Message[]) {
if (saveTimer) clearTimeout(saveTimer);
fetch("/api/ai/chat-history", {
method: "DELETE",
headers: { Authorization: `Bearer ${localStorage.getItem("token") ?? ""}` },
headers: { "Content-Type": "application/json", Authorization: `Bearer ${localStorage.getItem("token") ?? ""}` },
body: JSON.stringify({ messages: msgs.filter((m) => !m.isLoading) }),
}).catch(() => {});
}
@@ -477,7 +485,7 @@ export function ChatbotButton() {
try {
sessionStorage.setItem(CHAT_STORAGE_KEY, JSON.stringify(fresh));
} catch {}
clearChatHistoryOnServer();
clearChatHistoryOnServer(messages);
setMessages(fresh);
};
@@ -61,6 +61,15 @@ interface ServiceHistoryRow {
serviceDate: string | null;
}
interface PreauthHistoryRow {
id: number;
preAuthNumber: string;
submittedCode: string;
toothQuadArchSurface: string | null;
paidAmount: string | null;
status: string | null;
}
interface PatientApiResponse {
patients: Patient[];
totalCount: number;
@@ -731,6 +740,16 @@ export function PatientTable({
enabled: isViewPatientOpen && !!currentPatient?.id,
});
const { data: preauthHistory = [], isLoading: isPreauthHistoryLoading } = useQuery<PreauthHistoryRow[]>({
queryKey: ["patient-preauth-history", currentPatient?.id],
queryFn: async () => {
const res = await apiRequest("GET", `/api/patients/${currentPatient?.id}/preauth-history`);
if (!res.ok) throw new Error("Failed to load preauth history");
return res.json();
},
enabled: isViewPatientOpen && !!currentPatient?.id,
});
const searchKeyPart = debouncedSearchCriteria?.searchTerm || "recent";
const {
@@ -1394,13 +1413,47 @@ export function PatientTable({
</div>
</div>
<div className="pt-4">
<h4 className="font-medium text-gray-900">Preauth History</h4>
{isPreauthHistoryLoading ? (
<p className="mt-2 text-gray-500">Loading...</p>
) : preauthHistory.length === 0 ? (
<p className="mt-2 text-gray-500">
No preauth history on file. It is saved when Tufts SCO Check PreAuth is run.
</p>
) : (
<Table className="mt-2">
<TableHeader>
<TableRow>
<TableHead>Preauth #</TableHead>
<TableHead>Submitted Code</TableHead>
<TableHead>Tooth/Arch/Quad/Surface</TableHead>
<TableHead>Paid Amount</TableHead>
<TableHead>Status</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{preauthHistory.map((row) => (
<TableRow key={row.id}>
<TableCell>{row.preAuthNumber}</TableCell>
<TableCell>{row.submittedCode}</TableCell>
<TableCell>{row.toothQuadArchSurface}</TableCell>
<TableCell>{row.paidAmount}</TableCell>
<TableCell>{row.status}</TableCell>
</TableRow>
))}
</TableBody>
</Table>
)}
</div>
<div className="pt-4">
<h4 className="font-medium text-gray-900">Service History</h4>
{isServiceHistoryLoading ? (
<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 eligibility is checked.
No service history on file. It is saved when MH or Tufts SCO eligibility is checked.
</p>
) : (
<Table className="mt-2">
@@ -0,0 +1,92 @@
import re
import time
from selenium.webdriver.common.by import By
# Procedure history on the DentaQuest member page, columns in this order:
# Date of service | Procedure code | Procedure code description | Tooth / arch / quad / surface | Place of service
# The column headers are rendered apart from the data rows, so rows are found by their
# content (a date cell and a "D####" code cell) rather than by header names. The claims
# table above has a date but no procedure code cell, so it is skipped.
_ROWS_JS = """
const cellText = (el) => (el.innerText || el.textContent || '').replace(/\\s+/g, ' ').trim();
const out = [];
for (const row of document.querySelectorAll('tr, [role="row"]')) {
let cells = Array.from(row.querySelectorAll('td, th, [role="cell"], [role="gridcell"]'));
if (cells.length === 0) cells = Array.from(row.children);
const texts = cells.map(cellText);
if (texts.some(t => /^D\\d{4}$/.test(t))) out.push(texts);
}
return out;
"""
_DATE_RE = re.compile(r"^\d{1,2}/\d{1,2}/\d{4}$")
_CODE_RE = re.compile(r"^D\d{4}$")
# Fallback for one line of page text, e.g.
# 02/12/2026 D0220 intraoral - periapical first radiographic image 27 / -- / -- / -- Office
_LINE_RE = re.compile(
r"^(\d{1,2}/\d{1,2}/\d{4})\s+(D\d{4})\s+(.+?)\s+(\S+\s*/\s*\S+\s*/\s*\S+\s*/\s*\S+)\s+(\S.*)$"
)
def parse_row_cells(rows):
"""Map row cell texts to service history dicts."""
result = []
for cells in rows:
code_i = next((i for i, c in enumerate(cells) if _CODE_RE.match(c)), None)
if code_i is None:
continue
date = next((c for c in cells if _DATE_RE.match(c)), "")
rest = cells[code_i + 1:] + ["", "", ""]
result.append({
"procedureCode": cells[code_i],
"description": rest[0],
"toothQuadArchSurface": rest[1],
"placeOfService": rest[2],
"serviceDate": date,
})
return result
def parse_page_text(text):
"""Service history rows from the page's text, one row per line."""
result = []
for line in text.splitlines():
line = re.sub(r"\s+", " ", line).strip()
m = _LINE_RE.match(line)
if m:
result.append({
"procedureCode": m.group(2),
"description": m.group(3),
"toothQuadArchSurface": m.group(4),
"placeOfService": m.group(5),
"serviceDate": m.group(1),
})
return result
def extract_service_history(driver, timeout=10):
"""Read the procedure history from the DentaQuest member details page.
Returns [] when nothing was found — this can't tell "no history" from "the page
was too slow", so callers must not treat it as "no history".
"""
deadline = time.time() + timeout
history = []
while True:
try:
history = parse_row_cells(driver.execute_script(_ROWS_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"[dentaquest extract_service_history] reading page failed: {e}")
if time.time() >= deadline:
break
time.sleep(1)
print(f"[dentaquest extract_service_history] {len(history)} row(s)")
return history
@@ -14,6 +14,7 @@ import base64
from dentaquest_browser_manager import get_browser_manager
from dentaquest_member_details import extract_member_address
from dentaquest_service_history import extract_service_history
class AutomationDentaQuestEligibilityCheck:
def __init__(self, data):
@@ -680,6 +681,7 @@ class AutomationDentaQuestEligibilityCheck:
# Address from the Member's information block (empty on the search results page)
member_address = extract_member_address(self.driver) if detail_url else {}
service_history = extract_service_history(self.driver) if detail_url else []
# Wait for page to fully load before generating PDF
try:
@@ -739,8 +741,9 @@ class AutomationDentaQuestEligibilityCheck:
"patientName": patientName,
"memberId": foundMemberId, # Member ID extracted from the page
**member_address, # address, city, state, zipCode
"service_history": service_history,
}
print(f"[DentaQuest step2] Success: {output}")
print(f"[DentaQuest step2] Success: { {k: v for k, v in output.items() if k != 'service_history'} }")
return output
except Exception as e:
@@ -8,6 +8,7 @@ import os
import time
from selenium_DentaQuest_eligibilityCheckWorker import AutomationDentaQuestEligibilityCheck
from tuftssco_preauth_procedures import extract_preauth_procedures
SUBMITTED_URL = "https://providers.dentaquest.com/pre-auth-claims/submitted/"
@@ -20,7 +21,8 @@ class AutomationTuftsSCOPreAuthCheck(AutomationDentaQuestEligibilityCheck):
step1: open Pre-authorizations and Claims > Submitted, clear the date range,
search by pre-auth / claim number.
step2: open the pre-auth from the result row and save its detail page as a PDF
(filed under the patient's Approval folder by the backend).
(filed under the patient's Approval folder by the backend), and read its
procedure lines for the patient's Preauth History.
"""
def __init__(self, data):
@@ -111,6 +113,9 @@ class AutomationTuftsSCOPreAuthCheck(AutomationDentaQuestEligibilityCheck):
return {"status": "error", "message": f"Detail page for #{number} did not load."}
time.sleep(2) # let the procedure table finish rendering
# Procedure lines for the patient's Preauth History
procedures = extract_preauth_procedures(self.driver)
# 3) The page's Print button opens Chrome's print dialog, which Selenium can't drive;
# printing to PDF through DevTools produces the same printable page.
pdf = self.driver.execute_cdp_cmd("Page.printToPDF", {
@@ -141,6 +146,7 @@ class AutomationTuftsSCOPreAuthCheck(AutomationDentaQuestEligibilityCheck):
"message": f"Tufts SCO pre-auth #{number}" + (f": {status}." if status else "."),
"preAuthNumber": number,
"preAuthStatus": status,
"procedures": procedures,
"approval_pdf_path": pdf_path,
}
except Exception as e:
@@ -0,0 +1,92 @@
import re
import time
from selenium.webdriver.common.by import By
# "Procedure information" table on a DentaQuest pre-auth detail page, columns in this order:
# [expand] | Submitted code | Tooth / arch / quad / surface | Paid code | Total submitted |
# Deductible amount | Member responsibility | Plan payment | Provider responsibility | Status | Processing policy
# Rows are found by their content (a "D####" code cell followed by money cells), since
# the column headers may be rendered apart from the data rows.
_ROWS_JS = """
const cellText = (el) => (el.innerText || el.textContent || '').replace(/\\s+/g, ' ').trim();
const out = [];
for (const row of document.querySelectorAll('tr, [role="row"]')) {
let cells = Array.from(row.querySelectorAll('td, th, [role="cell"], [role="gridcell"]'));
if (cells.length === 0) cells = Array.from(row.children);
const texts = cells.map(cellText);
if (texts.some(t => /^D\\d{4}$/.test(t))) out.push(texts);
}
return out;
"""
_CODE_RE = re.compile(r"^D\d{4}$")
_MONEY_RE = re.compile(r"^-?\$[\d,]+\.\d{2}$")
# Fallback for one line of page text, e.g.
# D3320 29 / / LR / D3320 $1,050.00 $0.00 $0.00 $564.00 $486.00 Approved
_LINE_RE = re.compile(
r"^(D\d{4})\s+(.*?)\s*(D\d{4})\s+"
r"(\$[\d,.]+)\s+(\$[\d,.]+)\s+(\$[\d,.]+)\s+(\$[\d,.]+)\s+(\$[\d,.]+)\s+(\S.*)$"
)
def parse_row_cells(rows):
"""Map row cell texts to procedure dicts: submittedCode, toothQuadArchSurface,
paidAmount (the "Plan payment" column), status."""
result = []
for cells in rows:
code_i = next((i for i, c in enumerate(cells) if _CODE_RE.match(c)), None)
if code_i is None:
continue
rest = cells[code_i + 1:]
money = [i for i, c in enumerate(rest) if _MONEY_RE.match(c)]
# Total submitted, deductible, member responsibility, plan payment, provider responsibility
if len(money) < 5:
continue
status_i = money[4] + 1
result.append({
"submittedCode": cells[code_i],
"toothQuadArchSurface": rest[0] if not _CODE_RE.match(rest[0]) else "",
"paidAmount": rest[money[3]],
"status": rest[status_i] if status_i < len(rest) else "",
})
return result
def parse_page_text(text):
"""Procedure rows from the page's text, one row per line."""
result = []
for line in text.splitlines():
line = re.sub(r"\s+", " ", line).strip()
m = _LINE_RE.match(line)
if m:
result.append({
"submittedCode": m.group(1),
"toothQuadArchSurface": m.group(2),
"paidAmount": m.group(7),
"status": m.group(9),
})
return result
def extract_preauth_procedures(driver, timeout=10):
"""Read the procedure lines from the pre-auth detail page. [] when none were found."""
deadline = time.time() + timeout
procedures = []
while True:
try:
procedures = parse_row_cells(driver.execute_script(_ROWS_JS) or [])
if not procedures:
text = driver.find_element(By.TAG_NAME, "body").get_attribute("innerText") or ""
procedures = parse_page_text(text)
if procedures:
break
except Exception as e:
print(f"[extract_preauth_procedures] reading page failed: {e}")
if time.time() >= deadline:
break
time.sleep(1)
print(f"[extract_preauth_procedures] {len(procedures)} row(s): {procedures}")
return procedures