feat: Check Preauth from claim details, Tufts SCO approval PDF, all-folder appointment picker

- Same patient may be booked at the same time in different columns (appointment + preauth)
- New preauths save service lines and attachments so the details view shows them
- Claim/Preauth Details: renamed, Check Preauth button picks the worker from the claim's
  insurance (MassHealth, United SCO, Tufts SCO, CCA); OTP popup survives closing the window,
  window closes after a successful check
- Tufts SCO Check Preauth: searches Submitted by pre-auth number, saves the detail page PDF
  to the patient's new Approval folder (PdfTitleKey PREAUTH_APPROVAL migration)
- Appointment attachment picker lists files from all of the patient's folders

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-06 23:01:20 -05:00
co-authored by Claude Opus 5.5
parent 33bea3822c
commit 4cd780e9b2
40 changed files with 1003 additions and 113 deletions
+13
View File
@@ -34,6 +34,7 @@ import { runCmspEligibilityHistoryRemainingProcessor } from "./processors/cmspEl
import { runBcbsMaEligibilityProcessor } from "./processors/bcbsMaEligibilityProcessor";
import { runMetLifeEligibilityProcessor } from "./processors/metlifeEligibilityProcessor";
import { runAltusEligibilityProcessor } from "./processors/altusEligibilityProcessor";
import { runPreAuthCheckProcessor } from "./processors/preAuthCheckProcessor";
import type { SeleniumJobData, OcrJobData } from "./queues";
// ── Queue instances ──────────────────────────────────────────────────────────
@@ -374,6 +375,18 @@ export function enqueueSeleniumJob(data: SeleniumJobData): string {
formDob: data.formDob,
});
}
if (jobType === "preauth-check") {
return runPreAuthCheckProcessor(
{
siteKey: data.enrichedPayload.insuranceSiteKey,
enrichedPayload: data.enrichedPayload,
socketId: data.socketId,
userId: data.userId,
claimId: data.claimId,
},
job.id
);
}
throw new Error(`Unknown selenium jobType: ${jobType}`);
});
@@ -0,0 +1,152 @@
import axios from "axios";
import fs from "fs/promises";
import path from "path";
import { storage } from "../../storage";
import { callPythonSync, sleep } from "./_shared";
import { io } from "../../socket";
const SELENIUM_BASE_URL =
process.env.SELENIUM_AGENT_BASE_URL || "http://localhost:5002";
export const PREAUTH_CHECK_SITE_KEYS = ["MH", "UNITED_SCO", "TUFTS_SCO", "CCA"] as const;
export type PreAuthCheckSiteKey = (typeof PREAUTH_CHECK_SITE_KEYS)[number];
export const PREAUTH_CHECK_LABELS: Record<PreAuthCheckSiteKey, string> = {
MH: "MassHealth",
UNITED_SCO: "United SCO",
TUFTS_SCO: "Tufts SCO",
CCA: "CCA",
};
// Picks the Check PreAuth worker from the claim's insuranceProvider; null if none applies.
export function preAuthCheckSiteKeyFor(insuranceProvider?: string | null): PreAuthCheckSiteKey | null {
const p = (insuranceProvider ?? "").toLowerCase().trim();
if (p.includes("masshealth") || p.includes("mass health")) return "MH";
if (p === "cca" || p.includes("commonwealth care")) return "CCA";
if (p.includes("tufts") || p.includes("dentaquest")) return "TUFTS_SCO";
// United SCO's portal is DentalHub, so "United/DentalHub" records use it
if (p.includes("dentalhub") || (p.includes("united") && p.includes("sco"))) return "UNITED_SCO";
return null;
}
const ENDPOINTS: Record<PreAuthCheckSiteKey, string> = {
MH: "/mh-preauth-check",
UNITED_SCO: "/unitedsco-preauth-check",
TUFTS_SCO: "/tuftssco-preauth-check",
CCA: "/cca-preauth-check",
};
function log(msg: string, ctx?: any) {
console.log(`${new Date().toISOString()} [preauth-check-processor] ${msg}`, ctx ?? "");
}
function emitToSocket(socketId: string | undefined, event: string, payload: any) {
if (!socketId || !io) return;
io.sockets.sockets.get(socketId)?.emit(event, payload);
}
async function pollSession(
sessionId: string,
socketId: string | undefined,
jobId: string,
timeoutMs = 5 * 60 * 1000
): Promise<any> {
const deadline = Date.now() + timeoutMs;
let transientErrors = 0;
while (Date.now() < deadline) {
let st: any;
try {
st = (await axios.get(`${SELENIUM_BASE_URL}/session/${sessionId}/status`)).data;
transientErrors = 0;
} catch (err: any) {
if (err?.response?.status === 404) throw new Error("Selenium session ended unexpectedly");
if (++transientErrors > 10) throw new Error(`Lost contact with Selenium: ${err?.message}`);
await sleep(2000);
continue;
}
const status: string = st?.status ?? "unknown";
if (status === "completed") return st.result;
if (status === "error") throw new Error(st?.message || "Check PreAuth failed in Selenium");
// Repeated while waiting (like the eligibility checks) so a missed event doesn't hide the popup
if (status === "waiting_for_otp") {
emitToSocket(socketId, "selenium:otp_required", {
session_id: sessionId,
jobId,
message: "OTP required. Please enter the verification code.",
});
}
await sleep(1000);
}
throw new Error(`Check PreAuth timed out after ${Math.round(timeoutMs / 1000)}s`);
}
// Selenium leaves PDFs/screenshots in its downloads folder; delete them once handled
// rather than leave patient documents behind.
async function removeDownloadedFiles(result: any) {
for (const key of ["pdf_path", "ss_path", "screenshot_path", "approval_pdf_path"]) {
const p = result?.[key];
if (typeof p === "string" && p) await fs.unlink(p).catch(() => {});
}
}
// Files the portal's pre-auth detail page PDF under the claim's patient > Approval.
async function saveApprovalPdf(userId: number, claimId: number | undefined, pdfPath: string): Promise<boolean> {
const claim = claimId ? await storage.getClaim(claimId) : undefined;
if (!claim?.patientId) {
log("approval PDF not saved: claim/patient not found", { claimId });
return false;
}
const patient = await storage.getPatient(claim.patientId);
const patientName =
`${patient?.firstName ?? ""} ${patient?.lastName ?? ""}`.trim() || claim.patientName || `Patient ${claim.patientId}`;
const buffer = await fs.readFile(pdfPath);
await storage.savePdfToCloudStorage(userId, claim.patientId, patientName, "Approval", path.basename(pdfPath), buffer);
log("approval PDF saved", { claimId, patientId: claim.patientId });
return true;
}
export async function runPreAuthCheckProcessor(
input: {
siteKey: PreAuthCheckSiteKey;
enrichedPayload: any;
socketId?: string;
userId: number;
claimId?: number;
},
jobId: string
): Promise<{ siteKey: PreAuthCheckSiteKey; message: string }> {
const { siteKey, enrichedPayload, socketId, userId, claimId } = input;
log("starting", { siteKey, jobId });
let result: any;
if (siteKey === "MH") {
result = await callPythonSync(ENDPOINTS.MH, { data: enrichedPayload });
} else {
const start = (await axios.post(`${SELENIUM_BASE_URL}${ENDPOINTS[siteKey]}`, { data: enrichedPayload })).data;
if (!start?.session_id) throw new Error("Selenium did not return a session_id for Check PreAuth");
emitToSocket(socketId, "selenium:preauth_check_session_started", {
session_id: start.session_id,
jobId,
});
result = await pollSession(start.session_id, socketId, jobId);
}
if (!result || result.status === "error") {
throw new Error(result?.message ?? "Check PreAuth returned an error");
}
let message = typeof result.message === "string" ? result.message : "completed";
try {
if (result.approval_pdf_path) {
const saved = await saveApprovalPdf(userId, claimId, result.approval_pdf_path);
message += saved ? " Saved to the patient's Approval folder." : "";
}
} finally {
await removeDownloadedFiles(result);
}
log("done", { siteKey, jobId });
return { siteKey, message };
}
+2 -1
View File
@@ -29,7 +29,8 @@ export type SeleniumJobType =
| "cmsp-eligibility-history-remaining-check"
| "bcbs-ma-eligibility-check"
| "metlife-eligibility-check"
| "altus-eligibility-check";
| "altus-eligibility-check"
| "preauth-check";
export interface SeleniumJobData {
jobType: SeleniumJobType;
+2 -14
View File
@@ -378,26 +378,14 @@ router.put(
.json({ message: "Changing patientId is not allowed" });
}
// 5. Check for conflicting appointments (same patient OR staff at same time)
// 5. Check for conflicting appointments for this staff member at the same time
// (same patient at the same time in different columns is allowed, e.g. appointment + preauth)
const date = appointmentData.date ?? existingAppointment.date;
const startTime =
appointmentData.startTime ?? existingAppointment.startTime;
const staffId = appointmentData.staffId ?? existingAppointment.staffId;
const patientConflict = await storage.getPatientConflictAppointment(
existingAppointment.patientId,
date,
startTime,
appointmentId
);
if (patientConflict) {
return res.status(409).json({
message: "This patient already has an appointment at this time.",
});
}
const staffConflict = await storage.getStaffConflictAppointment(
staffId,
date,
+28 -23
View File
@@ -21,7 +21,8 @@ import { forwardToSeleniumClaimPreAuthAgent } from "../services/seleniumInsuranc
import { formatDobForAgent } from "../utils/dateUtils";
import { ADA_PAYERS, adaPayerKeyForProvider, buildAdaClaimPdf } from "../services/adaClaimForm";
import { backupScreenshots } from "../utils/screenshotBackup";
import { appendAppointmentFiles } from "../utils/appointmentAttachments";
import { appendAppointmentFiles, autoLinkAppointmentFiles } from "../utils/appointmentAttachments";
import { buildPreAuthClaimDetails } from "../utils/preAuthClaim";
const router = Router();
@@ -220,6 +221,29 @@ router.get(
}
);
// GET /api/claims/patient-files?patientId=123
// Lists every file in this patient's Cloud Storage folders (Attachments, Approval, Eligibility, ...)
// with the folder each one is in, so any of them can be attached to an appointment.
router.get(
"/patient-files",
async (req: Request, res: Response): Promise<any> => {
if (!req.user?.id) return res.status(401).json({ error: "Unauthorized" });
const patientId = Number(req.query.patientId);
if (!patientId || isNaN(patientId)) {
return res.status(400).json({ error: "Invalid patientId" });
}
try {
const files = await storage.listPatientAllCloudFiles(patientId);
return res.json({ error: false, data: files });
} catch (err: any) {
console.error("[patient-files]", err);
return res.status(500).json({ error: "Failed to list patient files", message: err?.message });
}
}
);
// GET /api/claims/recent-attachments?limit=20
// Lists recently saved Cloud Storage "Attachments" across all patients (e.g. Copy Agent
// screenshots), for use in contexts (like the AI chatbot) that don't have a patient in scope yet.
@@ -517,7 +541,7 @@ router.post(
massdhpPassword: credentials.password,
};
// Create a minimal PREAUTH claim record so the preauth number can be stored and shown
// Create a PREAUTH claim record so the preauth number and details can be stored and shown
let preAuthClaimId: number | undefined;
try {
const serviceDate = claimData.serviceDate
@@ -540,8 +564,10 @@ router.post(
serviceDate,
insuranceProvider: "MassHealth",
status: "PREAUTH",
...buildPreAuthClaimDetails(claimData, serviceDate),
} as any);
preAuthClaimId = preAuthRecord.id;
await autoLinkAppointmentFiles(preAuthRecord.id!, preAuthRecord.appointmentId);
} catch (e: any) {
console.error("[preauth] failed to create preauth record:", e?.message);
}
@@ -1346,27 +1372,6 @@ router.get("/:id", async (req: Request, res: Response): Promise<any> => {
}
});
// Links AppointmentFile records to a claim as ClaimFile records (dedup by filename).
// Called after claim create or update so files saved in the procedures form always appear.
async function autoLinkAppointmentFiles(claimId: number, appointmentId: number | null | undefined) {
if (!appointmentId) return;
const { prisma: db } = await import("@repo/db/client");
const aptFiles = await db.appointmentFile.findMany({ where: { appointmentId } });
if (!aptFiles.length) return;
const existing = await db.claimFile.findMany({ where: { claimId }, select: { filename: true } });
const existingNames = new Set(existing.map((f: any) => f.filename));
const toLink = aptFiles.filter((f: any) => f.filename && !existingNames.has(f.filename));
if (!toLink.length) return;
await db.claimFile.createMany({
data: toLink.map((f: any) => ({
claimId,
filename: f.filename,
mimeType: f.mimeType ?? "",
...(f.filePath ? { filePath: String(f.filePath) } : {}),
})),
});
}
// Create a new claim
router.post("/", async (req: Request, res: Response): Promise<any> => {
try {
+1
View File
@@ -157,6 +157,7 @@ const TITLE_KEY_TO_CLOUD_CATEGORY: Record<string, string> = {
INSURANCE_CLAIM: "Claims",
INSURANCE_CLAIM_PREAUTH: "PreAuth",
CLAIM_STATUS: "Claim Status",
PREAUTH_APPROVAL: "Approval",
OTHER: "Attachments",
};
+2
View File
@@ -28,6 +28,7 @@ import insuranceStatusUnitedDHClaimRoutes from "./insuranceStatusUnitedDHClaim";
import insuranceStatusUnitedDHPreAuthRoutes from "./insuranceStatusUnitedDHPreAuth";
import insuranceStatusTuftsSCOClaimRoutes from "./insuranceStatusTuftsSCOClaim";
import insuranceStatusTuftsSCOPreAuthRoutes from "./insuranceStatusTuftsSCOPreAuth";
import preAuthCheckRoutes from "./preAuthCheck";
import insuranceStatusUnitedUcardClaimRoutes from "./insuranceStatusUnitedUcardClaim";
import paymentsRoutes from "./payments";
import databaseManagementRoutes from "./database-management";
@@ -91,6 +92,7 @@ router.use("/claims", insuranceStatusUnitedDHClaimRoutes);
router.use("/claims", insuranceStatusUnitedDHPreAuthRoutes);
router.use("/claims", insuranceStatusTuftsSCOClaimRoutes);
router.use("/claims", insuranceStatusTuftsSCOPreAuthRoutes);
router.use("/claims", preAuthCheckRoutes);
router.use("/claims", insuranceStatusUnitedUcardClaimRoutes);
router.use("/payments", paymentsRoutes);
router.use("/database-management", databaseManagementRoutes);
@@ -2,7 +2,8 @@ import { Router, Request, Response } from "express";
import { storage } from "../storage";
import { enqueueSeleniumJob } from "../queue/jobRunner";
import multer from "multer";
import { appendAppointmentFiles } from "../utils/appointmentAttachments";
import { appendAppointmentFiles, autoLinkAppointmentFiles } from "../utils/appointmentAttachments";
import { buildPreAuthClaimDetails } from "../utils/preAuthClaim";
const router = Router();
const upload = multer({ storage: multer.memoryStorage() });
@@ -95,8 +96,10 @@ router.post(
serviceDate,
insuranceProvider: "CCA",
status: "PREAUTH",
...buildPreAuthClaimDetails(claimData, serviceDate),
} as any);
claimId = record.id;
await autoLinkAppointmentFiles(record.id!, record.appointmentId);
console.log(`[cca-preauth route] created claim record id=${claimId}`);
} catch (e: any) {
console.error("[cca-preauth route] failed to create claim record:", e?.message);
@@ -1,5 +1,7 @@
import { Router, Request, Response } from "express";
import { storage } from "../storage";
import { autoLinkAppointmentFiles } from "../utils/appointmentAttachments";
import { buildPreAuthClaimDetails } from "../utils/preAuthClaim";
import { enqueueSeleniumJob } from "../queue/jobRunner";
import { forwardOtpToSeleniumTuftsSCOPreAuthAgent } from "../services/seleniumTuftsSCOPreAuthClient";
import { io } from "../socket";
@@ -72,8 +74,10 @@ router.post("/tuftssco-preauth", async (req: Request, res: Response): Promise<an
serviceDate,
insuranceProvider: "Tufts SCO",
status: "PREAUTH",
...buildPreAuthClaimDetails(claimData, serviceDate),
} as any);
claimId = record.id;
await autoLinkAppointmentFiles(record.id!, record.appointmentId);
console.log(`[tuftssco-preauth route] created claim record id=${claimId}`);
} catch (e: any) {
console.error("[tuftssco-preauth route] failed to create claim record:", e?.message);
@@ -1,5 +1,7 @@
import { Router, Request, Response } from "express";
import { storage } from "../storage";
import { autoLinkAppointmentFiles } from "../utils/appointmentAttachments";
import { buildPreAuthClaimDetails } from "../utils/preAuthClaim";
import { enqueueSeleniumJob } from "../queue/jobRunner";
import { forwardOtpToSeleniumUnitedDHPreAuthAgent } from "../services/seleniumUnitedDHPreAuthClient";
import { io } from "../socket";
@@ -67,23 +69,6 @@ router.post("/uniteddh-preauth", async (req: Request, res: Response): Promise<an
? new Date(claimData.dateOfBirth)
: new Date("2000-01-01");
const rawLines = Array.isArray(claimData.serviceLines) ? claimData.serviceLines : [];
const serviceLinesInput = rawLines.length > 0
? {
create: rawLines.map((sl: any) => ({
procedureCode: sl.procedureCode ?? "",
procedureDate: sl.procedureDate ? new Date(sl.procedureDate) : serviceDate,
quad: sl.quad ?? "",
arch: sl.arch ?? "",
toothNumber: sl.toothNumber ?? "",
toothSurface: sl.toothSurface ?? "",
totalBilled: Number(sl.totalBilled ?? 0),
totalAdjusted: Number(sl.totalAdjusted ?? 0),
totalPaid: Number(sl.totalPaid ?? 0),
})),
}
: undefined;
const record = await storage.createClaim({
patientId: Number(claimData.patientId),
appointmentId: claimData.appointmentId ? Number(claimData.appointmentId) : null,
@@ -97,10 +82,11 @@ router.post("/uniteddh-preauth", async (req: Request, res: Response): Promise<an
serviceDate,
insuranceProvider: "United/DentalHub",
status: "PREAUTH",
...(serviceLinesInput ? { serviceLines: serviceLinesInput } : {}),
...buildPreAuthClaimDetails(claimData, serviceDate),
} as any);
claimId = record.id;
console.log(`[uniteddh-preauth route] created claim record id=${claimId} with ${rawLines.length} service line(s)`);
await autoLinkAppointmentFiles(record.id!, record.appointmentId);
console.log(`[uniteddh-preauth route] created claim record id=${claimId}`);
} catch (e: any) {
console.error("[uniteddh-preauth route] failed to create claim record:", e?.message);
}
+107
View File
@@ -0,0 +1,107 @@
import { Router, Request, Response } from "express";
import axios from "axios";
import { storage } from "../storage";
import { io } from "../socket";
import { enqueueSeleniumJob } from "../queue/jobRunner";
import { prisma as db } from "@repo/db/client";
import {
PREAUTH_CHECK_LABELS,
PreAuthCheckSiteKey,
preAuthCheckSiteKeyFor,
} from "../queue/processors/preAuthCheckProcessor";
const router = Router();
const SELENIUM_BASE_URL =
process.env.SELENIUM_AGENT_BASE_URL || "http://localhost:5002";
// Credential field names each insurer's eligibility worker expects
const CREDENTIAL_FIELDS: Record<PreAuthCheckSiteKey, [string, string]> = {
MH: ["massdhpUsername", "massdhpPassword"],
UNITED_SCO: ["unitedscoUsername", "unitedscoPassword"],
TUFTS_SCO: ["dentaquestUsername", "dentaquestPassword"],
CCA: ["cca_username", "cca_password"],
};
/**
* POST /api/claims/preauth-check
* Body: { claimId, socketId }
* Runs the Check PreAuth worker matching the claim's insurance (MH, United SCO, Tufts SCO, CCA).
*/
router.post("/preauth-check", async (req: Request, res: Response): Promise<any> => {
if (!req.user?.id) return res.status(401).json({ error: "Unauthorized" });
const { claimId, socketId } = req.body ?? {};
try {
const claim = await storage.getClaim(Number(claimId));
if (!claim) return res.status(404).json({ error: "Claim not found" });
const siteKey = preAuthCheckSiteKeyFor(claim.insuranceProvider);
if (!siteKey) {
return res.status(400).json({
error: `Check Preauth isn't available for ${claim.insuranceProvider || "this insurance"}. It supports MassHealth, United SCO, Tufts SCO and CCA.`,
});
}
const patient = await storage.getPatient(claim.patientId);
const credentials = await storage.getInsuranceCredentialByUserAndSiteKey(req.user.id, siteKey);
if (!credentials) {
return res.status(404).json({
error: `No credentials found for ${siteKey}. Please add them on the Settings page.`,
});
}
const [userField, passField] = CREDENTIAL_FIELDS[siteKey];
const enrichedPayload: Record<string, any> = {
memberId: claim.memberId,
dateOfBirth: new Date(claim.dateOfBirth).toISOString().slice(0, 10),
firstName: patient?.firstName ?? "",
lastName: patient?.lastName ?? "",
preAuthNumber: (claim as any).preAuthNumber ?? "",
claimNumber: claim.claimNumber ?? "",
insuranceSiteKey: siteKey,
[userField]: credentials.username,
[passField]: credentials.password,
};
if (siteKey === "UNITED_SCO") {
const seleniumSettings = await db.seleniumSettings.findUnique({ where: { userId: req.user.id } });
enrichedPayload.paymentGroupId = seleniumSettings?.paymentGroupId ?? "";
}
const jobId = enqueueSeleniumJob({
jobType: "preauth-check",
userId: req.user.id,
socketId,
enrichedPayload,
claimId: claim.id,
});
return res.json({ status: "queued", jobId, siteKey, label: PREAUTH_CHECK_LABELS[siteKey] });
} catch (err: any) {
console.error("[preauth-check route] error:", err);
return res.status(500).json({ error: err?.message || "Failed to start Check PreAuth" });
}
});
/**
* POST /api/claims/preauth-check/submit-otp
* Body: { session_id, otp, socketId }
*/
router.post("/preauth-check/submit-otp", async (req: Request, res: Response): Promise<any> => {
const { session_id: sessionId, otp, socketId } = req.body ?? {};
if (!sessionId || !otp) {
return res.status(400).json({ error: "session_id and otp are required" });
}
try {
const r = await axios.post(`${SELENIUM_BASE_URL}/submit-otp`, { session_id: sessionId, otp });
if (socketId) io?.to(socketId).emit("selenium:otp_submitted", { session_id: sessionId });
return res.json(r.data);
} catch (err: any) {
console.error("[preauth-check route] submit-otp failed:", err?.response?.data || err?.message);
return res.status(500).json({ error: err?.response?.data?.detail || "Failed to submit the code" });
}
});
export default router;
@@ -38,12 +38,6 @@ export interface IStorage {
startTime: string,
excludeId?: number
): Promise<Appointment | undefined>;
getPatientConflictAppointment(
patientId: number,
date: Date,
startTime: string,
excludeId: number
): Promise<Appointment | undefined>;
getStaffConflictAppointment(
staffId: number,
date: Date,
@@ -175,24 +169,6 @@ export const appointmentsStorage: IStorage = {
);
},
async getPatientConflictAppointment(
patientId: number,
date: Date,
startTime: string,
excludeId: number
): Promise<Appointment | undefined> {
return (
(await db.appointment.findFirst({
where: {
patientId,
date,
startTime,
NOT: { id: excludeId },
},
})) ?? undefined
);
},
async getStaffConflictAppointment(
staffId: number,
date: Date,
@@ -153,7 +153,7 @@ export interface IStorage {
userId: number,
patientId: number,
patientName: string,
category: "Eligibility" | "Claims" | "PreAuth" | "Claim Status" | "Attachments",
category: "Eligibility" | "Claims" | "PreAuth" | "Claim Status" | "Approval" | "Attachments",
filename: string,
buffer: Buffer,
mimeType?: string
@@ -163,6 +163,9 @@ export interface IStorage {
category: string
): Promise<CloudFile[]>;
listRecentAttachmentFiles(limit?: number): Promise<CloudFile[]>;
listPatientAllCloudFiles(
patientId: number
): Promise<(CloudFile & { folderName: string })[]>;
}
/* ------------------------------- Implementation ------------------------------- */
@@ -595,7 +598,7 @@ export const cloudStorageStorage: IStorage = {
userId: number,
patientId: number,
patientName: string,
category: "Eligibility" | "Claims" | "PreAuth" | "Claim Status" | "Attachments",
category: "Eligibility" | "Claims" | "PreAuth" | "Claim Status" | "Approval" | "Attachments",
filename: string,
buffer: Buffer,
mimeType: string = "application/pdf"
@@ -631,6 +634,7 @@ export const cloudStorageStorage: IStorage = {
Claims: { titleKey: "INSURANCE_CLAIM", title: "Claims" },
PreAuth: { titleKey: "INSURANCE_CLAIM_PREAUTH", title: "Preauth" },
"Claim Status": { titleKey: "CLAIM_STATUS", title: "Claim Status" },
Approval: { titleKey: "PREAUTH_APPROVAL", title: "Approval" },
Attachments: { titleKey: "OTHER", title: "Attachments" },
};
const mapping = CATEGORY_TO_TITLE_KEY[category];
@@ -672,6 +676,43 @@ export const cloudStorageStorage: IStorage = {
return files.map(serializeFile) as unknown as CloudFile[];
},
// Every file in the patient's folder and its subfolders (Approval, Eligibility, ...),
// each tagged with the name of the folder it's in.
async listPatientAllCloudFiles(patientId: number) {
const patientFolder = await db.cloudFolder.findFirst({ where: { patientId } });
if (!patientFolder) return [];
const folderNames = new Map<number, string>([[patientFolder.id, patientFolder.name]]);
let frontier = [patientFolder.id];
while (frontier.length > 0) {
const children = await db.cloudFolder.findMany({
where: { parentId: { in: frontier } },
select: { id: true, name: true },
});
children.forEach((c: { id: number; name: string }) => folderNames.set(c.id, c.name));
frontier = children.map((c: { id: number }) => c.id);
}
const files = await db.cloudFile.findMany({
where: { folderId: { in: [...folderNames.keys()] }, isComplete: true },
orderBy: { createdAt: "desc" },
select: {
id: true,
name: true,
mimeType: true,
fileSize: true,
folderId: true,
isComplete: true,
createdAt: true,
updatedAt: true,
},
});
return files.map((f: any) => ({
...serializeFile(f),
folderName: folderNames.get(f.folderId as number) ?? "",
})) as unknown as (CloudFile & { folderName: string })[];
},
async listRecentAttachmentFiles(limit: number = 20) {
const files = await db.cloudFile.findMany({
where: { folder: { name: "Attachments" }, isComplete: true },
@@ -25,3 +25,24 @@ export async function appendAppointmentFiles(
seenNames.add(f.filename);
}
}
// Links AppointmentFile records to a claim as ClaimFile records (dedup by filename).
// Called after claim create or update so files saved in the procedures form always appear.
export async function autoLinkAppointmentFiles(claimId: number, appointmentId: number | null | undefined) {
if (!appointmentId) return;
const { prisma: db } = await import("@repo/db/client");
const aptFiles = await db.appointmentFile.findMany({ where: { appointmentId } });
if (!aptFiles.length) return;
const existing = await db.claimFile.findMany({ where: { claimId }, select: { filename: true } });
const existingNames = new Set(existing.map((f: any) => f.filename));
const toLink = aptFiles.filter((f: any) => f.filename && !existingNames.has(f.filename));
if (!toLink.length) return;
await db.claimFile.createMany({
data: toLink.map((f: any) => ({
claimId,
filename: f.filename,
mimeType: f.mimeType ?? "",
...(f.filePath ? { filePath: String(f.filePath) } : {}),
})),
});
}
+46
View File
@@ -0,0 +1,46 @@
const safeDate = (value: unknown, fallback: Date): Date => {
if (!value) return fallback;
const parsed = new Date(value as string);
return isNaN(parsed.getTime()) ? fallback : parsed;
};
// Procedures, attachments and missing teeth to save on a PREAUTH claim record, so its
// details match a regular claim. Bad values fall back rather than throw: a failed
// createClaim would lose the record that holds the preauth number.
export function buildPreAuthClaimDetails(claimData: any, serviceDate: Date) {
const rawLines: any[] = Array.isArray(claimData.serviceLines) ? claimData.serviceLines : [];
const rawFiles: any[] = Array.isArray(claimData.claimFiles) ? claimData.claimFiles : [];
const files = rawFiles.filter((f) => f?.filename);
return {
...(rawLines.length > 0
? {
serviceLines: {
create: rawLines.map((sl) => ({
procedureCode: sl.procedureCode ?? "",
procedureDate: safeDate(sl.procedureDate, serviceDate),
quad: sl.quad ?? "",
arch: sl.arch ?? "",
toothNumber: sl.toothNumber ?? "",
toothSurface: sl.toothSurface ?? "",
totalBilled: Number(sl.totalBilled) || 0,
totalAdjusted: Number(sl.totalAdjusted) || 0,
totalPaid: Number(sl.totalPaid) || 0,
})),
},
}
: {}),
...(files.length > 0
? {
claimFiles: {
create: files.map((f) => ({
filename: String(f.filename),
mimeType: String(f.mimeType ?? ""),
...(f.filePath ? { filePath: String(f.filePath) } : {}),
})),
},
}
: {}),
...(claimData.missingTeeth ? { missingTeeth: claimData.missingTeeth } : {}),
};
}
@@ -242,7 +242,7 @@ export function AppointmentAttachments({ appointmentId, patientId }: Appointment
type="button"
variant="ghost"
size="icon"
title="Choose from scanned attachments"
title="Choose from patient files"
onClick={() => setPickerOpen(true)}
>
<ImageIcon className="h-4 w-4" />
@@ -315,6 +315,7 @@ export function AppointmentAttachments({ appointmentId, patientId }: Appointment
open={pickerOpen}
onClose={() => setPickerOpen(false)}
patientId={patientId}
allFolders
onFilesSelected={handleServerFilesSelected}
/>
@@ -0,0 +1,178 @@
import { useState, useSyncExternalStore } from "react";
import { LoaderCircleIcon } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import {
Dialog,
DialogContent,
DialogFooter,
DialogHeader,
DialogTitle,
} from "@/components/ui/dialog";
import { toast } from "@/hooks/use-toast";
import { apiRequest } from "@/lib/queryClient";
import { socket } from "@/lib/socket";
// Runs the Check PreAuth worker matching the claim's insurance (the backend picks it:
// MassHealth, United SCO, Tufts SCO or CCA).
//
// Running checks live in this module, not in the button, so a check (and its OTP popup)
// keeps going after the Claim/Preauth Details window that started it is closed.
// <PreauthCheckHost /> renders the OTP popup and must stay mounted on the page.
type OtpRequest = { jobId: string; sessionId: string; label: string };
type State = { runningClaimIds: number[]; otp: OtpRequest | null };
let state: State = { runningClaimIds: [], otp: null };
const subscribers = new Set<() => void>();
// Jobs whose OTP popup was answered or dismissed; the backend keeps repeating
// "otp required" while it waits, which must not reopen the popup.
const otpHandledJobIds = new Set<string>();
function setState(patch: Partial<State>) {
state = { ...state, ...patch };
subscribers.forEach((fn) => fn());
}
function subscribe(fn: () => void) {
subscribers.add(fn);
return () => subscribers.delete(fn);
}
const usePreauthCheckState = () => useSyncExternalStore(subscribe, () => state);
async function startPreauthCheck(claimId: number, onCompleted?: () => void) {
if (state.runningClaimIds.includes(claimId)) return;
setState({ runningClaimIds: [...state.runningClaimIds, claimId] });
let jobId = "";
let sessionId: string | null = null;
let label = "";
const handlers: Record<string, (ev: any) => void> = {
"selenium:preauth_check_session_started": (ev) => {
if (String(ev?.jobId) === jobId) sessionId = ev.session_id ?? null;
},
"selenium:otp_required": (ev) => {
if (String(ev?.jobId) !== jobId) return;
sessionId = ev.session_id ?? sessionId;
if (sessionId && !otpHandledJobIds.has(jobId) && state.otp?.jobId !== jobId) setState({ otp: { jobId, sessionId, label } });
},
"job:update": (ev) => {
if (String(ev?.jobId) !== jobId || ev.status === "active") return;
if (ev.status === "completed") {
toast({ title: `${label} Check PreAuth complete`, description: ev.result?.message ?? "" });
onCompleted?.();
} else {
toast({
title: `${label} Check PreAuth failed`,
description: ev.error ?? "The check did not finish.",
variant: "destructive",
});
}
finish();
},
};
const finish = () => {
Object.entries(handlers).forEach(([event, fn]) => socket.off(event, fn));
otpHandledJobIds.delete(jobId);
setState({
runningClaimIds: state.runningClaimIds.filter((id) => id !== claimId),
otp: state.otp?.jobId === jobId ? null : state.otp,
});
};
// Listen before the request so no event from a fast job is missed.
Object.entries(handlers).forEach(([event, fn]) => socket.on(event, fn));
try {
const res = await apiRequest("POST", "/api/claims/preauth-check", {
claimId,
socketId: socket.id,
});
const body = await res.json();
if (!res.ok || body.error) throw new Error(body.error || `Server error (${res.status})`);
jobId = String(body.jobId);
label = body.label ?? "";
toast({ title: `${label} Check PreAuth started`, description: "The browser will open shortly." });
} catch (err: any) {
toast({ title: "Check PreAuth error", description: err?.message ?? "Failed to start.", variant: "destructive" });
finish();
}
}
// onCompleted runs after a successful check (the PDF is saved by then); it may fire after the
// details window has closed, so callers must guard against acting on a stale window.
export function CheckPreauthButton({ claimId, onCompleted }: { claimId: number; onCompleted?: () => void }) {
const { runningClaimIds } = usePreauthCheckState();
const running = runningClaimIds.includes(claimId);
return (
<Button variant="outline" disabled={running} onClick={() => void startPreauthCheck(claimId, onCompleted)}>
{running ? (
<>
<LoaderCircleIcon className="mr-2 h-4 w-4 animate-spin" /> Checking…
</>
) : (
"Check Preauth"
)}
</Button>
);
}
export function PreauthCheckHost() {
const { otp: request } = usePreauthCheckState();
const [otp, setOtp] = useState("");
const [submitting, setSubmitting] = useState(false);
const close = () => {
if (request) otpHandledJobIds.add(request.jobId);
setOtp("");
setState({ otp: null });
};
const submitOtp = async () => {
if (!otp.trim() || !request) return;
setSubmitting(true);
try {
const res = await apiRequest("POST", "/api/claims/preauth-check/submit-otp", {
session_id: request.sessionId,
otp: otp.trim(),
socketId: socket.id,
});
const body = await res.json().catch(() => ({}));
if (!res.ok || body.error) throw new Error(body.error || "Failed to submit the code");
close();
} catch (err: any) {
toast({ title: "Code not accepted", description: err?.message, variant: "destructive" });
} finally {
setSubmitting(false);
}
};
return (
<Dialog open={!!request} onOpenChange={(open) => !open && close()}>
<DialogContent className="sm:max-w-[400px]">
<DialogHeader>
<DialogTitle>Enter verification code</DialogTitle>
</DialogHeader>
<p className="text-sm text-muted-foreground">
{request?.label} sent a verification code. Enter it here, or type it directly in the browser window.
</p>
<Input
value={otp}
onChange={(e) => setOtp(e.target.value)}
placeholder="Verification code"
onKeyDown={(e) => e.key === "Enter" && void submitOtp()}
autoFocus
/>
<DialogFooter>
<Button variant="outline" onClick={close}>
Cancel
</Button>
<Button onClick={() => void submitOtp()} disabled={submitting || !otp.trim()}>
{submitting ? "Submitting…" : "Submit"}
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
);
}
@@ -1132,6 +1132,8 @@ export function ClaimForm({
return;
}
const preAuthFilesMeta = await savePreAuthAttachments(f.uploadedFiles);
// sending form data to selenium service
onHandleForMHSeleniumClaimPreAuth({
...f,
@@ -1143,6 +1145,7 @@ export function ClaimForm({
insuranceProvider: "Mass Health",
insuranceSiteKey: "MH",
appointmentId: appointmentId ?? 0,
claimFiles: mergeWithExistingAttachments(preAuthFilesMeta),
});
// 5. Close form
@@ -1698,6 +1701,8 @@ export function ClaimForm({
return;
}
const preAuthFilesMeta = await savePreAuthAttachments(form.uploadedFiles);
onHandleForCCASeleniumPreAuth({
...form,
serviceLines: filteredServiceLines,
@@ -1706,6 +1711,7 @@ export function ClaimForm({
insuranceProvider: "CCA",
insuranceSiteKey: "CCA",
appointmentId: appointmentId ?? 0,
claimFiles: mergeWithExistingAttachments(preAuthFilesMeta),
});
onClose();
@@ -1849,6 +1855,21 @@ export function ClaimForm({
return (data.data ?? []) as ClaimFileMeta[];
};
// MH and CCA send the files to Selenium in the request itself, so saving a copy for the
// claim's details must not block the submission if it fails (e.g. over the 5MB limit).
const savePreAuthAttachments = async (files?: File[]): Promise<ClaimFileMeta[]> => {
try {
return await uploadAttachmentsToLocalFolder(files ?? []);
} catch (err: any) {
toast({
title: "Attachments not saved to the PreAuth record",
description: err?.message ?? "They will still be sent with the PreAuth.",
variant: "destructive",
});
return [];
}
};
const handleSave = async () => {
const filteredServiceLines = form.serviceLines.filter(
(line) => (line.procedureCode ?? "").trim() !== "",
@@ -6,12 +6,13 @@ import {
DialogDescription,
} from "@/components/ui/dialog";
import { Button } from "@/components/ui/button";
import React from "react";
import React, { useEffect, useRef } from "react";
import { formatDateToHumanReadable } from "@/utils/dateUtils";
import { ClaimFileMeta, ClaimWithServiceLines } from "@repo/db/types";
import { FileText, Paperclip, Printer } from "lucide-react";
import { toast } from "@/hooks/use-toast";
import { openPendingTab, showAdaClaimForm } from "@/utils/adaClaimForm";
import { CheckPreauthButton } from "./check-preauth-button";
import {
safeParseMissingTeeth,
splitTeeth,
@@ -68,11 +69,23 @@ export default function ClaimViewModal({
const claimFiles = getClaimFilesArray(claim);
// Check PreAuth finishes after a delay; only close this window if it is still open.
const mountedRef = useRef(true);
useEffect(() => {
mountedRef.current = true;
return () => {
mountedRef.current = false;
};
}, []);
const closeAfterPreauthCheck = () => {
if (mountedRef.current) onOpenChange(false);
};
return (
<Dialog open={isOpen} onOpenChange={onOpenChange}>
<DialogContent className="sm:max-w-[700px] max-h-[90vh] overflow-y-auto">
<DialogHeader>
<DialogTitle>Claim Details</DialogTitle>
<DialogTitle>Claim/Preauth Details</DialogTitle>
<DialogDescription>
Detailed view of the selected claim.
</DialogDescription>
@@ -379,6 +392,7 @@ export default function ClaimViewModal({
<Printer className="mr-2 h-4 w-4" /> Print ADA Form
</Button>
)}
{claim.id != null && <CheckPreauthButton claimId={claim.id} onCompleted={closeAfterPreauthCheck} />}
<Button
onClick={() => {
onOpenChange(false);
@@ -12,9 +12,14 @@ interface ServerAttachmentsPickerModalProps {
// When set, lists only this patient's saved attachments. When omitted, lists
// recently saved attachments across all patients (used where no patient is in scope yet).
patientId?: number;
// With patientId: list files from all of the patient's folders (Approval, Eligibility, ...)
// instead of only Attachments, with a filter per folder.
allFolders?: boolean;
onFilesSelected: (files: File[]) => void;
}
type PickerFile = CloudFile & { folderName?: string };
function fileIcon(mime: string | undefined | null) {
if (mime?.startsWith("image/")) return ImageIcon;
if (mime === "application/pdf") return FileText;
@@ -59,36 +64,50 @@ export function ServerAttachmentsPickerModal({
open,
onClose,
patientId,
allFolders = false,
onFilesSelected,
}: ServerAttachmentsPickerModalProps) {
const { toast } = useToast();
const [selectedIds, setSelectedIds] = useState<Set<number>>(new Set());
const [isAdding, setIsAdding] = useState(false);
const [folderFilter, setFolderFilter] = useState<string | null>(null);
const endpoint = patientId
? `/api/claims/patient-attachments?patientId=${patientId}`
: `/api/claims/recent-attachments?limit=40`;
const showAllFolders = allFolders && !!patientId;
const endpoint = showAllFolders
? `/api/claims/patient-files?patientId=${patientId}`
: patientId
? `/api/claims/patient-attachments?patientId=${patientId}`
: `/api/claims/recent-attachments?limit=40`;
const { data, isLoading, isError } = useQuery<CloudFile[]>({
queryKey: ["/api/claims/attachments-picker", patientId ?? "recent"],
const { data, isLoading, isError } = useQuery<PickerFile[]>({
queryKey: ["/api/claims/attachments-picker", patientId ?? "recent", showAllFolders],
queryFn: async () => {
const res = await apiRequest("GET", endpoint);
const json = await res.json();
if (!res.ok || json.error) {
throw new Error(json.message || "Failed to load attachments");
}
return (json.data ?? []) as CloudFile[];
return (json.data ?? []) as PickerFile[];
},
enabled: open,
});
useEffect(() => {
if (!open) setSelectedIds(new Set());
if (!open) {
setSelectedIds(new Set());
setFolderFilter(null);
}
}, [open]);
if (!open) return null;
const files = data ?? [];
const allFiles = data ?? [];
const folderNames = showAllFolders
? [...new Set(allFiles.map((f) => f.folderName || "Other"))].sort()
: [];
const files = folderFilter
? allFiles.filter((f) => (f.folderName || "Other") === folderFilter)
: allFiles;
const toggleSelected = (id: number) => {
setSelectedIds((prev) => {
@@ -103,7 +122,7 @@ export function ServerAttachmentsPickerModal({
if (selectedIds.size === 0) return;
setIsAdding(true);
try {
const selectedFiles = files.filter((f) => selectedIds.has(f.id as number));
const selectedFiles = allFiles.filter((f) => selectedIds.has(f.id as number));
const built = await Promise.all(
selectedFiles.map(async (f) => {
const res = await apiRequest("GET", `/api/cloud-storage/files/${f.id}/content`);
@@ -135,12 +154,31 @@ export function ServerAttachmentsPickerModal({
<div className="relative w-full max-w-2xl mx-4 bg-white rounded-lg shadow-lg flex flex-col max-h-[80vh]">
<div className="p-4 border-b">
<h3 className="text-lg font-medium">Choose from Server Attachments</h3>
<h3 className="text-lg font-medium">
{showAllFolders ? "Choose from Patient Files" : "Choose from Server Attachments"}
</h3>
<p className="text-sm text-muted-foreground mt-1">
{patientId
? "Previously saved screenshots and files for this patient."
: "Recently saved screenshots and files across all patients."}
{showAllFolders
? "Files saved in any of this patient's folders (Approval, Eligibility, Attachments, ...)."
: patientId
? "Previously saved screenshots and files for this patient."
: "Recently saved screenshots and files across all patients."}
</p>
{folderNames.length > 1 && (
<div className="flex flex-wrap gap-2 mt-3">
{[null, ...folderNames].map((name) => (
<Button
key={name ?? "__all"}
type="button"
size="sm"
variant={folderFilter === name ? "default" : "outline"}
onClick={() => setFolderFilter(name)}
>
{name ?? "All"}
</Button>
))}
</div>
)}
</div>
<div className="p-4 overflow-y-auto flex-1" style={{ minHeight: "200px" }}>
@@ -154,7 +192,9 @@ export function ServerAttachmentsPickerModal({
</p>
) : files.length === 0 ? (
<p className="text-sm text-muted-foreground text-center py-8">
{patientId
{showAllFolders
? "No files saved yet for this patient."
: patientId
? "No screenshots saved yet for this patient."
: "No screenshots saved yet."}
</p>
@@ -175,7 +215,10 @@ export function ServerAttachmentsPickerModal({
<AttachmentThumbnail file={file} />
</div>
<div className="p-2">
<p className="text-xs font-medium truncate">{file.name}</p>
<p className="text-xs font-medium truncate" title={file.name}>{file.name}</p>
{showAllFolders && file.folderName && (
<p className="text-[11px] text-muted-foreground truncate">{file.folderName}</p>
)}
</div>
{isSelected && (
<div className="absolute top-1 right-1 bg-primary text-primary-foreground rounded-full p-0.5">
+4
View File
@@ -30,6 +30,7 @@ import ClaimsRecentTable, {
} from "@/components/claims/claims-recent-table";
import { QK_APPOINTMENTS_BASE } from "@/pages/appointments-page";
import ClaimsOfPatientModal from "@/components/claims/claims-of-patient-table";
import { PreauthCheckHost } from "@/components/claims/check-preauth-button";
import {
Claim,
UpdatePatient,
@@ -1372,6 +1373,9 @@ export default function ClaimsPage() {
{/* Recent Claims by Patients also handles new claims */}
<ClaimsOfPatientModal onNewClaim={handleNewClaim} />
{/* Check PreAuth OTP popup; here so it outlives the Claim/Preauth Details window */}
<PreauthCheckHost />
{/* Recent Claims Section */}
<Card>
<CardHeader>
@@ -193,6 +193,7 @@ export default function DocumentsPage() {
const preferredOrder = [
"INSURANCE_CLAIM",
"INSURANCE_CLAIM_PREAUTH",
"PREAUTH_APPROVAL",
"ELIGIBILITY_STATUS",
"CLAIM_STATUS",
"OTHER",
+91
View File
@@ -13,6 +13,10 @@ from selenium_preAuthWorker import AutomationMassHealthPreAuth
from selenium_MHSinglePaymentCheckWorker import AutomationMassHealthSinglePaymentCheck
from selenium_MHBatchPaymentCheckWorker import AutomationMassHealthBatchPaymentCheck
from selenium_Altus_eligibilityCheckWorker import AutomationAltusEligibilityCheck
from selenium_MH_preAuthCheckWorker import AutomationMassHealthPreAuthCheck
from selenium_UnitedSCO_preAuthCheckWorker import AutomationUnitedSCOPreAuthCheck
from selenium_TuftsSCO_preAuthCheckWorker import AutomationTuftsSCOPreAuthCheck
from selenium_CCA_preAuthCheckWorker import AutomationCCAPreAuthCheck
import os
import time
import helpers_ddma_eligibility as hddma
@@ -1253,6 +1257,93 @@ async def cca_preauth(request: Request):
return {"status": "started", "session_id": sid}
# ── Check PreAuth (MH, United SCO, Tufts SCO, CCA) ──────────────────────────
# Same flow as each insurer's eligibility check, run with its own preauth-check worker.
# United SCO / Tufts SCO / CCA share the eligibility session stores, so /session/{sid}/status
# and /submit-otp already cover them.
@app.post("/mh-preauth-check")
async def mh_preauth_check(request: Request):
global active_jobs, waiting_jobs
data = await request.json()
async with lock:
waiting_jobs += 1
async with semaphore:
async with lock:
waiting_jobs -= 1
active_jobs += 1
try:
bot = AutomationMassHealthPreAuthCheck(data)
result = bot.main_workflow("https://provider.masshealth-dental.org/mh_provider_login")
if result.get("status") != "success":
return {"status": "error", "message": result.get("message")}
return result
except Exception as e:
return {"status": "error", "message": str(e)}
finally:
async with lock:
active_jobs -= 1
async def _preauth_check_wrapper(start_run, sid: str, data: dict, url: str, worker_cls):
"""Background worker for a Check PreAuth session — acquires semaphore, updates counters."""
global active_jobs, waiting_jobs
async with semaphore:
async with lock:
waiting_jobs -= 1
active_jobs += 1
try:
await start_run(sid, data, url, worker_cls=worker_cls)
finally:
async with lock:
active_jobs -= 1
async def _start_preauth_check(request: Request, helper, start_run, session_type: str, url: str, worker_cls):
global waiting_jobs
body = await request.json()
data = body.get("data", {})
sid = helper.make_session_entry()
helper.sessions[sid]["type"] = session_type
helper.sessions[sid]["last_activity"] = time.time()
async with lock:
waiting_jobs += 1
asyncio.create_task(_preauth_check_wrapper(start_run, sid, data, url, worker_cls))
return {"status": "started", "session_id": sid}
@app.post("/unitedsco-preauth-check")
async def unitedsco_preauth_check(request: Request):
return await _start_preauth_check(
request, hunitedsco, hunitedsco.start_unitedsco_run, "unitedsco_preauth_check",
"https://app.dentalhub.com/app/login", AutomationUnitedSCOPreAuthCheck,
)
@app.post("/tuftssco-preauth-check")
async def tuftssco_preauth_check(request: Request):
return await _start_preauth_check(
request, hdentaquest, hdentaquest.start_dentaquest_run, "tuftssco_preauth_check",
"https://providers.dentaquest.com/", AutomationTuftsSCOPreAuthCheck,
)
@app.post("/cca-preauth-check")
async def cca_preauth_check(request: Request):
return await _start_preauth_check(
request, hcca, hcca.start_cca_run, "cca_preauth_check",
"https://pwp.sciondental.com/PWP/Landing", AutomationCCAPreAuthCheck,
)
@app.post("/submit-otp")
async def submit_otp(request: Request):
"""
@@ -71,7 +71,7 @@ def _close_browser(bot):
print(f"[CCA] Could not close browser: {e}")
async def start_cca_run(sid: str, data: dict, url: str):
async def start_cca_run(sid: str, data: dict, url: str, worker_cls=None):
"""
Run the CCA eligibility check workflow (no OTP):
1. Login
@@ -87,7 +87,8 @@ async def start_cca_run(sid: str, data: dict, url: str):
bot = None
try:
bot = AutomationCCAEligibilityCheck({"data": data})
# worker_cls lets Check PreAuth reuse this flow with its own worker
bot = (worker_cls or AutomationCCAEligibilityCheck)({"data": data})
bot.config_driver()
s["bot"] = bot
@@ -66,7 +66,7 @@ async def _remove_session_later(sid: str, delay: int = 30):
sessions.pop(sid, None)
async def start_dentaquest_run(sid: str, data: dict, url: str):
async def start_dentaquest_run(sid: str, data: dict, url: str, worker_cls=None):
"""
Run the DentaQuest workflow for a session (WITHOUT managing semaphore/counters).
Called by agent.py inside a wrapper that handles queue/counters.
@@ -79,7 +79,8 @@ async def start_dentaquest_run(sid: str, data: dict, url: str):
s["last_activity"] = time.time()
try:
bot = AutomationDentaQuestEligibilityCheck({"data": data})
# worker_cls lets Check PreAuth reuse this flow with its own worker
bot = (worker_cls or AutomationDentaQuestEligibilityCheck)({"data": data})
bot.config_driver()
s["bot"] = bot
@@ -99,7 +99,7 @@ def _minimize_browser(bot):
print(f"[UnitedSCO] Could not hide browser: {e}")
async def start_unitedsco_run(sid: str, data: dict, url: str):
async def start_unitedsco_run(sid: str, data: dict, url: str, worker_cls=None):
"""
Run the United SCO workflow for a session (WITHOUT managing semaphore/counters).
Called by agent.py inside a wrapper that handles queue/counters.
@@ -112,7 +112,8 @@ async def start_unitedsco_run(sid: str, data: dict, url: str):
s["last_activity"] = time.time()
try:
bot = AutomationUnitedSCOEligibilityCheck({"data": data})
# worker_cls lets Check PreAuth reuse this flow with its own worker
bot = (worker_cls or AutomationUnitedSCOEligibilityCheck)({"data": data})
bot.config_driver()
s["bot"] = bot
@@ -0,0 +1,11 @@
from selenium_CCA_eligibilityCheckWorker import AutomationCCAEligibilityCheck
class AutomationCCAPreAuthCheck(AutomationCCAEligibilityCheck):
"""
CCA (ScionDental) Check PreAuth.
Starts with the same steps as the eligibility check: login, step1, step2.
Reuses the eligibility check's persistent browser session (same Chrome profile and cookies).
Override a step here when the preauth check needs to do something different.
"""
@@ -0,0 +1,11 @@
from selenium_eligibilityCheckWorker import AutomationMassHealthEligibilityCheck
class AutomationMassHealthPreAuthCheck(AutomationMassHealthEligibilityCheck):
"""
MassHealth Check PreAuth.
Starts with the same steps as the eligibility check: login, step1, step2.
Fresh login every run (MassHealth keeps no persistent session).
Override a step here when the preauth check needs to do something different.
"""
@@ -0,0 +1,147 @@
from selenium.common.exceptions import TimeoutException
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import base64
import os
import time
from selenium_DentaQuest_eligibilityCheckWorker import AutomationDentaQuestEligibilityCheck
SUBMITTED_URL = "https://providers.dentaquest.com/pre-auth-claims/submitted/"
class AutomationTuftsSCOPreAuthCheck(AutomationDentaQuestEligibilityCheck):
"""
Tufts SCO (DentaQuest) Check PreAuth.
login: same as the eligibility check (persistent browser session, OTP if asked).
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).
"""
def __init__(self, data):
super().__init__(data)
self.preAuthNumber = str(self.data.get("preAuthNumber") or "").strip()
self.claimNumber = str(self.data.get("claimNumber") or "").strip()
def step1(self):
number = self.preAuthNumber or self.claimNumber
if not number:
return "ERROR: This record has no pre-auth or claim number to search for."
wait = WebDriverWait(self.driver, 30)
try:
print(f"[TuftsSCO PreAuthCheck step1] Opening {SUBMITTED_URL}")
self.driver.get(SUBMITTED_URL)
if self._is_maintenance_page():
return "ERROR: DentaQuest server is temporarily unavailable (maintenance). Please try again later."
# Clear "Set date range" (defaults to the last 2 weeks) so older preauths are found
try:
clear_btn = WebDriverWait(self.driver, 15).until(EC.element_to_be_clickable(
(By.XPATH, "//button[@aria-label='Clear date range']")
))
clear_btn.click()
print("[TuftsSCO PreAuthCheck step1] Cleared date range")
time.sleep(0.5)
except TimeoutException:
print("[TuftsSCO PreAuthCheck step1] No date range to clear")
number_input = wait.until(EC.element_to_be_clickable(
(By.XPATH, "//input[@data-testid='claims-search_claim-number_input']")
))
number_input.click()
number_input.send_keys(Keys.CONTROL, "a")
number_input.send_keys(Keys.DELETE)
number_input.send_keys(number)
print(f"[TuftsSCO PreAuthCheck step1] Entered number: {number}")
search_btn = wait.until(EC.element_to_be_clickable(
(By.XPATH, "//button[@data-testid='claims-search_submit-btn']")
))
search_btn.click()
print("[TuftsSCO PreAuthCheck step1] Clicked Search")
return "SUCCESS"
except TimeoutException:
return "ERROR: Pre-auth/claim search form not found on the Submitted page."
except Exception as e:
return f"ERROR: Pre-auth search failed: {e}"
def step2(self):
number = self.preAuthNumber or self.claimNumber
try:
# 1) Wait for the result row and click the pre-auth number in its first column
try:
id_link = WebDriverWait(self.driver, 30).until(EC.element_to_be_clickable(
(By.XPATH, f"//tbody//tr[1]/*[1]//*[self::a or self::button][contains(normalize-space(.), '{number}')]")
))
except TimeoutException:
body = self.driver.find_element(By.TAG_NAME, "body").text
if "0 records found" in body or "no records" in body.lower() or "no results" in body.lower():
return {"status": "error", "message": f"Tufts SCO found no pre-auth/claim #{number}."}
return {"status": "error", "message": f"Search result for #{number} did not load."}
# Status column of the result row (e.g. "Approved"), read before leaving the page
status = ""
try:
headers = [h.text.strip().lower() for h in self.driver.find_elements(By.XPATH, "//thead//th")]
cells = self.driver.find_elements(By.XPATH, "//tbody//tr[1]/td")
if "status" in headers and headers.index("status") < len(cells):
status = cells[headers.index("status")].text.strip()
except Exception:
pass
print(f"[TuftsSCO PreAuthCheck step2] Status: {status!r}")
id_link.click()
print(f"[TuftsSCO PreAuthCheck step2] Opened #{number}")
# 2) Wait for the detail page ("Pre-authorization <number> for <name>")
try:
WebDriverWait(self.driver, 30).until(EC.presence_of_element_located(
(By.XPATH, f"//h1[contains(., '{number}')] | //*[self::h1 or self::h2][contains(., 'for ')][contains(., '{number}')]")
))
WebDriverWait(self.driver, 30).until(EC.presence_of_element_located(
(By.XPATH, "//*[contains(normalize-space(.), 'Procedure information')]")
))
except TimeoutException:
return {"status": "error", "message": f"Detail page for #{number} did not load."}
time.sleep(2) # let the procedure table finish rendering
# 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", {
"printBackground": True,
"paperWidth": 8.5,
"paperHeight": 11,
"marginTop": 0.4,
"marginBottom": 0.4,
"marginLeft": 0.4,
"marginRight": 0.4,
})
pdf_path = os.path.join(
self.download_dir, f"tuftssco_preauth_approval_{number}_{int(time.time())}.pdf"
)
with open(pdf_path, "wb") as f:
f.write(base64.b64decode(pdf.get("data", "")))
print(f"[TuftsSCO PreAuthCheck step2] PDF saved: {pdf_path}")
# Leave the browser idle so the session stays logged in for the next run
try:
self.driver.get("about:blank")
self.driver.minimize_window()
except Exception:
pass
return {
"status": "success",
"message": f"Tufts SCO pre-auth #{number}" + (f": {status}." if status else "."),
"preAuthNumber": number,
"preAuthStatus": status,
"approval_pdf_path": pdf_path,
}
except Exception as e:
return {"status": "error", "message": f"Tufts SCO pre-auth check failed: {e}"}
@@ -0,0 +1,11 @@
from selenium_UnitedSCO_eligibilityCheckWorker import AutomationUnitedSCOEligibilityCheck
class AutomationUnitedSCOPreAuthCheck(AutomationUnitedSCOEligibilityCheck):
"""
United SCO (DentalHub) Check PreAuth.
Starts with the same steps as the eligibility check: login, step1, step2.
Reuses the eligibility check's persistent browser session (same Chrome profile and cookies).
Override a step here when the preauth check needs to do something different.
"""