feat: MassHealth service history extraction, shown in Patient Details
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -128,6 +128,17 @@ export async function runCmspEligibilityHistoryRemainingProcessor(
|
||||
if (Object.keys(updates).length > 0) {
|
||||
await storage.updatePatient(patient.id, updates);
|
||||
}
|
||||
|
||||
// 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("[cmspProcessor] saving service history failed:", e.message);
|
||||
}
|
||||
}
|
||||
|
||||
outputResult.patientUpdateStatus = newStatus
|
||||
? `Patient status updated to ${newStatus}`
|
||||
: "Eligibility unknown — status not changed";
|
||||
|
||||
@@ -422,4 +422,17 @@ router.get("/:id/communications", async (req: Request, res: Response): Promise<a
|
||||
}
|
||||
});
|
||||
|
||||
// GET /api/patients/:id/service-history
|
||||
router.get("/:id/service-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.getPatientServiceHistory(patientId);
|
||||
return res.status(200).json(history);
|
||||
} catch (err) {
|
||||
return res.status(500).json({ error: "Failed to fetch service history", details: String(err) });
|
||||
}
|
||||
});
|
||||
|
||||
export default router;
|
||||
|
||||
@@ -6,6 +6,14 @@ import {
|
||||
} from "@repo/db/types";
|
||||
import { prisma as db } from "@repo/db/client";
|
||||
|
||||
export type ServiceHistoryRow = {
|
||||
procedureCode: string;
|
||||
description?: string | null;
|
||||
toothQuadArchSurface?: string | null;
|
||||
placeOfService?: string | null;
|
||||
serviceDate?: string | null;
|
||||
};
|
||||
|
||||
export interface IStorage {
|
||||
// Patient methods
|
||||
getPatient(id: number): Promise<Patient | undefined>;
|
||||
@@ -49,6 +57,11 @@ export interface IStorage {
|
||||
limit?: number,
|
||||
offset?: number
|
||||
): Promise<{ rows: any[]; totalCount: number }>;
|
||||
getPatientServiceHistory(patientId: number): Promise<(ServiceHistoryRow & { id: number })[]>;
|
||||
replacePatientServiceHistory(
|
||||
patientId: number,
|
||||
rows: ServiceHistoryRow[]
|
||||
): Promise<void>;
|
||||
}
|
||||
|
||||
export const patientsStorage: IStorage = {
|
||||
@@ -157,6 +170,30 @@ export const patientsStorage: IStorage = {
|
||||
} catch (_) {}
|
||||
},
|
||||
|
||||
// Rows are kept in the portal's order (newest service first)
|
||||
async getPatientServiceHistory(patientId: number) {
|
||||
return db.patientServiceHistory.findMany({
|
||||
where: { patientId },
|
||||
orderBy: { id: "asc" },
|
||||
});
|
||||
},
|
||||
|
||||
async replacePatientServiceHistory(patientId: number, rows: ServiceHistoryRow[]) {
|
||||
await db.$transaction([
|
||||
db.patientServiceHistory.deleteMany({ where: { patientId } }),
|
||||
db.patientServiceHistory.createMany({
|
||||
data: rows.map((row) => ({
|
||||
patientId,
|
||||
procedureCode: row.procedureCode,
|
||||
description: row.description ?? null,
|
||||
toothQuadArchSurface: row.toothQuadArchSurface ?? null,
|
||||
placeOfService: row.placeOfService ?? null,
|
||||
serviceDate: row.serviceDate ?? null,
|
||||
})),
|
||||
}),
|
||||
]);
|
||||
},
|
||||
|
||||
async deletePatient(id: number): Promise<void> {
|
||||
try {
|
||||
await db.patient.delete({ where: { id } });
|
||||
|
||||
@@ -51,6 +51,15 @@ import {
|
||||
type PatientDocument
|
||||
} from "@/lib/api/documents";
|
||||
|
||||
interface ServiceHistoryRow {
|
||||
id: number;
|
||||
procedureCode: string;
|
||||
description: string | null;
|
||||
toothQuadArchSurface: string | null;
|
||||
placeOfService: string | null;
|
||||
serviceDate: string | null;
|
||||
}
|
||||
|
||||
interface PatientApiResponse {
|
||||
patients: Patient[];
|
||||
totalCount: number;
|
||||
@@ -707,6 +716,16 @@ export function PatientTable({
|
||||
}
|
||||
};
|
||||
|
||||
const { data: serviceHistory = [], isLoading: isServiceHistoryLoading } = useQuery<ServiceHistoryRow[]>({
|
||||
queryKey: ["patient-service-history", currentPatient?.id],
|
||||
queryFn: async () => {
|
||||
const res = await apiRequest("GET", `/api/patients/${currentPatient?.id}/service-history`);
|
||||
if (!res.ok) throw new Error("Failed to load service history");
|
||||
return res.json();
|
||||
},
|
||||
enabled: isViewPatientOpen && !!currentPatient?.id,
|
||||
});
|
||||
|
||||
const searchKeyPart = debouncedSearchCriteria?.searchTerm || "recent";
|
||||
|
||||
const {
|
||||
@@ -1197,7 +1216,7 @@ export function PatientTable({
|
||||
|
||||
{/* View Patient Modal */}
|
||||
<Dialog open={isViewPatientOpen} onOpenChange={setIsViewPatientOpen}>
|
||||
<DialogContent className="sm:max-w-[600px]">
|
||||
<DialogContent className="sm:max-w-[800px] max-h-[90vh] overflow-y-auto">
|
||||
<DialogHeader>
|
||||
<DialogTitle>Patient Details</DialogTitle>
|
||||
<DialogDescription>
|
||||
@@ -1348,6 +1367,40 @@ export function PatientTable({
|
||||
</div>
|
||||
</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.
|
||||
</p>
|
||||
) : (
|
||||
<Table className="mt-2">
|
||||
<TableHeader>
|
||||
<TableRow>
|
||||
<TableHead>Procedure Code</TableHead>
|
||||
<TableHead>Procedure Code Description</TableHead>
|
||||
<TableHead>Tooth/Quad/Arch/Surface</TableHead>
|
||||
<TableHead>Place of Service</TableHead>
|
||||
<TableHead>Service Date</TableHead>
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
{serviceHistory.map((row) => (
|
||||
<TableRow key={row.id}>
|
||||
<TableCell>{row.procedureCode}</TableCell>
|
||||
<TableCell>{row.description}</TableCell>
|
||||
<TableCell>{row.toothQuadArchSurface}</TableCell>
|
||||
<TableCell>{row.placeOfService}</TableCell>
|
||||
<TableCell>{row.serviceDate}</TableCell>
|
||||
</TableRow>
|
||||
))}
|
||||
</TableBody>
|
||||
</Table>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="flex justify-end space-x-2 pt-4">
|
||||
<Button
|
||||
variant="outline"
|
||||
|
||||
@@ -0,0 +1,75 @@
|
||||
import time
|
||||
|
||||
# Service history table: header cells plus the cell texts of every row.
|
||||
# innerText (not .text) so cells rendered off-screen still return their text.
|
||||
_TABLE_JS = """
|
||||
for (const table of document.querySelectorAll('table')) {
|
||||
const headers = Array.from(table.querySelectorAll('thead th, thead td'))
|
||||
.map(th => (th.innerText || th.textContent || '').toLowerCase().replace(/[^a-z]/g, ''));
|
||||
if (!headers.some(h => h.includes('procedurecode')) || !headers.some(h => h.includes('servicedate'))) continue;
|
||||
const rows = Array.from(table.querySelectorAll('tbody tr'))
|
||||
.map(tr => Array.from(tr.querySelectorAll('td'))
|
||||
.map(td => (td.innerText || td.textContent || '').replace(/\\s+/g, ' ').trim()));
|
||||
return {headers, rows, paged: !!document.querySelector('.pagination, [class*="paginat"]')};
|
||||
}
|
||||
return null;
|
||||
"""
|
||||
|
||||
|
||||
def _column_indexes(headers):
|
||||
def find(match):
|
||||
return next((i for i, h in enumerate(headers) if match(h)), None)
|
||||
|
||||
return {
|
||||
"procedureCode": find(lambda h: "procedurecode" in h and "description" not in h),
|
||||
"description": find(lambda h: "description" in h),
|
||||
"toothQuadArchSurface": find(lambda h: "tooth" in h),
|
||||
"placeOfService": find(lambda h: "placeofservice" in h),
|
||||
"serviceDate": find(lambda h: "servicedate" in h),
|
||||
}
|
||||
|
||||
|
||||
def parse_service_history(headers, rows):
|
||||
"""Map raw table cells to row dicts, dropping placeholder rows (e.g. a
|
||||
single "no records" cell) and rows without a procedure code."""
|
||||
columns = _column_indexes(headers)
|
||||
result = []
|
||||
for cells in rows:
|
||||
if len(cells) < len(headers):
|
||||
continue
|
||||
row = {
|
||||
key: cells[i] if i is not None and i < len(cells) else ""
|
||||
for key, i in columns.items()
|
||||
}
|
||||
if row["procedureCode"]:
|
||||
result.append(row)
|
||||
return result
|
||||
|
||||
|
||||
def extract_service_history(driver, timeout=15):
|
||||
"""Read the MassHealth Service History table.
|
||||
|
||||
AngularJS adds the rows after the page loads, so keep polling until every
|
||||
row has its procedure code. A member with no history waits the full
|
||||
timeout. 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:
|
||||
table = driver.execute_script(_TABLE_JS)
|
||||
if table:
|
||||
history = parse_service_history(table["headers"], table["rows"])
|
||||
if history and len(history) == len(table["rows"]):
|
||||
if table["paged"]:
|
||||
print("[extract_service_history] pagination found — only the current page was read")
|
||||
break
|
||||
except Exception as e:
|
||||
print(f"[extract_service_history] reading table failed: {e}")
|
||||
if time.time() >= deadline:
|
||||
break
|
||||
time.sleep(1)
|
||||
|
||||
print(f"[extract_service_history] {len(history)} row(s)")
|
||||
return history
|
||||
@@ -11,6 +11,7 @@ import base64
|
||||
|
||||
from mh_eligibility_results import extract_eligibility_row
|
||||
from mh_member_details import extract_member_demographics
|
||||
from mh_service_history import extract_service_history
|
||||
|
||||
|
||||
class AutomationCMSPEligibilityHistoryRemainingCheck:
|
||||
@@ -351,6 +352,10 @@ class AutomationCMSPEligibilityHistoryRemainingCheck:
|
||||
wait.until(lambda d: d.execute_script("return document.readyState") == "complete")
|
||||
time.sleep(3)
|
||||
|
||||
service_history = extract_service_history(self.driver)
|
||||
if service_history:
|
||||
self.extracted_data["service_history"] = service_history
|
||||
|
||||
safe_member = "".join(c for c in str(self.memberId) if c.isalnum() or c in "-_.")
|
||||
pdf_filename = f"mh_history_{safe_member}.pdf"
|
||||
pdf_data = self.driver.execute_cdp_cmd("Page.printToPDF", {"printBackground": True})
|
||||
|
||||
Reference in New Issue
Block a user