feat: Tufts SCO claim automation, Claim All button, fee schedule updates
- Add full Tufts SCO claim Selenium worker (steps 1-8): login with OTP support, member search, Create Claim, fill form, attach files, submit, extract claim number and save confirmation PDF - Fix DentaQuest browser manager to preserve device trust token on startup (only clear cookies, not LocalStorage/IndexedDB) so OTP is only needed once for both eligibility and Tufts claim - Fix Tufts SCO claim route credential lookup key (TUFTS_SCO not TuftsSCO) - Add Tufts SCO and United/DentalHub entries to fee schedule update route - Add "Claim All" button that auto-routes to the correct claim handler based on the Insurance Type dropdown value - Add fee schedule JSON files for DDMA, Tufts SCO, and United/DentalHub Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
145
apps/Backend/src/queue/processors/tuftsSCOClaimProcessor.ts
Normal file
145
apps/Backend/src/queue/processors/tuftsSCOClaimProcessor.ts
Normal file
@@ -0,0 +1,145 @@
|
||||
/**
|
||||
* Processor for "tuftssco-claim-submit" jobs.
|
||||
* Opens a claim on the Tufts SCO (DentaQuest) provider portal via Selenium.
|
||||
*
|
||||
* Flow:
|
||||
* 1. POST /tuftssco-claim to Python agent → get session_id
|
||||
* 2. Emit selenium:tuftssco_claim_started to frontend
|
||||
* 3. Poll until completed/error
|
||||
* 4. Emit result
|
||||
*/
|
||||
import {
|
||||
forwardToSeleniumTuftsSCOClaimAgent,
|
||||
getSeleniumTuftsSCOClaimSessionStatus,
|
||||
} from "../../services/seleniumTuftsSCOClaimClient";
|
||||
import { io } from "../../socket";
|
||||
import { storage } from "../../storage";
|
||||
|
||||
function log(tag: string, msg: string, ctx?: any) {
|
||||
console.log(`${new Date().toISOString()} [${tag}] ${msg}`, ctx ?? "");
|
||||
}
|
||||
|
||||
function emitToSocket(socketId: string | undefined, event: string, payload: any) {
|
||||
if (!socketId || !io) return;
|
||||
try {
|
||||
const socket = io.sockets.sockets.get(socketId);
|
||||
if (socket) socket.emit(event, payload);
|
||||
} catch (_) {}
|
||||
}
|
||||
|
||||
async function pollUntilDone(
|
||||
sessionId: string,
|
||||
socketId: string | undefined,
|
||||
jobId: string,
|
||||
pollTimeoutMs = 10 * 60 * 1000
|
||||
): Promise<any> {
|
||||
const maxAttempts = 1200;
|
||||
const pollIntervalMs = 500;
|
||||
const maxTransientErrors = 12;
|
||||
let transientErrors = 0;
|
||||
let lastOtpEmit = 0;
|
||||
const deadline = Date.now() + pollTimeoutMs;
|
||||
|
||||
for (let attempt = 0; attempt < maxAttempts; attempt++) {
|
||||
if (Date.now() > deadline) {
|
||||
throw new Error(`Tufts SCO claim polling timeout for session ${sessionId}`);
|
||||
}
|
||||
try {
|
||||
const st = await getSeleniumTuftsSCOClaimSessionStatus(sessionId);
|
||||
const status: string = st?.status ?? "unknown";
|
||||
log("tuftssco-claim-processor", `poll attempt=${attempt}`, { sessionId, status });
|
||||
transientErrors = 0;
|
||||
|
||||
if (status === "waiting_for_otp") {
|
||||
if (Date.now() - lastOtpEmit > 5000) {
|
||||
emitToSocket(socketId, "selenium:otp_required", {
|
||||
session_id: sessionId,
|
||||
jobId,
|
||||
message: "OTP required. Please enter the OTP shown by the Tufts SCO portal.",
|
||||
});
|
||||
lastOtpEmit = Date.now();
|
||||
}
|
||||
await new Promise((r) => setTimeout(r, pollIntervalMs));
|
||||
continue;
|
||||
}
|
||||
|
||||
if (status === "completed") return st.result;
|
||||
if (status === "error" || status === "not_found") {
|
||||
throw new Error(st?.message || `Tufts SCO claim session ended with status: ${status}`);
|
||||
}
|
||||
await new Promise((r) => setTimeout(r, pollIntervalMs));
|
||||
} catch (err: any) {
|
||||
const isTerminal =
|
||||
err?.response?.status === 404 ||
|
||||
(typeof err?.message === "string" &&
|
||||
(err.message.includes("not_found") || err.message.includes("polling timeout")));
|
||||
if (isTerminal) throw err;
|
||||
transientErrors++;
|
||||
if (transientErrors > maxTransientErrors) {
|
||||
throw new Error(`Too many transient errors polling Tufts SCO claim session ${sessionId}`);
|
||||
}
|
||||
const backoff = Math.min(30_000, 500 * Math.pow(2, transientErrors - 1));
|
||||
await new Promise((r) => setTimeout(r, backoff));
|
||||
}
|
||||
}
|
||||
throw new Error(`Tufts SCO claim polling exhausted all attempts for session ${sessionId}`);
|
||||
}
|
||||
|
||||
export interface TuftsSCOClaimProcessorInput {
|
||||
enrichedPayload: any;
|
||||
userId: number;
|
||||
claimId?: number;
|
||||
socketId?: string;
|
||||
}
|
||||
|
||||
export async function runTuftsSCOClaimProcessor(
|
||||
input: TuftsSCOClaimProcessorInput,
|
||||
jobId: string
|
||||
): Promise<{ status: string; pdf_url?: string; claimNumber?: string }> {
|
||||
const { enrichedPayload, userId, claimId, socketId } = input;
|
||||
|
||||
log("tuftssco-claim-processor", "starting Python agent session", { claimId });
|
||||
const agentResp = await forwardToSeleniumTuftsSCOClaimAgent(enrichedPayload);
|
||||
|
||||
if (!agentResp?.session_id) {
|
||||
throw new Error("Python agent did not return a session_id for Tufts SCO claim");
|
||||
}
|
||||
|
||||
const sessionId = agentResp.session_id as string;
|
||||
log("tuftssco-claim-processor", "got session_id", { sessionId });
|
||||
|
||||
emitToSocket(socketId, "selenium:tuftssco_claim_started", { session_id: sessionId, jobId });
|
||||
|
||||
const seleniumResult = await pollUntilDone(sessionId, socketId, jobId);
|
||||
|
||||
if (!seleniumResult || seleniumResult.status === "error") {
|
||||
throw new Error(seleniumResult?.message ?? "Tufts SCO claim session returned an error");
|
||||
}
|
||||
|
||||
const claimNumber: string | undefined = seleniumResult.claimNumber ?? undefined;
|
||||
const pdf_url: string | undefined = seleniumResult.pdf_url ?? undefined;
|
||||
|
||||
if (claimId) {
|
||||
try {
|
||||
const updates: Record<string, any> = { status: "REVIEW" };
|
||||
if (claimNumber) updates.claimNumber = claimNumber;
|
||||
await storage.updateClaim(claimId, updates);
|
||||
log("tuftssco-claim-processor", "claim record updated", { claimId, claimNumber });
|
||||
} catch (e) {
|
||||
log("tuftssco-claim-processor", "failed to update claim record (non-fatal)", { error: e });
|
||||
}
|
||||
}
|
||||
|
||||
emitToSocket(socketId, "selenium:tuftssco_claim_completed", {
|
||||
jobId,
|
||||
claimId,
|
||||
claimNumber,
|
||||
pdf_url,
|
||||
message: claimNumber
|
||||
? `Tufts SCO claim submitted — Claim #: ${claimNumber}`
|
||||
: (seleniumResult?.message ?? "Tufts SCO claim submitted successfully"),
|
||||
});
|
||||
|
||||
log("tuftssco-claim-processor", "done", { claimId, claimNumber });
|
||||
return { status: "success", pdf_url, claimNumber };
|
||||
}
|
||||
@@ -9,6 +9,10 @@ const SCHEDULE_FILES: Record<string, string> = {
|
||||
MASSHEALTH: "procedureCodesMH.json",
|
||||
CCA: "procedureCodesCCA.json",
|
||||
DDMA: "procedureCodesDDMA.json",
|
||||
TUFTSSCO: "procedureCodesTuftsSCO.json",
|
||||
TUFTS_SCO: "procedureCodesTuftsSCO.json",
|
||||
UNITEDDH: "procedureCodesUnitedDH.json",
|
||||
UNITED_SCO: "procedureCodesUnitedDH.json",
|
||||
};
|
||||
|
||||
function getSchedulePath(siteKey: string): string | null {
|
||||
|
||||
94
apps/Backend/src/routes/insuranceStatusTuftsSCOClaim.ts
Normal file
94
apps/Backend/src/routes/insuranceStatusTuftsSCOClaim.ts
Normal file
@@ -0,0 +1,94 @@
|
||||
import { Router, Request, Response } from "express";
|
||||
import { storage } from "../storage";
|
||||
import { enqueueSeleniumJob } from "../queue/jobRunner";
|
||||
import { forwardOtpToSeleniumTuftsSCOClaimAgent } from "../services/seleniumTuftsSCOClaimClient";
|
||||
import { io } from "../socket";
|
||||
|
||||
const router = Router();
|
||||
|
||||
/**
|
||||
* POST /tuftssco-claim
|
||||
*
|
||||
* Enqueues a Tufts SCO (DentaQuest) claim submission job.
|
||||
*
|
||||
* Body fields (JSON):
|
||||
* data — claim payload (memberId, dateOfBirth, serviceDate, serviceLines, patientName, etc.)
|
||||
* socketId — socket.io client id
|
||||
* claimId — existing claim DB id (optional)
|
||||
*
|
||||
* Response: { status: "queued", jobId: "…" }
|
||||
*/
|
||||
router.post("/tuftssco-claim", async (req: Request, res: Response): Promise<any> => {
|
||||
if (!req.user?.id) {
|
||||
return res.status(401).json({ error: "Unauthorized: user info missing" });
|
||||
}
|
||||
|
||||
try {
|
||||
const claimData =
|
||||
typeof req.body.data === "string"
|
||||
? JSON.parse(req.body.data)
|
||||
: req.body.data ?? req.body ?? {};
|
||||
|
||||
// Fetch Tufts SCO (DentaQuest) credentials
|
||||
const credentials = await storage.getInsuranceCredentialByUserAndSiteKey(
|
||||
req.user.id,
|
||||
"TUFTS_SCO"
|
||||
);
|
||||
if (!credentials) {
|
||||
return res.status(404).json({
|
||||
error: "No Tufts SCO credentials found. Please add them on the Settings page.",
|
||||
});
|
||||
}
|
||||
|
||||
const enrichedPayload = {
|
||||
claim: {
|
||||
...claimData,
|
||||
dentaquestUsername: credentials.username,
|
||||
dentaquestPassword: credentials.password,
|
||||
},
|
||||
};
|
||||
|
||||
const socketId: string | undefined = req.body.socketId;
|
||||
const claimId: number | undefined = claimData.claimId
|
||||
? Number(claimData.claimId)
|
||||
: undefined;
|
||||
|
||||
const jobId = enqueueSeleniumJob({
|
||||
jobType: "tuftssco-claim-submit",
|
||||
userId: req.user.id,
|
||||
socketId,
|
||||
enrichedPayload,
|
||||
claimId,
|
||||
});
|
||||
|
||||
return res.json({ status: "queued", jobId });
|
||||
} catch (err: any) {
|
||||
console.error("[tuftssco-claim route] error:", err);
|
||||
return res.status(500).json({
|
||||
error: err.message || "Failed to enqueue Tufts SCO claim job",
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
/**
|
||||
* POST /claims/tuftssco-claim/selenium/submit-otp
|
||||
* Body: { session_id, otp, socketId? }
|
||||
*/
|
||||
router.post("/tuftssco-claim/selenium/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 forwardOtpToSeleniumTuftsSCOClaimAgent(sessionId, otp);
|
||||
if (socketId && io) {
|
||||
io.to(socketId).emit("selenium:otp_submitted", { session_id: sessionId });
|
||||
}
|
||||
return res.json(r);
|
||||
} catch (err: any) {
|
||||
console.error("[tuftssco-claim] submit-otp failed:", err?.message);
|
||||
return res.status(500).json({ error: err?.message || "Failed to forward OTP" });
|
||||
}
|
||||
});
|
||||
|
||||
export default router;
|
||||
35
apps/Backend/src/services/seleniumTuftsSCOClaimClient.ts
Normal file
35
apps/Backend/src/services/seleniumTuftsSCOClaimClient.ts
Normal file
@@ -0,0 +1,35 @@
|
||||
import axios from "axios";
|
||||
|
||||
const SELENIUM_BASE = process.env.SELENIUM_SERVICE_URL ?? "http://localhost:5002";
|
||||
|
||||
/**
|
||||
* POST /tuftssco-claim
|
||||
* Returns { status: "started", session_id: "<uuid>" }
|
||||
*/
|
||||
export async function forwardToSeleniumTuftsSCOClaimAgent(
|
||||
data: Record<string, any>
|
||||
): Promise<{ status: string; session_id: string }> {
|
||||
const resp = await axios.post(`${SELENIUM_BASE}/tuftssco-claim`, data);
|
||||
return resp.data;
|
||||
}
|
||||
|
||||
/**
|
||||
* GET /session/{sid}/status
|
||||
*/
|
||||
export async function getSeleniumTuftsSCOClaimSessionStatus(
|
||||
sessionId: string
|
||||
): Promise<Record<string, any>> {
|
||||
const resp = await axios.get(`${SELENIUM_BASE}/session/${sessionId}/status`);
|
||||
return resp.data;
|
||||
}
|
||||
|
||||
/**
|
||||
* POST /submit-otp
|
||||
*/
|
||||
export async function forwardOtpToSeleniumTuftsSCOClaimAgent(
|
||||
sessionId: string,
|
||||
otp: string
|
||||
): Promise<Record<string, any>> {
|
||||
const resp = await axios.post(`${SELENIUM_BASE}/submit-otp`, { session_id: sessionId, otp });
|
||||
return resp.data;
|
||||
}
|
||||
Reference in New Issue
Block a user