feat: United/DentalHub + Tufts SCO pre-auth, cloud storage search & file thumbnails
- Add United/DentalHub pre-authorization Selenium worker, helpers, backend route/processor/client, and frontend OTP modal + wired button - Add Tufts SCO pre-authorization Selenium worker, helpers, backend route/processor/client, and frontend OTP modal + wired button - Fix btnSubmitAuthorization selector for UnitedDH preauth step2 - Fix Tufts SCO preauth step3 to target <span>pre-authorization</span> button - Cloud storage search: default to "both" mode so patient folder names match on first search - Cloud storage folder panel: auto-scroll to panel when opened from search results - Cloud storage files: show inline image thumbnails and PDF badge in file grid Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
@@ -20,6 +20,8 @@ import { runCCAClaimProcessor } from "./processors/ccaClaimProcessor";
|
||||
import { runCCAPreAuthProcessor } from "./processors/ccaPreAuthProcessor";
|
||||
import { runDDMAClaimProcessor } from "./processors/ddmaClaimProcessor";
|
||||
import { runUnitedDHClaimProcessor } from "./processors/unitedDHClaimProcessor";
|
||||
import { runUnitedDHPreAuthProcessor } from "./processors/unitedDHPreAuthProcessor";
|
||||
import { runTuftsSCOPreAuthProcessor } from "./processors/tuftsSCOPreAuthProcessor";
|
||||
import { runTuftsSCOClaimProcessor } from "./processors/tuftsSCOClaimProcessor";
|
||||
import { runEligibilityHistoryProcessor } from "./processors/eligibilityHistoryProcessor";
|
||||
import { runCmspEligibilityHistoryRemainingProcessor } from "./processors/cmspEligibilityHistoryRemainingProcessor";
|
||||
@@ -182,6 +184,28 @@ export function enqueueSeleniumJob(data: SeleniumJobData): string {
|
||||
job.id
|
||||
);
|
||||
}
|
||||
if (jobType === "uniteddh-preauth-submit") {
|
||||
return runUnitedDHPreAuthProcessor(
|
||||
{
|
||||
enrichedPayload: data.enrichedPayload,
|
||||
userId: data.userId,
|
||||
claimId: data.claimId,
|
||||
socketId: data.socketId,
|
||||
},
|
||||
job.id
|
||||
);
|
||||
}
|
||||
if (jobType === "tuftssco-preauth-submit") {
|
||||
return runTuftsSCOPreAuthProcessor(
|
||||
{
|
||||
enrichedPayload: data.enrichedPayload,
|
||||
userId: data.userId,
|
||||
claimId: data.claimId,
|
||||
socketId: data.socketId,
|
||||
},
|
||||
job.id
|
||||
);
|
||||
}
|
||||
if (jobType === "tuftssco-claim-submit") {
|
||||
return runTuftsSCOClaimProcessor(
|
||||
{
|
||||
|
||||
178
apps/Backend/src/queue/processors/tuftsSCOPreAuthProcessor.ts
Normal file
178
apps/Backend/src/queue/processors/tuftsSCOPreAuthProcessor.ts
Normal file
@@ -0,0 +1,178 @@
|
||||
import {
|
||||
forwardToSeleniumTuftsSCOPreAuthAgent,
|
||||
getSeleniumTuftsSCOPreAuthSessionStatus,
|
||||
} from "../../services/seleniumTuftsSCOPreAuthClient";
|
||||
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 = 5 * 60 * 1000
|
||||
): Promise<any> {
|
||||
const maxAttempts = 600;
|
||||
const pollIntervalMs = 500;
|
||||
const maxTransientErrors = 12;
|
||||
const noProgressLimit = 240;
|
||||
let transientErrors = 0;
|
||||
let consecutiveNoProgress = 0;
|
||||
let lastStatus: string | null = null;
|
||||
const deadline = Date.now() + pollTimeoutMs;
|
||||
|
||||
for (let attempt = 0; attempt < maxAttempts; attempt++) {
|
||||
if (Date.now() > deadline) {
|
||||
throw new Error(`Tufts SCO preauth polling timeout for session ${sessionId}`);
|
||||
}
|
||||
try {
|
||||
const st = await getSeleniumTuftsSCOPreAuthSessionStatus(sessionId);
|
||||
const status: string = st?.status ?? "unknown";
|
||||
log("tuftssco-preauth-processor", `poll attempt=${attempt}`, { sessionId, status });
|
||||
transientErrors = 0;
|
||||
|
||||
const isTerminal = status === "completed" || status === "error" || status === "not_found";
|
||||
if (status === lastStatus && !isTerminal) {
|
||||
consecutiveNoProgress++;
|
||||
} else {
|
||||
consecutiveNoProgress = 0;
|
||||
}
|
||||
lastStatus = status;
|
||||
|
||||
if (consecutiveNoProgress >= noProgressLimit) {
|
||||
throw new Error(`No progress from Python agent (status="${status}") after ${consecutiveNoProgress} polls`);
|
||||
}
|
||||
|
||||
if (status === "waiting_for_otp") {
|
||||
emitToSocket(socketId, "selenium:otp_required", {
|
||||
session_id: sessionId,
|
||||
jobId,
|
||||
message: "OTP required. Please enter the OTP sent by the DentaQuest portal.",
|
||||
});
|
||||
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 preauth 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 preauth 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 preauth polling exhausted all attempts for session ${sessionId}`);
|
||||
}
|
||||
|
||||
async function savePdfFromSelenium(pdf_path: string, patientId: number) {
|
||||
try {
|
||||
const filename = path.basename(pdf_path);
|
||||
const seleniumPort = process.env.SELENIUM_PORT || "5002";
|
||||
const localUrl = `http://localhost:${seleniumPort}/downloads/${filename}`;
|
||||
const resp = await axios.get(localUrl, { responseType: "arraybuffer", timeout: 30000 });
|
||||
|
||||
let group = await storage.findPdfGroupByPatientTitleKey(patientId, "INSURANCE_CLAIM_PREAUTH");
|
||||
if (!group) {
|
||||
group = await storage.createPdfGroup(patientId, "PreAuth", "INSURANCE_CLAIM_PREAUTH");
|
||||
}
|
||||
await storage.createPdfFile(group.id!, filename, resp.data);
|
||||
log("tuftssco-preauth-processor", "PDF saved", { patientId, filename });
|
||||
} catch (err: any) {
|
||||
log("tuftssco-preauth-processor", "failed to save PDF (non-fatal)", { error: err?.message ?? err });
|
||||
}
|
||||
}
|
||||
|
||||
export interface TuftsSCOPreAuthProcessorInput {
|
||||
enrichedPayload: any;
|
||||
userId: number;
|
||||
claimId?: number;
|
||||
socketId?: string;
|
||||
}
|
||||
|
||||
export async function runTuftsSCOPreAuthProcessor(
|
||||
input: TuftsSCOPreAuthProcessorInput,
|
||||
jobId: string
|
||||
): Promise<{ status: string; pdf_path?: string; preAuthNumber?: string }> {
|
||||
const { enrichedPayload, userId, claimId, socketId } = input;
|
||||
|
||||
log("tuftssco-preauth-processor", "starting Python agent session", { claimId });
|
||||
const agentResp = await forwardToSeleniumTuftsSCOPreAuthAgent(enrichedPayload);
|
||||
|
||||
if (!agentResp?.session_id) {
|
||||
throw new Error("Python agent did not return a session_id for Tufts SCO preauth");
|
||||
}
|
||||
|
||||
const sessionId = agentResp.session_id as string;
|
||||
log("tuftssco-preauth-processor", "got session_id", { sessionId });
|
||||
|
||||
emitToSocket(socketId, "selenium:tuftssco_preauth_started", { session_id: sessionId, jobId });
|
||||
|
||||
const seleniumResult = await pollUntilDone(sessionId, socketId, jobId);
|
||||
|
||||
if (!seleniumResult || seleniumResult.status === "error") {
|
||||
throw new Error(seleniumResult?.message ?? "Tufts SCO preauth session returned an error");
|
||||
}
|
||||
|
||||
const preAuthNumber: string | undefined = seleniumResult.preAuthNumber ?? undefined;
|
||||
const pdf_path: string | undefined = seleniumResult.pdf_path ?? undefined;
|
||||
|
||||
if (claimId) {
|
||||
try {
|
||||
const updates: Record<string, any> = { status: "PREAUTH" };
|
||||
if (preAuthNumber) updates.claimNumber = preAuthNumber;
|
||||
await storage.updateClaim(claimId, updates);
|
||||
log("tuftssco-preauth-processor", "claim record updated", { claimId, preAuthNumber });
|
||||
|
||||
const claim = await storage.getClaim(claimId);
|
||||
if (claim?.patientId) {
|
||||
await storage.touchPatient(claim.patientId);
|
||||
log("tuftssco-preauth-processor", "patient touched", { patientId: claim.patientId });
|
||||
}
|
||||
} catch (e) {
|
||||
log("tuftssco-preauth-processor", "failed to update claim record (non-fatal)", { error: e });
|
||||
}
|
||||
}
|
||||
|
||||
if (pdf_path && !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_path, Number(patientId));
|
||||
}
|
||||
|
||||
emitToSocket(socketId, "selenium:tuftssco_preauth_completed", {
|
||||
jobId,
|
||||
claimId,
|
||||
preAuthNumber,
|
||||
pdf_path,
|
||||
message: preAuthNumber
|
||||
? `Tufts SCO pre-authorization submitted — PreAuth #: ${preAuthNumber}`
|
||||
: (seleniumResult?.message ?? "Tufts SCO pre-authorization submitted successfully"),
|
||||
});
|
||||
|
||||
log("tuftssco-preauth-processor", "done", { claimId, preAuthNumber });
|
||||
return { status: "success", pdf_path, preAuthNumber };
|
||||
}
|
||||
189
apps/Backend/src/queue/processors/unitedDHPreAuthProcessor.ts
Normal file
189
apps/Backend/src/queue/processors/unitedDHPreAuthProcessor.ts
Normal file
@@ -0,0 +1,189 @@
|
||||
/**
|
||||
* Processor for "uniteddh-preauth-submit" jobs.
|
||||
* Submits a dental pre-authorization to the United/DentalHub portal via Selenium.
|
||||
*
|
||||
* Flow:
|
||||
* 1. POST /uniteddh-preauth to Python agent → get session_id
|
||||
* 2. Emit selenium:uniteddh_preauth_started to frontend
|
||||
* 3. Poll until completed/error (emitting otp_required as needed)
|
||||
* 4. Save PDF + preAuthNumber, emit result
|
||||
*/
|
||||
import {
|
||||
forwardToSeleniumUnitedDHPreAuthAgent,
|
||||
getSeleniumUnitedDHPreAuthSessionStatus,
|
||||
} from "../../services/seleniumUnitedDHPreAuthClient";
|
||||
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 = 5 * 60 * 1000
|
||||
): Promise<any> {
|
||||
const maxAttempts = 600;
|
||||
const pollIntervalMs = 500;
|
||||
const maxTransientErrors = 12;
|
||||
const noProgressLimit = 240;
|
||||
let transientErrors = 0;
|
||||
let consecutiveNoProgress = 0;
|
||||
let lastStatus: string | null = null;
|
||||
const deadline = Date.now() + pollTimeoutMs;
|
||||
|
||||
for (let attempt = 0; attempt < maxAttempts; attempt++) {
|
||||
if (Date.now() > deadline) {
|
||||
throw new Error(`UnitedDH preauth polling timeout for session ${sessionId}`);
|
||||
}
|
||||
try {
|
||||
const st = await getSeleniumUnitedDHPreAuthSessionStatus(sessionId);
|
||||
const status: string = st?.status ?? "unknown";
|
||||
log("uniteddh-preauth-processor", `poll attempt=${attempt}`, { sessionId, status });
|
||||
transientErrors = 0;
|
||||
|
||||
const isTerminal = status === "completed" || status === "error" || status === "not_found";
|
||||
if (status === lastStatus && !isTerminal) {
|
||||
consecutiveNoProgress++;
|
||||
} else {
|
||||
consecutiveNoProgress = 0;
|
||||
}
|
||||
lastStatus = status;
|
||||
|
||||
if (consecutiveNoProgress >= noProgressLimit) {
|
||||
throw new Error(`No progress from Python agent (status="${status}") after ${consecutiveNoProgress} polls`);
|
||||
}
|
||||
|
||||
if (status === "waiting_for_otp") {
|
||||
emitToSocket(socketId, "selenium:otp_required", {
|
||||
session_id: sessionId,
|
||||
jobId,
|
||||
message: "OTP required. Please enter the OTP shown by the DentalHub portal.",
|
||||
});
|
||||
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 || `UnitedDH preauth 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 UnitedDH preauth session ${sessionId}`);
|
||||
}
|
||||
const backoff = Math.min(30_000, 500 * Math.pow(2, transientErrors - 1));
|
||||
await new Promise((r) => setTimeout(r, backoff));
|
||||
}
|
||||
}
|
||||
throw new Error(`UnitedDH preauth polling exhausted all attempts for session ${sessionId}`);
|
||||
}
|
||||
|
||||
async function savePdfFromSelenium(pdf_url: string, patientId: 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 });
|
||||
|
||||
let group = await storage.findPdfGroupByPatientTitleKey(patientId, "INSURANCE_CLAIM_PREAUTH");
|
||||
if (!group) {
|
||||
group = await storage.createPdfGroup(patientId, "PreAuth", "INSURANCE_CLAIM_PREAUTH");
|
||||
}
|
||||
await storage.createPdfFile(group.id!, filename, resp.data);
|
||||
log("uniteddh-preauth-processor", "PDF saved", { patientId, filename });
|
||||
} catch (err: any) {
|
||||
log("uniteddh-preauth-processor", "failed to save PDF (non-fatal)", { error: err?.message ?? err });
|
||||
}
|
||||
}
|
||||
|
||||
export interface UnitedDHPreAuthProcessorInput {
|
||||
enrichedPayload: any;
|
||||
userId: number;
|
||||
claimId?: number;
|
||||
socketId?: string;
|
||||
}
|
||||
|
||||
export async function runUnitedDHPreAuthProcessor(
|
||||
input: UnitedDHPreAuthProcessorInput,
|
||||
jobId: string
|
||||
): Promise<{ status: string; pdf_url?: string; preAuthNumber?: string }> {
|
||||
const { enrichedPayload, userId, claimId, socketId } = input;
|
||||
|
||||
log("uniteddh-preauth-processor", "starting Python agent session", { claimId });
|
||||
const agentResp = await forwardToSeleniumUnitedDHPreAuthAgent(enrichedPayload);
|
||||
|
||||
if (!agentResp?.session_id) {
|
||||
throw new Error("Python agent did not return a session_id for UnitedDH preauth");
|
||||
}
|
||||
|
||||
const sessionId = agentResp.session_id as string;
|
||||
log("uniteddh-preauth-processor", "got session_id", { sessionId });
|
||||
|
||||
emitToSocket(socketId, "selenium:uniteddh_preauth_started", { session_id: sessionId, jobId });
|
||||
|
||||
const seleniumResult = await pollUntilDone(sessionId, socketId, jobId);
|
||||
|
||||
if (!seleniumResult || seleniumResult.status === "error") {
|
||||
throw new Error(seleniumResult?.message ?? "UnitedDH preauth session returned an error");
|
||||
}
|
||||
|
||||
const preAuthNumber: string | undefined = seleniumResult.preAuthNumber ?? undefined;
|
||||
const pdf_url: string | undefined = seleniumResult.pdf_url ?? undefined;
|
||||
|
||||
if (claimId) {
|
||||
try {
|
||||
const updates: Record<string, any> = { status: "PREAUTH" };
|
||||
if (preAuthNumber) updates.claimNumber = preAuthNumber;
|
||||
await storage.updateClaim(claimId, updates);
|
||||
log("uniteddh-preauth-processor", "claim record updated", { claimId, preAuthNumber });
|
||||
|
||||
const claim = await storage.getClaim(claimId);
|
||||
if (claim?.patientId) {
|
||||
await storage.touchPatient(claim.patientId);
|
||||
log("uniteddh-preauth-processor", "patient touched", { patientId: claim.patientId });
|
||||
}
|
||||
} catch (e) {
|
||||
log("uniteddh-preauth-processor", "failed to update claim record (non-fatal)", { error: e });
|
||||
}
|
||||
}
|
||||
|
||||
// Auto-save PDF when called without a frontend socket 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));
|
||||
}
|
||||
|
||||
emitToSocket(socketId, "selenium:uniteddh_preauth_completed", {
|
||||
jobId,
|
||||
claimId,
|
||||
preAuthNumber,
|
||||
pdf_url,
|
||||
message: preAuthNumber
|
||||
? `United/DentalHub pre-authorization submitted — PreAuth #: ${preAuthNumber}`
|
||||
: (seleniumResult?.message ?? "United/DentalHub pre-authorization submitted successfully"),
|
||||
});
|
||||
|
||||
log("uniteddh-preauth-processor", "done", { claimId, preAuthNumber });
|
||||
return { status: "success", pdf_url, preAuthNumber };
|
||||
}
|
||||
@@ -16,6 +16,8 @@ export type SeleniumJobType =
|
||||
| "ddma-claim-submit"
|
||||
| "tuftssco-claim-submit"
|
||||
| "uniteddh-claim-submit"
|
||||
| "uniteddh-preauth-submit"
|
||||
| "tuftssco-preauth-submit"
|
||||
| "tuftssco-eligibility-check"
|
||||
| "mh-eligibility-history-check"
|
||||
| "cmsp-eligibility-history-remaining-check"
|
||||
|
||||
@@ -20,7 +20,9 @@ import insuranceStatusCCAClaimRoutes from "./insuranceStatusCCAClaim";
|
||||
import insuranceStatusCCAPreAuthRoutes from "./insuranceStatusCCAPreAuth";
|
||||
import insuranceStatusDDMAClaimRoutes from "./insuranceStatusDDMAClaim";
|
||||
import insuranceStatusUnitedDHClaimRoutes from "./insuranceStatusUnitedDHClaim";
|
||||
import insuranceStatusUnitedDHPreAuthRoutes from "./insuranceStatusUnitedDHPreAuth";
|
||||
import insuranceStatusTuftsSCOClaimRoutes from "./insuranceStatusTuftsSCOClaim";
|
||||
import insuranceStatusTuftsSCOPreAuthRoutes from "./insuranceStatusTuftsSCOPreAuth";
|
||||
import paymentsRoutes from "./payments";
|
||||
import databaseManagementRoutes from "./database-management";
|
||||
import notificationsRoutes from "./notifications";
|
||||
@@ -66,7 +68,9 @@ router.use("/claims", insuranceStatusCCAClaimRoutes);
|
||||
router.use("/claims", insuranceStatusCCAPreAuthRoutes);
|
||||
router.use("/claims", insuranceStatusDDMAClaimRoutes);
|
||||
router.use("/claims", insuranceStatusUnitedDHClaimRoutes);
|
||||
router.use("/claims", insuranceStatusUnitedDHPreAuthRoutes);
|
||||
router.use("/claims", insuranceStatusTuftsSCOClaimRoutes);
|
||||
router.use("/claims", insuranceStatusTuftsSCOPreAuthRoutes);
|
||||
router.use("/payments", paymentsRoutes);
|
||||
router.use("/database-management", databaseManagementRoutes);
|
||||
router.use("/notifications", notificationsRoutes);
|
||||
|
||||
122
apps/Backend/src/routes/insuranceStatusTuftsSCOPreAuth.ts
Normal file
122
apps/Backend/src/routes/insuranceStatusTuftsSCOPreAuth.ts
Normal file
@@ -0,0 +1,122 @@
|
||||
import { Router, Request, Response } from "express";
|
||||
import { storage } from "../storage";
|
||||
import { enqueueSeleniumJob } from "../queue/jobRunner";
|
||||
import { forwardOtpToSeleniumTuftsSCOPreAuthAgent } from "../services/seleniumTuftsSCOPreAuthClient";
|
||||
import { io } from "../socket";
|
||||
|
||||
const router = Router();
|
||||
|
||||
/**
|
||||
* POST /tuftssco-preauth
|
||||
*
|
||||
* Enqueues a Tufts SCO (DentaQuest) pre-authorization submission job.
|
||||
*
|
||||
* Body fields (JSON):
|
||||
* data — preauth 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-preauth", 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 ?? {};
|
||||
|
||||
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;
|
||||
let claimId: number | undefined = claimData.claimId
|
||||
? Number(claimData.claimId)
|
||||
: undefined;
|
||||
|
||||
if (!claimId && claimData.patientId) {
|
||||
try {
|
||||
const serviceDate = claimData.serviceDate
|
||||
? new Date(claimData.serviceDate)
|
||||
: new Date();
|
||||
const dob = claimData.dateOfBirth
|
||||
? new Date(claimData.dateOfBirth)
|
||||
: new Date("2000-01-01");
|
||||
const record = await storage.createClaim({
|
||||
patientId: Number(claimData.patientId),
|
||||
appointmentId: claimData.appointmentId ? Number(claimData.appointmentId) : null,
|
||||
userId: req.user.id,
|
||||
staffId: Number(claimData.staffId) || 1,
|
||||
patientName: claimData.patientName || "",
|
||||
memberId: claimData.memberId || "",
|
||||
dateOfBirth: dob,
|
||||
remarks: claimData.remarks || "",
|
||||
missingTeethStatus: claimData.missingTeethStatus || "No_missing",
|
||||
serviceDate,
|
||||
insuranceProvider: "Tufts SCO",
|
||||
status: "PREAUTH",
|
||||
} as any);
|
||||
claimId = record.id;
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
const jobId = enqueueSeleniumJob({
|
||||
jobType: "tuftssco-preauth-submit",
|
||||
userId: req.user.id,
|
||||
socketId,
|
||||
enrichedPayload,
|
||||
claimId,
|
||||
});
|
||||
|
||||
return res.json({ status: "queued", jobId });
|
||||
} catch (err: any) {
|
||||
console.error("[tuftssco-preauth route] error:", err);
|
||||
return res.status(500).json({
|
||||
error: err.message || "Failed to enqueue Tufts SCO preauth job",
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
/**
|
||||
* POST /claims/tuftssco-preauth/selenium/submit-otp
|
||||
* Body: { session_id, otp, socketId? }
|
||||
*/
|
||||
router.post("/tuftssco-preauth/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 forwardOtpToSeleniumTuftsSCOPreAuthAgent(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-preauth] submit-otp failed:", err?.message);
|
||||
return res.status(500).json({ error: err?.message || "Failed to forward OTP" });
|
||||
}
|
||||
});
|
||||
|
||||
export default router;
|
||||
124
apps/Backend/src/routes/insuranceStatusUnitedDHPreAuth.ts
Normal file
124
apps/Backend/src/routes/insuranceStatusUnitedDHPreAuth.ts
Normal file
@@ -0,0 +1,124 @@
|
||||
import { Router, Request, Response } from "express";
|
||||
import { storage } from "../storage";
|
||||
import { enqueueSeleniumJob } from "../queue/jobRunner";
|
||||
import { forwardOtpToSeleniumUnitedDHPreAuthAgent } from "../services/seleniumUnitedDHPreAuthClient";
|
||||
import { io } from "../socket";
|
||||
|
||||
const router = Router();
|
||||
|
||||
/**
|
||||
* POST /uniteddh-preauth
|
||||
*
|
||||
* Enqueues a United/DentalHub pre-authorization submission job.
|
||||
*
|
||||
* Body fields (JSON):
|
||||
* data — preauth payload (memberId, dateOfBirth, serviceDate, serviceLines, patientName, etc.)
|
||||
* socketId — socket.io client id
|
||||
* claimId — existing claim DB id (optional)
|
||||
*
|
||||
* Response: { status: "queued", jobId: "…" }
|
||||
*/
|
||||
router.post("/uniteddh-preauth", 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 United/DentalHub credentials — same portal as UnitedSCO
|
||||
const credentials = await storage.getInsuranceCredentialByUserAndSiteKey(
|
||||
req.user.id,
|
||||
"UNITED_SCO"
|
||||
);
|
||||
if (!credentials) {
|
||||
return res.status(404).json({
|
||||
error: "No United/DentalHub credentials found. Please add them on the Settings page.",
|
||||
});
|
||||
}
|
||||
|
||||
const enrichedPayload = {
|
||||
claim: {
|
||||
...claimData,
|
||||
uniteddhUsername: credentials.username,
|
||||
uniteddhPassword: credentials.password,
|
||||
},
|
||||
};
|
||||
|
||||
const socketId: string | undefined = req.body.socketId;
|
||||
let claimId: number | undefined = claimData.claimId
|
||||
? Number(claimData.claimId)
|
||||
: undefined;
|
||||
|
||||
// Create a PREAUTH claim record so preAuthNumber can be stored
|
||||
if (!claimId && claimData.patientId) {
|
||||
try {
|
||||
const serviceDate = claimData.serviceDate
|
||||
? new Date(claimData.serviceDate)
|
||||
: new Date();
|
||||
const dob = claimData.dateOfBirth
|
||||
? new Date(claimData.dateOfBirth)
|
||||
: new Date("2000-01-01");
|
||||
const record = await storage.createClaim({
|
||||
patientId: Number(claimData.patientId),
|
||||
appointmentId: claimData.appointmentId ? Number(claimData.appointmentId) : null,
|
||||
userId: req.user.id,
|
||||
staffId: Number(claimData.staffId) || 1,
|
||||
patientName: claimData.patientName || "",
|
||||
memberId: claimData.memberId || "",
|
||||
dateOfBirth: dob,
|
||||
remarks: claimData.remarks || "",
|
||||
missingTeethStatus: claimData.missingTeethStatus || "No_missing",
|
||||
serviceDate,
|
||||
insuranceProvider: "United/DentalHub",
|
||||
status: "PREAUTH",
|
||||
} as any);
|
||||
claimId = record.id;
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
const jobId = enqueueSeleniumJob({
|
||||
jobType: "uniteddh-preauth-submit",
|
||||
userId: req.user.id,
|
||||
socketId,
|
||||
enrichedPayload,
|
||||
claimId,
|
||||
});
|
||||
|
||||
return res.json({ status: "queued", jobId });
|
||||
} catch (err: any) {
|
||||
console.error("[uniteddh-preauth route] error:", err);
|
||||
return res.status(500).json({
|
||||
error: err.message || "Failed to enqueue United/DentalHub preauth job",
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
/**
|
||||
* POST /claims/uniteddh-preauth/selenium/submit-otp
|
||||
* Body: { session_id, otp, socketId? }
|
||||
*/
|
||||
router.post("/uniteddh-preauth/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 forwardOtpToSeleniumUnitedDHPreAuthAgent(sessionId, otp);
|
||||
if (socketId && io) {
|
||||
io.to(socketId).emit("selenium:otp_submitted", { session_id: sessionId });
|
||||
}
|
||||
return res.json(r);
|
||||
} catch (err: any) {
|
||||
console.error("[uniteddh-preauth] submit-otp failed:", err?.message);
|
||||
return res.status(500).json({ error: err?.message || "Failed to forward OTP" });
|
||||
}
|
||||
});
|
||||
|
||||
export default router;
|
||||
26
apps/Backend/src/services/seleniumTuftsSCOPreAuthClient.ts
Normal file
26
apps/Backend/src/services/seleniumTuftsSCOPreAuthClient.ts
Normal file
@@ -0,0 +1,26 @@
|
||||
import axios from "axios";
|
||||
|
||||
const SELENIUM_BASE = process.env.SELENIUM_SERVICE_URL || "http://localhost:8000";
|
||||
|
||||
export async function forwardToSeleniumTuftsSCOPreAuthAgent(data: any) {
|
||||
const response = await axios.post(`${SELENIUM_BASE}/tuftssco-preauth`, data, {
|
||||
timeout: 30000,
|
||||
});
|
||||
return response.data;
|
||||
}
|
||||
|
||||
export async function getSeleniumTuftsSCOPreAuthSessionStatus(sessionId: string) {
|
||||
const response = await axios.get(`${SELENIUM_BASE}/session/${sessionId}/status`, {
|
||||
timeout: 10000,
|
||||
});
|
||||
return response.data;
|
||||
}
|
||||
|
||||
export async function forwardOtpToSeleniumTuftsSCOPreAuthAgent(sessionId: string, otp: string) {
|
||||
const response = await axios.post(
|
||||
`${SELENIUM_BASE}/submit-otp`,
|
||||
{ session_id: sessionId, otp },
|
||||
{ timeout: 10000 }
|
||||
);
|
||||
return response.data;
|
||||
}
|
||||
35
apps/Backend/src/services/seleniumUnitedDHPreAuthClient.ts
Normal file
35
apps/Backend/src/services/seleniumUnitedDHPreAuthClient.ts
Normal file
@@ -0,0 +1,35 @@
|
||||
import axios from "axios";
|
||||
|
||||
const SELENIUM_BASE = process.env.SELENIUM_SERVICE_URL ?? "http://localhost:5002";
|
||||
|
||||
/**
|
||||
* POST /uniteddh-preauth
|
||||
* Returns { status: "started", session_id: "<uuid>" }
|
||||
*/
|
||||
export async function forwardToSeleniumUnitedDHPreAuthAgent(
|
||||
data: Record<string, any>
|
||||
): Promise<{ status: string; session_id: string }> {
|
||||
const resp = await axios.post(`${SELENIUM_BASE}/uniteddh-preauth`, data);
|
||||
return resp.data;
|
||||
}
|
||||
|
||||
/**
|
||||
* GET /session/{sid}/status
|
||||
*/
|
||||
export async function getSeleniumUnitedDHPreAuthSessionStatus(
|
||||
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 forwardOtpToSeleniumUnitedDHPreAuthAgent(
|
||||
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