feat: add Deltains claim submission flow
Adds a full "Deltains Claim" button next to Delta MA Claim, mirroring the DDMA claim flow across frontend, backend queue/routes, and a new Selenium worker. Reuses the existing Deltains eligibility login/OTP code and was iteratively wired against the live portal (patient roster search, per-service-line fields, tooth number/surface selects, review and submit). Also fixes chatbot/insurance-alias carrier recognition so "deltains" resolves correctly instead of falling back to MassHealth.
This commit is contained in:
@@ -12,6 +12,7 @@
|
||||
|
||||
{ "keyword": "delta dental ins", "siteKey": "DELTA_INS" },
|
||||
{ "keyword": "delta ins", "siteKey": "DELTA_INS" },
|
||||
{ "keyword": "deltains", "siteKey": "DELTA_INS" },
|
||||
{ "keyword": "delta dental", "siteKey": "DELTA_INS" },
|
||||
|
||||
{ "keyword": "tufts sco", "siteKey": "TUFTS_SCO" },
|
||||
|
||||
@@ -20,6 +20,7 @@ import { runCCAEligibilityProcessor } from "./processors/ccaEligibilityProcessor
|
||||
import { runCCAClaimProcessor } from "./processors/ccaClaimProcessor";
|
||||
import { runCCAPreAuthProcessor } from "./processors/ccaPreAuthProcessor";
|
||||
import { runDDMAClaimProcessor } from "./processors/ddmaClaimProcessor";
|
||||
import { runDeltainsClaimProcessor } from "./processors/deltainsClaimProcessor";
|
||||
import { runUnitedDHClaimProcessor } from "./processors/unitedDHClaimProcessor";
|
||||
import { runUnitedDHPreAuthProcessor } from "./processors/unitedDHPreAuthProcessor";
|
||||
import { runTuftsSCOPreAuthProcessor } from "./processors/tuftsSCOPreAuthProcessor";
|
||||
@@ -191,6 +192,17 @@ export function enqueueSeleniumJob(data: SeleniumJobData): string {
|
||||
job.id
|
||||
);
|
||||
}
|
||||
if (jobType === "deltains-claim-submit") {
|
||||
return runDeltainsClaimProcessor(
|
||||
{
|
||||
enrichedPayload: data.enrichedPayload,
|
||||
userId: data.userId,
|
||||
claimId: data.claimId,
|
||||
socketId: data.socketId,
|
||||
},
|
||||
job.id
|
||||
);
|
||||
}
|
||||
if (jobType === "uniteddh-claim-submit") {
|
||||
return runUnitedDHClaimProcessor(
|
||||
{
|
||||
|
||||
@@ -0,0 +1,185 @@
|
||||
/**
|
||||
* Processor for "deltains-claim-submit" jobs.
|
||||
* Opens a claim on the Delta Dental Ins provider portal via Selenium.
|
||||
*
|
||||
* Flow:
|
||||
* 1. POST /deltains-claim to Python agent → get session_id
|
||||
* 2. Emit selenium:deltains_claim_started to frontend
|
||||
* 3. Poll until completed/error
|
||||
* 4. Emit result
|
||||
*/
|
||||
import {
|
||||
forwardToSeleniumDeltainsClaimAgent,
|
||||
getSeleniumDeltainsClaimSessionStatus,
|
||||
} from "../../services/seleniumDeltainsClaimClient";
|
||||
import { io } from "../../socket";
|
||||
import { storage } from "../../storage";
|
||||
import axios from "axios";
|
||||
import path from "path";
|
||||
|
||||
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(`Deltains claim polling timeout for session ${sessionId}`);
|
||||
}
|
||||
try {
|
||||
const st = await getSeleniumDeltainsClaimSessionStatus(sessionId);
|
||||
const status: string = st?.status ?? "unknown";
|
||||
log("deltains-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 Deltains 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 || `Deltains 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 Deltains 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(`Deltains claim polling exhausted all attempts for session ${sessionId}`);
|
||||
}
|
||||
|
||||
async function savePdfFromSelenium(pdf_url: string, patientId: number, userId: number) {
|
||||
try {
|
||||
const filename = path.basename(new URL(pdf_url).pathname);
|
||||
const seleniumPort = process.env.SELENIUM_PORT || "5002";
|
||||
const localUrl = `http://localhost:${seleniumPort}/downloads/${filename}`;
|
||||
const resp = await axios.get(localUrl, { responseType: "arraybuffer", timeout: 30000 });
|
||||
const patient = await storage.getPatient(patientId);
|
||||
const patientName = patient ? `${patient.firstName} ${patient.lastName}` : `Patient ${patientId}`;
|
||||
await storage.savePdfToCloudStorage(
|
||||
userId,
|
||||
patientId,
|
||||
patientName,
|
||||
"Claims",
|
||||
filename,
|
||||
Buffer.from(resp.data)
|
||||
);
|
||||
log("deltains-claim-processor", "PDF saved", { patientId, filename });
|
||||
} catch (err: any) {
|
||||
log("deltains-claim-processor", "failed to save PDF (non-fatal)", { error: err?.message ?? err });
|
||||
}
|
||||
}
|
||||
|
||||
export interface DeltainsClaimProcessorInput {
|
||||
enrichedPayload: any;
|
||||
userId: number;
|
||||
claimId?: number;
|
||||
socketId?: string;
|
||||
}
|
||||
|
||||
export async function runDeltainsClaimProcessor(
|
||||
input: DeltainsClaimProcessorInput,
|
||||
jobId: string
|
||||
): Promise<{ status: string; pdf_url?: string; claimNumber?: string }> {
|
||||
const { enrichedPayload, userId, claimId, socketId } = input;
|
||||
|
||||
log("deltains-claim-processor", "starting Python agent session", { claimId });
|
||||
const agentResp = await forwardToSeleniumDeltainsClaimAgent(enrichedPayload);
|
||||
|
||||
if (!agentResp?.session_id) {
|
||||
throw new Error("Python agent did not return a session_id for Deltains claim");
|
||||
}
|
||||
|
||||
const sessionId = agentResp.session_id as string;
|
||||
log("deltains-claim-processor", "got session_id", { sessionId });
|
||||
|
||||
emitToSocket(socketId, "selenium:deltains_claim_started", { session_id: sessionId, jobId });
|
||||
|
||||
const seleniumResult = await pollUntilDone(sessionId, socketId, jobId);
|
||||
|
||||
if (!seleniumResult || seleniumResult.status === "error") {
|
||||
throw new Error(seleniumResult?.message ?? "Deltains 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("deltains-claim-processor", "claim record updated", { claimId, claimNumber });
|
||||
|
||||
// Touch patient so they rise to top of the list across all pages
|
||||
const claim = await storage.getClaim(claimId);
|
||||
if (claim?.patientId) {
|
||||
await storage.touchPatient(claim.patientId);
|
||||
log("deltains-claim-processor", "patient touched", { patientId: claim.patientId });
|
||||
}
|
||||
} catch (e) {
|
||||
log("deltains-claim-processor", "failed to update claim record (non-fatal)", { error: e });
|
||||
}
|
||||
}
|
||||
|
||||
// Auto-save PDF for batch-column calls (no socketId = no frontend listener)
|
||||
if (pdf_url && !socketId) {
|
||||
const claim = claimId ? await storage.getClaim(claimId).catch(() => null) : null;
|
||||
const patientId = claim?.patientId ?? enrichedPayload?.claim?.patientId ?? enrichedPayload?.patientId;
|
||||
if (patientId) await savePdfFromSelenium(pdf_url, Number(patientId), userId);
|
||||
}
|
||||
|
||||
emitToSocket(socketId, "selenium:deltains_claim_completed", {
|
||||
jobId,
|
||||
claimId,
|
||||
claimNumber,
|
||||
pdf_url,
|
||||
message: claimNumber
|
||||
? `Deltains claim submitted — Claim #: ${claimNumber}`
|
||||
: (seleniumResult?.message ?? "Deltains claim submitted successfully"),
|
||||
});
|
||||
|
||||
log("deltains-claim-processor", "done", { claimId, claimNumber });
|
||||
return { status: "success", pdf_url, claimNumber };
|
||||
}
|
||||
@@ -15,6 +15,7 @@ export type SeleniumJobType =
|
||||
| "cca-claim-submit"
|
||||
| "cca-preauth-submit"
|
||||
| "ddma-claim-submit"
|
||||
| "deltains-claim-submit"
|
||||
| "tuftssco-claim-submit"
|
||||
| "uniteducard-claim-submit"
|
||||
| "uniteddh-claim-submit"
|
||||
|
||||
@@ -588,6 +588,7 @@ function batchColumnDeriveSiteKey(provider: string): string {
|
||||
if (!p || p.includes("masshealth") || p === "mh" || p === "mass health") return "MH";
|
||||
if (p.includes("commonwealth care alliance") || p === "cca") return "CCA";
|
||||
if (p.includes("ddma") || p.includes("delta dental ma")) return "DDMA";
|
||||
if (p.includes("delta ins") || p === "deltains") return "DELTAINS";
|
||||
if (p.includes("tufts") || p.includes("dentaquest") || p === "tuftssco") return "TUFTS_SCO";
|
||||
if ((p.includes("united") && p.includes("sco")) || p.includes("dentalhub") || p === "united_sco") return "UNITED_SCO";
|
||||
if (p.includes("ucard") || p.includes("onehealthcareid") || p.includes("one healthcare id")) return "UNITED_UCARD";
|
||||
@@ -599,6 +600,7 @@ function batchColumnCanonicalName(siteKey: string): string {
|
||||
switch (siteKey) {
|
||||
case "CCA": return "CCA";
|
||||
case "DDMA": return "Delta Dental MA";
|
||||
case "DELTAINS": return "Delta Dental Ins";
|
||||
case "TUFTS_SCO": return "Tufts SCO";
|
||||
case "UNITED_SCO": return "United/DentalHub";
|
||||
case "UNITED_UCARD": return "United Ucard";
|
||||
@@ -947,6 +949,24 @@ router.post(
|
||||
enrichedPayload,
|
||||
claimId,
|
||||
});
|
||||
} else if (siteKey === "DELTAINS") {
|
||||
const enrichedPayload = {
|
||||
claim: {
|
||||
...baseClaimPayload,
|
||||
insuranceProvider: "Delta Dental Ins",
|
||||
insuranceSiteKey: "DELTAINS",
|
||||
deltainsUsername: credentials.username,
|
||||
deltainsPassword: credentials.password,
|
||||
providerName: resolvedNpiProvider?.providerName ?? "",
|
||||
claimFiles: diskClaimFiles,
|
||||
},
|
||||
};
|
||||
jobId = enqueueSeleniumJob({
|
||||
jobType: "deltains-claim-submit",
|
||||
userId: req.user.id,
|
||||
enrichedPayload,
|
||||
claimId,
|
||||
});
|
||||
} else if (siteKey === "TUFTS_SCO") {
|
||||
const enrichedPayload = {
|
||||
claim: {
|
||||
|
||||
@@ -20,6 +20,7 @@ import insuranceStatusCCARoutes from "./insuranceStatusCCA";
|
||||
import insuranceStatusCCAClaimRoutes from "./insuranceStatusCCAClaim";
|
||||
import insuranceStatusCCAPreAuthRoutes from "./insuranceStatusCCAPreAuth";
|
||||
import insuranceStatusDDMAClaimRoutes from "./insuranceStatusDDMAClaim";
|
||||
import insuranceStatusDeltainsClaimRoutes from "./insuranceStatusDeltainsClaim";
|
||||
import insuranceStatusUnitedDHClaimRoutes from "./insuranceStatusUnitedDHClaim";
|
||||
import insuranceStatusUnitedDHPreAuthRoutes from "./insuranceStatusUnitedDHPreAuth";
|
||||
import insuranceStatusTuftsSCOClaimRoutes from "./insuranceStatusTuftsSCOClaim";
|
||||
@@ -75,6 +76,7 @@ router.use("/insurance-status-bcbs-ma", insuranceStatusBcbsMaRoutes);
|
||||
router.use("/claims", insuranceStatusCCAClaimRoutes);
|
||||
router.use("/claims", insuranceStatusCCAPreAuthRoutes);
|
||||
router.use("/claims", insuranceStatusDDMAClaimRoutes);
|
||||
router.use("/claims", insuranceStatusDeltainsClaimRoutes);
|
||||
router.use("/claims", insuranceStatusUnitedDHClaimRoutes);
|
||||
router.use("/claims", insuranceStatusUnitedDHPreAuthRoutes);
|
||||
router.use("/claims", insuranceStatusTuftsSCOClaimRoutes);
|
||||
|
||||
@@ -0,0 +1,103 @@
|
||||
import { Router, Request, Response } from "express";
|
||||
import { storage } from "../storage";
|
||||
import { enqueueSeleniumJob } from "../queue/jobRunner";
|
||||
import { forwardOtpToSeleniumDeltainsClaimAgent } from "../services/seleniumDeltainsClaimClient";
|
||||
import { io } from "../socket";
|
||||
|
||||
const router = Router();
|
||||
|
||||
/**
|
||||
* POST /deltains-claim
|
||||
*
|
||||
* Enqueues a Delta Dental Ins 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("/deltains-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 Deltains credentials
|
||||
const credentials = await storage.getInsuranceCredentialByUserAndSiteKey(
|
||||
req.user.id,
|
||||
"DELTAINS"
|
||||
);
|
||||
if (!credentials) {
|
||||
return res.status(404).json({
|
||||
error: "No Delta Dental Ins credentials found. Please add them on the Settings page.",
|
||||
});
|
||||
}
|
||||
|
||||
// Use provider from the claim form if set; fall back to Provider #1 (default)
|
||||
const npiProviders = await storage.getNpiProvidersByUser(req.user.id);
|
||||
const primaryProvider = npiProviders[0];
|
||||
const providerName =
|
||||
(claimData.npiProvider?.providerName as string | undefined)?.trim() ||
|
||||
primaryProvider?.providerName ||
|
||||
"";
|
||||
|
||||
const enrichedPayload = {
|
||||
claim: {
|
||||
...claimData,
|
||||
deltainsUsername: credentials.username,
|
||||
deltainsPassword: credentials.password,
|
||||
providerName,
|
||||
},
|
||||
};
|
||||
|
||||
const socketId: string | undefined = req.body.socketId;
|
||||
const claimId: number | undefined = claimData.claimId
|
||||
? Number(claimData.claimId)
|
||||
: undefined;
|
||||
|
||||
const jobId = enqueueSeleniumJob({
|
||||
jobType: "deltains-claim-submit",
|
||||
userId: req.user.id,
|
||||
socketId,
|
||||
enrichedPayload,
|
||||
claimId,
|
||||
});
|
||||
|
||||
return res.json({ status: "queued", jobId });
|
||||
} catch (err: any) {
|
||||
console.error("[deltains-claim route] error:", err);
|
||||
return res.status(500).json({
|
||||
error: err.message || "Failed to enqueue Deltains claim job",
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
/**
|
||||
* POST /claims/deltains-claim/selenium/submit-otp
|
||||
* Body: { session_id, otp, socketId? }
|
||||
*/
|
||||
router.post("/deltains-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 forwardOtpToSeleniumDeltainsClaimAgent(sessionId, otp);
|
||||
if (socketId && io) {
|
||||
io.to(socketId).emit("selenium:otp_submitted", { session_id: sessionId });
|
||||
}
|
||||
return res.json(r);
|
||||
} catch (err: any) {
|
||||
console.error("[deltains-claim] submit-otp failed:", err?.message);
|
||||
return res.status(500).json({ error: err?.message || "Failed to forward OTP" });
|
||||
}
|
||||
});
|
||||
|
||||
export default router;
|
||||
@@ -0,0 +1,35 @@
|
||||
import axios from "axios";
|
||||
|
||||
const SELENIUM_BASE = process.env.SELENIUM_SERVICE_URL ?? "http://localhost:5002";
|
||||
|
||||
/**
|
||||
* POST /deltains-claim
|
||||
* Returns { status: "started", session_id: "<uuid>" }
|
||||
*/
|
||||
export async function forwardToSeleniumDeltainsClaimAgent(
|
||||
data: Record<string, any>
|
||||
): Promise<{ status: string; session_id: string }> {
|
||||
const resp = await axios.post(`${SELENIUM_BASE}/deltains-claim`, data);
|
||||
return resp.data;
|
||||
}
|
||||
|
||||
/**
|
||||
* GET /session/{sid}/status
|
||||
*/
|
||||
export async function getSeleniumDeltainsClaimSessionStatus(
|
||||
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 forwardOtpToSeleniumDeltainsClaimAgent(
|
||||
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