feat: DDMA claim submission with OTP, PDF, claim number extraction
- Add full DDMA claim Selenium flow (steps 1-8): search patient, open member page, create claim, fill form, attach files, next, submit, extract claim number and save confirmation PDF - Add fee schedule price-mismatch dialog for all claim buttons (MH, CCA, DDMA, United, Tufts, Save) with optional price update to JSON - Add OTP modal for DDMA claim when session expires, mirroring eligibility OTP flow - Close Chrome after claim submission via quit_driver() (session preserved in profile) - Move Map Price button between Direct Submission and procedure table, right-aligned above Billed Amount column - Add fee-schedule update-price backend route - Add DDMA claim processor with claimNumber/pdf_url result handling Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
@@ -17,6 +17,8 @@ import { runUnitedSCOEligibilityProcessor } from "./processors/unitedSCOEligibil
|
||||
import { runDentaQuestEligibilityProcessor } from "./processors/dentaQuestEligibilityProcessor";
|
||||
import { runCCAEligibilityProcessor } from "./processors/ccaEligibilityProcessor";
|
||||
import { runCCAClaimProcessor } from "./processors/ccaClaimProcessor";
|
||||
import { runCCAPreAuthProcessor } from "./processors/ccaPreAuthProcessor";
|
||||
import { runDDMAClaimProcessor } from "./processors/ddmaClaimProcessor";
|
||||
import { runEligibilityHistoryProcessor } from "./processors/eligibilityHistoryProcessor";
|
||||
import { runCmspEligibilityHistoryRemainingProcessor } from "./processors/cmspEligibilityHistoryRemainingProcessor";
|
||||
import type { SeleniumJobData, OcrJobData } from "./queues";
|
||||
@@ -144,6 +146,28 @@ export function enqueueSeleniumJob(data: SeleniumJobData): string {
|
||||
job.id
|
||||
);
|
||||
}
|
||||
if (jobType === "cca-preauth-submit") {
|
||||
return runCCAPreAuthProcessor(
|
||||
{
|
||||
enrichedPayload: data.enrichedPayload,
|
||||
userId: data.userId,
|
||||
claimId: data.claimId,
|
||||
socketId: data.socketId,
|
||||
},
|
||||
job.id
|
||||
);
|
||||
}
|
||||
if (jobType === "ddma-claim-submit") {
|
||||
return runDDMAClaimProcessor(
|
||||
{
|
||||
enrichedPayload: data.enrichedPayload,
|
||||
userId: data.userId,
|
||||
claimId: data.claimId,
|
||||
socketId: data.socketId,
|
||||
},
|
||||
job.id
|
||||
);
|
||||
}
|
||||
if (jobType === "cca-eligibility-check") {
|
||||
return runCCAEligibilityProcessor(
|
||||
{
|
||||
|
||||
147
apps/Backend/src/queue/processors/ddmaClaimProcessor.ts
Normal file
147
apps/Backend/src/queue/processors/ddmaClaimProcessor.ts
Normal file
@@ -0,0 +1,147 @@
|
||||
/**
|
||||
* Processor for "ddma-claim-submit" jobs.
|
||||
* Opens a claim on the Delta Dental MA provider portal via Selenium.
|
||||
*
|
||||
* Flow:
|
||||
* 1. POST /ddma-claim to Python agent → get session_id
|
||||
* 2. Emit selenium:ddma_claim_started to frontend
|
||||
* 3. Poll until completed/error
|
||||
* 4. Emit result
|
||||
*/
|
||||
import {
|
||||
forwardToSeleniumDDMAClaimAgent,
|
||||
getSeleniumDDMAClaimSessionStatus,
|
||||
} from "../../services/seleniumDDMAClaimClient";
|
||||
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(`DDMA claim polling timeout for session ${sessionId}`);
|
||||
}
|
||||
try {
|
||||
const st = await getSeleniumDDMAClaimSessionStatus(sessionId);
|
||||
const status: string = st?.status ?? "unknown";
|
||||
log("ddma-claim-processor", `poll attempt=${attempt}`, { sessionId, status });
|
||||
transientErrors = 0;
|
||||
|
||||
if (status === "waiting_for_otp") {
|
||||
// Throttle: emit at most once every 5 s so the frontend isn't flooded
|
||||
if (Date.now() - lastOtpEmit > 5000) {
|
||||
emitToSocket(socketId, "selenium:otp_required", {
|
||||
session_id: sessionId,
|
||||
jobId,
|
||||
message: "OTP required. Please enter the OTP shown by the DDMA 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 || `DDMA 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 DDMA 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(`DDMA claim polling exhausted all attempts for session ${sessionId}`);
|
||||
}
|
||||
|
||||
export interface DDMAClaimProcessorInput {
|
||||
enrichedPayload: any;
|
||||
userId: number;
|
||||
claimId?: number;
|
||||
socketId?: string;
|
||||
}
|
||||
|
||||
export async function runDDMAClaimProcessor(
|
||||
input: DDMAClaimProcessorInput,
|
||||
jobId: string
|
||||
): Promise<{ status: string; pdf_url?: string; claimNumber?: string }> {
|
||||
const { enrichedPayload, userId, claimId, socketId } = input;
|
||||
|
||||
log("ddma-claim-processor", "starting Python agent session", { claimId });
|
||||
const agentResp = await forwardToSeleniumDDMAClaimAgent(enrichedPayload);
|
||||
|
||||
if (!agentResp?.session_id) {
|
||||
throw new Error("Python agent did not return a session_id for DDMA claim");
|
||||
}
|
||||
|
||||
const sessionId = agentResp.session_id as string;
|
||||
log("ddma-claim-processor", "got session_id", { sessionId });
|
||||
|
||||
emitToSocket(socketId, "selenium:ddma_claim_started", { session_id: sessionId, jobId });
|
||||
|
||||
const seleniumResult = await pollUntilDone(sessionId, socketId, jobId);
|
||||
|
||||
if (!seleniumResult || seleniumResult.status === "error") {
|
||||
throw new Error(seleniumResult?.message ?? "DDMA claim session returned an error");
|
||||
}
|
||||
|
||||
const claimNumber: string | undefined = seleniumResult.claimNumber ?? undefined;
|
||||
const pdf_url: string | undefined = seleniumResult.pdf_url ?? undefined;
|
||||
|
||||
// Persist claim number and update status
|
||||
if (claimId) {
|
||||
try {
|
||||
const updates: Record<string, any> = { status: "REVIEW" };
|
||||
if (claimNumber) updates.claimNumber = claimNumber;
|
||||
await storage.updateClaim(claimId, updates);
|
||||
log("ddma-claim-processor", "claim record updated", { claimId, claimNumber });
|
||||
} catch (e) {
|
||||
log("ddma-claim-processor", "failed to update claim record (non-fatal)", { error: e });
|
||||
}
|
||||
}
|
||||
|
||||
emitToSocket(socketId, "selenium:ddma_claim_completed", {
|
||||
jobId,
|
||||
claimId,
|
||||
claimNumber,
|
||||
pdf_url,
|
||||
message: claimNumber
|
||||
? `DDMA claim submitted — Claim #: ${claimNumber}`
|
||||
: (seleniumResult?.message ?? "DDMA claim submitted successfully"),
|
||||
});
|
||||
|
||||
log("ddma-claim-processor", "done", { claimId, claimNumber });
|
||||
return { status: "success", pdf_url, claimNumber };
|
||||
}
|
||||
@@ -12,6 +12,8 @@ export type SeleniumJobType =
|
||||
| "unitedsco-eligibility-check"
|
||||
| "cca-eligibility-check"
|
||||
| "cca-claim-submit"
|
||||
| "cca-preauth-submit"
|
||||
| "ddma-claim-submit"
|
||||
| "tuftssco-eligibility-check"
|
||||
| "mh-eligibility-history-check"
|
||||
| "cmsp-eligibility-history-remaining-check";
|
||||
|
||||
69
apps/Backend/src/routes/feeSchedule.ts
Normal file
69
apps/Backend/src/routes/feeSchedule.ts
Normal file
@@ -0,0 +1,69 @@
|
||||
import { Router, Request, Response } from "express";
|
||||
import path from "path";
|
||||
import fs from "fs";
|
||||
|
||||
const router = Router();
|
||||
|
||||
const SCHEDULE_FILES: Record<string, string> = {
|
||||
MH: "procedureCodesMH.json",
|
||||
MASSHEALTH: "procedureCodesMH.json",
|
||||
CCA: "procedureCodesCCA.json",
|
||||
DDMA: "procedureCodesDDMA.json",
|
||||
};
|
||||
|
||||
function getSchedulePath(siteKey: string): string | null {
|
||||
const filename = SCHEDULE_FILES[siteKey.toUpperCase()];
|
||||
if (!filename) return null;
|
||||
return path.join(process.cwd(), "..", "Frontend", "src", "assets", "data", filename);
|
||||
}
|
||||
|
||||
/**
|
||||
* POST /api/fee-schedule/update-price
|
||||
* Body: { siteKey, procedureCode, price }
|
||||
* Updates the matching row's Price field in the fee schedule JSON.
|
||||
*/
|
||||
router.post("/update-price", async (req: Request, res: Response): Promise<any> => {
|
||||
if (!req.user?.id) return res.status(401).json({ error: "Unauthorized" });
|
||||
|
||||
const { siteKey, procedureCode, price } = req.body;
|
||||
if (!siteKey || !procedureCode || price == null) {
|
||||
return res.status(400).json({ error: "siteKey, procedureCode and price are required" });
|
||||
}
|
||||
|
||||
const filePath = getSchedulePath(siteKey);
|
||||
if (!filePath) {
|
||||
return res.status(400).json({ error: `No fee schedule for siteKey: ${siteKey}` });
|
||||
}
|
||||
|
||||
try {
|
||||
const raw = fs.readFileSync(filePath, "utf-8");
|
||||
const rows: any[] = JSON.parse(raw);
|
||||
const normalizedCode = String(procedureCode).trim().toUpperCase();
|
||||
let updated = false;
|
||||
|
||||
for (const row of rows) {
|
||||
const rowCode = String(row["Procedure Code"] || "").trim().toUpperCase();
|
||||
if (rowCode === normalizedCode) {
|
||||
// Update whichever price field(s) exist in this row
|
||||
if ("Price" in row) row["Price"] = price;
|
||||
if ("PriceLTEQ21" in row) row["PriceLTEQ21"] = price;
|
||||
if ("PriceGT21" in row) row["PriceGT21"] = price;
|
||||
updated = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (!updated) {
|
||||
return res.status(404).json({ error: `Procedure code ${procedureCode} not found in ${siteKey} schedule` });
|
||||
}
|
||||
|
||||
fs.writeFileSync(filePath, JSON.stringify(rows, null, 2), "utf-8");
|
||||
console.log(`[feeSchedule] Updated ${siteKey} ${procedureCode} → ${price}`);
|
||||
return res.json({ success: true });
|
||||
} catch (err: any) {
|
||||
console.error("[feeSchedule] Error:", err);
|
||||
return res.status(500).json({ error: err.message });
|
||||
}
|
||||
});
|
||||
|
||||
export default router;
|
||||
@@ -17,6 +17,8 @@ import insuranceStatusUnitedSCORoutes from "./insuranceStatusUnitedSCO";
|
||||
import insuranceStatusTuftsSCORoutes from "./insuranceStatusTuftsSCO";
|
||||
import insuranceStatusCCARoutes from "./insuranceStatusCCA";
|
||||
import insuranceStatusCCAClaimRoutes from "./insuranceStatusCCAClaim";
|
||||
import insuranceStatusCCAPreAuthRoutes from "./insuranceStatusCCAPreAuth";
|
||||
import insuranceStatusDDMAClaimRoutes from "./insuranceStatusDDMAClaim";
|
||||
import paymentsRoutes from "./payments";
|
||||
import databaseManagementRoutes from "./database-management";
|
||||
import notificationsRoutes from "./notifications";
|
||||
@@ -34,6 +36,7 @@ import procedureTimeslotRoutes from "./procedure-timeslot";
|
||||
import insuranceContactsRoutes from "./insurance-contacts";
|
||||
import commissionsRoutes from "./commissions";
|
||||
import shoppingVendorsRoutes from "./shopping-vendors";
|
||||
import feeScheduleRoutes from "./feeSchedule";
|
||||
|
||||
const router = Router();
|
||||
|
||||
@@ -55,6 +58,8 @@ router.use("/insurance-status-unitedsco", insuranceStatusUnitedSCORoutes);
|
||||
router.use("/insurance-status-tuftssco", insuranceStatusTuftsSCORoutes);
|
||||
router.use("/insurance-status-cca", insuranceStatusCCARoutes);
|
||||
router.use("/claims", insuranceStatusCCAClaimRoutes);
|
||||
router.use("/claims", insuranceStatusCCAPreAuthRoutes);
|
||||
router.use("/claims", insuranceStatusDDMAClaimRoutes);
|
||||
router.use("/payments", paymentsRoutes);
|
||||
router.use("/database-management", databaseManagementRoutes);
|
||||
router.use("/notifications", notificationsRoutes);
|
||||
@@ -72,5 +77,6 @@ router.use("/procedure-timeslot", procedureTimeslotRoutes);
|
||||
router.use("/insurance-contacts", insuranceContactsRoutes);
|
||||
router.use("/commissions", commissionsRoutes);
|
||||
router.use("/shopping-vendors", shoppingVendorsRoutes);
|
||||
router.use("/fee-schedule", feeScheduleRoutes);
|
||||
|
||||
export default router;
|
||||
|
||||
94
apps/Backend/src/routes/insuranceStatusDDMAClaim.ts
Normal file
94
apps/Backend/src/routes/insuranceStatusDDMAClaim.ts
Normal file
@@ -0,0 +1,94 @@
|
||||
import { Router, Request, Response } from "express";
|
||||
import { storage } from "../storage";
|
||||
import { enqueueSeleniumJob } from "../queue/jobRunner";
|
||||
import { forwardOtpToSeleniumDDMAClaimAgent } from "../services/seleniumDDMAClaimClient";
|
||||
import { io } from "../socket";
|
||||
|
||||
const router = Router();
|
||||
|
||||
/**
|
||||
* POST /ddma-claim
|
||||
*
|
||||
* Enqueues a Delta Dental MA 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("/ddma-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 DDMA credentials
|
||||
const credentials = await storage.getInsuranceCredentialByUserAndSiteKey(
|
||||
req.user.id,
|
||||
"DDMA"
|
||||
);
|
||||
if (!credentials) {
|
||||
return res.status(404).json({
|
||||
error: "No Delta Dental MA credentials found. Please add them on the Settings page.",
|
||||
});
|
||||
}
|
||||
|
||||
const enrichedPayload = {
|
||||
claim: {
|
||||
...claimData,
|
||||
massddmaUsername: credentials.username,
|
||||
massddmaPassword: credentials.password,
|
||||
},
|
||||
};
|
||||
|
||||
const socketId: string | undefined = req.body.socketId;
|
||||
const claimId: number | undefined = claimData.claimId
|
||||
? Number(claimData.claimId)
|
||||
: undefined;
|
||||
|
||||
const jobId = enqueueSeleniumJob({
|
||||
jobType: "ddma-claim-submit",
|
||||
userId: req.user.id,
|
||||
socketId,
|
||||
enrichedPayload,
|
||||
claimId,
|
||||
});
|
||||
|
||||
return res.json({ status: "queued", jobId });
|
||||
} catch (err: any) {
|
||||
console.error("[ddma-claim route] error:", err);
|
||||
return res.status(500).json({
|
||||
error: err.message || "Failed to enqueue DDMA claim job",
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
/**
|
||||
* POST /claims/ddma-claim/selenium/submit-otp
|
||||
* Body: { session_id, otp, socketId? }
|
||||
*/
|
||||
router.post("/ddma-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 forwardOtpToSeleniumDDMAClaimAgent(sessionId, otp);
|
||||
if (socketId && io) {
|
||||
io.to(socketId).emit("selenium:otp_submitted", { session_id: sessionId });
|
||||
}
|
||||
return res.json(r);
|
||||
} catch (err: any) {
|
||||
console.error("[ddma-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/seleniumDDMAClaimClient.ts
Normal file
35
apps/Backend/src/services/seleniumDDMAClaimClient.ts
Normal file
@@ -0,0 +1,35 @@
|
||||
import axios from "axios";
|
||||
|
||||
const SELENIUM_BASE = process.env.SELENIUM_SERVICE_URL ?? "http://localhost:5002";
|
||||
|
||||
/**
|
||||
* POST /ddma-claim
|
||||
* Returns { status: "started", session_id: "<uuid>" }
|
||||
*/
|
||||
export async function forwardToSeleniumDDMAClaimAgent(
|
||||
data: Record<string, any>
|
||||
): Promise<{ status: string; session_id: string }> {
|
||||
const resp = await axios.post(`${SELENIUM_BASE}/ddma-claim`, data);
|
||||
return resp.data;
|
||||
}
|
||||
|
||||
/**
|
||||
* GET /session/{sid}/status
|
||||
*/
|
||||
export async function getSeleniumDDMAClaimSessionStatus(
|
||||
sessionId: string
|
||||
): Promise<Record<string, any>> {
|
||||
const resp = await axios.get(`${SELENIUM_BASE}/session/${sessionId}/status`);
|
||||
return resp.data;
|
||||
}
|
||||
|
||||
/**
|
||||
* POST /session/{sid}/submit-otp
|
||||
*/
|
||||
export async function forwardOtpToSeleniumDDMAClaimAgent(
|
||||
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