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:
@@ -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 };
|
||||
}
|
||||
@@ -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;
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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",
|
||||
};
|
||||
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
|
||||
@@ -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) } : {}),
|
||||
})),
|
||||
});
|
||||
}
|
||||
|
||||
@@ -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 } : {}),
|
||||
};
|
||||
}
|
||||
Reference in New Issue
Block a user