feat: improve CCA preauth cell filling, implants category, preauth no recording
- Selenium: bulletproof Wait→Click→Clear→Type→Verify for tooth, billed amt cells - Selenium: fix billed amt to click td[23] (correct column) to trigger edit mode - Selenium: skip tentative date (auto-filled by page after tooth entry) - Frontend: add Implants category with Implant/Abut/Crown, Fixture, Abutment, Crown buttons (D6010/D6057/D6058) - Frontend: pdf-preview-modal renders PNG screenshots as <img> instead of PDF iframe - Backend: CCA preauth route creates claim record if none exists - Backend: CCA preauth processor saves authNumber into claimNumber column after submission Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
145
apps/Backend/src/queue/processors/ccaPreAuthProcessor.ts
Normal file
145
apps/Backend/src/queue/processors/ccaPreAuthProcessor.ts
Normal file
@@ -0,0 +1,145 @@
|
||||
/**
|
||||
* Processor for "cca-preauth-submit" jobs.
|
||||
* Submits a dental pre-authorization to CCA via the ScionDental portal.
|
||||
*/
|
||||
import { storage } from "../../storage";
|
||||
import {
|
||||
forwardToSeleniumCCAPreAuthAgent,
|
||||
getSeleniumCCAPreAuthSessionStatus,
|
||||
} from "../../services/seleniumCCAPreAuthClient";
|
||||
import { io } from "../../socket";
|
||||
|
||||
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,
|
||||
pollTimeoutMs = 10 * 60 * 1000
|
||||
): Promise<any> {
|
||||
const maxAttempts = 1200;
|
||||
const pollIntervalMs = 500;
|
||||
const maxTransientErrors = 12;
|
||||
let transientErrors = 0;
|
||||
const deadline = Date.now() + pollTimeoutMs;
|
||||
|
||||
for (let attempt = 0; attempt < maxAttempts; attempt++) {
|
||||
if (Date.now() > deadline) {
|
||||
throw new Error(`CCA preauth polling timeout for session ${sessionId}`);
|
||||
}
|
||||
try {
|
||||
const st = await getSeleniumCCAPreAuthSessionStatus(sessionId);
|
||||
const status: string = st?.status ?? "unknown";
|
||||
log("cca-preauth-processor", `poll attempt=${attempt}`, { sessionId, status });
|
||||
transientErrors = 0;
|
||||
|
||||
if (status === "completed") return st.result;
|
||||
if (status === "error" || status === "not_found") {
|
||||
throw new Error(st?.message || `CCA 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 CCA 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(`CCA preauth polling exhausted all attempts for session ${sessionId}`);
|
||||
}
|
||||
|
||||
export interface CCAPreAuthProcessorInput {
|
||||
enrichedPayload: any;
|
||||
userId: number;
|
||||
claimId?: number;
|
||||
socketId?: string;
|
||||
}
|
||||
|
||||
export async function runCCAPreAuthProcessor(
|
||||
input: CCAPreAuthProcessorInput,
|
||||
jobId: string
|
||||
): Promise<{ status: string; authNumber?: string | null; pdfFileId?: number | null }> {
|
||||
const { enrichedPayload, userId, claimId, socketId } = input;
|
||||
|
||||
log("cca-preauth-processor", "starting Python agent session", { claimId });
|
||||
const agentResp = await forwardToSeleniumCCAPreAuthAgent(enrichedPayload);
|
||||
|
||||
if (!agentResp?.session_id) {
|
||||
throw new Error("Python agent did not return a session_id for CCA preauth");
|
||||
}
|
||||
|
||||
const sessionId = agentResp.session_id as string;
|
||||
log("cca-preauth-processor", "got session_id", { sessionId });
|
||||
|
||||
emitToSocket(socketId, "selenium:cca_preauth_started", { session_id: sessionId, jobId });
|
||||
|
||||
const seleniumResult = await pollUntilDone(sessionId);
|
||||
|
||||
if (!seleniumResult || seleniumResult.status === "error") {
|
||||
throw new Error(seleniumResult?.message ?? "CCA preauth session returned an error");
|
||||
}
|
||||
|
||||
const authNumber: string | null = seleniumResult?.authNumber ?? null;
|
||||
const pdfBase64: string = seleniumResult?.pdfBase64 ?? "";
|
||||
const pdfFilename: string =
|
||||
seleniumResult?.pdfFilename || `cca_preauth_${claimId ?? "unknown"}_${Date.now()}.pdf`;
|
||||
|
||||
// Save authNumber into the claim record (preauth no column)
|
||||
if (claimId && authNumber) {
|
||||
try {
|
||||
await storage.updateClaim(claimId, { claimNumber: authNumber, status: "APPROVED" } as any);
|
||||
log("cca-preauth-processor", "authNumber saved to claim", { claimId, authNumber });
|
||||
} catch (e: any) {
|
||||
log("cca-preauth-processor", "failed to save authNumber to claim", { error: e?.message });
|
||||
}
|
||||
}
|
||||
|
||||
// Save PDF to patient's PreAuth document group
|
||||
let pdfFileId: number | null = null;
|
||||
if (pdfBase64 && enrichedPayload?.claim?.patientId) {
|
||||
try {
|
||||
const patientId = Number(enrichedPayload.claim.patientId);
|
||||
const pdfBuffer = Buffer.from(pdfBase64, "base64");
|
||||
let group = await storage.findPdfGroupByPatientTitleKey(patientId, "INSURANCE_CLAIM_PREAUTH");
|
||||
if (!group) {
|
||||
group = await storage.createPdfGroup(patientId, "PreAuth", "INSURANCE_CLAIM_PREAUTH");
|
||||
}
|
||||
const created = await storage.createPdfFile(group.id!, pdfFilename, pdfBuffer);
|
||||
if (created && typeof created === "object" && "id" in created) {
|
||||
pdfFileId = Number((created as any).id);
|
||||
}
|
||||
log("cca-preauth-processor", "PDF saved", { pdfFilename, pdfFileId, patientId });
|
||||
} catch (e: any) {
|
||||
log("cca-preauth-processor", "failed to save PDF", { error: e?.message });
|
||||
}
|
||||
}
|
||||
|
||||
emitToSocket(socketId, "selenium:cca_preauth_completed", {
|
||||
jobId,
|
||||
claimId,
|
||||
authNumber,
|
||||
pdfFileId,
|
||||
pdfFilename,
|
||||
message: authNumber
|
||||
? `CCA pre-authorization submitted — auth number: ${authNumber}`
|
||||
: "CCA pre-authorization submitted successfully",
|
||||
});
|
||||
|
||||
log("cca-preauth-processor", "done", { claimId, authNumber });
|
||||
return { status: "success", authNumber, pdfFileId };
|
||||
}
|
||||
121
apps/Backend/src/routes/insuranceStatusCCAPreAuth.ts
Normal file
121
apps/Backend/src/routes/insuranceStatusCCAPreAuth.ts
Normal file
@@ -0,0 +1,121 @@
|
||||
import { Router, Request, Response } from "express";
|
||||
import { storage } from "../storage";
|
||||
import { enqueueSeleniumJob } from "../queue/jobRunner";
|
||||
import multer from "multer";
|
||||
|
||||
const router = Router();
|
||||
const upload = multer({ storage: multer.memoryStorage() });
|
||||
|
||||
/**
|
||||
* POST /cca-preauth
|
||||
*
|
||||
* Enqueues a CCA pre-authorization submission job.
|
||||
* Accepts multipart/form-data with optional pdfs/images attachments.
|
||||
*
|
||||
* Body fields:
|
||||
* data — JSON string with preauth payload (memberId, dateOfBirth, serviceDate,
|
||||
* serviceLines, patientName, etc.)
|
||||
* socketId — socket.io client id
|
||||
* claimId — existing claim DB id (optional)
|
||||
*/
|
||||
router.post(
|
||||
"/cca-preauth",
|
||||
upload.fields([
|
||||
{ name: "pdfs", maxCount: 10 },
|
||||
{ name: "images", maxCount: 10 },
|
||||
]),
|
||||
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 ?? {};
|
||||
|
||||
const pdfs =
|
||||
(req.files as Record<string, Express.Multer.File[]>)?.pdfs ?? [];
|
||||
const images =
|
||||
(req.files as Record<string, Express.Multer.File[]>)?.images ?? [];
|
||||
|
||||
const credentials = await storage.getInsuranceCredentialByUserAndSiteKey(
|
||||
req.user.id,
|
||||
"CCA"
|
||||
);
|
||||
if (!credentials) {
|
||||
return res.status(404).json({
|
||||
error: "No CCA credentials found. Please add them on the Settings page.",
|
||||
});
|
||||
}
|
||||
|
||||
const filesForQueue = [...pdfs, ...images].map((f) => ({
|
||||
originalname: f.originalname,
|
||||
bufferBase64: f.buffer.toString("base64"),
|
||||
mimetype: f.mimetype,
|
||||
}));
|
||||
|
||||
const enrichedPayload = {
|
||||
claim: {
|
||||
...claimData,
|
||||
cca_username: credentials.username,
|
||||
cca_password: credentials.password,
|
||||
},
|
||||
files: filesForQueue,
|
||||
};
|
||||
|
||||
const socketId: string | undefined = req.body.socketId;
|
||||
let claimId: number | undefined = claimData.claimId
|
||||
? Number(claimData.claimId)
|
||||
: undefined;
|
||||
|
||||
// Create a PREAUTH claim record so authNumber can be stored in claimNumber column
|
||||
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: "CCA",
|
||||
status: "PREAUTH",
|
||||
} as any);
|
||||
claimId = record.id;
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
const jobId = enqueueSeleniumJob({
|
||||
jobType: "cca-preauth-submit",
|
||||
userId: req.user.id,
|
||||
socketId,
|
||||
enrichedPayload,
|
||||
claimId,
|
||||
});
|
||||
|
||||
return res.json({ status: "queued", jobId });
|
||||
} catch (err: any) {
|
||||
console.error("[cca-preauth route] error:", err);
|
||||
return res.status(500).json({
|
||||
error: err.message || "Failed to enqueue CCA preauth job",
|
||||
});
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
export default router;
|
||||
@@ -76,6 +76,7 @@ interface ClaimFormProps {
|
||||
onHandleForMHSeleniumClaim: (data: ClaimFormData) => void;
|
||||
onHandleForMHSeleniumClaimPreAuth: (data: ClaimPreAuthData) => void;
|
||||
onHandleForCCASeleniumClaim: (data: ClaimFormData) => void;
|
||||
onHandleForCCASeleniumPreAuth: (data: ClaimPreAuthData) => void;
|
||||
onClose: () => void;
|
||||
}
|
||||
|
||||
@@ -89,6 +90,7 @@ export function ClaimForm({
|
||||
onHandleForMHSeleniumClaim,
|
||||
onHandleForMHSeleniumClaimPreAuth,
|
||||
onHandleForCCASeleniumClaim,
|
||||
onHandleForCCASeleniumPreAuth,
|
||||
onSubmit,
|
||||
onClose,
|
||||
}: ClaimFormProps) {
|
||||
@@ -974,6 +976,44 @@ export function ClaimForm({
|
||||
onClose();
|
||||
};
|
||||
|
||||
const handleCCAPreAuth = async () => {
|
||||
const missingFields: string[] = [];
|
||||
if (!form.memberId?.trim()) missingFields.push("Member ID");
|
||||
if (!form.dateOfBirth?.trim()) missingFields.push("Date of Birth");
|
||||
if (!patient?.firstName?.trim()) missingFields.push("First Name");
|
||||
if (missingFields.length > 0) {
|
||||
toast({
|
||||
title: "Missing Required Fields",
|
||||
description: `Please fill out the following field(s): ${missingFields.join(", ")}`,
|
||||
variant: "destructive",
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
const filteredServiceLines = (form.serviceLines || []).filter(
|
||||
(line) => (line.procedureCode ?? "").trim() !== "",
|
||||
);
|
||||
if (filteredServiceLines.length === 0) {
|
||||
toast({
|
||||
title: "No procedure codes",
|
||||
description: "Please add at least one procedure code before submitting the pre-authorization.",
|
||||
variant: "destructive",
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
onHandleForCCASeleniumPreAuth({
|
||||
...form,
|
||||
serviceLines: filteredServiceLines,
|
||||
staffId: appointmentStaffId ?? Number(staff?.id),
|
||||
patientId,
|
||||
insuranceProvider: "CCA",
|
||||
insuranceSiteKey: "CCA",
|
||||
});
|
||||
|
||||
onClose();
|
||||
};
|
||||
|
||||
const uploadAttachmentsToLocalFolder = async (files: File[]): Promise<ClaimFileMeta[]> => {
|
||||
if (!files.length) return [];
|
||||
|
||||
@@ -1824,7 +1864,7 @@ export function ClaimForm({
|
||||
</Button>
|
||||
</div>
|
||||
) : (
|
||||
<div className="flex justify-between">
|
||||
<div className="flex flex-wrap gap-2 justify-center">
|
||||
<Button
|
||||
className="w-32 bg-blue-600 hover:bg-blue-700 text-white"
|
||||
onClick={() => handleMHSubmit()}
|
||||
@@ -1837,8 +1877,14 @@ export function ClaimForm({
|
||||
>
|
||||
CCA Claim
|
||||
</Button>
|
||||
<Button className="w-36" variant="outline">
|
||||
Delta MA Claim
|
||||
</Button>
|
||||
<Button className="w-44" variant="outline">
|
||||
United/DentalHub Claim
|
||||
</Button>
|
||||
<Button className="w-32" variant="outline">
|
||||
Delta MA
|
||||
Tufts Claim
|
||||
</Button>
|
||||
<Button
|
||||
className="w-36 bg-emerald-600 hover:bg-emerald-700 text-white"
|
||||
@@ -1954,7 +2000,7 @@ export function ClaimForm({
|
||||
<SelectItem value="Others">Others</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
<Label className="flex items-center">Service Date</Label>
|
||||
<Label className="flex items-center">Tentative Service Date</Label>
|
||||
<Popover
|
||||
open={serviceDateOpen}
|
||||
onOpenChange={setServiceDateOpen}
|
||||
@@ -2342,14 +2388,31 @@ export function ClaimForm({
|
||||
<h3 className="text-xl font-semibold mb-4 text-center">
|
||||
PreAuth
|
||||
</h3>
|
||||
<div className="flex justify-center">
|
||||
<div className="flex flex-wrap gap-2 justify-center">
|
||||
<Button
|
||||
className="w-32"
|
||||
variant="secondary"
|
||||
className="w-32 bg-blue-600 hover:bg-blue-700 text-white"
|
||||
onClick={() => handleMHPreAuth()}
|
||||
>
|
||||
MH PreAuth
|
||||
</Button>
|
||||
<Button
|
||||
className="w-32 bg-blue-600 hover:bg-blue-700 text-white"
|
||||
onClick={handleCCAPreAuth}
|
||||
>
|
||||
CCA PreAuth
|
||||
</Button>
|
||||
<Button
|
||||
className="w-44"
|
||||
variant="secondary"
|
||||
>
|
||||
United/DentalHub PreAuth
|
||||
</Button>
|
||||
<Button
|
||||
className="w-32"
|
||||
variant="secondary"
|
||||
>
|
||||
Tufts PreAuth
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -54,6 +54,7 @@ export function PdfPreviewModal({
|
||||
autoDownload = false,
|
||||
}: Props) {
|
||||
const [fileBlobUrl, setFileBlobUrl] = useState<string | null>(null);
|
||||
const [isImage, setIsImage] = useState(false);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [resolvedFilename, setResolvedFilename] = useState<string | null>(null);
|
||||
@@ -98,8 +99,13 @@ export function PdfPreviewModal({
|
||||
const arrayBuffer = await res.arrayBuffer();
|
||||
if (aborted) return;
|
||||
|
||||
const blob = new Blob([arrayBuffer], { type: "application/pdf" });
|
||||
const lowerName = finalName.toLowerCase();
|
||||
const isPng = lowerName.endsWith(".png");
|
||||
const isJpg = lowerName.endsWith(".jpg") || lowerName.endsWith(".jpeg");
|
||||
const mimeType = isPng ? "image/png" : isJpg ? "image/jpeg" : "application/pdf";
|
||||
const blob = new Blob([arrayBuffer], { type: mimeType });
|
||||
objectUrl = URL.createObjectURL(blob);
|
||||
setIsImage(isPng || isJpg);
|
||||
setFileBlobUrl(objectUrl);
|
||||
|
||||
if (autoDownload) {
|
||||
@@ -132,6 +138,7 @@ export function PdfPreviewModal({
|
||||
controller.abort();
|
||||
if (objectUrl) URL.revokeObjectURL(objectUrl);
|
||||
setFileBlobUrl(null);
|
||||
setIsImage(false);
|
||||
setError(null);
|
||||
setLoading(false);
|
||||
setResolvedFilename(null);
|
||||
@@ -194,12 +201,20 @@ export function PdfPreviewModal({
|
||||
{loading && <div>Loading PDF…</div>}
|
||||
{error && <div className="text-destructive">Error: {error}</div>}
|
||||
{fileBlobUrl && (
|
||||
<iframe
|
||||
title="PDF Preview"
|
||||
src={fileBlobUrl}
|
||||
className="w-full h-full border"
|
||||
style={{ minHeight: 0 }}
|
||||
/>
|
||||
isImage ? (
|
||||
<img
|
||||
src={fileBlobUrl}
|
||||
alt={resolvedFilename ?? "Preview"}
|
||||
className="max-w-full max-h-full object-contain mx-auto"
|
||||
/>
|
||||
) : (
|
||||
<iframe
|
||||
title="PDF Preview"
|
||||
src={fileBlobUrl}
|
||||
className="w-full h-full border"
|
||||
style={{ minHeight: 0 }}
|
||||
/>
|
||||
)
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -454,6 +454,34 @@ export default function ClaimsPage() {
|
||||
}
|
||||
};
|
||||
|
||||
// CCA pre-auth selenium handler
|
||||
const handleCCAPreAuthSubmitSelenium = async (data: any) => {
|
||||
const formData = new FormData();
|
||||
formData.append("data", JSON.stringify(data));
|
||||
if (socketId) formData.append("socketId", socketId);
|
||||
const uploadedFiles: File[] = data.uploadedFiles ?? [];
|
||||
uploadedFiles.forEach((file: File) => {
|
||||
if (file.type === "application/pdf") {
|
||||
formData.append("pdfs", file);
|
||||
} else if (file.type.startsWith("image/")) {
|
||||
formData.append("images", file);
|
||||
}
|
||||
});
|
||||
try {
|
||||
dispatch(setTaskStatus({ key: "claimSubmit", status: "pending", message: "Submitting CCA PreAuth..." }));
|
||||
const response = await apiRequest("POST", "/api/claims/cca-preauth", formData);
|
||||
const result = await response.json();
|
||||
if (result.error) throw new Error(result.error);
|
||||
pendingClaimMeta.current = { patientId: selectedPatientId, groupKey: "INSURANCE_CLAIM_PREAUTH" };
|
||||
setPendingClaimJobId(result.jobId);
|
||||
dispatch(setTaskStatus({ key: "claimSubmit", status: "pending", message: "CCA PreAuth queued. Awaiting Selenium..." }));
|
||||
toast({ title: "CCA PreAuth queued", description: "Selenium is processing the pre-authorization.", variant: "default" });
|
||||
} catch (error: any) {
|
||||
dispatch(setTaskStatus({ key: "claimSubmit", status: "error", message: error.message || "CCA PreAuth failed" }));
|
||||
toast({ title: "CCA PreAuth error", description: error.message || "An error occurred.", variant: "destructive" });
|
||||
}
|
||||
};
|
||||
|
||||
// 5. selenium pdf download handler
|
||||
const handleMHSeleniumPdfDownload = async (
|
||||
data: any,
|
||||
@@ -666,6 +694,7 @@ export default function ClaimsPage() {
|
||||
onHandleForMHSeleniumClaim={handleMHClaimSubmitSelenium}
|
||||
onHandleForMHSeleniumClaimPreAuth={handleMHClaimPreAuthSubmitSelenium}
|
||||
onHandleForCCASeleniumClaim={handleCCAClaimSubmitSelenium}
|
||||
onHandleForCCASeleniumPreAuth={handleCCAPreAuthSubmitSelenium}
|
||||
/>
|
||||
)}
|
||||
|
||||
|
||||
@@ -233,6 +233,28 @@ export const PROCEDURE_COMBOS: Record<
|
||||
codes: ["D5214"],
|
||||
},
|
||||
|
||||
// Implants
|
||||
implantFull: {
|
||||
id: "implantFull",
|
||||
label: "Implant/Abut/Crown",
|
||||
codes: ["D6010", "D6057", "D6058"],
|
||||
},
|
||||
implantFixture: {
|
||||
id: "implantFixture",
|
||||
label: "Implant Fixture",
|
||||
codes: ["D6010"],
|
||||
},
|
||||
implantAbutment: {
|
||||
id: "implantAbutment",
|
||||
label: "Abutment",
|
||||
codes: ["D6057"],
|
||||
},
|
||||
implantCrown: {
|
||||
id: "implantCrown",
|
||||
label: "Implant Crown",
|
||||
codes: ["D6058"],
|
||||
},
|
||||
|
||||
// Endodontics
|
||||
rctAnterior: {
|
||||
id: "rctAnterior",
|
||||
@@ -357,6 +379,7 @@ export const COMBO_CATEGORIES: Record<
|
||||
"plResin",
|
||||
"plCast",
|
||||
],
|
||||
Implants: ["implantFull", "implantFixture", "implantAbutment", "implantCrown"],
|
||||
Endodontics: ["rctAnterior", "rctPremolar", "rctMolar", "postCore", "coreBU"],
|
||||
Prosthodontics: ["crown"],
|
||||
Periodontics: ["deepCleaning"],
|
||||
|
||||
222
apps/SeleniumService/helpers_cca_preauth.py
Normal file
222
apps/SeleniumService/helpers_cca_preauth.py
Normal file
@@ -0,0 +1,222 @@
|
||||
import os
|
||||
import time
|
||||
import asyncio
|
||||
from typing import Dict, Any
|
||||
from selenium.common.exceptions import WebDriverException
|
||||
|
||||
from selenium_CCA_preAuthWorker import AutomationCCAPreAuth
|
||||
from cca_browser_manager import get_browser_manager
|
||||
|
||||
sessions: Dict[str, Dict[str, Any]] = {}
|
||||
|
||||
|
||||
def make_session_entry() -> str:
|
||||
import uuid
|
||||
sid = str(uuid.uuid4())
|
||||
sessions[sid] = {
|
||||
"status": "created",
|
||||
"created_at": time.time(),
|
||||
"last_activity": time.time(),
|
||||
"bot": None,
|
||||
"driver": None,
|
||||
"result": None,
|
||||
"message": None,
|
||||
}
|
||||
return sid
|
||||
|
||||
|
||||
async def cleanup_session(sid: str, message: str | None = None):
|
||||
s = sessions.get(sid)
|
||||
if not s:
|
||||
return
|
||||
try:
|
||||
if s.get("status") not in ("completed", "error"):
|
||||
s["status"] = "error"
|
||||
if message:
|
||||
s["message"] = message
|
||||
finally:
|
||||
sessions.pop(sid, None)
|
||||
|
||||
|
||||
async def _remove_session_later(sid: str, delay: int = 30):
|
||||
await asyncio.sleep(delay)
|
||||
await cleanup_session(sid)
|
||||
|
||||
|
||||
def _close_browser(bot):
|
||||
try:
|
||||
bm = get_browser_manager()
|
||||
try:
|
||||
bm.save_cookies()
|
||||
except Exception:
|
||||
pass
|
||||
try:
|
||||
bm.quit_driver()
|
||||
print("[CCA PreAuth] Browser closed")
|
||||
except Exception:
|
||||
pass
|
||||
except Exception as e:
|
||||
print(f"[CCA PreAuth] Could not close browser: {e}")
|
||||
|
||||
|
||||
async def start_cca_preauth_run(sid: str, data: dict, url: str):
|
||||
"""
|
||||
Run the CCA pre-authorization workflow:
|
||||
1. Login to ScionDental portal
|
||||
2. Navigate to Authorization Entry page
|
||||
3. Fill patient info and verify eligibility
|
||||
4. Fill services grid and submit authorization
|
||||
5. Capture confirmation PDF
|
||||
"""
|
||||
s = sessions.get(sid)
|
||||
if not s:
|
||||
return {"status": "error", "message": "session not found"}
|
||||
|
||||
s["status"] = "running"
|
||||
s["last_activity"] = time.time()
|
||||
bot = None
|
||||
|
||||
try:
|
||||
bot = AutomationCCAPreAuth(data)
|
||||
bot.config_driver()
|
||||
|
||||
s["bot"] = bot
|
||||
s["driver"] = bot.driver
|
||||
s["last_activity"] = time.time()
|
||||
|
||||
try:
|
||||
bot.driver.maximize_window()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# --- Login ---
|
||||
try:
|
||||
login_result = bot.login(url)
|
||||
except WebDriverException as wde:
|
||||
s["status"] = "error"
|
||||
s["message"] = f"Selenium driver error during login: {wde}"
|
||||
s["result"] = {"status": "error", "message": s["message"]}
|
||||
_close_browser(bot)
|
||||
asyncio.create_task(_remove_session_later(sid, 30))
|
||||
return {"status": "error", "message": s["message"]}
|
||||
except Exception as e:
|
||||
s["status"] = "error"
|
||||
s["message"] = f"Unexpected error during login: {e}"
|
||||
s["result"] = {"status": "error", "message": s["message"]}
|
||||
_close_browser(bot)
|
||||
asyncio.create_task(_remove_session_later(sid, 30))
|
||||
return {"status": "error", "message": s["message"]}
|
||||
|
||||
if isinstance(login_result, str) and login_result == "ALREADY_LOGGED_IN":
|
||||
print("[CCA PreAuth] Session persisted - skipping login")
|
||||
get_browser_manager().save_cookies()
|
||||
|
||||
elif isinstance(login_result, str) and login_result.startswith("ERROR"):
|
||||
s["status"] = "error"
|
||||
s["message"] = login_result
|
||||
s["result"] = {"status": "error", "message": login_result}
|
||||
_close_browser(bot)
|
||||
asyncio.create_task(_remove_session_later(sid, 30))
|
||||
return {"status": "error", "message": login_result}
|
||||
|
||||
elif isinstance(login_result, str) and login_result == "SUCCESS":
|
||||
print("[CCA PreAuth] Login succeeded")
|
||||
get_browser_manager().save_cookies()
|
||||
|
||||
# --- Navigate to Authorization Entry ---
|
||||
step1_result = bot.step1_navigate_to_auth_entry()
|
||||
print(f"[CCA PreAuth] step1 result: {step1_result}")
|
||||
|
||||
if isinstance(step1_result, str) and step1_result.startswith("ERROR"):
|
||||
s["status"] = "error"
|
||||
s["message"] = step1_result
|
||||
s["result"] = {"status": "error", "message": step1_result}
|
||||
_close_browser(bot)
|
||||
asyncio.create_task(_remove_session_later(sid, 30))
|
||||
return {"status": "error", "message": step1_result}
|
||||
|
||||
# --- Fill patient eligibility form & verify ---
|
||||
step2_result = bot.step2_fill_patient_eligibility()
|
||||
print(f"[CCA PreAuth] step2 result: {step2_result}")
|
||||
|
||||
if isinstance(step2_result, str) and step2_result.startswith("ERROR"):
|
||||
try:
|
||||
page_url = bot.driver.current_url
|
||||
body = bot.driver.find_element(
|
||||
__import__('selenium').webdriver.common.by.By.TAG_NAME, "body"
|
||||
).text[:600]
|
||||
print(f"[CCA PreAuth] step2 error — URL: {page_url}")
|
||||
print(f"[CCA PreAuth] step2 error — page text: {body}")
|
||||
except Exception:
|
||||
pass
|
||||
s["status"] = "error"
|
||||
s["message"] = step2_result
|
||||
s["result"] = {"status": "error", "message": step2_result}
|
||||
_close_browser(bot)
|
||||
asyncio.create_task(_remove_session_later(sid, 30))
|
||||
return {"status": "error", "message": step2_result}
|
||||
|
||||
# --- Fill Services grid, attach docs, submit ---
|
||||
step3_result = bot.step3_fill_services_and_submit()
|
||||
print(f"[CCA PreAuth] step3 result: {step3_result}")
|
||||
|
||||
if isinstance(step3_result, str) and step3_result.startswith("ERROR"):
|
||||
try:
|
||||
page_url = bot.driver.current_url
|
||||
body = bot.driver.find_element(
|
||||
__import__('selenium').webdriver.common.by.By.TAG_NAME, "body"
|
||||
).text[:600]
|
||||
print(f"[CCA PreAuth] step3 error — URL: {page_url}")
|
||||
print(f"[CCA PreAuth] step3 error — page text: {body}")
|
||||
except Exception:
|
||||
pass
|
||||
s["status"] = "error"
|
||||
s["message"] = step3_result
|
||||
s["result"] = {"status": "error", "message": step3_result}
|
||||
_close_browser(bot)
|
||||
asyncio.create_task(_remove_session_later(sid, 30))
|
||||
return {"status": "error", "message": step3_result}
|
||||
|
||||
# --- Capture confirmation PDF + auth number ---
|
||||
step4_result = bot.step4_capture_confirmation()
|
||||
print(f"[CCA PreAuth] step4 authNumber={step4_result.get('authNumber')}, "
|
||||
f"pdfLen={len(step4_result.get('pdfBase64', ''))}")
|
||||
|
||||
_close_browser(bot)
|
||||
|
||||
result = {
|
||||
"status": "success",
|
||||
"message": "CCA pre-authorization submitted successfully",
|
||||
"authNumber": step4_result.get("authNumber"),
|
||||
"pdfBase64": step4_result.get("pdfBase64", ""),
|
||||
"pdfFilename": step4_result.get("pdfFilename", ""),
|
||||
}
|
||||
s["status"] = "completed"
|
||||
s["result"] = result
|
||||
s["message"] = "completed"
|
||||
asyncio.create_task(_remove_session_later(sid, 60))
|
||||
return result
|
||||
|
||||
except Exception as e:
|
||||
if s:
|
||||
s["status"] = "error"
|
||||
s["message"] = f"worker exception: {e}"
|
||||
s["result"] = {"status": "error", "message": s["message"]}
|
||||
if bot:
|
||||
_close_browser(bot)
|
||||
asyncio.create_task(_remove_session_later(sid, 30))
|
||||
return {"status": "error", "message": f"worker exception: {e}"}
|
||||
|
||||
|
||||
def get_session_status(sid: str) -> Dict[str, Any]:
|
||||
s = sessions.get(sid)
|
||||
if not s:
|
||||
return {"status": "not_found"}
|
||||
return {
|
||||
"session_id": sid,
|
||||
"status": s.get("status"),
|
||||
"message": s.get("message"),
|
||||
"created_at": s.get("created_at"),
|
||||
"last_activity": s.get("last_activity"),
|
||||
"result": s.get("result") if s.get("status") in ("completed", "error") else None,
|
||||
}
|
||||
1076
apps/SeleniumService/selenium_CCA_preAuthWorker.py
Normal file
1076
apps/SeleniumService/selenium_CCA_preAuthWorker.py
Normal file
File diff suppressed because it is too large
Load Diff
Reference in New Issue
Block a user