diff --git a/apps/Backend/src/queue/jobRunner.ts b/apps/Backend/src/queue/jobRunner.ts index a36b274a..a21e1c34 100644 --- a/apps/Backend/src/queue/jobRunner.ts +++ b/apps/Backend/src/queue/jobRunner.ts @@ -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}`); }); diff --git a/apps/Backend/src/queue/processors/preAuthCheckProcessor.ts b/apps/Backend/src/queue/processors/preAuthCheckProcessor.ts new file mode 100644 index 00000000..62e1b95d --- /dev/null +++ b/apps/Backend/src/queue/processors/preAuthCheckProcessor.ts @@ -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 = { + 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 = { + 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 { + 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 { + 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 }; +} diff --git a/apps/Backend/src/queue/queues.ts b/apps/Backend/src/queue/queues.ts index 6e803cba..5fce42c2 100644 --- a/apps/Backend/src/queue/queues.ts +++ b/apps/Backend/src/queue/queues.ts @@ -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; diff --git a/apps/Backend/src/routes/appointments.ts b/apps/Backend/src/routes/appointments.ts index 759201d9..c57a1a79 100755 --- a/apps/Backend/src/routes/appointments.ts +++ b/apps/Backend/src/routes/appointments.ts @@ -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, diff --git a/apps/Backend/src/routes/claims.ts b/apps/Backend/src/routes/claims.ts index cc78b11d..17e1dfb7 100755 --- a/apps/Backend/src/routes/claims.ts +++ b/apps/Backend/src/routes/claims.ts @@ -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 => { + 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 => { } }); -// 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 => { try { diff --git a/apps/Backend/src/routes/documents.ts b/apps/Backend/src/routes/documents.ts index 5d964517..46bea80f 100755 --- a/apps/Backend/src/routes/documents.ts +++ b/apps/Backend/src/routes/documents.ts @@ -157,6 +157,7 @@ const TITLE_KEY_TO_CLOUD_CATEGORY: Record = { INSURANCE_CLAIM: "Claims", INSURANCE_CLAIM_PREAUTH: "PreAuth", CLAIM_STATUS: "Claim Status", + PREAUTH_APPROVAL: "Approval", OTHER: "Attachments", }; diff --git a/apps/Backend/src/routes/index.ts b/apps/Backend/src/routes/index.ts index 06267286..d361afcf 100755 --- a/apps/Backend/src/routes/index.ts +++ b/apps/Backend/src/routes/index.ts @@ -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); diff --git a/apps/Backend/src/routes/insuranceStatusCCAPreAuth.ts b/apps/Backend/src/routes/insuranceStatusCCAPreAuth.ts index f92ab1ad..8f921695 100644 --- a/apps/Backend/src/routes/insuranceStatusCCAPreAuth.ts +++ b/apps/Backend/src/routes/insuranceStatusCCAPreAuth.ts @@ -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); diff --git a/apps/Backend/src/routes/insuranceStatusTuftsSCOPreAuth.ts b/apps/Backend/src/routes/insuranceStatusTuftsSCOPreAuth.ts index 4521a1e8..e2e6af9f 100644 --- a/apps/Backend/src/routes/insuranceStatusTuftsSCOPreAuth.ts +++ b/apps/Backend/src/routes/insuranceStatusTuftsSCOPreAuth.ts @@ -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 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 = { + 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 => { + 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 = { + 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 => { + 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; diff --git a/apps/Backend/src/storage/appointments-storage.ts b/apps/Backend/src/storage/appointments-storage.ts index f7f05103..34c279a1 100755 --- a/apps/Backend/src/storage/appointments-storage.ts +++ b/apps/Backend/src/storage/appointments-storage.ts @@ -38,12 +38,6 @@ export interface IStorage { startTime: string, excludeId?: number ): Promise; - getPatientConflictAppointment( - patientId: number, - date: Date, - startTime: string, - excludeId: number - ): Promise; getStaffConflictAppointment( staffId: number, date: Date, @@ -175,24 +169,6 @@ export const appointmentsStorage: IStorage = { ); }, - async getPatientConflictAppointment( - patientId: number, - date: Date, - startTime: string, - excludeId: number - ): Promise { - return ( - (await db.appointment.findFirst({ - where: { - patientId, - date, - startTime, - NOT: { id: excludeId }, - }, - })) ?? undefined - ); - }, - async getStaffConflictAppointment( staffId: number, date: Date, diff --git a/apps/Backend/src/storage/cloudStorage-storage.ts b/apps/Backend/src/storage/cloudStorage-storage.ts index 35426936..005e11d1 100755 --- a/apps/Backend/src/storage/cloudStorage-storage.ts +++ b/apps/Backend/src/storage/cloudStorage-storage.ts @@ -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; listRecentAttachmentFiles(limit?: number): Promise; + 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([[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 }, diff --git a/apps/Backend/src/utils/appointmentAttachments.ts b/apps/Backend/src/utils/appointmentAttachments.ts index c0b648b1..f066d302 100644 --- a/apps/Backend/src/utils/appointmentAttachments.ts +++ b/apps/Backend/src/utils/appointmentAttachments.ts @@ -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) } : {}), + })), + }); +} diff --git a/apps/Backend/src/utils/preAuthClaim.ts b/apps/Backend/src/utils/preAuthClaim.ts new file mode 100644 index 00000000..e1c276d9 --- /dev/null +++ b/apps/Backend/src/utils/preAuthClaim.ts @@ -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 } : {}), + }; +} diff --git a/apps/Frontend/src/components/appointments/appointment-attachments.tsx b/apps/Frontend/src/components/appointments/appointment-attachments.tsx index 47c5d32a..441da94c 100644 --- a/apps/Frontend/src/components/appointments/appointment-attachments.tsx +++ b/apps/Frontend/src/components/appointments/appointment-attachments.tsx @@ -242,7 +242,7 @@ export function AppointmentAttachments({ appointmentId, patientId }: Appointment type="button" variant="ghost" size="icon" - title="Choose from scanned attachments" + title="Choose from patient files" onClick={() => setPickerOpen(true)} > @@ -315,6 +315,7 @@ export function AppointmentAttachments({ appointmentId, patientId }: Appointment open={pickerOpen} onClose={() => setPickerOpen(false)} patientId={patientId} + allFolders onFilesSelected={handleServerFilesSelected} /> diff --git a/apps/Frontend/src/components/claims/check-preauth-button.tsx b/apps/Frontend/src/components/claims/check-preauth-button.tsx new file mode 100644 index 00000000..804835da --- /dev/null +++ b/apps/Frontend/src/components/claims/check-preauth-button.tsx @@ -0,0 +1,178 @@ +import { useState, useSyncExternalStore } from "react"; +import { LoaderCircleIcon } from "lucide-react"; +import { Button } from "@/components/ui/button"; +import { Input } from "@/components/ui/input"; +import { + Dialog, + DialogContent, + DialogFooter, + DialogHeader, + DialogTitle, +} from "@/components/ui/dialog"; +import { toast } from "@/hooks/use-toast"; +import { apiRequest } from "@/lib/queryClient"; +import { socket } from "@/lib/socket"; + +// Runs the Check PreAuth worker matching the claim's insurance (the backend picks it: +// MassHealth, United SCO, Tufts SCO or CCA). +// +// Running checks live in this module, not in the button, so a check (and its OTP popup) +// keeps going after the Claim/Preauth Details window that started it is closed. +// renders the OTP popup and must stay mounted on the page. + +type OtpRequest = { jobId: string; sessionId: string; label: string }; +type State = { runningClaimIds: number[]; otp: OtpRequest | null }; + +let state: State = { runningClaimIds: [], otp: null }; +const subscribers = new Set<() => void>(); +// Jobs whose OTP popup was answered or dismissed; the backend keeps repeating +// "otp required" while it waits, which must not reopen the popup. +const otpHandledJobIds = new Set(); + +function setState(patch: Partial) { + state = { ...state, ...patch }; + subscribers.forEach((fn) => fn()); +} + +function subscribe(fn: () => void) { + subscribers.add(fn); + return () => subscribers.delete(fn); +} + +const usePreauthCheckState = () => useSyncExternalStore(subscribe, () => state); + +async function startPreauthCheck(claimId: number, onCompleted?: () => void) { + if (state.runningClaimIds.includes(claimId)) return; + setState({ runningClaimIds: [...state.runningClaimIds, claimId] }); + + let jobId = ""; + let sessionId: string | null = null; + let label = ""; + const handlers: Record void> = { + "selenium:preauth_check_session_started": (ev) => { + if (String(ev?.jobId) === jobId) sessionId = ev.session_id ?? null; + }, + "selenium:otp_required": (ev) => { + if (String(ev?.jobId) !== jobId) return; + sessionId = ev.session_id ?? sessionId; + if (sessionId && !otpHandledJobIds.has(jobId) && state.otp?.jobId !== jobId) setState({ otp: { jobId, sessionId, label } }); + }, + "job:update": (ev) => { + if (String(ev?.jobId) !== jobId || ev.status === "active") return; + if (ev.status === "completed") { + toast({ title: `${label} Check PreAuth complete`, description: ev.result?.message ?? "" }); + onCompleted?.(); + } else { + toast({ + title: `${label} Check PreAuth failed`, + description: ev.error ?? "The check did not finish.", + variant: "destructive", + }); + } + finish(); + }, + }; + const finish = () => { + Object.entries(handlers).forEach(([event, fn]) => socket.off(event, fn)); + otpHandledJobIds.delete(jobId); + setState({ + runningClaimIds: state.runningClaimIds.filter((id) => id !== claimId), + otp: state.otp?.jobId === jobId ? null : state.otp, + }); + }; + + // Listen before the request so no event from a fast job is missed. + Object.entries(handlers).forEach(([event, fn]) => socket.on(event, fn)); + try { + const res = await apiRequest("POST", "/api/claims/preauth-check", { + claimId, + socketId: socket.id, + }); + const body = await res.json(); + if (!res.ok || body.error) throw new Error(body.error || `Server error (${res.status})`); + jobId = String(body.jobId); + label = body.label ?? ""; + toast({ title: `${label} Check PreAuth started`, description: "The browser will open shortly." }); + } catch (err: any) { + toast({ title: "Check PreAuth error", description: err?.message ?? "Failed to start.", variant: "destructive" }); + finish(); + } +} + +// onCompleted runs after a successful check (the PDF is saved by then); it may fire after the +// details window has closed, so callers must guard against acting on a stale window. +export function CheckPreauthButton({ claimId, onCompleted }: { claimId: number; onCompleted?: () => void }) { + const { runningClaimIds } = usePreauthCheckState(); + const running = runningClaimIds.includes(claimId); + + return ( + + ); +} + +export function PreauthCheckHost() { + const { otp: request } = usePreauthCheckState(); + const [otp, setOtp] = useState(""); + const [submitting, setSubmitting] = useState(false); + + const close = () => { + if (request) otpHandledJobIds.add(request.jobId); + setOtp(""); + setState({ otp: null }); + }; + + const submitOtp = async () => { + if (!otp.trim() || !request) return; + setSubmitting(true); + try { + const res = await apiRequest("POST", "/api/claims/preauth-check/submit-otp", { + session_id: request.sessionId, + otp: otp.trim(), + socketId: socket.id, + }); + const body = await res.json().catch(() => ({})); + if (!res.ok || body.error) throw new Error(body.error || "Failed to submit the code"); + close(); + } catch (err: any) { + toast({ title: "Code not accepted", description: err?.message, variant: "destructive" }); + } finally { + setSubmitting(false); + } + }; + + return ( + !open && close()}> + + + Enter verification code + +

+ {request?.label} sent a verification code. Enter it here, or type it directly in the browser window. +

+ setOtp(e.target.value)} + placeholder="Verification code" + onKeyDown={(e) => e.key === "Enter" && void submitOtp()} + autoFocus + /> + + + + +
+
+ ); +} diff --git a/apps/Frontend/src/components/claims/claim-form.tsx b/apps/Frontend/src/components/claims/claim-form.tsx index 7951be0a..012485cc 100755 --- a/apps/Frontend/src/components/claims/claim-form.tsx +++ b/apps/Frontend/src/components/claims/claim-form.tsx @@ -1132,6 +1132,8 @@ export function ClaimForm({ return; } + const preAuthFilesMeta = await savePreAuthAttachments(f.uploadedFiles); + // sending form data to selenium service onHandleForMHSeleniumClaimPreAuth({ ...f, @@ -1143,6 +1145,7 @@ export function ClaimForm({ insuranceProvider: "Mass Health", insuranceSiteKey: "MH", appointmentId: appointmentId ?? 0, + claimFiles: mergeWithExistingAttachments(preAuthFilesMeta), }); // 5. Close form @@ -1698,6 +1701,8 @@ export function ClaimForm({ return; } + const preAuthFilesMeta = await savePreAuthAttachments(form.uploadedFiles); + onHandleForCCASeleniumPreAuth({ ...form, serviceLines: filteredServiceLines, @@ -1706,6 +1711,7 @@ export function ClaimForm({ insuranceProvider: "CCA", insuranceSiteKey: "CCA", appointmentId: appointmentId ?? 0, + claimFiles: mergeWithExistingAttachments(preAuthFilesMeta), }); onClose(); @@ -1849,6 +1855,21 @@ export function ClaimForm({ return (data.data ?? []) as ClaimFileMeta[]; }; + // MH and CCA send the files to Selenium in the request itself, so saving a copy for the + // claim's details must not block the submission if it fails (e.g. over the 5MB limit). + const savePreAuthAttachments = async (files?: File[]): Promise => { + try { + return await uploadAttachmentsToLocalFolder(files ?? []); + } catch (err: any) { + toast({ + title: "Attachments not saved to the PreAuth record", + description: err?.message ?? "They will still be sent with the PreAuth.", + variant: "destructive", + }); + return []; + } + }; + const handleSave = async () => { const filteredServiceLines = form.serviceLines.filter( (line) => (line.procedureCode ?? "").trim() !== "", diff --git a/apps/Frontend/src/components/claims/claim-view-modal.tsx b/apps/Frontend/src/components/claims/claim-view-modal.tsx index a4fb473c..daebffd2 100755 --- a/apps/Frontend/src/components/claims/claim-view-modal.tsx +++ b/apps/Frontend/src/components/claims/claim-view-modal.tsx @@ -6,12 +6,13 @@ import { DialogDescription, } from "@/components/ui/dialog"; import { Button } from "@/components/ui/button"; -import React from "react"; +import React, { useEffect, useRef } from "react"; import { formatDateToHumanReadable } from "@/utils/dateUtils"; import { ClaimFileMeta, ClaimWithServiceLines } from "@repo/db/types"; import { FileText, Paperclip, Printer } from "lucide-react"; import { toast } from "@/hooks/use-toast"; import { openPendingTab, showAdaClaimForm } from "@/utils/adaClaimForm"; +import { CheckPreauthButton } from "./check-preauth-button"; import { safeParseMissingTeeth, splitTeeth, @@ -68,11 +69,23 @@ export default function ClaimViewModal({ const claimFiles = getClaimFilesArray(claim); + // Check PreAuth finishes after a delay; only close this window if it is still open. + const mountedRef = useRef(true); + useEffect(() => { + mountedRef.current = true; + return () => { + mountedRef.current = false; + }; + }, []); + const closeAfterPreauthCheck = () => { + if (mountedRef.current) onOpenChange(false); + }; + return ( - Claim Details + Claim/Preauth Details Detailed view of the selected claim. @@ -379,6 +392,7 @@ export default function ClaimViewModal({ Print ADA Form )} + {claim.id != null && } + ))} + + )}
@@ -154,7 +192,9 @@ export function ServerAttachmentsPickerModal({

) : files.length === 0 ? (

- {patientId + {showAllFolders + ? "No files saved yet for this patient." + : patientId ? "No screenshots saved yet for this patient." : "No screenshots saved yet."}

@@ -175,7 +215,10 @@ export function ServerAttachmentsPickerModal({
-

{file.name}

+

{file.name}

+ {showAllFolders && file.folderName && ( +

{file.folderName}

+ )}
{isSelected && (
diff --git a/apps/Frontend/src/pages/claims-page.tsx b/apps/Frontend/src/pages/claims-page.tsx index ccaa48b8..bf677304 100755 --- a/apps/Frontend/src/pages/claims-page.tsx +++ b/apps/Frontend/src/pages/claims-page.tsx @@ -30,6 +30,7 @@ import ClaimsRecentTable, { } from "@/components/claims/claims-recent-table"; import { QK_APPOINTMENTS_BASE } from "@/pages/appointments-page"; import ClaimsOfPatientModal from "@/components/claims/claims-of-patient-table"; +import { PreauthCheckHost } from "@/components/claims/check-preauth-button"; import { Claim, UpdatePatient, @@ -1372,6 +1373,9 @@ export default function ClaimsPage() { {/* Recent Claims by Patients also handles new claims */} + {/* Check PreAuth OTP popup; here so it outlives the Claim/Preauth Details window */} + + {/* Recent Claims Section */} diff --git a/apps/Frontend/src/pages/documents-page.tsx b/apps/Frontend/src/pages/documents-page.tsx index 3cac2d1c..eb41f4ce 100755 --- a/apps/Frontend/src/pages/documents-page.tsx +++ b/apps/Frontend/src/pages/documents-page.tsx @@ -193,6 +193,7 @@ export default function DocumentsPage() { const preferredOrder = [ "INSURANCE_CLAIM", "INSURANCE_CLAIM_PREAUTH", + "PREAUTH_APPROVAL", "ELIGIBILITY_STATUS", "CLAIM_STATUS", "OTHER", diff --git a/apps/SeleniumService/agent.py b/apps/SeleniumService/agent.py index e0fed95d..11ca5316 100755 --- a/apps/SeleniumService/agent.py +++ b/apps/SeleniumService/agent.py @@ -13,6 +13,10 @@ from selenium_preAuthWorker import AutomationMassHealthPreAuth from selenium_MHSinglePaymentCheckWorker import AutomationMassHealthSinglePaymentCheck from selenium_MHBatchPaymentCheckWorker import AutomationMassHealthBatchPaymentCheck from selenium_Altus_eligibilityCheckWorker import AutomationAltusEligibilityCheck +from selenium_MH_preAuthCheckWorker import AutomationMassHealthPreAuthCheck +from selenium_UnitedSCO_preAuthCheckWorker import AutomationUnitedSCOPreAuthCheck +from selenium_TuftsSCO_preAuthCheckWorker import AutomationTuftsSCOPreAuthCheck +from selenium_CCA_preAuthCheckWorker import AutomationCCAPreAuthCheck import os import time import helpers_ddma_eligibility as hddma @@ -1253,6 +1257,93 @@ async def cca_preauth(request: Request): return {"status": "started", "session_id": sid} +# ── Check PreAuth (MH, United SCO, Tufts SCO, CCA) ────────────────────────── +# Same flow as each insurer's eligibility check, run with its own preauth-check worker. +# United SCO / Tufts SCO / CCA share the eligibility session stores, so /session/{sid}/status +# and /submit-otp already cover them. + +@app.post("/mh-preauth-check") +async def mh_preauth_check(request: Request): + global active_jobs, waiting_jobs + data = await request.json() + + async with lock: + waiting_jobs += 1 + + async with semaphore: + async with lock: + waiting_jobs -= 1 + active_jobs += 1 + try: + bot = AutomationMassHealthPreAuthCheck(data) + result = bot.main_workflow("https://provider.masshealth-dental.org/mh_provider_login") + + if result.get("status") != "success": + return {"status": "error", "message": result.get("message")} + return result + except Exception as e: + return {"status": "error", "message": str(e)} + finally: + async with lock: + active_jobs -= 1 + + +async def _preauth_check_wrapper(start_run, sid: str, data: dict, url: str, worker_cls): + """Background worker for a Check PreAuth session — acquires semaphore, updates counters.""" + global active_jobs, waiting_jobs + async with semaphore: + async with lock: + waiting_jobs -= 1 + active_jobs += 1 + try: + await start_run(sid, data, url, worker_cls=worker_cls) + finally: + async with lock: + active_jobs -= 1 + + +async def _start_preauth_check(request: Request, helper, start_run, session_type: str, url: str, worker_cls): + global waiting_jobs + + body = await request.json() + data = body.get("data", {}) + + sid = helper.make_session_entry() + helper.sessions[sid]["type"] = session_type + helper.sessions[sid]["last_activity"] = time.time() + + async with lock: + waiting_jobs += 1 + + asyncio.create_task(_preauth_check_wrapper(start_run, sid, data, url, worker_cls)) + + return {"status": "started", "session_id": sid} + + +@app.post("/unitedsco-preauth-check") +async def unitedsco_preauth_check(request: Request): + return await _start_preauth_check( + request, hunitedsco, hunitedsco.start_unitedsco_run, "unitedsco_preauth_check", + "https://app.dentalhub.com/app/login", AutomationUnitedSCOPreAuthCheck, + ) + + +@app.post("/tuftssco-preauth-check") +async def tuftssco_preauth_check(request: Request): + return await _start_preauth_check( + request, hdentaquest, hdentaquest.start_dentaquest_run, "tuftssco_preauth_check", + "https://providers.dentaquest.com/", AutomationTuftsSCOPreAuthCheck, + ) + + +@app.post("/cca-preauth-check") +async def cca_preauth_check(request: Request): + return await _start_preauth_check( + request, hcca, hcca.start_cca_run, "cca_preauth_check", + "https://pwp.sciondental.com/PWP/Landing", AutomationCCAPreAuthCheck, + ) + + @app.post("/submit-otp") async def submit_otp(request: Request): """ diff --git a/apps/SeleniumService/helpers_cca_eligibility.py b/apps/SeleniumService/helpers_cca_eligibility.py index 3514cfad..f228ebb3 100644 --- a/apps/SeleniumService/helpers_cca_eligibility.py +++ b/apps/SeleniumService/helpers_cca_eligibility.py @@ -71,7 +71,7 @@ def _close_browser(bot): print(f"[CCA] Could not close browser: {e}") -async def start_cca_run(sid: str, data: dict, url: str): +async def start_cca_run(sid: str, data: dict, url: str, worker_cls=None): """ Run the CCA eligibility check workflow (no OTP): 1. Login @@ -87,7 +87,8 @@ async def start_cca_run(sid: str, data: dict, url: str): bot = None try: - bot = AutomationCCAEligibilityCheck({"data": data}) + # worker_cls lets Check PreAuth reuse this flow with its own worker + bot = (worker_cls or AutomationCCAEligibilityCheck)({"data": data}) bot.config_driver() s["bot"] = bot diff --git a/apps/SeleniumService/helpers_dentaquest_eligibility.py b/apps/SeleniumService/helpers_dentaquest_eligibility.py index f579c332..b6d567af 100644 --- a/apps/SeleniumService/helpers_dentaquest_eligibility.py +++ b/apps/SeleniumService/helpers_dentaquest_eligibility.py @@ -66,7 +66,7 @@ async def _remove_session_later(sid: str, delay: int = 30): sessions.pop(sid, None) -async def start_dentaquest_run(sid: str, data: dict, url: str): +async def start_dentaquest_run(sid: str, data: dict, url: str, worker_cls=None): """ Run the DentaQuest workflow for a session (WITHOUT managing semaphore/counters). Called by agent.py inside a wrapper that handles queue/counters. @@ -79,7 +79,8 @@ async def start_dentaquest_run(sid: str, data: dict, url: str): s["last_activity"] = time.time() try: - bot = AutomationDentaQuestEligibilityCheck({"data": data}) + # worker_cls lets Check PreAuth reuse this flow with its own worker + bot = (worker_cls or AutomationDentaQuestEligibilityCheck)({"data": data}) bot.config_driver() s["bot"] = bot diff --git a/apps/SeleniumService/helpers_unitedsco_eligibility.py b/apps/SeleniumService/helpers_unitedsco_eligibility.py index 0df2e29e..f6bc5421 100644 --- a/apps/SeleniumService/helpers_unitedsco_eligibility.py +++ b/apps/SeleniumService/helpers_unitedsco_eligibility.py @@ -99,7 +99,7 @@ def _minimize_browser(bot): print(f"[UnitedSCO] Could not hide browser: {e}") -async def start_unitedsco_run(sid: str, data: dict, url: str): +async def start_unitedsco_run(sid: str, data: dict, url: str, worker_cls=None): """ Run the United SCO workflow for a session (WITHOUT managing semaphore/counters). Called by agent.py inside a wrapper that handles queue/counters. @@ -112,7 +112,8 @@ async def start_unitedsco_run(sid: str, data: dict, url: str): s["last_activity"] = time.time() try: - bot = AutomationUnitedSCOEligibilityCheck({"data": data}) + # worker_cls lets Check PreAuth reuse this flow with its own worker + bot = (worker_cls or AutomationUnitedSCOEligibilityCheck)({"data": data}) bot.config_driver() s["bot"] = bot diff --git a/apps/SeleniumService/selenium_CCA_preAuthCheckWorker.py b/apps/SeleniumService/selenium_CCA_preAuthCheckWorker.py new file mode 100644 index 00000000..fd5c0d18 --- /dev/null +++ b/apps/SeleniumService/selenium_CCA_preAuthCheckWorker.py @@ -0,0 +1,11 @@ +from selenium_CCA_eligibilityCheckWorker import AutomationCCAEligibilityCheck + + +class AutomationCCAPreAuthCheck(AutomationCCAEligibilityCheck): + """ + CCA (ScionDental) Check PreAuth. + + Starts with the same steps as the eligibility check: login, step1, step2. + Reuses the eligibility check's persistent browser session (same Chrome profile and cookies). + Override a step here when the preauth check needs to do something different. + """ diff --git a/apps/SeleniumService/selenium_MH_preAuthCheckWorker.py b/apps/SeleniumService/selenium_MH_preAuthCheckWorker.py new file mode 100644 index 00000000..c2f56e90 --- /dev/null +++ b/apps/SeleniumService/selenium_MH_preAuthCheckWorker.py @@ -0,0 +1,11 @@ +from selenium_eligibilityCheckWorker import AutomationMassHealthEligibilityCheck + + +class AutomationMassHealthPreAuthCheck(AutomationMassHealthEligibilityCheck): + """ + MassHealth Check PreAuth. + + Starts with the same steps as the eligibility check: login, step1, step2. + Fresh login every run (MassHealth keeps no persistent session). + Override a step here when the preauth check needs to do something different. + """ diff --git a/apps/SeleniumService/selenium_TuftsSCO_preAuthCheckWorker.py b/apps/SeleniumService/selenium_TuftsSCO_preAuthCheckWorker.py new file mode 100644 index 00000000..7fa224dc --- /dev/null +++ b/apps/SeleniumService/selenium_TuftsSCO_preAuthCheckWorker.py @@ -0,0 +1,147 @@ +from selenium.common.exceptions import TimeoutException +from selenium.webdriver.common.by import By +from selenium.webdriver.common.keys import Keys +from selenium.webdriver.support.ui import WebDriverWait +from selenium.webdriver.support import expected_conditions as EC +import base64 +import os +import time + +from selenium_DentaQuest_eligibilityCheckWorker import AutomationDentaQuestEligibilityCheck + +SUBMITTED_URL = "https://providers.dentaquest.com/pre-auth-claims/submitted/" + + +class AutomationTuftsSCOPreAuthCheck(AutomationDentaQuestEligibilityCheck): + """ + Tufts SCO (DentaQuest) Check PreAuth. + + login: same as the eligibility check (persistent browser session, OTP if asked). + step1: open Pre-authorizations and Claims > Submitted, clear the date range, + search by pre-auth / claim number. + step2: open the pre-auth from the result row and save its detail page as a PDF + (filed under the patient's Approval folder by the backend). + """ + + def __init__(self, data): + super().__init__(data) + self.preAuthNumber = str(self.data.get("preAuthNumber") or "").strip() + self.claimNumber = str(self.data.get("claimNumber") or "").strip() + + def step1(self): + number = self.preAuthNumber or self.claimNumber + if not number: + return "ERROR: This record has no pre-auth or claim number to search for." + + wait = WebDriverWait(self.driver, 30) + try: + print(f"[TuftsSCO PreAuthCheck step1] Opening {SUBMITTED_URL}") + self.driver.get(SUBMITTED_URL) + + if self._is_maintenance_page(): + return "ERROR: DentaQuest server is temporarily unavailable (maintenance). Please try again later." + + # Clear "Set date range" (defaults to the last 2 weeks) so older preauths are found + try: + clear_btn = WebDriverWait(self.driver, 15).until(EC.element_to_be_clickable( + (By.XPATH, "//button[@aria-label='Clear date range']") + )) + clear_btn.click() + print("[TuftsSCO PreAuthCheck step1] Cleared date range") + time.sleep(0.5) + except TimeoutException: + print("[TuftsSCO PreAuthCheck step1] No date range to clear") + + number_input = wait.until(EC.element_to_be_clickable( + (By.XPATH, "//input[@data-testid='claims-search_claim-number_input']") + )) + number_input.click() + number_input.send_keys(Keys.CONTROL, "a") + number_input.send_keys(Keys.DELETE) + number_input.send_keys(number) + print(f"[TuftsSCO PreAuthCheck step1] Entered number: {number}") + + search_btn = wait.until(EC.element_to_be_clickable( + (By.XPATH, "//button[@data-testid='claims-search_submit-btn']") + )) + search_btn.click() + print("[TuftsSCO PreAuthCheck step1] Clicked Search") + return "SUCCESS" + except TimeoutException: + return "ERROR: Pre-auth/claim search form not found on the Submitted page." + except Exception as e: + return f"ERROR: Pre-auth search failed: {e}" + + def step2(self): + number = self.preAuthNumber or self.claimNumber + try: + # 1) Wait for the result row and click the pre-auth number in its first column + try: + id_link = WebDriverWait(self.driver, 30).until(EC.element_to_be_clickable( + (By.XPATH, f"//tbody//tr[1]/*[1]//*[self::a or self::button][contains(normalize-space(.), '{number}')]") + )) + except TimeoutException: + body = self.driver.find_element(By.TAG_NAME, "body").text + if "0 records found" in body or "no records" in body.lower() or "no results" in body.lower(): + return {"status": "error", "message": f"Tufts SCO found no pre-auth/claim #{number}."} + return {"status": "error", "message": f"Search result for #{number} did not load."} + # Status column of the result row (e.g. "Approved"), read before leaving the page + status = "" + try: + headers = [h.text.strip().lower() for h in self.driver.find_elements(By.XPATH, "//thead//th")] + cells = self.driver.find_elements(By.XPATH, "//tbody//tr[1]/td") + if "status" in headers and headers.index("status") < len(cells): + status = cells[headers.index("status")].text.strip() + except Exception: + pass + print(f"[TuftsSCO PreAuthCheck step2] Status: {status!r}") + + id_link.click() + print(f"[TuftsSCO PreAuthCheck step2] Opened #{number}") + + # 2) Wait for the detail page ("Pre-authorization for ") + try: + WebDriverWait(self.driver, 30).until(EC.presence_of_element_located( + (By.XPATH, f"//h1[contains(., '{number}')] | //*[self::h1 or self::h2][contains(., 'for ')][contains(., '{number}')]") + )) + WebDriverWait(self.driver, 30).until(EC.presence_of_element_located( + (By.XPATH, "//*[contains(normalize-space(.), 'Procedure information')]") + )) + except TimeoutException: + return {"status": "error", "message": f"Detail page for #{number} did not load."} + time.sleep(2) # let the procedure table finish rendering + + # 3) The page's Print button opens Chrome's print dialog, which Selenium can't drive; + # printing to PDF through DevTools produces the same printable page. + pdf = self.driver.execute_cdp_cmd("Page.printToPDF", { + "printBackground": True, + "paperWidth": 8.5, + "paperHeight": 11, + "marginTop": 0.4, + "marginBottom": 0.4, + "marginLeft": 0.4, + "marginRight": 0.4, + }) + pdf_path = os.path.join( + self.download_dir, f"tuftssco_preauth_approval_{number}_{int(time.time())}.pdf" + ) + with open(pdf_path, "wb") as f: + f.write(base64.b64decode(pdf.get("data", ""))) + print(f"[TuftsSCO PreAuthCheck step2] PDF saved: {pdf_path}") + + # Leave the browser idle so the session stays logged in for the next run + try: + self.driver.get("about:blank") + self.driver.minimize_window() + except Exception: + pass + + return { + "status": "success", + "message": f"Tufts SCO pre-auth #{number}" + (f": {status}." if status else "."), + "preAuthNumber": number, + "preAuthStatus": status, + "approval_pdf_path": pdf_path, + } + except Exception as e: + return {"status": "error", "message": f"Tufts SCO pre-auth check failed: {e}"} diff --git a/apps/SeleniumService/selenium_UnitedSCO_preAuthCheckWorker.py b/apps/SeleniumService/selenium_UnitedSCO_preAuthCheckWorker.py new file mode 100644 index 00000000..ea12165a --- /dev/null +++ b/apps/SeleniumService/selenium_UnitedSCO_preAuthCheckWorker.py @@ -0,0 +1,11 @@ +from selenium_UnitedSCO_eligibilityCheckWorker import AutomationUnitedSCOEligibilityCheck + + +class AutomationUnitedSCOPreAuthCheck(AutomationUnitedSCOEligibilityCheck): + """ + United SCO (DentalHub) Check PreAuth. + + Starts with the same steps as the eligibility check: login, step1, step2. + Reuses the eligibility check's persistent browser session (same Chrome profile and cookies). + Override a step here when the preauth check needs to do something different. + """ diff --git a/packages/db/generated/prisma/edge.js b/packages/db/generated/prisma/edge.js index 1a743588..0f4dd370 100644 --- a/packages/db/generated/prisma/edge.js +++ b/packages/db/generated/prisma/edge.js @@ -618,6 +618,7 @@ exports.PdfTitleKey = exports.$Enums.PdfTitleKey = { INSURANCE_CLAIM_PREAUTH: 'INSURANCE_CLAIM_PREAUTH', ELIGIBILITY_STATUS: 'ELIGIBILITY_STATUS', CLAIM_STATUS: 'CLAIM_STATUS', + PREAUTH_APPROVAL: 'PREAUTH_APPROVAL', OTHER: 'OTHER' }; @@ -718,7 +719,7 @@ const config = { "clientVersion": "7.4.1", "engineVersion": "55ae170b1ced7fc6ed07a15f110549408c501bb3", "activeProvider": "postgresql", - "inlineSchema": "// This is your Prisma schema file,\n// learn more about it in the docs: https://pris.ly/d/prisma-schema\n\n// Looking for ways to speed up your queries, or scale easily with your serverless or edge functions?\n// Try Prisma Accelerate: https://pris.ly/cli/accelerate-init\n\ngenerator client {\n provider = \"prisma-client-js\"\n output = \"../generated/prisma\"\n}\n\ngenerator zod {\n provider = \"prisma-zod-generator\"\n output = \"../shared/\" // Zod schemas will be generated here inside `db/shared`\n}\n\ndatasource db {\n provider = \"postgresql\"\n}\n\nmodel User {\n id Int @id @default(autoincrement())\n username String @unique\n password String\n autoBackupEnabled Boolean @default(true)\n autoBackupHour Int @default(20)\n usbBackupEnabled Boolean @default(false)\n usbBackupHour Int @default(21)\n autoMhCheckEnabled Boolean @default(false)\n autoMhCheckDayOfWeek Int @default(1)\n autoMhCheckHour Int @default(13)\n patients Patient[]\n appointments Appointment[]\n staff Staff[]\n npiProviders NpiProvider[]\n claims Claim[]\n insuranceCredentials InsuranceCredential[]\n shoppingVendors ShoppingVendor[]\n updatedPayments Payment[] @relation(\"PaymentUpdatedBy\")\n backups DatabaseBackup[]\n backupDestinations BackupDestination[]\n notifications Notification[]\n cloudFolders CloudFolder[]\n cloudFiles CloudFile[]\n communications Communication[]\n twilioSettings TwilioSettings?\n telnyxSettings TelnyxSettings?\n aiSettings AiSettings?\n officeHours OfficeHours?\n officeContact OfficeContact?\n procedureTimeslot ProcedureTimeslot?\n insuranceContacts InsuranceContact[]\n patientConversations PatientConversation[]\n labRxTemplates LabRxTemplate[]\n seleniumSettings SeleniumSettings?\n}\n\nmodel Patient {\n id Int @id @default(autoincrement())\n firstName String\n lastName String\n dateOfBirth DateTime? @db.Date\n gender String\n phone String\n email String?\n address String?\n city String?\n state String? @default(\"MA\")\n zipCode String?\n insuranceProvider String?\n insuranceId String?\n groupNumber String?\n policyHolder String?\n policyHolderPatientId Int? // patient record of the policy holder, when picked from the DB\n policyHolderRelationship String? // ADA box 18: SELF | SPOUSE | DEPENDENT | OTHER\n allergies String?\n medicalConditions String?\n preferredLanguage String? @default(\"English\")\n status PatientStatus @default(UNKNOWN)\n remainingBenefit String?\n thirdPartyInsurance String?\n userId Int\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n user User @relation(fields: [userId], references: [id])\n appointments Appointment[]\n procedures AppointmentProcedure[]\n claims Claim[]\n groups PdfGroup[]\n payment Payment[]\n communications Communication[]\n documents PatientDocument[]\n conversation PatientConversation?\n cloudFolders CloudFolder[] @relation(\"PatientCloudFolder\")\n serviceHistory PatientServiceHistory[]\n\n @@index([insuranceId])\n @@index([createdAt])\n}\n\nenum PatientStatus {\n ACTIVE\n INACTIVE\n UNKNOWN\n PLAN_NOT_ACCEPTED\n}\n\nmodel Appointment {\n id Int @id @default(autoincrement())\n patientId Int\n userId Int\n staffId Int\n npiProviderId Int?\n title String\n date DateTime @db.Date\n startTime String // Store time as \"hh:mm\"\n endTime String // Store time as \"hh:mm\"\n type String // e.g., \"checkup\", \"cleaning\", \"filling\", etc.\n typeLocked Boolean @default(false) // true = user manually set; auto-sync will not overwrite\n notes String?\n procedureCodeNotes String?\n status String @default(\"scheduled\") // \"scheduled\", \"completed\", \"cancelled\", \"no-show\"\n movedByAi Boolean @default(false)\n createdAt DateTime @default(now())\n\n eligibilityStatus PatientStatus @default(UNKNOWN)\n\n patient Patient @relation(fields: [patientId], references: [id], onDelete: Cascade)\n user User @relation(fields: [userId], references: [id])\n staff Staff? @relation(fields: [staffId], references: [id])\n npiProvider NpiProvider? @relation(fields: [npiProviderId], references: [id])\n procedures AppointmentProcedure[]\n claims Claim[]\n files AppointmentFile[]\n\n @@index([patientId])\n @@index([date])\n}\n\nmodel AppointmentFile {\n id Int @id @default(autoincrement())\n appointmentId Int\n filename String\n mimeType String?\n filePath String?\n\n appointment Appointment @relation(fields: [appointmentId], references: [id], onDelete: Cascade)\n\n @@index([appointmentId])\n}\n\nmodel Staff {\n id Int @id @default(autoincrement())\n userId Int\n name String\n email String?\n role String // e.g., \"Dentist\", \"Hygienist\", \"Assistant\"\n phone String?\n createdAt DateTime @default(now())\n user User? @relation(fields: [userId], references: [id], onDelete: Cascade)\n appointments Appointment[]\n claims Claim[] @relation(\"ClaimStaff\")\n}\n\nmodel NpiProvider {\n id Int @id @default(autoincrement())\n userId Int\n npiNumber String\n providerName String\n /// State dental license (ADA claim form item 55)\n licenseNumber String?\n sortOrder Int @default(0)\n createdAt DateTime @default(now())\n\n user User @relation(fields: [userId], references: [id], onDelete: Cascade)\n claims Claim[]\n payments Payment[]\n commissionBatches CommissionBatch[]\n appointmentProcedures AppointmentProcedure[]\n appointments Appointment[]\n\n @@unique([userId, npiNumber])\n @@index([userId])\n}\n\nenum ProcedureSource {\n COMBO\n MANUAL\n}\n\nmodel AppointmentProcedure {\n id Int @id @default(autoincrement())\n appointmentId Int\n patientId Int\n npiProviderId Int?\n\n procedureCode String\n procedureLabel String?\n fee Decimal? @db.Decimal(10, 2)\n\n category String?\n\n toothNumber String?\n toothSurface String?\n oralCavityArea String?\n\n source ProcedureSource @default(MANUAL)\n comboKey String?\n\n createdAt DateTime @default(now())\n\n appointment Appointment @relation(fields: [appointmentId], references: [id], onDelete: Cascade)\n patient Patient @relation(fields: [patientId], references: [id], onDelete: Cascade)\n npiProvider NpiProvider? @relation(fields: [npiProviderId], references: [id])\n\n @@index([appointmentId])\n @@index([patientId])\n}\n\nmodel Claim {\n id Int @id @default(autoincrement())\n patientId Int\n /// @zod.number.int().nullable().optional()\n appointmentId Int?\n userId Int\n staffId Int\n patientName String\n memberId String\n dateOfBirth DateTime @db.Date\n remarks String\n missingTeethStatus MissingTeethStatus @default(No_missing)\n missingTeeth Json? // { \"T_14\": \"X\", \"T_G\": \"O\", ... }\n serviceDate DateTime\n insuranceProvider String // e.g., \"Delta MA\"\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n status ClaimStatus @default(PENDING)\n claimNumber String?\n preAuthNumber String?\n npiProviderId Int?\n\n patient Patient @relation(fields: [patientId], references: [id], onDelete: Cascade)\n appointment Appointment? @relation(fields: [appointmentId], references: [id], onDelete: Cascade)\n user User? @relation(fields: [userId], references: [id])\n staff Staff? @relation(\"ClaimStaff\", fields: [staffId], references: [id])\n npiProvider NpiProvider? @relation(fields: [npiProviderId], references: [id])\n\n serviceLines ServiceLine[]\n claimFiles ClaimFile[]\n payment Payment?\n}\n\nenum ClaimStatus {\n PENDING\n APPROVED\n CANCELLED\n REVIEW\n VOID\n PREAUTH\n}\n\nenum MissingTeethStatus {\n No_missing\n endentulous\n Yes_missing\n}\n\nmodel ServiceLine {\n id Int @id @default(autoincrement())\n claimId Int?\n paymentId Int?\n procedureCode String\n procedureDate DateTime @db.Date\n quad String?\n arch String?\n toothNumber String?\n toothSurface String?\n icn String?\n paidCode String?\n allowedAmount Decimal? @db.Decimal(10, 2)\n totalBilled Decimal @db.Decimal(10, 2)\n totalPaid Decimal @default(0.00) @db.Decimal(10, 2)\n totalAdjusted Decimal @default(0.00) @db.Decimal(10, 2)\n totalDue Decimal @default(0.00) @db.Decimal(10, 2)\n status ServiceLineStatus @default(UNPAID)\n\n claim Claim? @relation(fields: [claimId], references: [id], onDelete: Cascade)\n payment Payment? @relation(fields: [paymentId], references: [id], onDelete: Cascade)\n\n serviceLineTransactions ServiceLineTransaction[]\n}\n\nenum ServiceLineStatus {\n PENDING\n PARTIALLY_PAID\n PAID\n UNPAID\n ADJUSTED\n OVERPAID\n DENIED\n}\n\nmodel ClaimFile {\n id Int @id @default(autoincrement())\n claimId Int\n filename String\n mimeType String\n filePath String?\n\n claim Claim @relation(fields: [claimId], references: [id], onDelete: Cascade)\n}\n\nmodel InsuranceCredential {\n id Int @id @default(autoincrement())\n userId Int\n siteKey String\n username String\n password String\n\n user User @relation(fields: [userId], references: [id], onDelete: Cascade)\n\n @@unique([userId, siteKey])\n @@index([userId])\n}\n\nmodel ShoppingVendor {\n id Int @id @default(autoincrement())\n userId Int\n vendorName String\n websiteUrl String\n loginUsername String\n loginPassword String\n\n user User @relation(fields: [userId], references: [id], onDelete: Cascade)\n\n @@index([userId])\n}\n\nmodel PdfGroup {\n id Int @id @default(autoincrement())\n title String\n titleKey PdfTitleKey @default(OTHER)\n createdAt DateTime @default(now())\n patientId Int\n patient Patient @relation(fields: [patientId], references: [id], onDelete: Cascade)\n pdfs PdfFile[]\n\n @@index([patientId])\n @@index([titleKey])\n}\n\nmodel PdfFile {\n id Int @id @default(autoincrement())\n filename String\n pdfData Bytes\n uploadedAt DateTime @default(now())\n groupId Int\n group PdfGroup @relation(fields: [groupId], references: [id], onDelete: Cascade)\n\n @@index([groupId])\n}\n\nenum PdfTitleKey {\n INSURANCE_CLAIM\n INSURANCE_CLAIM_PREAUTH\n ELIGIBILITY_STATUS\n CLAIM_STATUS\n OTHER\n}\n\nmodel Payment {\n id Int @id @default(autoincrement())\n claimId Int? @unique\n patientId Int\n userId Int\n updatedById Int?\n npiProviderId Int?\n totalBilled Decimal @db.Decimal(10, 2)\n totalPaid Decimal @default(0.00) @db.Decimal(10, 2)\n totalAdjusted Decimal @default(0.00) @db.Decimal(10, 2)\n totalDue Decimal @db.Decimal(10, 2)\n mhPaidAmount Decimal? @db.Decimal(10, 2)\n copayment Decimal @default(0.00) @db.Decimal(10, 2)\n adjustment Decimal @default(0.00) @db.Decimal(10, 2)\n status PaymentStatus @default(PENDING)\n notes String?\n icn String?\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n\n claim Claim? @relation(fields: [claimId], references: [id], onDelete: Cascade)\n patient Patient @relation(fields: [patientId], references: [id], onDelete: Cascade)\n updatedBy User? @relation(\"PaymentUpdatedBy\", fields: [updatedById], references: [id])\n npiProvider NpiProvider? @relation(fields: [npiProviderId], references: [id])\n serviceLineTransactions ServiceLineTransaction[]\n serviceLines ServiceLine[]\n commissionBatchItems CommissionBatchItem[]\n\n @@index([claimId])\n @@index([patientId])\n @@index([createdAt])\n}\n\nmodel ServiceLineTransaction {\n id Int @id @default(autoincrement())\n paymentId Int\n serviceLineId Int\n transactionId String?\n paidAmount Decimal @db.Decimal(10, 2)\n adjustedAmount Decimal @default(0.00) @db.Decimal(10, 2)\n method PaymentMethod\n receivedDate DateTime\n payerName String?\n notes String?\n createdAt DateTime @default(now())\n\n payment Payment @relation(fields: [paymentId], references: [id], onDelete: Cascade)\n serviceLine ServiceLine @relation(fields: [serviceLineId], references: [id], onDelete: Cascade)\n\n @@index([paymentId])\n @@index([serviceLineId])\n}\n\nenum PaymentStatus {\n PENDING\n PARTIALLY_PAID\n PAID\n OVERPAID\n DENIED\n VOID\n}\n\nenum PaymentMethod {\n EFT\n CHECK\n CASH\n CARD\n OTHER\n}\n\n// Database management page\nmodel DatabaseBackup {\n id Int @id @default(autoincrement())\n userId Int\n createdAt DateTime @default(now())\n\n user User @relation(fields: [userId], references: [id], onDelete: Cascade)\n\n @@index([userId])\n @@index([createdAt])\n}\n\nmodel BackupDestination {\n id Int @id @default(autoincrement())\n userId Int\n path String\n isActive Boolean @default(true)\n createdAt DateTime @default(now())\n\n user User @relation(fields: [userId], references: [id])\n}\n\nmodel Notification {\n id Int @id @default(autoincrement())\n userId Int\n type NotificationTypes\n message String\n createdAt DateTime @default(now())\n read Boolean @default(false)\n\n user User @relation(fields: [userId], references: [id], onDelete: Cascade)\n\n @@index([userId])\n @@index([createdAt])\n}\n\nenum NotificationTypes {\n BACKUP\n CLAIM\n PAYMENT\n ETC\n}\n\n// Cron job execution log\nmodel CronJobLog {\n id Int @id @default(autoincrement())\n jobName String // e.g. \"local-backup\", \"usb-backup\"\n status String // \"success\" | \"failed\" | \"skipped\"\n startedAt DateTime\n completedAt DateTime?\n durationMs Int?\n errorMessage String?\n\n @@index([jobName])\n @@index([startedAt])\n @@index([status])\n}\n\nmodel CloudFolder {\n id Int @id @default(autoincrement())\n userId Int\n name String\n parentId Int?\n patientId Int?\n parent CloudFolder? @relation(\"FolderChildren\", fields: [parentId], references: [id], onDelete: Cascade)\n children CloudFolder[] @relation(\"FolderChildren\")\n user User @relation(fields: [userId], references: [id])\n patient Patient? @relation(\"PatientCloudFolder\", fields: [patientId], references: [id], onDelete: SetNull)\n files CloudFile[]\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n\n @@unique([userId, parentId, name]) // prevents sibling folder name duplicates\n @@index([parentId])\n @@index([patientId])\n}\n\nmodel CloudFile {\n id Int @id @default(autoincrement())\n userId Int\n name String\n mimeType String?\n fileSize BigInt @db.BigInt\n folderId Int? // optional: null => root\n isComplete Boolean @default(false) // upload completed?\n totalChunks Int? // optional: expected number of chunks\n diskPath String? // relative path on disk under uploads/\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n user User @relation(fields: [userId], references: [id])\n folder CloudFolder? @relation(fields: [folderId], references: [id], onDelete: SetNull)\n\n chunks CloudFileChunk[]\n\n @@index([folderId])\n}\n\nmodel CloudFileChunk {\n id Int @id @default(autoincrement())\n fileId Int\n seq Int\n data Bytes\n createdAt DateTime @default(now())\n\n file CloudFile @relation(fields: [fileId], references: [id], onDelete: Cascade)\n\n @@unique([fileId, seq])\n @@index([fileId, seq])\n}\n\n// patient-connection-\nenum CommunicationChannel {\n sms\n voice\n}\n\nenum CommunicationDirection {\n outbound\n inbound\n}\n\nenum CommunicationStatus {\n queued\n sent\n delivered\n failed\n completed\n busy\n no_answer\n}\n\nenum CommunicationProvider {\n twilio\n telnyx\n}\n\nmodel Communication {\n id Int @id @default(autoincrement())\n patientId Int\n userId Int?\n\n channel CommunicationChannel\n direction CommunicationDirection\n status CommunicationStatus\n // Which platform produced twilioSid — twilio for dial-pad-originated calls,\n // telnyx for everything else (SMS, inbound/AI voice, staff-triggered outbound calls).\n provider CommunicationProvider @default(twilio)\n\n body String?\n callDuration Int?\n // Provider SID — Twilio MessageSid/CallSid, or Telnyx message/call id. See `provider`.\n twilioSid String?\n\n createdAt DateTime @default(now())\n\n // Relations\n patient Patient @relation(fields: [patientId], references: [id])\n user User? @relation(fields: [userId], references: [id])\n\n @@map(\"communications\")\n}\n\nmodel PatientDocument {\n id Int @id @default(autoincrement())\n patientId Int\n filename String\n originalName String\n mimeType String\n fileSize BigInt\n filePath String\n uploadedAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n patient Patient @relation(fields: [patientId], references: [id], onDelete: Cascade)\n\n @@index([patientId])\n @@index([uploadedAt])\n}\n\nmodel TwilioSettings {\n id Int @id @default(autoincrement())\n userId Int @unique\n accountSid String\n authToken String\n phoneNumber String\n // Vestigial — inbound voice moved to Telnyx (TelnyxSettings.greetingMessage). No longer\n // read/written; kept to avoid a destructive migration for a cosmetic cleanup.\n greetingMessage String?\n templates Json?\n\n user User @relation(fields: [userId], references: [id], onDelete: Cascade)\n\n @@map(\"twilio_settings\")\n}\n\nmodel TelnyxSettings {\n id Int @id @default(autoincrement())\n userId Int @unique\n apiKey String\n // Telnyx account SID (Mission Control Portal), required to place outbound\n // TeXML calls via POST /texml/Accounts/{accountSid}/Calls — separate from apiKey.\n accountSid String?\n phoneNumber String\n texmlApplicationId String?\n messagingProfileId String?\n webhookPublicKey String?\n greetingMessage String?\n\n user User @relation(fields: [userId], references: [id], onDelete: Cascade)\n\n @@map(\"telnyx_settings\")\n}\n\nmodel AiSettings {\n id Int @id @default(autoincrement())\n userId Int @unique\n apiKey String\n aiEnabled Boolean @default(true)\n openAiKey String @default(\"\")\n openAiEnabled Boolean @default(false)\n claudeAiKey String @default(\"\")\n claudeAiEnabled Boolean @default(false)\n claudeAiModel String @default(\"claude-haiku-4-5-20251001\")\n openAiModel String @default(\"gpt-5.2\")\n googleAiModel String @default(\"gemini-2.5-flash\")\n dentalMgmtKey String @default(\"\")\n dentalMgmtEnabled Boolean @default(false)\n afterHoursEnabled Boolean @default(true)\n openPhoneReply Boolean @default(false)\n\n user User @relation(fields: [userId], references: [id], onDelete: Cascade)\n\n @@map(\"ai_settings\")\n}\n\nmodel OfficeHours {\n id Int @id @default(autoincrement())\n userId Int @unique\n data Json\n\n user User @relation(fields: [userId], references: [id], onDelete: Cascade)\n\n @@map(\"office_hours\")\n}\n\nmodel OfficeContact {\n id Int @id @default(autoincrement())\n userId Int @unique\n /// Legal (registered) business name — ADA claim form items 48 and 56\n legalName String?\n /// Dental office name as the public knows it (DBA)\n officeName String?\n receptionistName String?\n dentistName String?\n phoneNumber String?\n email String?\n fax String?\n streetAddress String?\n city String?\n state String?\n zipCode String?\n /// Office (billing) NPI — ADA claim form items 48-51\n billingName String?\n billingNpi String?\n billingLicense String?\n billingTaxId String?\n\n user User @relation(fields: [userId], references: [id], onDelete: Cascade)\n\n @@map(\"office_contact\")\n}\n\nmodel InsuranceContact {\n id Int @id @default(autoincrement())\n userId Int\n name String\n phoneNumber String?\n createdAt DateTime @default(now())\n\n user User @relation(fields: [userId], references: [id], onDelete: Cascade)\n\n @@map(\"insurance_contact\")\n}\n\nmodel ProcedureTimeslot {\n id Int @id @default(autoincrement())\n userId Int @unique\n data Json\n\n user User @relation(fields: [userId], references: [id], onDelete: Cascade)\n\n @@map(\"procedure_timeslot\")\n}\n\nmodel PatientConversation {\n id Int @id @default(autoincrement())\n patientId Int @unique\n userId Int\n stage String @default(\"initial\")\n aiHandoff Boolean @default(true)\n updatedAt DateTime @updatedAt\n\n patient Patient @relation(fields: [patientId], references: [id], onDelete: Cascade)\n user User @relation(fields: [userId], references: [id], onDelete: Cascade)\n\n @@map(\"patient_conversation\")\n}\n\n// Snapshot of the MassHealth Service History table, replaced on each eligibility check\nmodel PatientServiceHistory {\n id Int @id @default(autoincrement())\n patientId Int\n procedureCode String\n description String?\n toothQuadArchSurface String?\n placeOfService String?\n serviceDate String? // as shown by the portal, e.g. 10/15/2026\n createdAt DateTime @default(now())\n\n patient Patient @relation(fields: [patientId], references: [id], onDelete: Cascade)\n\n @@index([patientId])\n @@map(\"patient_service_history\")\n}\n\nmodel LabRxTemplate {\n id Int @id @default(autoincrement())\n userId Int\n name String\n labName String?\n labPhone String?\n labFax String?\n labAddress String?\n labAccount String?\n caseType String?\n material String?\n instructions String?\n sortOrder Int @default(0)\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n\n user User @relation(fields: [userId], references: [id], onDelete: Cascade)\n\n @@index([userId])\n @@map(\"lab_rx_template\")\n}\n\n// Commission tracking\nmodel CommissionBatch {\n id Int @id @default(autoincrement())\n npiProviderId Int\n totalCollection Decimal @db.Decimal(14, 2)\n commissionAmount Decimal @db.Decimal(14, 2)\n notes String?\n createdAt DateTime @default(now())\n\n npiProvider NpiProvider @relation(fields: [npiProviderId], references: [id])\n items CommissionBatchItem[]\n\n @@index([npiProviderId])\n}\n\nmodel CommissionBatchItem {\n id Int @id @default(autoincrement())\n commissionBatchId Int\n paymentId Int\n collectionAmount Decimal @db.Decimal(14, 2)\n\n commissionBatch CommissionBatch @relation(fields: [commissionBatchId], references: [id], onDelete: Cascade)\n payment Payment @relation(fields: [paymentId], references: [id])\n\n @@unique([commissionBatchId, paymentId])\n @@index([paymentId])\n}\n\nmodel SeleniumSettings {\n id Int @id @default(autoincrement())\n userId Int @unique\n paymentGroupId String @default(\"\")\n\n user User @relation(fields: [userId], references: [id], onDelete: Cascade)\n\n @@map(\"selenium_settings\")\n}\n" + "inlineSchema": "// This is your Prisma schema file,\n// learn more about it in the docs: https://pris.ly/d/prisma-schema\n\n// Looking for ways to speed up your queries, or scale easily with your serverless or edge functions?\n// Try Prisma Accelerate: https://pris.ly/cli/accelerate-init\n\ngenerator client {\n provider = \"prisma-client-js\"\n output = \"../generated/prisma\"\n}\n\ngenerator zod {\n provider = \"prisma-zod-generator\"\n output = \"../shared/\" // Zod schemas will be generated here inside `db/shared`\n}\n\ndatasource db {\n provider = \"postgresql\"\n}\n\nmodel User {\n id Int @id @default(autoincrement())\n username String @unique\n password String\n autoBackupEnabled Boolean @default(true)\n autoBackupHour Int @default(20)\n usbBackupEnabled Boolean @default(false)\n usbBackupHour Int @default(21)\n autoMhCheckEnabled Boolean @default(false)\n autoMhCheckDayOfWeek Int @default(1)\n autoMhCheckHour Int @default(13)\n patients Patient[]\n appointments Appointment[]\n staff Staff[]\n npiProviders NpiProvider[]\n claims Claim[]\n insuranceCredentials InsuranceCredential[]\n shoppingVendors ShoppingVendor[]\n updatedPayments Payment[] @relation(\"PaymentUpdatedBy\")\n backups DatabaseBackup[]\n backupDestinations BackupDestination[]\n notifications Notification[]\n cloudFolders CloudFolder[]\n cloudFiles CloudFile[]\n communications Communication[]\n twilioSettings TwilioSettings?\n telnyxSettings TelnyxSettings?\n aiSettings AiSettings?\n officeHours OfficeHours?\n officeContact OfficeContact?\n procedureTimeslot ProcedureTimeslot?\n insuranceContacts InsuranceContact[]\n patientConversations PatientConversation[]\n labRxTemplates LabRxTemplate[]\n seleniumSettings SeleniumSettings?\n}\n\nmodel Patient {\n id Int @id @default(autoincrement())\n firstName String\n lastName String\n dateOfBirth DateTime? @db.Date\n gender String\n phone String\n email String?\n address String?\n city String?\n state String? @default(\"MA\")\n zipCode String?\n insuranceProvider String?\n insuranceId String?\n groupNumber String?\n policyHolder String?\n policyHolderPatientId Int? // patient record of the policy holder, when picked from the DB\n policyHolderRelationship String? // ADA box 18: SELF | SPOUSE | DEPENDENT | OTHER\n allergies String?\n medicalConditions String?\n preferredLanguage String? @default(\"English\")\n status PatientStatus @default(UNKNOWN)\n remainingBenefit String?\n thirdPartyInsurance String?\n userId Int\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n user User @relation(fields: [userId], references: [id])\n appointments Appointment[]\n procedures AppointmentProcedure[]\n claims Claim[]\n groups PdfGroup[]\n payment Payment[]\n communications Communication[]\n documents PatientDocument[]\n conversation PatientConversation?\n cloudFolders CloudFolder[] @relation(\"PatientCloudFolder\")\n serviceHistory PatientServiceHistory[]\n\n @@index([insuranceId])\n @@index([createdAt])\n}\n\nenum PatientStatus {\n ACTIVE\n INACTIVE\n UNKNOWN\n PLAN_NOT_ACCEPTED\n}\n\nmodel Appointment {\n id Int @id @default(autoincrement())\n patientId Int\n userId Int\n staffId Int\n npiProviderId Int?\n title String\n date DateTime @db.Date\n startTime String // Store time as \"hh:mm\"\n endTime String // Store time as \"hh:mm\"\n type String // e.g., \"checkup\", \"cleaning\", \"filling\", etc.\n typeLocked Boolean @default(false) // true = user manually set; auto-sync will not overwrite\n notes String?\n procedureCodeNotes String?\n status String @default(\"scheduled\") // \"scheduled\", \"completed\", \"cancelled\", \"no-show\"\n movedByAi Boolean @default(false)\n createdAt DateTime @default(now())\n\n eligibilityStatus PatientStatus @default(UNKNOWN)\n\n patient Patient @relation(fields: [patientId], references: [id], onDelete: Cascade)\n user User @relation(fields: [userId], references: [id])\n staff Staff? @relation(fields: [staffId], references: [id])\n npiProvider NpiProvider? @relation(fields: [npiProviderId], references: [id])\n procedures AppointmentProcedure[]\n claims Claim[]\n files AppointmentFile[]\n\n @@index([patientId])\n @@index([date])\n}\n\nmodel AppointmentFile {\n id Int @id @default(autoincrement())\n appointmentId Int\n filename String\n mimeType String?\n filePath String?\n\n appointment Appointment @relation(fields: [appointmentId], references: [id], onDelete: Cascade)\n\n @@index([appointmentId])\n}\n\nmodel Staff {\n id Int @id @default(autoincrement())\n userId Int\n name String\n email String?\n role String // e.g., \"Dentist\", \"Hygienist\", \"Assistant\"\n phone String?\n createdAt DateTime @default(now())\n user User? @relation(fields: [userId], references: [id], onDelete: Cascade)\n appointments Appointment[]\n claims Claim[] @relation(\"ClaimStaff\")\n}\n\nmodel NpiProvider {\n id Int @id @default(autoincrement())\n userId Int\n npiNumber String\n providerName String\n /// State dental license (ADA claim form item 55)\n licenseNumber String?\n sortOrder Int @default(0)\n createdAt DateTime @default(now())\n\n user User @relation(fields: [userId], references: [id], onDelete: Cascade)\n claims Claim[]\n payments Payment[]\n commissionBatches CommissionBatch[]\n appointmentProcedures AppointmentProcedure[]\n appointments Appointment[]\n\n @@unique([userId, npiNumber])\n @@index([userId])\n}\n\nenum ProcedureSource {\n COMBO\n MANUAL\n}\n\nmodel AppointmentProcedure {\n id Int @id @default(autoincrement())\n appointmentId Int\n patientId Int\n npiProviderId Int?\n\n procedureCode String\n procedureLabel String?\n fee Decimal? @db.Decimal(10, 2)\n\n category String?\n\n toothNumber String?\n toothSurface String?\n oralCavityArea String?\n\n source ProcedureSource @default(MANUAL)\n comboKey String?\n\n createdAt DateTime @default(now())\n\n appointment Appointment @relation(fields: [appointmentId], references: [id], onDelete: Cascade)\n patient Patient @relation(fields: [patientId], references: [id], onDelete: Cascade)\n npiProvider NpiProvider? @relation(fields: [npiProviderId], references: [id])\n\n @@index([appointmentId])\n @@index([patientId])\n}\n\nmodel Claim {\n id Int @id @default(autoincrement())\n patientId Int\n /// @zod.number.int().nullable().optional()\n appointmentId Int?\n userId Int\n staffId Int\n patientName String\n memberId String\n dateOfBirth DateTime @db.Date\n remarks String\n missingTeethStatus MissingTeethStatus @default(No_missing)\n missingTeeth Json? // { \"T_14\": \"X\", \"T_G\": \"O\", ... }\n serviceDate DateTime\n insuranceProvider String // e.g., \"Delta MA\"\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n status ClaimStatus @default(PENDING)\n claimNumber String?\n preAuthNumber String?\n npiProviderId Int?\n\n patient Patient @relation(fields: [patientId], references: [id], onDelete: Cascade)\n appointment Appointment? @relation(fields: [appointmentId], references: [id], onDelete: Cascade)\n user User? @relation(fields: [userId], references: [id])\n staff Staff? @relation(\"ClaimStaff\", fields: [staffId], references: [id])\n npiProvider NpiProvider? @relation(fields: [npiProviderId], references: [id])\n\n serviceLines ServiceLine[]\n claimFiles ClaimFile[]\n payment Payment?\n}\n\nenum ClaimStatus {\n PENDING\n APPROVED\n CANCELLED\n REVIEW\n VOID\n PREAUTH\n}\n\nenum MissingTeethStatus {\n No_missing\n endentulous\n Yes_missing\n}\n\nmodel ServiceLine {\n id Int @id @default(autoincrement())\n claimId Int?\n paymentId Int?\n procedureCode String\n procedureDate DateTime @db.Date\n quad String?\n arch String?\n toothNumber String?\n toothSurface String?\n icn String?\n paidCode String?\n allowedAmount Decimal? @db.Decimal(10, 2)\n totalBilled Decimal @db.Decimal(10, 2)\n totalPaid Decimal @default(0.00) @db.Decimal(10, 2)\n totalAdjusted Decimal @default(0.00) @db.Decimal(10, 2)\n totalDue Decimal @default(0.00) @db.Decimal(10, 2)\n status ServiceLineStatus @default(UNPAID)\n\n claim Claim? @relation(fields: [claimId], references: [id], onDelete: Cascade)\n payment Payment? @relation(fields: [paymentId], references: [id], onDelete: Cascade)\n\n serviceLineTransactions ServiceLineTransaction[]\n}\n\nenum ServiceLineStatus {\n PENDING\n PARTIALLY_PAID\n PAID\n UNPAID\n ADJUSTED\n OVERPAID\n DENIED\n}\n\nmodel ClaimFile {\n id Int @id @default(autoincrement())\n claimId Int\n filename String\n mimeType String\n filePath String?\n\n claim Claim @relation(fields: [claimId], references: [id], onDelete: Cascade)\n}\n\nmodel InsuranceCredential {\n id Int @id @default(autoincrement())\n userId Int\n siteKey String\n username String\n password String\n\n user User @relation(fields: [userId], references: [id], onDelete: Cascade)\n\n @@unique([userId, siteKey])\n @@index([userId])\n}\n\nmodel ShoppingVendor {\n id Int @id @default(autoincrement())\n userId Int\n vendorName String\n websiteUrl String\n loginUsername String\n loginPassword String\n\n user User @relation(fields: [userId], references: [id], onDelete: Cascade)\n\n @@index([userId])\n}\n\nmodel PdfGroup {\n id Int @id @default(autoincrement())\n title String\n titleKey PdfTitleKey @default(OTHER)\n createdAt DateTime @default(now())\n patientId Int\n patient Patient @relation(fields: [patientId], references: [id], onDelete: Cascade)\n pdfs PdfFile[]\n\n @@index([patientId])\n @@index([titleKey])\n}\n\nmodel PdfFile {\n id Int @id @default(autoincrement())\n filename String\n pdfData Bytes\n uploadedAt DateTime @default(now())\n groupId Int\n group PdfGroup @relation(fields: [groupId], references: [id], onDelete: Cascade)\n\n @@index([groupId])\n}\n\nenum PdfTitleKey {\n INSURANCE_CLAIM\n INSURANCE_CLAIM_PREAUTH\n ELIGIBILITY_STATUS\n CLAIM_STATUS\n PREAUTH_APPROVAL\n OTHER\n}\n\nmodel Payment {\n id Int @id @default(autoincrement())\n claimId Int? @unique\n patientId Int\n userId Int\n updatedById Int?\n npiProviderId Int?\n totalBilled Decimal @db.Decimal(10, 2)\n totalPaid Decimal @default(0.00) @db.Decimal(10, 2)\n totalAdjusted Decimal @default(0.00) @db.Decimal(10, 2)\n totalDue Decimal @db.Decimal(10, 2)\n mhPaidAmount Decimal? @db.Decimal(10, 2)\n copayment Decimal @default(0.00) @db.Decimal(10, 2)\n adjustment Decimal @default(0.00) @db.Decimal(10, 2)\n status PaymentStatus @default(PENDING)\n notes String?\n icn String?\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n\n claim Claim? @relation(fields: [claimId], references: [id], onDelete: Cascade)\n patient Patient @relation(fields: [patientId], references: [id], onDelete: Cascade)\n updatedBy User? @relation(\"PaymentUpdatedBy\", fields: [updatedById], references: [id])\n npiProvider NpiProvider? @relation(fields: [npiProviderId], references: [id])\n serviceLineTransactions ServiceLineTransaction[]\n serviceLines ServiceLine[]\n commissionBatchItems CommissionBatchItem[]\n\n @@index([claimId])\n @@index([patientId])\n @@index([createdAt])\n}\n\nmodel ServiceLineTransaction {\n id Int @id @default(autoincrement())\n paymentId Int\n serviceLineId Int\n transactionId String?\n paidAmount Decimal @db.Decimal(10, 2)\n adjustedAmount Decimal @default(0.00) @db.Decimal(10, 2)\n method PaymentMethod\n receivedDate DateTime\n payerName String?\n notes String?\n createdAt DateTime @default(now())\n\n payment Payment @relation(fields: [paymentId], references: [id], onDelete: Cascade)\n serviceLine ServiceLine @relation(fields: [serviceLineId], references: [id], onDelete: Cascade)\n\n @@index([paymentId])\n @@index([serviceLineId])\n}\n\nenum PaymentStatus {\n PENDING\n PARTIALLY_PAID\n PAID\n OVERPAID\n DENIED\n VOID\n}\n\nenum PaymentMethod {\n EFT\n CHECK\n CASH\n CARD\n OTHER\n}\n\n// Database management page\nmodel DatabaseBackup {\n id Int @id @default(autoincrement())\n userId Int\n createdAt DateTime @default(now())\n\n user User @relation(fields: [userId], references: [id], onDelete: Cascade)\n\n @@index([userId])\n @@index([createdAt])\n}\n\nmodel BackupDestination {\n id Int @id @default(autoincrement())\n userId Int\n path String\n isActive Boolean @default(true)\n createdAt DateTime @default(now())\n\n user User @relation(fields: [userId], references: [id])\n}\n\nmodel Notification {\n id Int @id @default(autoincrement())\n userId Int\n type NotificationTypes\n message String\n createdAt DateTime @default(now())\n read Boolean @default(false)\n\n user User @relation(fields: [userId], references: [id], onDelete: Cascade)\n\n @@index([userId])\n @@index([createdAt])\n}\n\nenum NotificationTypes {\n BACKUP\n CLAIM\n PAYMENT\n ETC\n}\n\n// Cron job execution log\nmodel CronJobLog {\n id Int @id @default(autoincrement())\n jobName String // e.g. \"local-backup\", \"usb-backup\"\n status String // \"success\" | \"failed\" | \"skipped\"\n startedAt DateTime\n completedAt DateTime?\n durationMs Int?\n errorMessage String?\n\n @@index([jobName])\n @@index([startedAt])\n @@index([status])\n}\n\nmodel CloudFolder {\n id Int @id @default(autoincrement())\n userId Int\n name String\n parentId Int?\n patientId Int?\n parent CloudFolder? @relation(\"FolderChildren\", fields: [parentId], references: [id], onDelete: Cascade)\n children CloudFolder[] @relation(\"FolderChildren\")\n user User @relation(fields: [userId], references: [id])\n patient Patient? @relation(\"PatientCloudFolder\", fields: [patientId], references: [id], onDelete: SetNull)\n files CloudFile[]\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n\n @@unique([userId, parentId, name]) // prevents sibling folder name duplicates\n @@index([parentId])\n @@index([patientId])\n}\n\nmodel CloudFile {\n id Int @id @default(autoincrement())\n userId Int\n name String\n mimeType String?\n fileSize BigInt @db.BigInt\n folderId Int? // optional: null => root\n isComplete Boolean @default(false) // upload completed?\n totalChunks Int? // optional: expected number of chunks\n diskPath String? // relative path on disk under uploads/\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n user User @relation(fields: [userId], references: [id])\n folder CloudFolder? @relation(fields: [folderId], references: [id], onDelete: SetNull)\n\n chunks CloudFileChunk[]\n\n @@index([folderId])\n}\n\nmodel CloudFileChunk {\n id Int @id @default(autoincrement())\n fileId Int\n seq Int\n data Bytes\n createdAt DateTime @default(now())\n\n file CloudFile @relation(fields: [fileId], references: [id], onDelete: Cascade)\n\n @@unique([fileId, seq])\n @@index([fileId, seq])\n}\n\n// patient-connection-\nenum CommunicationChannel {\n sms\n voice\n}\n\nenum CommunicationDirection {\n outbound\n inbound\n}\n\nenum CommunicationStatus {\n queued\n sent\n delivered\n failed\n completed\n busy\n no_answer\n}\n\nenum CommunicationProvider {\n twilio\n telnyx\n}\n\nmodel Communication {\n id Int @id @default(autoincrement())\n patientId Int\n userId Int?\n\n channel CommunicationChannel\n direction CommunicationDirection\n status CommunicationStatus\n // Which platform produced twilioSid — twilio for dial-pad-originated calls,\n // telnyx for everything else (SMS, inbound/AI voice, staff-triggered outbound calls).\n provider CommunicationProvider @default(twilio)\n\n body String?\n callDuration Int?\n // Provider SID — Twilio MessageSid/CallSid, or Telnyx message/call id. See `provider`.\n twilioSid String?\n\n createdAt DateTime @default(now())\n\n // Relations\n patient Patient @relation(fields: [patientId], references: [id])\n user User? @relation(fields: [userId], references: [id])\n\n @@map(\"communications\")\n}\n\nmodel PatientDocument {\n id Int @id @default(autoincrement())\n patientId Int\n filename String\n originalName String\n mimeType String\n fileSize BigInt\n filePath String\n uploadedAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n patient Patient @relation(fields: [patientId], references: [id], onDelete: Cascade)\n\n @@index([patientId])\n @@index([uploadedAt])\n}\n\nmodel TwilioSettings {\n id Int @id @default(autoincrement())\n userId Int @unique\n accountSid String\n authToken String\n phoneNumber String\n // Vestigial — inbound voice moved to Telnyx (TelnyxSettings.greetingMessage). No longer\n // read/written; kept to avoid a destructive migration for a cosmetic cleanup.\n greetingMessage String?\n templates Json?\n\n user User @relation(fields: [userId], references: [id], onDelete: Cascade)\n\n @@map(\"twilio_settings\")\n}\n\nmodel TelnyxSettings {\n id Int @id @default(autoincrement())\n userId Int @unique\n apiKey String\n // Telnyx account SID (Mission Control Portal), required to place outbound\n // TeXML calls via POST /texml/Accounts/{accountSid}/Calls — separate from apiKey.\n accountSid String?\n phoneNumber String\n texmlApplicationId String?\n messagingProfileId String?\n webhookPublicKey String?\n greetingMessage String?\n\n user User @relation(fields: [userId], references: [id], onDelete: Cascade)\n\n @@map(\"telnyx_settings\")\n}\n\nmodel AiSettings {\n id Int @id @default(autoincrement())\n userId Int @unique\n apiKey String\n aiEnabled Boolean @default(true)\n openAiKey String @default(\"\")\n openAiEnabled Boolean @default(false)\n claudeAiKey String @default(\"\")\n claudeAiEnabled Boolean @default(false)\n claudeAiModel String @default(\"claude-haiku-4-5-20251001\")\n openAiModel String @default(\"gpt-5.2\")\n googleAiModel String @default(\"gemini-2.5-flash\")\n dentalMgmtKey String @default(\"\")\n dentalMgmtEnabled Boolean @default(false)\n afterHoursEnabled Boolean @default(true)\n openPhoneReply Boolean @default(false)\n\n user User @relation(fields: [userId], references: [id], onDelete: Cascade)\n\n @@map(\"ai_settings\")\n}\n\nmodel OfficeHours {\n id Int @id @default(autoincrement())\n userId Int @unique\n data Json\n\n user User @relation(fields: [userId], references: [id], onDelete: Cascade)\n\n @@map(\"office_hours\")\n}\n\nmodel OfficeContact {\n id Int @id @default(autoincrement())\n userId Int @unique\n /// Legal (registered) business name — ADA claim form items 48 and 56\n legalName String?\n /// Dental office name as the public knows it (DBA)\n officeName String?\n receptionistName String?\n dentistName String?\n phoneNumber String?\n email String?\n fax String?\n streetAddress String?\n city String?\n state String?\n zipCode String?\n /// Office (billing) NPI — ADA claim form items 48-51\n billingName String?\n billingNpi String?\n billingLicense String?\n billingTaxId String?\n\n user User @relation(fields: [userId], references: [id], onDelete: Cascade)\n\n @@map(\"office_contact\")\n}\n\nmodel InsuranceContact {\n id Int @id @default(autoincrement())\n userId Int\n name String\n phoneNumber String?\n createdAt DateTime @default(now())\n\n user User @relation(fields: [userId], references: [id], onDelete: Cascade)\n\n @@map(\"insurance_contact\")\n}\n\nmodel ProcedureTimeslot {\n id Int @id @default(autoincrement())\n userId Int @unique\n data Json\n\n user User @relation(fields: [userId], references: [id], onDelete: Cascade)\n\n @@map(\"procedure_timeslot\")\n}\n\nmodel PatientConversation {\n id Int @id @default(autoincrement())\n patientId Int @unique\n userId Int\n stage String @default(\"initial\")\n aiHandoff Boolean @default(true)\n updatedAt DateTime @updatedAt\n\n patient Patient @relation(fields: [patientId], references: [id], onDelete: Cascade)\n user User @relation(fields: [userId], references: [id], onDelete: Cascade)\n\n @@map(\"patient_conversation\")\n}\n\n// Snapshot of the MassHealth Service History table, replaced on each eligibility check\nmodel PatientServiceHistory {\n id Int @id @default(autoincrement())\n patientId Int\n procedureCode String\n description String?\n toothQuadArchSurface String?\n placeOfService String?\n serviceDate String? // as shown by the portal, e.g. 10/15/2026\n createdAt DateTime @default(now())\n\n patient Patient @relation(fields: [patientId], references: [id], onDelete: Cascade)\n\n @@index([patientId])\n @@map(\"patient_service_history\")\n}\n\nmodel LabRxTemplate {\n id Int @id @default(autoincrement())\n userId Int\n name String\n labName String?\n labPhone String?\n labFax String?\n labAddress String?\n labAccount String?\n caseType String?\n material String?\n instructions String?\n sortOrder Int @default(0)\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n\n user User @relation(fields: [userId], references: [id], onDelete: Cascade)\n\n @@index([userId])\n @@map(\"lab_rx_template\")\n}\n\n// Commission tracking\nmodel CommissionBatch {\n id Int @id @default(autoincrement())\n npiProviderId Int\n totalCollection Decimal @db.Decimal(14, 2)\n commissionAmount Decimal @db.Decimal(14, 2)\n notes String?\n createdAt DateTime @default(now())\n\n npiProvider NpiProvider @relation(fields: [npiProviderId], references: [id])\n items CommissionBatchItem[]\n\n @@index([npiProviderId])\n}\n\nmodel CommissionBatchItem {\n id Int @id @default(autoincrement())\n commissionBatchId Int\n paymentId Int\n collectionAmount Decimal @db.Decimal(14, 2)\n\n commissionBatch CommissionBatch @relation(fields: [commissionBatchId], references: [id], onDelete: Cascade)\n payment Payment @relation(fields: [paymentId], references: [id])\n\n @@unique([commissionBatchId, paymentId])\n @@index([paymentId])\n}\n\nmodel SeleniumSettings {\n id Int @id @default(autoincrement())\n userId Int @unique\n paymentGroupId String @default(\"\")\n\n user User @relation(fields: [userId], references: [id], onDelete: Cascade)\n\n @@map(\"selenium_settings\")\n}\n" } config.runtimeDataModel = JSON.parse("{\"models\":{\"User\":{\"fields\":[{\"name\":\"id\",\"kind\":\"scalar\",\"type\":\"Int\"},{\"name\":\"username\",\"kind\":\"scalar\",\"type\":\"String\"},{\"name\":\"password\",\"kind\":\"scalar\",\"type\":\"String\"},{\"name\":\"autoBackupEnabled\",\"kind\":\"scalar\",\"type\":\"Boolean\"},{\"name\":\"autoBackupHour\",\"kind\":\"scalar\",\"type\":\"Int\"},{\"name\":\"usbBackupEnabled\",\"kind\":\"scalar\",\"type\":\"Boolean\"},{\"name\":\"usbBackupHour\",\"kind\":\"scalar\",\"type\":\"Int\"},{\"name\":\"autoMhCheckEnabled\",\"kind\":\"scalar\",\"type\":\"Boolean\"},{\"name\":\"autoMhCheckDayOfWeek\",\"kind\":\"scalar\",\"type\":\"Int\"},{\"name\":\"autoMhCheckHour\",\"kind\":\"scalar\",\"type\":\"Int\"},{\"name\":\"patients\",\"kind\":\"object\",\"type\":\"Patient\",\"relationName\":\"PatientToUser\"},{\"name\":\"appointments\",\"kind\":\"object\",\"type\":\"Appointment\",\"relationName\":\"AppointmentToUser\"},{\"name\":\"staff\",\"kind\":\"object\",\"type\":\"Staff\",\"relationName\":\"StaffToUser\"},{\"name\":\"npiProviders\",\"kind\":\"object\",\"type\":\"NpiProvider\",\"relationName\":\"NpiProviderToUser\"},{\"name\":\"claims\",\"kind\":\"object\",\"type\":\"Claim\",\"relationName\":\"ClaimToUser\"},{\"name\":\"insuranceCredentials\",\"kind\":\"object\",\"type\":\"InsuranceCredential\",\"relationName\":\"InsuranceCredentialToUser\"},{\"name\":\"shoppingVendors\",\"kind\":\"object\",\"type\":\"ShoppingVendor\",\"relationName\":\"ShoppingVendorToUser\"},{\"name\":\"updatedPayments\",\"kind\":\"object\",\"type\":\"Payment\",\"relationName\":\"PaymentUpdatedBy\"},{\"name\":\"backups\",\"kind\":\"object\",\"type\":\"DatabaseBackup\",\"relationName\":\"DatabaseBackupToUser\"},{\"name\":\"backupDestinations\",\"kind\":\"object\",\"type\":\"BackupDestination\",\"relationName\":\"BackupDestinationToUser\"},{\"name\":\"notifications\",\"kind\":\"object\",\"type\":\"Notification\",\"relationName\":\"NotificationToUser\"},{\"name\":\"cloudFolders\",\"kind\":\"object\",\"type\":\"CloudFolder\",\"relationName\":\"CloudFolderToUser\"},{\"name\":\"cloudFiles\",\"kind\":\"object\",\"type\":\"CloudFile\",\"relationName\":\"CloudFileToUser\"},{\"name\":\"communications\",\"kind\":\"object\",\"type\":\"Communication\",\"relationName\":\"CommunicationToUser\"},{\"name\":\"twilioSettings\",\"kind\":\"object\",\"type\":\"TwilioSettings\",\"relationName\":\"TwilioSettingsToUser\"},{\"name\":\"telnyxSettings\",\"kind\":\"object\",\"type\":\"TelnyxSettings\",\"relationName\":\"TelnyxSettingsToUser\"},{\"name\":\"aiSettings\",\"kind\":\"object\",\"type\":\"AiSettings\",\"relationName\":\"AiSettingsToUser\"},{\"name\":\"officeHours\",\"kind\":\"object\",\"type\":\"OfficeHours\",\"relationName\":\"OfficeHoursToUser\"},{\"name\":\"officeContact\",\"kind\":\"object\",\"type\":\"OfficeContact\",\"relationName\":\"OfficeContactToUser\"},{\"name\":\"procedureTimeslot\",\"kind\":\"object\",\"type\":\"ProcedureTimeslot\",\"relationName\":\"ProcedureTimeslotToUser\"},{\"name\":\"insuranceContacts\",\"kind\":\"object\",\"type\":\"InsuranceContact\",\"relationName\":\"InsuranceContactToUser\"},{\"name\":\"patientConversations\",\"kind\":\"object\",\"type\":\"PatientConversation\",\"relationName\":\"PatientConversationToUser\"},{\"name\":\"labRxTemplates\",\"kind\":\"object\",\"type\":\"LabRxTemplate\",\"relationName\":\"LabRxTemplateToUser\"},{\"name\":\"seleniumSettings\",\"kind\":\"object\",\"type\":\"SeleniumSettings\",\"relationName\":\"SeleniumSettingsToUser\"}],\"dbName\":null},\"Patient\":{\"fields\":[{\"name\":\"id\",\"kind\":\"scalar\",\"type\":\"Int\"},{\"name\":\"firstName\",\"kind\":\"scalar\",\"type\":\"String\"},{\"name\":\"lastName\",\"kind\":\"scalar\",\"type\":\"String\"},{\"name\":\"dateOfBirth\",\"kind\":\"scalar\",\"type\":\"DateTime\"},{\"name\":\"gender\",\"kind\":\"scalar\",\"type\":\"String\"},{\"name\":\"phone\",\"kind\":\"scalar\",\"type\":\"String\"},{\"name\":\"email\",\"kind\":\"scalar\",\"type\":\"String\"},{\"name\":\"address\",\"kind\":\"scalar\",\"type\":\"String\"},{\"name\":\"city\",\"kind\":\"scalar\",\"type\":\"String\"},{\"name\":\"state\",\"kind\":\"scalar\",\"type\":\"String\"},{\"name\":\"zipCode\",\"kind\":\"scalar\",\"type\":\"String\"},{\"name\":\"insuranceProvider\",\"kind\":\"scalar\",\"type\":\"String\"},{\"name\":\"insuranceId\",\"kind\":\"scalar\",\"type\":\"String\"},{\"name\":\"groupNumber\",\"kind\":\"scalar\",\"type\":\"String\"},{\"name\":\"policyHolder\",\"kind\":\"scalar\",\"type\":\"String\"},{\"name\":\"policyHolderPatientId\",\"kind\":\"scalar\",\"type\":\"Int\"},{\"name\":\"policyHolderRelationship\",\"kind\":\"scalar\",\"type\":\"String\"},{\"name\":\"allergies\",\"kind\":\"scalar\",\"type\":\"String\"},{\"name\":\"medicalConditions\",\"kind\":\"scalar\",\"type\":\"String\"},{\"name\":\"preferredLanguage\",\"kind\":\"scalar\",\"type\":\"String\"},{\"name\":\"status\",\"kind\":\"enum\",\"type\":\"PatientStatus\"},{\"name\":\"remainingBenefit\",\"kind\":\"scalar\",\"type\":\"String\"},{\"name\":\"thirdPartyInsurance\",\"kind\":\"scalar\",\"type\":\"String\"},{\"name\":\"userId\",\"kind\":\"scalar\",\"type\":\"Int\"},{\"name\":\"createdAt\",\"kind\":\"scalar\",\"type\":\"DateTime\"},{\"name\":\"updatedAt\",\"kind\":\"scalar\",\"type\":\"DateTime\"},{\"name\":\"user\",\"kind\":\"object\",\"type\":\"User\",\"relationName\":\"PatientToUser\"},{\"name\":\"appointments\",\"kind\":\"object\",\"type\":\"Appointment\",\"relationName\":\"AppointmentToPatient\"},{\"name\":\"procedures\",\"kind\":\"object\",\"type\":\"AppointmentProcedure\",\"relationName\":\"AppointmentProcedureToPatient\"},{\"name\":\"claims\",\"kind\":\"object\",\"type\":\"Claim\",\"relationName\":\"ClaimToPatient\"},{\"name\":\"groups\",\"kind\":\"object\",\"type\":\"PdfGroup\",\"relationName\":\"PatientToPdfGroup\"},{\"name\":\"payment\",\"kind\":\"object\",\"type\":\"Payment\",\"relationName\":\"PatientToPayment\"},{\"name\":\"communications\",\"kind\":\"object\",\"type\":\"Communication\",\"relationName\":\"CommunicationToPatient\"},{\"name\":\"documents\",\"kind\":\"object\",\"type\":\"PatientDocument\",\"relationName\":\"PatientToPatientDocument\"},{\"name\":\"conversation\",\"kind\":\"object\",\"type\":\"PatientConversation\",\"relationName\":\"PatientToPatientConversation\"},{\"name\":\"cloudFolders\",\"kind\":\"object\",\"type\":\"CloudFolder\",\"relationName\":\"PatientCloudFolder\"},{\"name\":\"serviceHistory\",\"kind\":\"object\",\"type\":\"PatientServiceHistory\",\"relationName\":\"PatientToPatientServiceHistory\"}],\"dbName\":null},\"Appointment\":{\"fields\":[{\"name\":\"id\",\"kind\":\"scalar\",\"type\":\"Int\"},{\"name\":\"patientId\",\"kind\":\"scalar\",\"type\":\"Int\"},{\"name\":\"userId\",\"kind\":\"scalar\",\"type\":\"Int\"},{\"name\":\"staffId\",\"kind\":\"scalar\",\"type\":\"Int\"},{\"name\":\"npiProviderId\",\"kind\":\"scalar\",\"type\":\"Int\"},{\"name\":\"title\",\"kind\":\"scalar\",\"type\":\"String\"},{\"name\":\"date\",\"kind\":\"scalar\",\"type\":\"DateTime\"},{\"name\":\"startTime\",\"kind\":\"scalar\",\"type\":\"String\"},{\"name\":\"endTime\",\"kind\":\"scalar\",\"type\":\"String\"},{\"name\":\"type\",\"kind\":\"scalar\",\"type\":\"String\"},{\"name\":\"typeLocked\",\"kind\":\"scalar\",\"type\":\"Boolean\"},{\"name\":\"notes\",\"kind\":\"scalar\",\"type\":\"String\"},{\"name\":\"procedureCodeNotes\",\"kind\":\"scalar\",\"type\":\"String\"},{\"name\":\"status\",\"kind\":\"scalar\",\"type\":\"String\"},{\"name\":\"movedByAi\",\"kind\":\"scalar\",\"type\":\"Boolean\"},{\"name\":\"createdAt\",\"kind\":\"scalar\",\"type\":\"DateTime\"},{\"name\":\"eligibilityStatus\",\"kind\":\"enum\",\"type\":\"PatientStatus\"},{\"name\":\"patient\",\"kind\":\"object\",\"type\":\"Patient\",\"relationName\":\"AppointmentToPatient\"},{\"name\":\"user\",\"kind\":\"object\",\"type\":\"User\",\"relationName\":\"AppointmentToUser\"},{\"name\":\"staff\",\"kind\":\"object\",\"type\":\"Staff\",\"relationName\":\"AppointmentToStaff\"},{\"name\":\"npiProvider\",\"kind\":\"object\",\"type\":\"NpiProvider\",\"relationName\":\"AppointmentToNpiProvider\"},{\"name\":\"procedures\",\"kind\":\"object\",\"type\":\"AppointmentProcedure\",\"relationName\":\"AppointmentToAppointmentProcedure\"},{\"name\":\"claims\",\"kind\":\"object\",\"type\":\"Claim\",\"relationName\":\"AppointmentToClaim\"},{\"name\":\"files\",\"kind\":\"object\",\"type\":\"AppointmentFile\",\"relationName\":\"AppointmentToAppointmentFile\"}],\"dbName\":null},\"AppointmentFile\":{\"fields\":[{\"name\":\"id\",\"kind\":\"scalar\",\"type\":\"Int\"},{\"name\":\"appointmentId\",\"kind\":\"scalar\",\"type\":\"Int\"},{\"name\":\"filename\",\"kind\":\"scalar\",\"type\":\"String\"},{\"name\":\"mimeType\",\"kind\":\"scalar\",\"type\":\"String\"},{\"name\":\"filePath\",\"kind\":\"scalar\",\"type\":\"String\"},{\"name\":\"appointment\",\"kind\":\"object\",\"type\":\"Appointment\",\"relationName\":\"AppointmentToAppointmentFile\"}],\"dbName\":null},\"Staff\":{\"fields\":[{\"name\":\"id\",\"kind\":\"scalar\",\"type\":\"Int\"},{\"name\":\"userId\",\"kind\":\"scalar\",\"type\":\"Int\"},{\"name\":\"name\",\"kind\":\"scalar\",\"type\":\"String\"},{\"name\":\"email\",\"kind\":\"scalar\",\"type\":\"String\"},{\"name\":\"role\",\"kind\":\"scalar\",\"type\":\"String\"},{\"name\":\"phone\",\"kind\":\"scalar\",\"type\":\"String\"},{\"name\":\"createdAt\",\"kind\":\"scalar\",\"type\":\"DateTime\"},{\"name\":\"user\",\"kind\":\"object\",\"type\":\"User\",\"relationName\":\"StaffToUser\"},{\"name\":\"appointments\",\"kind\":\"object\",\"type\":\"Appointment\",\"relationName\":\"AppointmentToStaff\"},{\"name\":\"claims\",\"kind\":\"object\",\"type\":\"Claim\",\"relationName\":\"ClaimStaff\"}],\"dbName\":null},\"NpiProvider\":{\"fields\":[{\"name\":\"id\",\"kind\":\"scalar\",\"type\":\"Int\"},{\"name\":\"userId\",\"kind\":\"scalar\",\"type\":\"Int\"},{\"name\":\"npiNumber\",\"kind\":\"scalar\",\"type\":\"String\"},{\"name\":\"providerName\",\"kind\":\"scalar\",\"type\":\"String\"},{\"name\":\"licenseNumber\",\"kind\":\"scalar\",\"type\":\"String\"},{\"name\":\"sortOrder\",\"kind\":\"scalar\",\"type\":\"Int\"},{\"name\":\"createdAt\",\"kind\":\"scalar\",\"type\":\"DateTime\"},{\"name\":\"user\",\"kind\":\"object\",\"type\":\"User\",\"relationName\":\"NpiProviderToUser\"},{\"name\":\"claims\",\"kind\":\"object\",\"type\":\"Claim\",\"relationName\":\"ClaimToNpiProvider\"},{\"name\":\"payments\",\"kind\":\"object\",\"type\":\"Payment\",\"relationName\":\"NpiProviderToPayment\"},{\"name\":\"commissionBatches\",\"kind\":\"object\",\"type\":\"CommissionBatch\",\"relationName\":\"CommissionBatchToNpiProvider\"},{\"name\":\"appointmentProcedures\",\"kind\":\"object\",\"type\":\"AppointmentProcedure\",\"relationName\":\"AppointmentProcedureToNpiProvider\"},{\"name\":\"appointments\",\"kind\":\"object\",\"type\":\"Appointment\",\"relationName\":\"AppointmentToNpiProvider\"}],\"dbName\":null},\"AppointmentProcedure\":{\"fields\":[{\"name\":\"id\",\"kind\":\"scalar\",\"type\":\"Int\"},{\"name\":\"appointmentId\",\"kind\":\"scalar\",\"type\":\"Int\"},{\"name\":\"patientId\",\"kind\":\"scalar\",\"type\":\"Int\"},{\"name\":\"npiProviderId\",\"kind\":\"scalar\",\"type\":\"Int\"},{\"name\":\"procedureCode\",\"kind\":\"scalar\",\"type\":\"String\"},{\"name\":\"procedureLabel\",\"kind\":\"scalar\",\"type\":\"String\"},{\"name\":\"fee\",\"kind\":\"scalar\",\"type\":\"Decimal\"},{\"name\":\"category\",\"kind\":\"scalar\",\"type\":\"String\"},{\"name\":\"toothNumber\",\"kind\":\"scalar\",\"type\":\"String\"},{\"name\":\"toothSurface\",\"kind\":\"scalar\",\"type\":\"String\"},{\"name\":\"oralCavityArea\",\"kind\":\"scalar\",\"type\":\"String\"},{\"name\":\"source\",\"kind\":\"enum\",\"type\":\"ProcedureSource\"},{\"name\":\"comboKey\",\"kind\":\"scalar\",\"type\":\"String\"},{\"name\":\"createdAt\",\"kind\":\"scalar\",\"type\":\"DateTime\"},{\"name\":\"appointment\",\"kind\":\"object\",\"type\":\"Appointment\",\"relationName\":\"AppointmentToAppointmentProcedure\"},{\"name\":\"patient\",\"kind\":\"object\",\"type\":\"Patient\",\"relationName\":\"AppointmentProcedureToPatient\"},{\"name\":\"npiProvider\",\"kind\":\"object\",\"type\":\"NpiProvider\",\"relationName\":\"AppointmentProcedureToNpiProvider\"}],\"dbName\":null},\"Claim\":{\"fields\":[{\"name\":\"id\",\"kind\":\"scalar\",\"type\":\"Int\"},{\"name\":\"patientId\",\"kind\":\"scalar\",\"type\":\"Int\"},{\"name\":\"appointmentId\",\"kind\":\"scalar\",\"type\":\"Int\"},{\"name\":\"userId\",\"kind\":\"scalar\",\"type\":\"Int\"},{\"name\":\"staffId\",\"kind\":\"scalar\",\"type\":\"Int\"},{\"name\":\"patientName\",\"kind\":\"scalar\",\"type\":\"String\"},{\"name\":\"memberId\",\"kind\":\"scalar\",\"type\":\"String\"},{\"name\":\"dateOfBirth\",\"kind\":\"scalar\",\"type\":\"DateTime\"},{\"name\":\"remarks\",\"kind\":\"scalar\",\"type\":\"String\"},{\"name\":\"missingTeethStatus\",\"kind\":\"enum\",\"type\":\"MissingTeethStatus\"},{\"name\":\"missingTeeth\",\"kind\":\"scalar\",\"type\":\"Json\"},{\"name\":\"serviceDate\",\"kind\":\"scalar\",\"type\":\"DateTime\"},{\"name\":\"insuranceProvider\",\"kind\":\"scalar\",\"type\":\"String\"},{\"name\":\"createdAt\",\"kind\":\"scalar\",\"type\":\"DateTime\"},{\"name\":\"updatedAt\",\"kind\":\"scalar\",\"type\":\"DateTime\"},{\"name\":\"status\",\"kind\":\"enum\",\"type\":\"ClaimStatus\"},{\"name\":\"claimNumber\",\"kind\":\"scalar\",\"type\":\"String\"},{\"name\":\"preAuthNumber\",\"kind\":\"scalar\",\"type\":\"String\"},{\"name\":\"npiProviderId\",\"kind\":\"scalar\",\"type\":\"Int\"},{\"name\":\"patient\",\"kind\":\"object\",\"type\":\"Patient\",\"relationName\":\"ClaimToPatient\"},{\"name\":\"appointment\",\"kind\":\"object\",\"type\":\"Appointment\",\"relationName\":\"AppointmentToClaim\"},{\"name\":\"user\",\"kind\":\"object\",\"type\":\"User\",\"relationName\":\"ClaimToUser\"},{\"name\":\"staff\",\"kind\":\"object\",\"type\":\"Staff\",\"relationName\":\"ClaimStaff\"},{\"name\":\"npiProvider\",\"kind\":\"object\",\"type\":\"NpiProvider\",\"relationName\":\"ClaimToNpiProvider\"},{\"name\":\"serviceLines\",\"kind\":\"object\",\"type\":\"ServiceLine\",\"relationName\":\"ClaimToServiceLine\"},{\"name\":\"claimFiles\",\"kind\":\"object\",\"type\":\"ClaimFile\",\"relationName\":\"ClaimToClaimFile\"},{\"name\":\"payment\",\"kind\":\"object\",\"type\":\"Payment\",\"relationName\":\"ClaimToPayment\"}],\"dbName\":null},\"ServiceLine\":{\"fields\":[{\"name\":\"id\",\"kind\":\"scalar\",\"type\":\"Int\"},{\"name\":\"claimId\",\"kind\":\"scalar\",\"type\":\"Int\"},{\"name\":\"paymentId\",\"kind\":\"scalar\",\"type\":\"Int\"},{\"name\":\"procedureCode\",\"kind\":\"scalar\",\"type\":\"String\"},{\"name\":\"procedureDate\",\"kind\":\"scalar\",\"type\":\"DateTime\"},{\"name\":\"quad\",\"kind\":\"scalar\",\"type\":\"String\"},{\"name\":\"arch\",\"kind\":\"scalar\",\"type\":\"String\"},{\"name\":\"toothNumber\",\"kind\":\"scalar\",\"type\":\"String\"},{\"name\":\"toothSurface\",\"kind\":\"scalar\",\"type\":\"String\"},{\"name\":\"icn\",\"kind\":\"scalar\",\"type\":\"String\"},{\"name\":\"paidCode\",\"kind\":\"scalar\",\"type\":\"String\"},{\"name\":\"allowedAmount\",\"kind\":\"scalar\",\"type\":\"Decimal\"},{\"name\":\"totalBilled\",\"kind\":\"scalar\",\"type\":\"Decimal\"},{\"name\":\"totalPaid\",\"kind\":\"scalar\",\"type\":\"Decimal\"},{\"name\":\"totalAdjusted\",\"kind\":\"scalar\",\"type\":\"Decimal\"},{\"name\":\"totalDue\",\"kind\":\"scalar\",\"type\":\"Decimal\"},{\"name\":\"status\",\"kind\":\"enum\",\"type\":\"ServiceLineStatus\"},{\"name\":\"claim\",\"kind\":\"object\",\"type\":\"Claim\",\"relationName\":\"ClaimToServiceLine\"},{\"name\":\"payment\",\"kind\":\"object\",\"type\":\"Payment\",\"relationName\":\"PaymentToServiceLine\"},{\"name\":\"serviceLineTransactions\",\"kind\":\"object\",\"type\":\"ServiceLineTransaction\",\"relationName\":\"ServiceLineToServiceLineTransaction\"}],\"dbName\":null},\"ClaimFile\":{\"fields\":[{\"name\":\"id\",\"kind\":\"scalar\",\"type\":\"Int\"},{\"name\":\"claimId\",\"kind\":\"scalar\",\"type\":\"Int\"},{\"name\":\"filename\",\"kind\":\"scalar\",\"type\":\"String\"},{\"name\":\"mimeType\",\"kind\":\"scalar\",\"type\":\"String\"},{\"name\":\"filePath\",\"kind\":\"scalar\",\"type\":\"String\"},{\"name\":\"claim\",\"kind\":\"object\",\"type\":\"Claim\",\"relationName\":\"ClaimToClaimFile\"}],\"dbName\":null},\"InsuranceCredential\":{\"fields\":[{\"name\":\"id\",\"kind\":\"scalar\",\"type\":\"Int\"},{\"name\":\"userId\",\"kind\":\"scalar\",\"type\":\"Int\"},{\"name\":\"siteKey\",\"kind\":\"scalar\",\"type\":\"String\"},{\"name\":\"username\",\"kind\":\"scalar\",\"type\":\"String\"},{\"name\":\"password\",\"kind\":\"scalar\",\"type\":\"String\"},{\"name\":\"user\",\"kind\":\"object\",\"type\":\"User\",\"relationName\":\"InsuranceCredentialToUser\"}],\"dbName\":null},\"ShoppingVendor\":{\"fields\":[{\"name\":\"id\",\"kind\":\"scalar\",\"type\":\"Int\"},{\"name\":\"userId\",\"kind\":\"scalar\",\"type\":\"Int\"},{\"name\":\"vendorName\",\"kind\":\"scalar\",\"type\":\"String\"},{\"name\":\"websiteUrl\",\"kind\":\"scalar\",\"type\":\"String\"},{\"name\":\"loginUsername\",\"kind\":\"scalar\",\"type\":\"String\"},{\"name\":\"loginPassword\",\"kind\":\"scalar\",\"type\":\"String\"},{\"name\":\"user\",\"kind\":\"object\",\"type\":\"User\",\"relationName\":\"ShoppingVendorToUser\"}],\"dbName\":null},\"PdfGroup\":{\"fields\":[{\"name\":\"id\",\"kind\":\"scalar\",\"type\":\"Int\"},{\"name\":\"title\",\"kind\":\"scalar\",\"type\":\"String\"},{\"name\":\"titleKey\",\"kind\":\"enum\",\"type\":\"PdfTitleKey\"},{\"name\":\"createdAt\",\"kind\":\"scalar\",\"type\":\"DateTime\"},{\"name\":\"patientId\",\"kind\":\"scalar\",\"type\":\"Int\"},{\"name\":\"patient\",\"kind\":\"object\",\"type\":\"Patient\",\"relationName\":\"PatientToPdfGroup\"},{\"name\":\"pdfs\",\"kind\":\"object\",\"type\":\"PdfFile\",\"relationName\":\"PdfFileToPdfGroup\"}],\"dbName\":null},\"PdfFile\":{\"fields\":[{\"name\":\"id\",\"kind\":\"scalar\",\"type\":\"Int\"},{\"name\":\"filename\",\"kind\":\"scalar\",\"type\":\"String\"},{\"name\":\"pdfData\",\"kind\":\"scalar\",\"type\":\"Bytes\"},{\"name\":\"uploadedAt\",\"kind\":\"scalar\",\"type\":\"DateTime\"},{\"name\":\"groupId\",\"kind\":\"scalar\",\"type\":\"Int\"},{\"name\":\"group\",\"kind\":\"object\",\"type\":\"PdfGroup\",\"relationName\":\"PdfFileToPdfGroup\"}],\"dbName\":null},\"Payment\":{\"fields\":[{\"name\":\"id\",\"kind\":\"scalar\",\"type\":\"Int\"},{\"name\":\"claimId\",\"kind\":\"scalar\",\"type\":\"Int\"},{\"name\":\"patientId\",\"kind\":\"scalar\",\"type\":\"Int\"},{\"name\":\"userId\",\"kind\":\"scalar\",\"type\":\"Int\"},{\"name\":\"updatedById\",\"kind\":\"scalar\",\"type\":\"Int\"},{\"name\":\"npiProviderId\",\"kind\":\"scalar\",\"type\":\"Int\"},{\"name\":\"totalBilled\",\"kind\":\"scalar\",\"type\":\"Decimal\"},{\"name\":\"totalPaid\",\"kind\":\"scalar\",\"type\":\"Decimal\"},{\"name\":\"totalAdjusted\",\"kind\":\"scalar\",\"type\":\"Decimal\"},{\"name\":\"totalDue\",\"kind\":\"scalar\",\"type\":\"Decimal\"},{\"name\":\"mhPaidAmount\",\"kind\":\"scalar\",\"type\":\"Decimal\"},{\"name\":\"copayment\",\"kind\":\"scalar\",\"type\":\"Decimal\"},{\"name\":\"adjustment\",\"kind\":\"scalar\",\"type\":\"Decimal\"},{\"name\":\"status\",\"kind\":\"enum\",\"type\":\"PaymentStatus\"},{\"name\":\"notes\",\"kind\":\"scalar\",\"type\":\"String\"},{\"name\":\"icn\",\"kind\":\"scalar\",\"type\":\"String\"},{\"name\":\"createdAt\",\"kind\":\"scalar\",\"type\":\"DateTime\"},{\"name\":\"updatedAt\",\"kind\":\"scalar\",\"type\":\"DateTime\"},{\"name\":\"claim\",\"kind\":\"object\",\"type\":\"Claim\",\"relationName\":\"ClaimToPayment\"},{\"name\":\"patient\",\"kind\":\"object\",\"type\":\"Patient\",\"relationName\":\"PatientToPayment\"},{\"name\":\"updatedBy\",\"kind\":\"object\",\"type\":\"User\",\"relationName\":\"PaymentUpdatedBy\"},{\"name\":\"npiProvider\",\"kind\":\"object\",\"type\":\"NpiProvider\",\"relationName\":\"NpiProviderToPayment\"},{\"name\":\"serviceLineTransactions\",\"kind\":\"object\",\"type\":\"ServiceLineTransaction\",\"relationName\":\"PaymentToServiceLineTransaction\"},{\"name\":\"serviceLines\",\"kind\":\"object\",\"type\":\"ServiceLine\",\"relationName\":\"PaymentToServiceLine\"},{\"name\":\"commissionBatchItems\",\"kind\":\"object\",\"type\":\"CommissionBatchItem\",\"relationName\":\"CommissionBatchItemToPayment\"}],\"dbName\":null},\"ServiceLineTransaction\":{\"fields\":[{\"name\":\"id\",\"kind\":\"scalar\",\"type\":\"Int\"},{\"name\":\"paymentId\",\"kind\":\"scalar\",\"type\":\"Int\"},{\"name\":\"serviceLineId\",\"kind\":\"scalar\",\"type\":\"Int\"},{\"name\":\"transactionId\",\"kind\":\"scalar\",\"type\":\"String\"},{\"name\":\"paidAmount\",\"kind\":\"scalar\",\"type\":\"Decimal\"},{\"name\":\"adjustedAmount\",\"kind\":\"scalar\",\"type\":\"Decimal\"},{\"name\":\"method\",\"kind\":\"enum\",\"type\":\"PaymentMethod\"},{\"name\":\"receivedDate\",\"kind\":\"scalar\",\"type\":\"DateTime\"},{\"name\":\"payerName\",\"kind\":\"scalar\",\"type\":\"String\"},{\"name\":\"notes\",\"kind\":\"scalar\",\"type\":\"String\"},{\"name\":\"createdAt\",\"kind\":\"scalar\",\"type\":\"DateTime\"},{\"name\":\"payment\",\"kind\":\"object\",\"type\":\"Payment\",\"relationName\":\"PaymentToServiceLineTransaction\"},{\"name\":\"serviceLine\",\"kind\":\"object\",\"type\":\"ServiceLine\",\"relationName\":\"ServiceLineToServiceLineTransaction\"}],\"dbName\":null},\"DatabaseBackup\":{\"fields\":[{\"name\":\"id\",\"kind\":\"scalar\",\"type\":\"Int\"},{\"name\":\"userId\",\"kind\":\"scalar\",\"type\":\"Int\"},{\"name\":\"createdAt\",\"kind\":\"scalar\",\"type\":\"DateTime\"},{\"name\":\"user\",\"kind\":\"object\",\"type\":\"User\",\"relationName\":\"DatabaseBackupToUser\"}],\"dbName\":null},\"BackupDestination\":{\"fields\":[{\"name\":\"id\",\"kind\":\"scalar\",\"type\":\"Int\"},{\"name\":\"userId\",\"kind\":\"scalar\",\"type\":\"Int\"},{\"name\":\"path\",\"kind\":\"scalar\",\"type\":\"String\"},{\"name\":\"isActive\",\"kind\":\"scalar\",\"type\":\"Boolean\"},{\"name\":\"createdAt\",\"kind\":\"scalar\",\"type\":\"DateTime\"},{\"name\":\"user\",\"kind\":\"object\",\"type\":\"User\",\"relationName\":\"BackupDestinationToUser\"}],\"dbName\":null},\"Notification\":{\"fields\":[{\"name\":\"id\",\"kind\":\"scalar\",\"type\":\"Int\"},{\"name\":\"userId\",\"kind\":\"scalar\",\"type\":\"Int\"},{\"name\":\"type\",\"kind\":\"enum\",\"type\":\"NotificationTypes\"},{\"name\":\"message\",\"kind\":\"scalar\",\"type\":\"String\"},{\"name\":\"createdAt\",\"kind\":\"scalar\",\"type\":\"DateTime\"},{\"name\":\"read\",\"kind\":\"scalar\",\"type\":\"Boolean\"},{\"name\":\"user\",\"kind\":\"object\",\"type\":\"User\",\"relationName\":\"NotificationToUser\"}],\"dbName\":null},\"CronJobLog\":{\"fields\":[{\"name\":\"id\",\"kind\":\"scalar\",\"type\":\"Int\"},{\"name\":\"jobName\",\"kind\":\"scalar\",\"type\":\"String\"},{\"name\":\"status\",\"kind\":\"scalar\",\"type\":\"String\"},{\"name\":\"startedAt\",\"kind\":\"scalar\",\"type\":\"DateTime\"},{\"name\":\"completedAt\",\"kind\":\"scalar\",\"type\":\"DateTime\"},{\"name\":\"durationMs\",\"kind\":\"scalar\",\"type\":\"Int\"},{\"name\":\"errorMessage\",\"kind\":\"scalar\",\"type\":\"String\"}],\"dbName\":null},\"CloudFolder\":{\"fields\":[{\"name\":\"id\",\"kind\":\"scalar\",\"type\":\"Int\"},{\"name\":\"userId\",\"kind\":\"scalar\",\"type\":\"Int\"},{\"name\":\"name\",\"kind\":\"scalar\",\"type\":\"String\"},{\"name\":\"parentId\",\"kind\":\"scalar\",\"type\":\"Int\"},{\"name\":\"patientId\",\"kind\":\"scalar\",\"type\":\"Int\"},{\"name\":\"parent\",\"kind\":\"object\",\"type\":\"CloudFolder\",\"relationName\":\"FolderChildren\"},{\"name\":\"children\",\"kind\":\"object\",\"type\":\"CloudFolder\",\"relationName\":\"FolderChildren\"},{\"name\":\"user\",\"kind\":\"object\",\"type\":\"User\",\"relationName\":\"CloudFolderToUser\"},{\"name\":\"patient\",\"kind\":\"object\",\"type\":\"Patient\",\"relationName\":\"PatientCloudFolder\"},{\"name\":\"files\",\"kind\":\"object\",\"type\":\"CloudFile\",\"relationName\":\"CloudFileToCloudFolder\"},{\"name\":\"createdAt\",\"kind\":\"scalar\",\"type\":\"DateTime\"},{\"name\":\"updatedAt\",\"kind\":\"scalar\",\"type\":\"DateTime\"}],\"dbName\":null},\"CloudFile\":{\"fields\":[{\"name\":\"id\",\"kind\":\"scalar\",\"type\":\"Int\"},{\"name\":\"userId\",\"kind\":\"scalar\",\"type\":\"Int\"},{\"name\":\"name\",\"kind\":\"scalar\",\"type\":\"String\"},{\"name\":\"mimeType\",\"kind\":\"scalar\",\"type\":\"String\"},{\"name\":\"fileSize\",\"kind\":\"scalar\",\"type\":\"BigInt\"},{\"name\":\"folderId\",\"kind\":\"scalar\",\"type\":\"Int\"},{\"name\":\"isComplete\",\"kind\":\"scalar\",\"type\":\"Boolean\"},{\"name\":\"totalChunks\",\"kind\":\"scalar\",\"type\":\"Int\"},{\"name\":\"diskPath\",\"kind\":\"scalar\",\"type\":\"String\"},{\"name\":\"createdAt\",\"kind\":\"scalar\",\"type\":\"DateTime\"},{\"name\":\"updatedAt\",\"kind\":\"scalar\",\"type\":\"DateTime\"},{\"name\":\"user\",\"kind\":\"object\",\"type\":\"User\",\"relationName\":\"CloudFileToUser\"},{\"name\":\"folder\",\"kind\":\"object\",\"type\":\"CloudFolder\",\"relationName\":\"CloudFileToCloudFolder\"},{\"name\":\"chunks\",\"kind\":\"object\",\"type\":\"CloudFileChunk\",\"relationName\":\"CloudFileToCloudFileChunk\"}],\"dbName\":null},\"CloudFileChunk\":{\"fields\":[{\"name\":\"id\",\"kind\":\"scalar\",\"type\":\"Int\"},{\"name\":\"fileId\",\"kind\":\"scalar\",\"type\":\"Int\"},{\"name\":\"seq\",\"kind\":\"scalar\",\"type\":\"Int\"},{\"name\":\"data\",\"kind\":\"scalar\",\"type\":\"Bytes\"},{\"name\":\"createdAt\",\"kind\":\"scalar\",\"type\":\"DateTime\"},{\"name\":\"file\",\"kind\":\"object\",\"type\":\"CloudFile\",\"relationName\":\"CloudFileToCloudFileChunk\"}],\"dbName\":null},\"Communication\":{\"fields\":[{\"name\":\"id\",\"kind\":\"scalar\",\"type\":\"Int\"},{\"name\":\"patientId\",\"kind\":\"scalar\",\"type\":\"Int\"},{\"name\":\"userId\",\"kind\":\"scalar\",\"type\":\"Int\"},{\"name\":\"channel\",\"kind\":\"enum\",\"type\":\"CommunicationChannel\"},{\"name\":\"direction\",\"kind\":\"enum\",\"type\":\"CommunicationDirection\"},{\"name\":\"status\",\"kind\":\"enum\",\"type\":\"CommunicationStatus\"},{\"name\":\"provider\",\"kind\":\"enum\",\"type\":\"CommunicationProvider\"},{\"name\":\"body\",\"kind\":\"scalar\",\"type\":\"String\"},{\"name\":\"callDuration\",\"kind\":\"scalar\",\"type\":\"Int\"},{\"name\":\"twilioSid\",\"kind\":\"scalar\",\"type\":\"String\"},{\"name\":\"createdAt\",\"kind\":\"scalar\",\"type\":\"DateTime\"},{\"name\":\"patient\",\"kind\":\"object\",\"type\":\"Patient\",\"relationName\":\"CommunicationToPatient\"},{\"name\":\"user\",\"kind\":\"object\",\"type\":\"User\",\"relationName\":\"CommunicationToUser\"}],\"dbName\":\"communications\"},\"PatientDocument\":{\"fields\":[{\"name\":\"id\",\"kind\":\"scalar\",\"type\":\"Int\"},{\"name\":\"patientId\",\"kind\":\"scalar\",\"type\":\"Int\"},{\"name\":\"filename\",\"kind\":\"scalar\",\"type\":\"String\"},{\"name\":\"originalName\",\"kind\":\"scalar\",\"type\":\"String\"},{\"name\":\"mimeType\",\"kind\":\"scalar\",\"type\":\"String\"},{\"name\":\"fileSize\",\"kind\":\"scalar\",\"type\":\"BigInt\"},{\"name\":\"filePath\",\"kind\":\"scalar\",\"type\":\"String\"},{\"name\":\"uploadedAt\",\"kind\":\"scalar\",\"type\":\"DateTime\"},{\"name\":\"updatedAt\",\"kind\":\"scalar\",\"type\":\"DateTime\"},{\"name\":\"patient\",\"kind\":\"object\",\"type\":\"Patient\",\"relationName\":\"PatientToPatientDocument\"}],\"dbName\":null},\"TwilioSettings\":{\"fields\":[{\"name\":\"id\",\"kind\":\"scalar\",\"type\":\"Int\"},{\"name\":\"userId\",\"kind\":\"scalar\",\"type\":\"Int\"},{\"name\":\"accountSid\",\"kind\":\"scalar\",\"type\":\"String\"},{\"name\":\"authToken\",\"kind\":\"scalar\",\"type\":\"String\"},{\"name\":\"phoneNumber\",\"kind\":\"scalar\",\"type\":\"String\"},{\"name\":\"greetingMessage\",\"kind\":\"scalar\",\"type\":\"String\"},{\"name\":\"templates\",\"kind\":\"scalar\",\"type\":\"Json\"},{\"name\":\"user\",\"kind\":\"object\",\"type\":\"User\",\"relationName\":\"TwilioSettingsToUser\"}],\"dbName\":\"twilio_settings\"},\"TelnyxSettings\":{\"fields\":[{\"name\":\"id\",\"kind\":\"scalar\",\"type\":\"Int\"},{\"name\":\"userId\",\"kind\":\"scalar\",\"type\":\"Int\"},{\"name\":\"apiKey\",\"kind\":\"scalar\",\"type\":\"String\"},{\"name\":\"accountSid\",\"kind\":\"scalar\",\"type\":\"String\"},{\"name\":\"phoneNumber\",\"kind\":\"scalar\",\"type\":\"String\"},{\"name\":\"texmlApplicationId\",\"kind\":\"scalar\",\"type\":\"String\"},{\"name\":\"messagingProfileId\",\"kind\":\"scalar\",\"type\":\"String\"},{\"name\":\"webhookPublicKey\",\"kind\":\"scalar\",\"type\":\"String\"},{\"name\":\"greetingMessage\",\"kind\":\"scalar\",\"type\":\"String\"},{\"name\":\"user\",\"kind\":\"object\",\"type\":\"User\",\"relationName\":\"TelnyxSettingsToUser\"}],\"dbName\":\"telnyx_settings\"},\"AiSettings\":{\"fields\":[{\"name\":\"id\",\"kind\":\"scalar\",\"type\":\"Int\"},{\"name\":\"userId\",\"kind\":\"scalar\",\"type\":\"Int\"},{\"name\":\"apiKey\",\"kind\":\"scalar\",\"type\":\"String\"},{\"name\":\"aiEnabled\",\"kind\":\"scalar\",\"type\":\"Boolean\"},{\"name\":\"openAiKey\",\"kind\":\"scalar\",\"type\":\"String\"},{\"name\":\"openAiEnabled\",\"kind\":\"scalar\",\"type\":\"Boolean\"},{\"name\":\"claudeAiKey\",\"kind\":\"scalar\",\"type\":\"String\"},{\"name\":\"claudeAiEnabled\",\"kind\":\"scalar\",\"type\":\"Boolean\"},{\"name\":\"claudeAiModel\",\"kind\":\"scalar\",\"type\":\"String\"},{\"name\":\"openAiModel\",\"kind\":\"scalar\",\"type\":\"String\"},{\"name\":\"googleAiModel\",\"kind\":\"scalar\",\"type\":\"String\"},{\"name\":\"dentalMgmtKey\",\"kind\":\"scalar\",\"type\":\"String\"},{\"name\":\"dentalMgmtEnabled\",\"kind\":\"scalar\",\"type\":\"Boolean\"},{\"name\":\"afterHoursEnabled\",\"kind\":\"scalar\",\"type\":\"Boolean\"},{\"name\":\"openPhoneReply\",\"kind\":\"scalar\",\"type\":\"Boolean\"},{\"name\":\"user\",\"kind\":\"object\",\"type\":\"User\",\"relationName\":\"AiSettingsToUser\"}],\"dbName\":\"ai_settings\"},\"OfficeHours\":{\"fields\":[{\"name\":\"id\",\"kind\":\"scalar\",\"type\":\"Int\"},{\"name\":\"userId\",\"kind\":\"scalar\",\"type\":\"Int\"},{\"name\":\"data\",\"kind\":\"scalar\",\"type\":\"Json\"},{\"name\":\"user\",\"kind\":\"object\",\"type\":\"User\",\"relationName\":\"OfficeHoursToUser\"}],\"dbName\":\"office_hours\"},\"OfficeContact\":{\"fields\":[{\"name\":\"id\",\"kind\":\"scalar\",\"type\":\"Int\"},{\"name\":\"userId\",\"kind\":\"scalar\",\"type\":\"Int\"},{\"name\":\"legalName\",\"kind\":\"scalar\",\"type\":\"String\"},{\"name\":\"officeName\",\"kind\":\"scalar\",\"type\":\"String\"},{\"name\":\"receptionistName\",\"kind\":\"scalar\",\"type\":\"String\"},{\"name\":\"dentistName\",\"kind\":\"scalar\",\"type\":\"String\"},{\"name\":\"phoneNumber\",\"kind\":\"scalar\",\"type\":\"String\"},{\"name\":\"email\",\"kind\":\"scalar\",\"type\":\"String\"},{\"name\":\"fax\",\"kind\":\"scalar\",\"type\":\"String\"},{\"name\":\"streetAddress\",\"kind\":\"scalar\",\"type\":\"String\"},{\"name\":\"city\",\"kind\":\"scalar\",\"type\":\"String\"},{\"name\":\"state\",\"kind\":\"scalar\",\"type\":\"String\"},{\"name\":\"zipCode\",\"kind\":\"scalar\",\"type\":\"String\"},{\"name\":\"billingName\",\"kind\":\"scalar\",\"type\":\"String\"},{\"name\":\"billingNpi\",\"kind\":\"scalar\",\"type\":\"String\"},{\"name\":\"billingLicense\",\"kind\":\"scalar\",\"type\":\"String\"},{\"name\":\"billingTaxId\",\"kind\":\"scalar\",\"type\":\"String\"},{\"name\":\"user\",\"kind\":\"object\",\"type\":\"User\",\"relationName\":\"OfficeContactToUser\"}],\"dbName\":\"office_contact\"},\"InsuranceContact\":{\"fields\":[{\"name\":\"id\",\"kind\":\"scalar\",\"type\":\"Int\"},{\"name\":\"userId\",\"kind\":\"scalar\",\"type\":\"Int\"},{\"name\":\"name\",\"kind\":\"scalar\",\"type\":\"String\"},{\"name\":\"phoneNumber\",\"kind\":\"scalar\",\"type\":\"String\"},{\"name\":\"createdAt\",\"kind\":\"scalar\",\"type\":\"DateTime\"},{\"name\":\"user\",\"kind\":\"object\",\"type\":\"User\",\"relationName\":\"InsuranceContactToUser\"}],\"dbName\":\"insurance_contact\"},\"ProcedureTimeslot\":{\"fields\":[{\"name\":\"id\",\"kind\":\"scalar\",\"type\":\"Int\"},{\"name\":\"userId\",\"kind\":\"scalar\",\"type\":\"Int\"},{\"name\":\"data\",\"kind\":\"scalar\",\"type\":\"Json\"},{\"name\":\"user\",\"kind\":\"object\",\"type\":\"User\",\"relationName\":\"ProcedureTimeslotToUser\"}],\"dbName\":\"procedure_timeslot\"},\"PatientConversation\":{\"fields\":[{\"name\":\"id\",\"kind\":\"scalar\",\"type\":\"Int\"},{\"name\":\"patientId\",\"kind\":\"scalar\",\"type\":\"Int\"},{\"name\":\"userId\",\"kind\":\"scalar\",\"type\":\"Int\"},{\"name\":\"stage\",\"kind\":\"scalar\",\"type\":\"String\"},{\"name\":\"aiHandoff\",\"kind\":\"scalar\",\"type\":\"Boolean\"},{\"name\":\"updatedAt\",\"kind\":\"scalar\",\"type\":\"DateTime\"},{\"name\":\"patient\",\"kind\":\"object\",\"type\":\"Patient\",\"relationName\":\"PatientToPatientConversation\"},{\"name\":\"user\",\"kind\":\"object\",\"type\":\"User\",\"relationName\":\"PatientConversationToUser\"}],\"dbName\":\"patient_conversation\"},\"PatientServiceHistory\":{\"fields\":[{\"name\":\"id\",\"kind\":\"scalar\",\"type\":\"Int\"},{\"name\":\"patientId\",\"kind\":\"scalar\",\"type\":\"Int\"},{\"name\":\"procedureCode\",\"kind\":\"scalar\",\"type\":\"String\"},{\"name\":\"description\",\"kind\":\"scalar\",\"type\":\"String\"},{\"name\":\"toothQuadArchSurface\",\"kind\":\"scalar\",\"type\":\"String\"},{\"name\":\"placeOfService\",\"kind\":\"scalar\",\"type\":\"String\"},{\"name\":\"serviceDate\",\"kind\":\"scalar\",\"type\":\"String\"},{\"name\":\"createdAt\",\"kind\":\"scalar\",\"type\":\"DateTime\"},{\"name\":\"patient\",\"kind\":\"object\",\"type\":\"Patient\",\"relationName\":\"PatientToPatientServiceHistory\"}],\"dbName\":\"patient_service_history\"},\"LabRxTemplate\":{\"fields\":[{\"name\":\"id\",\"kind\":\"scalar\",\"type\":\"Int\"},{\"name\":\"userId\",\"kind\":\"scalar\",\"type\":\"Int\"},{\"name\":\"name\",\"kind\":\"scalar\",\"type\":\"String\"},{\"name\":\"labName\",\"kind\":\"scalar\",\"type\":\"String\"},{\"name\":\"labPhone\",\"kind\":\"scalar\",\"type\":\"String\"},{\"name\":\"labFax\",\"kind\":\"scalar\",\"type\":\"String\"},{\"name\":\"labAddress\",\"kind\":\"scalar\",\"type\":\"String\"},{\"name\":\"labAccount\",\"kind\":\"scalar\",\"type\":\"String\"},{\"name\":\"caseType\",\"kind\":\"scalar\",\"type\":\"String\"},{\"name\":\"material\",\"kind\":\"scalar\",\"type\":\"String\"},{\"name\":\"instructions\",\"kind\":\"scalar\",\"type\":\"String\"},{\"name\":\"sortOrder\",\"kind\":\"scalar\",\"type\":\"Int\"},{\"name\":\"createdAt\",\"kind\":\"scalar\",\"type\":\"DateTime\"},{\"name\":\"updatedAt\",\"kind\":\"scalar\",\"type\":\"DateTime\"},{\"name\":\"user\",\"kind\":\"object\",\"type\":\"User\",\"relationName\":\"LabRxTemplateToUser\"}],\"dbName\":\"lab_rx_template\"},\"CommissionBatch\":{\"fields\":[{\"name\":\"id\",\"kind\":\"scalar\",\"type\":\"Int\"},{\"name\":\"npiProviderId\",\"kind\":\"scalar\",\"type\":\"Int\"},{\"name\":\"totalCollection\",\"kind\":\"scalar\",\"type\":\"Decimal\"},{\"name\":\"commissionAmount\",\"kind\":\"scalar\",\"type\":\"Decimal\"},{\"name\":\"notes\",\"kind\":\"scalar\",\"type\":\"String\"},{\"name\":\"createdAt\",\"kind\":\"scalar\",\"type\":\"DateTime\"},{\"name\":\"npiProvider\",\"kind\":\"object\",\"type\":\"NpiProvider\",\"relationName\":\"CommissionBatchToNpiProvider\"},{\"name\":\"items\",\"kind\":\"object\",\"type\":\"CommissionBatchItem\",\"relationName\":\"CommissionBatchToCommissionBatchItem\"}],\"dbName\":null},\"CommissionBatchItem\":{\"fields\":[{\"name\":\"id\",\"kind\":\"scalar\",\"type\":\"Int\"},{\"name\":\"commissionBatchId\",\"kind\":\"scalar\",\"type\":\"Int\"},{\"name\":\"paymentId\",\"kind\":\"scalar\",\"type\":\"Int\"},{\"name\":\"collectionAmount\",\"kind\":\"scalar\",\"type\":\"Decimal\"},{\"name\":\"commissionBatch\",\"kind\":\"object\",\"type\":\"CommissionBatch\",\"relationName\":\"CommissionBatchToCommissionBatchItem\"},{\"name\":\"payment\",\"kind\":\"object\",\"type\":\"Payment\",\"relationName\":\"CommissionBatchItemToPayment\"}],\"dbName\":null},\"SeleniumSettings\":{\"fields\":[{\"name\":\"id\",\"kind\":\"scalar\",\"type\":\"Int\"},{\"name\":\"userId\",\"kind\":\"scalar\",\"type\":\"Int\"},{\"name\":\"paymentGroupId\",\"kind\":\"scalar\",\"type\":\"String\"},{\"name\":\"user\",\"kind\":\"object\",\"type\":\"User\",\"relationName\":\"SeleniumSettingsToUser\"}],\"dbName\":\"selenium_settings\"}},\"enums\":{},\"types\":{}}") diff --git a/packages/db/generated/prisma/index-browser.js b/packages/db/generated/prisma/index-browser.js index 1e249761..df574a6a 100644 --- a/packages/db/generated/prisma/index-browser.js +++ b/packages/db/generated/prisma/index-browser.js @@ -646,6 +646,7 @@ exports.PdfTitleKey = exports.$Enums.PdfTitleKey = { INSURANCE_CLAIM_PREAUTH: 'INSURANCE_CLAIM_PREAUTH', ELIGIBILITY_STATUS: 'ELIGIBILITY_STATUS', CLAIM_STATUS: 'CLAIM_STATUS', + PREAUTH_APPROVAL: 'PREAUTH_APPROVAL', OTHER: 'OTHER' }; diff --git a/packages/db/generated/prisma/index.d.ts b/packages/db/generated/prisma/index.d.ts index d8ebaee3..20d8f2ca 100644 --- a/packages/db/generated/prisma/index.d.ts +++ b/packages/db/generated/prisma/index.d.ts @@ -265,6 +265,7 @@ export const PdfTitleKey: { INSURANCE_CLAIM_PREAUTH: 'INSURANCE_CLAIM_PREAUTH', ELIGIBILITY_STATUS: 'ELIGIBILITY_STATUS', CLAIM_STATUS: 'CLAIM_STATUS', + PREAUTH_APPROVAL: 'PREAUTH_APPROVAL', OTHER: 'OTHER' }; diff --git a/packages/db/generated/prisma/index.js b/packages/db/generated/prisma/index.js index df75c3ce..6efcf8ae 100644 --- a/packages/db/generated/prisma/index.js +++ b/packages/db/generated/prisma/index.js @@ -619,6 +619,7 @@ exports.PdfTitleKey = exports.$Enums.PdfTitleKey = { INSURANCE_CLAIM_PREAUTH: 'INSURANCE_CLAIM_PREAUTH', ELIGIBILITY_STATUS: 'ELIGIBILITY_STATUS', CLAIM_STATUS: 'CLAIM_STATUS', + PREAUTH_APPROVAL: 'PREAUTH_APPROVAL', OTHER: 'OTHER' }; @@ -719,7 +720,7 @@ const config = { "clientVersion": "7.4.1", "engineVersion": "55ae170b1ced7fc6ed07a15f110549408c501bb3", "activeProvider": "postgresql", - "inlineSchema": "// This is your Prisma schema file,\n// learn more about it in the docs: https://pris.ly/d/prisma-schema\n\n// Looking for ways to speed up your queries, or scale easily with your serverless or edge functions?\n// Try Prisma Accelerate: https://pris.ly/cli/accelerate-init\n\ngenerator client {\n provider = \"prisma-client-js\"\n output = \"../generated/prisma\"\n}\n\ngenerator zod {\n provider = \"prisma-zod-generator\"\n output = \"../shared/\" // Zod schemas will be generated here inside `db/shared`\n}\n\ndatasource db {\n provider = \"postgresql\"\n}\n\nmodel User {\n id Int @id @default(autoincrement())\n username String @unique\n password String\n autoBackupEnabled Boolean @default(true)\n autoBackupHour Int @default(20)\n usbBackupEnabled Boolean @default(false)\n usbBackupHour Int @default(21)\n autoMhCheckEnabled Boolean @default(false)\n autoMhCheckDayOfWeek Int @default(1)\n autoMhCheckHour Int @default(13)\n patients Patient[]\n appointments Appointment[]\n staff Staff[]\n npiProviders NpiProvider[]\n claims Claim[]\n insuranceCredentials InsuranceCredential[]\n shoppingVendors ShoppingVendor[]\n updatedPayments Payment[] @relation(\"PaymentUpdatedBy\")\n backups DatabaseBackup[]\n backupDestinations BackupDestination[]\n notifications Notification[]\n cloudFolders CloudFolder[]\n cloudFiles CloudFile[]\n communications Communication[]\n twilioSettings TwilioSettings?\n telnyxSettings TelnyxSettings?\n aiSettings AiSettings?\n officeHours OfficeHours?\n officeContact OfficeContact?\n procedureTimeslot ProcedureTimeslot?\n insuranceContacts InsuranceContact[]\n patientConversations PatientConversation[]\n labRxTemplates LabRxTemplate[]\n seleniumSettings SeleniumSettings?\n}\n\nmodel Patient {\n id Int @id @default(autoincrement())\n firstName String\n lastName String\n dateOfBirth DateTime? @db.Date\n gender String\n phone String\n email String?\n address String?\n city String?\n state String? @default(\"MA\")\n zipCode String?\n insuranceProvider String?\n insuranceId String?\n groupNumber String?\n policyHolder String?\n policyHolderPatientId Int? // patient record of the policy holder, when picked from the DB\n policyHolderRelationship String? // ADA box 18: SELF | SPOUSE | DEPENDENT | OTHER\n allergies String?\n medicalConditions String?\n preferredLanguage String? @default(\"English\")\n status PatientStatus @default(UNKNOWN)\n remainingBenefit String?\n thirdPartyInsurance String?\n userId Int\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n user User @relation(fields: [userId], references: [id])\n appointments Appointment[]\n procedures AppointmentProcedure[]\n claims Claim[]\n groups PdfGroup[]\n payment Payment[]\n communications Communication[]\n documents PatientDocument[]\n conversation PatientConversation?\n cloudFolders CloudFolder[] @relation(\"PatientCloudFolder\")\n serviceHistory PatientServiceHistory[]\n\n @@index([insuranceId])\n @@index([createdAt])\n}\n\nenum PatientStatus {\n ACTIVE\n INACTIVE\n UNKNOWN\n PLAN_NOT_ACCEPTED\n}\n\nmodel Appointment {\n id Int @id @default(autoincrement())\n patientId Int\n userId Int\n staffId Int\n npiProviderId Int?\n title String\n date DateTime @db.Date\n startTime String // Store time as \"hh:mm\"\n endTime String // Store time as \"hh:mm\"\n type String // e.g., \"checkup\", \"cleaning\", \"filling\", etc.\n typeLocked Boolean @default(false) // true = user manually set; auto-sync will not overwrite\n notes String?\n procedureCodeNotes String?\n status String @default(\"scheduled\") // \"scheduled\", \"completed\", \"cancelled\", \"no-show\"\n movedByAi Boolean @default(false)\n createdAt DateTime @default(now())\n\n eligibilityStatus PatientStatus @default(UNKNOWN)\n\n patient Patient @relation(fields: [patientId], references: [id], onDelete: Cascade)\n user User @relation(fields: [userId], references: [id])\n staff Staff? @relation(fields: [staffId], references: [id])\n npiProvider NpiProvider? @relation(fields: [npiProviderId], references: [id])\n procedures AppointmentProcedure[]\n claims Claim[]\n files AppointmentFile[]\n\n @@index([patientId])\n @@index([date])\n}\n\nmodel AppointmentFile {\n id Int @id @default(autoincrement())\n appointmentId Int\n filename String\n mimeType String?\n filePath String?\n\n appointment Appointment @relation(fields: [appointmentId], references: [id], onDelete: Cascade)\n\n @@index([appointmentId])\n}\n\nmodel Staff {\n id Int @id @default(autoincrement())\n userId Int\n name String\n email String?\n role String // e.g., \"Dentist\", \"Hygienist\", \"Assistant\"\n phone String?\n createdAt DateTime @default(now())\n user User? @relation(fields: [userId], references: [id], onDelete: Cascade)\n appointments Appointment[]\n claims Claim[] @relation(\"ClaimStaff\")\n}\n\nmodel NpiProvider {\n id Int @id @default(autoincrement())\n userId Int\n npiNumber String\n providerName String\n /// State dental license (ADA claim form item 55)\n licenseNumber String?\n sortOrder Int @default(0)\n createdAt DateTime @default(now())\n\n user User @relation(fields: [userId], references: [id], onDelete: Cascade)\n claims Claim[]\n payments Payment[]\n commissionBatches CommissionBatch[]\n appointmentProcedures AppointmentProcedure[]\n appointments Appointment[]\n\n @@unique([userId, npiNumber])\n @@index([userId])\n}\n\nenum ProcedureSource {\n COMBO\n MANUAL\n}\n\nmodel AppointmentProcedure {\n id Int @id @default(autoincrement())\n appointmentId Int\n patientId Int\n npiProviderId Int?\n\n procedureCode String\n procedureLabel String?\n fee Decimal? @db.Decimal(10, 2)\n\n category String?\n\n toothNumber String?\n toothSurface String?\n oralCavityArea String?\n\n source ProcedureSource @default(MANUAL)\n comboKey String?\n\n createdAt DateTime @default(now())\n\n appointment Appointment @relation(fields: [appointmentId], references: [id], onDelete: Cascade)\n patient Patient @relation(fields: [patientId], references: [id], onDelete: Cascade)\n npiProvider NpiProvider? @relation(fields: [npiProviderId], references: [id])\n\n @@index([appointmentId])\n @@index([patientId])\n}\n\nmodel Claim {\n id Int @id @default(autoincrement())\n patientId Int\n /// @zod.number.int().nullable().optional()\n appointmentId Int?\n userId Int\n staffId Int\n patientName String\n memberId String\n dateOfBirth DateTime @db.Date\n remarks String\n missingTeethStatus MissingTeethStatus @default(No_missing)\n missingTeeth Json? // { \"T_14\": \"X\", \"T_G\": \"O\", ... }\n serviceDate DateTime\n insuranceProvider String // e.g., \"Delta MA\"\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n status ClaimStatus @default(PENDING)\n claimNumber String?\n preAuthNumber String?\n npiProviderId Int?\n\n patient Patient @relation(fields: [patientId], references: [id], onDelete: Cascade)\n appointment Appointment? @relation(fields: [appointmentId], references: [id], onDelete: Cascade)\n user User? @relation(fields: [userId], references: [id])\n staff Staff? @relation(\"ClaimStaff\", fields: [staffId], references: [id])\n npiProvider NpiProvider? @relation(fields: [npiProviderId], references: [id])\n\n serviceLines ServiceLine[]\n claimFiles ClaimFile[]\n payment Payment?\n}\n\nenum ClaimStatus {\n PENDING\n APPROVED\n CANCELLED\n REVIEW\n VOID\n PREAUTH\n}\n\nenum MissingTeethStatus {\n No_missing\n endentulous\n Yes_missing\n}\n\nmodel ServiceLine {\n id Int @id @default(autoincrement())\n claimId Int?\n paymentId Int?\n procedureCode String\n procedureDate DateTime @db.Date\n quad String?\n arch String?\n toothNumber String?\n toothSurface String?\n icn String?\n paidCode String?\n allowedAmount Decimal? @db.Decimal(10, 2)\n totalBilled Decimal @db.Decimal(10, 2)\n totalPaid Decimal @default(0.00) @db.Decimal(10, 2)\n totalAdjusted Decimal @default(0.00) @db.Decimal(10, 2)\n totalDue Decimal @default(0.00) @db.Decimal(10, 2)\n status ServiceLineStatus @default(UNPAID)\n\n claim Claim? @relation(fields: [claimId], references: [id], onDelete: Cascade)\n payment Payment? @relation(fields: [paymentId], references: [id], onDelete: Cascade)\n\n serviceLineTransactions ServiceLineTransaction[]\n}\n\nenum ServiceLineStatus {\n PENDING\n PARTIALLY_PAID\n PAID\n UNPAID\n ADJUSTED\n OVERPAID\n DENIED\n}\n\nmodel ClaimFile {\n id Int @id @default(autoincrement())\n claimId Int\n filename String\n mimeType String\n filePath String?\n\n claim Claim @relation(fields: [claimId], references: [id], onDelete: Cascade)\n}\n\nmodel InsuranceCredential {\n id Int @id @default(autoincrement())\n userId Int\n siteKey String\n username String\n password String\n\n user User @relation(fields: [userId], references: [id], onDelete: Cascade)\n\n @@unique([userId, siteKey])\n @@index([userId])\n}\n\nmodel ShoppingVendor {\n id Int @id @default(autoincrement())\n userId Int\n vendorName String\n websiteUrl String\n loginUsername String\n loginPassword String\n\n user User @relation(fields: [userId], references: [id], onDelete: Cascade)\n\n @@index([userId])\n}\n\nmodel PdfGroup {\n id Int @id @default(autoincrement())\n title String\n titleKey PdfTitleKey @default(OTHER)\n createdAt DateTime @default(now())\n patientId Int\n patient Patient @relation(fields: [patientId], references: [id], onDelete: Cascade)\n pdfs PdfFile[]\n\n @@index([patientId])\n @@index([titleKey])\n}\n\nmodel PdfFile {\n id Int @id @default(autoincrement())\n filename String\n pdfData Bytes\n uploadedAt DateTime @default(now())\n groupId Int\n group PdfGroup @relation(fields: [groupId], references: [id], onDelete: Cascade)\n\n @@index([groupId])\n}\n\nenum PdfTitleKey {\n INSURANCE_CLAIM\n INSURANCE_CLAIM_PREAUTH\n ELIGIBILITY_STATUS\n CLAIM_STATUS\n OTHER\n}\n\nmodel Payment {\n id Int @id @default(autoincrement())\n claimId Int? @unique\n patientId Int\n userId Int\n updatedById Int?\n npiProviderId Int?\n totalBilled Decimal @db.Decimal(10, 2)\n totalPaid Decimal @default(0.00) @db.Decimal(10, 2)\n totalAdjusted Decimal @default(0.00) @db.Decimal(10, 2)\n totalDue Decimal @db.Decimal(10, 2)\n mhPaidAmount Decimal? @db.Decimal(10, 2)\n copayment Decimal @default(0.00) @db.Decimal(10, 2)\n adjustment Decimal @default(0.00) @db.Decimal(10, 2)\n status PaymentStatus @default(PENDING)\n notes String?\n icn String?\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n\n claim Claim? @relation(fields: [claimId], references: [id], onDelete: Cascade)\n patient Patient @relation(fields: [patientId], references: [id], onDelete: Cascade)\n updatedBy User? @relation(\"PaymentUpdatedBy\", fields: [updatedById], references: [id])\n npiProvider NpiProvider? @relation(fields: [npiProviderId], references: [id])\n serviceLineTransactions ServiceLineTransaction[]\n serviceLines ServiceLine[]\n commissionBatchItems CommissionBatchItem[]\n\n @@index([claimId])\n @@index([patientId])\n @@index([createdAt])\n}\n\nmodel ServiceLineTransaction {\n id Int @id @default(autoincrement())\n paymentId Int\n serviceLineId Int\n transactionId String?\n paidAmount Decimal @db.Decimal(10, 2)\n adjustedAmount Decimal @default(0.00) @db.Decimal(10, 2)\n method PaymentMethod\n receivedDate DateTime\n payerName String?\n notes String?\n createdAt DateTime @default(now())\n\n payment Payment @relation(fields: [paymentId], references: [id], onDelete: Cascade)\n serviceLine ServiceLine @relation(fields: [serviceLineId], references: [id], onDelete: Cascade)\n\n @@index([paymentId])\n @@index([serviceLineId])\n}\n\nenum PaymentStatus {\n PENDING\n PARTIALLY_PAID\n PAID\n OVERPAID\n DENIED\n VOID\n}\n\nenum PaymentMethod {\n EFT\n CHECK\n CASH\n CARD\n OTHER\n}\n\n// Database management page\nmodel DatabaseBackup {\n id Int @id @default(autoincrement())\n userId Int\n createdAt DateTime @default(now())\n\n user User @relation(fields: [userId], references: [id], onDelete: Cascade)\n\n @@index([userId])\n @@index([createdAt])\n}\n\nmodel BackupDestination {\n id Int @id @default(autoincrement())\n userId Int\n path String\n isActive Boolean @default(true)\n createdAt DateTime @default(now())\n\n user User @relation(fields: [userId], references: [id])\n}\n\nmodel Notification {\n id Int @id @default(autoincrement())\n userId Int\n type NotificationTypes\n message String\n createdAt DateTime @default(now())\n read Boolean @default(false)\n\n user User @relation(fields: [userId], references: [id], onDelete: Cascade)\n\n @@index([userId])\n @@index([createdAt])\n}\n\nenum NotificationTypes {\n BACKUP\n CLAIM\n PAYMENT\n ETC\n}\n\n// Cron job execution log\nmodel CronJobLog {\n id Int @id @default(autoincrement())\n jobName String // e.g. \"local-backup\", \"usb-backup\"\n status String // \"success\" | \"failed\" | \"skipped\"\n startedAt DateTime\n completedAt DateTime?\n durationMs Int?\n errorMessage String?\n\n @@index([jobName])\n @@index([startedAt])\n @@index([status])\n}\n\nmodel CloudFolder {\n id Int @id @default(autoincrement())\n userId Int\n name String\n parentId Int?\n patientId Int?\n parent CloudFolder? @relation(\"FolderChildren\", fields: [parentId], references: [id], onDelete: Cascade)\n children CloudFolder[] @relation(\"FolderChildren\")\n user User @relation(fields: [userId], references: [id])\n patient Patient? @relation(\"PatientCloudFolder\", fields: [patientId], references: [id], onDelete: SetNull)\n files CloudFile[]\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n\n @@unique([userId, parentId, name]) // prevents sibling folder name duplicates\n @@index([parentId])\n @@index([patientId])\n}\n\nmodel CloudFile {\n id Int @id @default(autoincrement())\n userId Int\n name String\n mimeType String?\n fileSize BigInt @db.BigInt\n folderId Int? // optional: null => root\n isComplete Boolean @default(false) // upload completed?\n totalChunks Int? // optional: expected number of chunks\n diskPath String? // relative path on disk under uploads/\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n user User @relation(fields: [userId], references: [id])\n folder CloudFolder? @relation(fields: [folderId], references: [id], onDelete: SetNull)\n\n chunks CloudFileChunk[]\n\n @@index([folderId])\n}\n\nmodel CloudFileChunk {\n id Int @id @default(autoincrement())\n fileId Int\n seq Int\n data Bytes\n createdAt DateTime @default(now())\n\n file CloudFile @relation(fields: [fileId], references: [id], onDelete: Cascade)\n\n @@unique([fileId, seq])\n @@index([fileId, seq])\n}\n\n// patient-connection-\nenum CommunicationChannel {\n sms\n voice\n}\n\nenum CommunicationDirection {\n outbound\n inbound\n}\n\nenum CommunicationStatus {\n queued\n sent\n delivered\n failed\n completed\n busy\n no_answer\n}\n\nenum CommunicationProvider {\n twilio\n telnyx\n}\n\nmodel Communication {\n id Int @id @default(autoincrement())\n patientId Int\n userId Int?\n\n channel CommunicationChannel\n direction CommunicationDirection\n status CommunicationStatus\n // Which platform produced twilioSid — twilio for dial-pad-originated calls,\n // telnyx for everything else (SMS, inbound/AI voice, staff-triggered outbound calls).\n provider CommunicationProvider @default(twilio)\n\n body String?\n callDuration Int?\n // Provider SID — Twilio MessageSid/CallSid, or Telnyx message/call id. See `provider`.\n twilioSid String?\n\n createdAt DateTime @default(now())\n\n // Relations\n patient Patient @relation(fields: [patientId], references: [id])\n user User? @relation(fields: [userId], references: [id])\n\n @@map(\"communications\")\n}\n\nmodel PatientDocument {\n id Int @id @default(autoincrement())\n patientId Int\n filename String\n originalName String\n mimeType String\n fileSize BigInt\n filePath String\n uploadedAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n patient Patient @relation(fields: [patientId], references: [id], onDelete: Cascade)\n\n @@index([patientId])\n @@index([uploadedAt])\n}\n\nmodel TwilioSettings {\n id Int @id @default(autoincrement())\n userId Int @unique\n accountSid String\n authToken String\n phoneNumber String\n // Vestigial — inbound voice moved to Telnyx (TelnyxSettings.greetingMessage). No longer\n // read/written; kept to avoid a destructive migration for a cosmetic cleanup.\n greetingMessage String?\n templates Json?\n\n user User @relation(fields: [userId], references: [id], onDelete: Cascade)\n\n @@map(\"twilio_settings\")\n}\n\nmodel TelnyxSettings {\n id Int @id @default(autoincrement())\n userId Int @unique\n apiKey String\n // Telnyx account SID (Mission Control Portal), required to place outbound\n // TeXML calls via POST /texml/Accounts/{accountSid}/Calls — separate from apiKey.\n accountSid String?\n phoneNumber String\n texmlApplicationId String?\n messagingProfileId String?\n webhookPublicKey String?\n greetingMessage String?\n\n user User @relation(fields: [userId], references: [id], onDelete: Cascade)\n\n @@map(\"telnyx_settings\")\n}\n\nmodel AiSettings {\n id Int @id @default(autoincrement())\n userId Int @unique\n apiKey String\n aiEnabled Boolean @default(true)\n openAiKey String @default(\"\")\n openAiEnabled Boolean @default(false)\n claudeAiKey String @default(\"\")\n claudeAiEnabled Boolean @default(false)\n claudeAiModel String @default(\"claude-haiku-4-5-20251001\")\n openAiModel String @default(\"gpt-5.2\")\n googleAiModel String @default(\"gemini-2.5-flash\")\n dentalMgmtKey String @default(\"\")\n dentalMgmtEnabled Boolean @default(false)\n afterHoursEnabled Boolean @default(true)\n openPhoneReply Boolean @default(false)\n\n user User @relation(fields: [userId], references: [id], onDelete: Cascade)\n\n @@map(\"ai_settings\")\n}\n\nmodel OfficeHours {\n id Int @id @default(autoincrement())\n userId Int @unique\n data Json\n\n user User @relation(fields: [userId], references: [id], onDelete: Cascade)\n\n @@map(\"office_hours\")\n}\n\nmodel OfficeContact {\n id Int @id @default(autoincrement())\n userId Int @unique\n /// Legal (registered) business name — ADA claim form items 48 and 56\n legalName String?\n /// Dental office name as the public knows it (DBA)\n officeName String?\n receptionistName String?\n dentistName String?\n phoneNumber String?\n email String?\n fax String?\n streetAddress String?\n city String?\n state String?\n zipCode String?\n /// Office (billing) NPI — ADA claim form items 48-51\n billingName String?\n billingNpi String?\n billingLicense String?\n billingTaxId String?\n\n user User @relation(fields: [userId], references: [id], onDelete: Cascade)\n\n @@map(\"office_contact\")\n}\n\nmodel InsuranceContact {\n id Int @id @default(autoincrement())\n userId Int\n name String\n phoneNumber String?\n createdAt DateTime @default(now())\n\n user User @relation(fields: [userId], references: [id], onDelete: Cascade)\n\n @@map(\"insurance_contact\")\n}\n\nmodel ProcedureTimeslot {\n id Int @id @default(autoincrement())\n userId Int @unique\n data Json\n\n user User @relation(fields: [userId], references: [id], onDelete: Cascade)\n\n @@map(\"procedure_timeslot\")\n}\n\nmodel PatientConversation {\n id Int @id @default(autoincrement())\n patientId Int @unique\n userId Int\n stage String @default(\"initial\")\n aiHandoff Boolean @default(true)\n updatedAt DateTime @updatedAt\n\n patient Patient @relation(fields: [patientId], references: [id], onDelete: Cascade)\n user User @relation(fields: [userId], references: [id], onDelete: Cascade)\n\n @@map(\"patient_conversation\")\n}\n\n// Snapshot of the MassHealth Service History table, replaced on each eligibility check\nmodel PatientServiceHistory {\n id Int @id @default(autoincrement())\n patientId Int\n procedureCode String\n description String?\n toothQuadArchSurface String?\n placeOfService String?\n serviceDate String? // as shown by the portal, e.g. 10/15/2026\n createdAt DateTime @default(now())\n\n patient Patient @relation(fields: [patientId], references: [id], onDelete: Cascade)\n\n @@index([patientId])\n @@map(\"patient_service_history\")\n}\n\nmodel LabRxTemplate {\n id Int @id @default(autoincrement())\n userId Int\n name String\n labName String?\n labPhone String?\n labFax String?\n labAddress String?\n labAccount String?\n caseType String?\n material String?\n instructions String?\n sortOrder Int @default(0)\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n\n user User @relation(fields: [userId], references: [id], onDelete: Cascade)\n\n @@index([userId])\n @@map(\"lab_rx_template\")\n}\n\n// Commission tracking\nmodel CommissionBatch {\n id Int @id @default(autoincrement())\n npiProviderId Int\n totalCollection Decimal @db.Decimal(14, 2)\n commissionAmount Decimal @db.Decimal(14, 2)\n notes String?\n createdAt DateTime @default(now())\n\n npiProvider NpiProvider @relation(fields: [npiProviderId], references: [id])\n items CommissionBatchItem[]\n\n @@index([npiProviderId])\n}\n\nmodel CommissionBatchItem {\n id Int @id @default(autoincrement())\n commissionBatchId Int\n paymentId Int\n collectionAmount Decimal @db.Decimal(14, 2)\n\n commissionBatch CommissionBatch @relation(fields: [commissionBatchId], references: [id], onDelete: Cascade)\n payment Payment @relation(fields: [paymentId], references: [id])\n\n @@unique([commissionBatchId, paymentId])\n @@index([paymentId])\n}\n\nmodel SeleniumSettings {\n id Int @id @default(autoincrement())\n userId Int @unique\n paymentGroupId String @default(\"\")\n\n user User @relation(fields: [userId], references: [id], onDelete: Cascade)\n\n @@map(\"selenium_settings\")\n}\n" + "inlineSchema": "// This is your Prisma schema file,\n// learn more about it in the docs: https://pris.ly/d/prisma-schema\n\n// Looking for ways to speed up your queries, or scale easily with your serverless or edge functions?\n// Try Prisma Accelerate: https://pris.ly/cli/accelerate-init\n\ngenerator client {\n provider = \"prisma-client-js\"\n output = \"../generated/prisma\"\n}\n\ngenerator zod {\n provider = \"prisma-zod-generator\"\n output = \"../shared/\" // Zod schemas will be generated here inside `db/shared`\n}\n\ndatasource db {\n provider = \"postgresql\"\n}\n\nmodel User {\n id Int @id @default(autoincrement())\n username String @unique\n password String\n autoBackupEnabled Boolean @default(true)\n autoBackupHour Int @default(20)\n usbBackupEnabled Boolean @default(false)\n usbBackupHour Int @default(21)\n autoMhCheckEnabled Boolean @default(false)\n autoMhCheckDayOfWeek Int @default(1)\n autoMhCheckHour Int @default(13)\n patients Patient[]\n appointments Appointment[]\n staff Staff[]\n npiProviders NpiProvider[]\n claims Claim[]\n insuranceCredentials InsuranceCredential[]\n shoppingVendors ShoppingVendor[]\n updatedPayments Payment[] @relation(\"PaymentUpdatedBy\")\n backups DatabaseBackup[]\n backupDestinations BackupDestination[]\n notifications Notification[]\n cloudFolders CloudFolder[]\n cloudFiles CloudFile[]\n communications Communication[]\n twilioSettings TwilioSettings?\n telnyxSettings TelnyxSettings?\n aiSettings AiSettings?\n officeHours OfficeHours?\n officeContact OfficeContact?\n procedureTimeslot ProcedureTimeslot?\n insuranceContacts InsuranceContact[]\n patientConversations PatientConversation[]\n labRxTemplates LabRxTemplate[]\n seleniumSettings SeleniumSettings?\n}\n\nmodel Patient {\n id Int @id @default(autoincrement())\n firstName String\n lastName String\n dateOfBirth DateTime? @db.Date\n gender String\n phone String\n email String?\n address String?\n city String?\n state String? @default(\"MA\")\n zipCode String?\n insuranceProvider String?\n insuranceId String?\n groupNumber String?\n policyHolder String?\n policyHolderPatientId Int? // patient record of the policy holder, when picked from the DB\n policyHolderRelationship String? // ADA box 18: SELF | SPOUSE | DEPENDENT | OTHER\n allergies String?\n medicalConditions String?\n preferredLanguage String? @default(\"English\")\n status PatientStatus @default(UNKNOWN)\n remainingBenefit String?\n thirdPartyInsurance String?\n userId Int\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n user User @relation(fields: [userId], references: [id])\n appointments Appointment[]\n procedures AppointmentProcedure[]\n claims Claim[]\n groups PdfGroup[]\n payment Payment[]\n communications Communication[]\n documents PatientDocument[]\n conversation PatientConversation?\n cloudFolders CloudFolder[] @relation(\"PatientCloudFolder\")\n serviceHistory PatientServiceHistory[]\n\n @@index([insuranceId])\n @@index([createdAt])\n}\n\nenum PatientStatus {\n ACTIVE\n INACTIVE\n UNKNOWN\n PLAN_NOT_ACCEPTED\n}\n\nmodel Appointment {\n id Int @id @default(autoincrement())\n patientId Int\n userId Int\n staffId Int\n npiProviderId Int?\n title String\n date DateTime @db.Date\n startTime String // Store time as \"hh:mm\"\n endTime String // Store time as \"hh:mm\"\n type String // e.g., \"checkup\", \"cleaning\", \"filling\", etc.\n typeLocked Boolean @default(false) // true = user manually set; auto-sync will not overwrite\n notes String?\n procedureCodeNotes String?\n status String @default(\"scheduled\") // \"scheduled\", \"completed\", \"cancelled\", \"no-show\"\n movedByAi Boolean @default(false)\n createdAt DateTime @default(now())\n\n eligibilityStatus PatientStatus @default(UNKNOWN)\n\n patient Patient @relation(fields: [patientId], references: [id], onDelete: Cascade)\n user User @relation(fields: [userId], references: [id])\n staff Staff? @relation(fields: [staffId], references: [id])\n npiProvider NpiProvider? @relation(fields: [npiProviderId], references: [id])\n procedures AppointmentProcedure[]\n claims Claim[]\n files AppointmentFile[]\n\n @@index([patientId])\n @@index([date])\n}\n\nmodel AppointmentFile {\n id Int @id @default(autoincrement())\n appointmentId Int\n filename String\n mimeType String?\n filePath String?\n\n appointment Appointment @relation(fields: [appointmentId], references: [id], onDelete: Cascade)\n\n @@index([appointmentId])\n}\n\nmodel Staff {\n id Int @id @default(autoincrement())\n userId Int\n name String\n email String?\n role String // e.g., \"Dentist\", \"Hygienist\", \"Assistant\"\n phone String?\n createdAt DateTime @default(now())\n user User? @relation(fields: [userId], references: [id], onDelete: Cascade)\n appointments Appointment[]\n claims Claim[] @relation(\"ClaimStaff\")\n}\n\nmodel NpiProvider {\n id Int @id @default(autoincrement())\n userId Int\n npiNumber String\n providerName String\n /// State dental license (ADA claim form item 55)\n licenseNumber String?\n sortOrder Int @default(0)\n createdAt DateTime @default(now())\n\n user User @relation(fields: [userId], references: [id], onDelete: Cascade)\n claims Claim[]\n payments Payment[]\n commissionBatches CommissionBatch[]\n appointmentProcedures AppointmentProcedure[]\n appointments Appointment[]\n\n @@unique([userId, npiNumber])\n @@index([userId])\n}\n\nenum ProcedureSource {\n COMBO\n MANUAL\n}\n\nmodel AppointmentProcedure {\n id Int @id @default(autoincrement())\n appointmentId Int\n patientId Int\n npiProviderId Int?\n\n procedureCode String\n procedureLabel String?\n fee Decimal? @db.Decimal(10, 2)\n\n category String?\n\n toothNumber String?\n toothSurface String?\n oralCavityArea String?\n\n source ProcedureSource @default(MANUAL)\n comboKey String?\n\n createdAt DateTime @default(now())\n\n appointment Appointment @relation(fields: [appointmentId], references: [id], onDelete: Cascade)\n patient Patient @relation(fields: [patientId], references: [id], onDelete: Cascade)\n npiProvider NpiProvider? @relation(fields: [npiProviderId], references: [id])\n\n @@index([appointmentId])\n @@index([patientId])\n}\n\nmodel Claim {\n id Int @id @default(autoincrement())\n patientId Int\n /// @zod.number.int().nullable().optional()\n appointmentId Int?\n userId Int\n staffId Int\n patientName String\n memberId String\n dateOfBirth DateTime @db.Date\n remarks String\n missingTeethStatus MissingTeethStatus @default(No_missing)\n missingTeeth Json? // { \"T_14\": \"X\", \"T_G\": \"O\", ... }\n serviceDate DateTime\n insuranceProvider String // e.g., \"Delta MA\"\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n status ClaimStatus @default(PENDING)\n claimNumber String?\n preAuthNumber String?\n npiProviderId Int?\n\n patient Patient @relation(fields: [patientId], references: [id], onDelete: Cascade)\n appointment Appointment? @relation(fields: [appointmentId], references: [id], onDelete: Cascade)\n user User? @relation(fields: [userId], references: [id])\n staff Staff? @relation(\"ClaimStaff\", fields: [staffId], references: [id])\n npiProvider NpiProvider? @relation(fields: [npiProviderId], references: [id])\n\n serviceLines ServiceLine[]\n claimFiles ClaimFile[]\n payment Payment?\n}\n\nenum ClaimStatus {\n PENDING\n APPROVED\n CANCELLED\n REVIEW\n VOID\n PREAUTH\n}\n\nenum MissingTeethStatus {\n No_missing\n endentulous\n Yes_missing\n}\n\nmodel ServiceLine {\n id Int @id @default(autoincrement())\n claimId Int?\n paymentId Int?\n procedureCode String\n procedureDate DateTime @db.Date\n quad String?\n arch String?\n toothNumber String?\n toothSurface String?\n icn String?\n paidCode String?\n allowedAmount Decimal? @db.Decimal(10, 2)\n totalBilled Decimal @db.Decimal(10, 2)\n totalPaid Decimal @default(0.00) @db.Decimal(10, 2)\n totalAdjusted Decimal @default(0.00) @db.Decimal(10, 2)\n totalDue Decimal @default(0.00) @db.Decimal(10, 2)\n status ServiceLineStatus @default(UNPAID)\n\n claim Claim? @relation(fields: [claimId], references: [id], onDelete: Cascade)\n payment Payment? @relation(fields: [paymentId], references: [id], onDelete: Cascade)\n\n serviceLineTransactions ServiceLineTransaction[]\n}\n\nenum ServiceLineStatus {\n PENDING\n PARTIALLY_PAID\n PAID\n UNPAID\n ADJUSTED\n OVERPAID\n DENIED\n}\n\nmodel ClaimFile {\n id Int @id @default(autoincrement())\n claimId Int\n filename String\n mimeType String\n filePath String?\n\n claim Claim @relation(fields: [claimId], references: [id], onDelete: Cascade)\n}\n\nmodel InsuranceCredential {\n id Int @id @default(autoincrement())\n userId Int\n siteKey String\n username String\n password String\n\n user User @relation(fields: [userId], references: [id], onDelete: Cascade)\n\n @@unique([userId, siteKey])\n @@index([userId])\n}\n\nmodel ShoppingVendor {\n id Int @id @default(autoincrement())\n userId Int\n vendorName String\n websiteUrl String\n loginUsername String\n loginPassword String\n\n user User @relation(fields: [userId], references: [id], onDelete: Cascade)\n\n @@index([userId])\n}\n\nmodel PdfGroup {\n id Int @id @default(autoincrement())\n title String\n titleKey PdfTitleKey @default(OTHER)\n createdAt DateTime @default(now())\n patientId Int\n patient Patient @relation(fields: [patientId], references: [id], onDelete: Cascade)\n pdfs PdfFile[]\n\n @@index([patientId])\n @@index([titleKey])\n}\n\nmodel PdfFile {\n id Int @id @default(autoincrement())\n filename String\n pdfData Bytes\n uploadedAt DateTime @default(now())\n groupId Int\n group PdfGroup @relation(fields: [groupId], references: [id], onDelete: Cascade)\n\n @@index([groupId])\n}\n\nenum PdfTitleKey {\n INSURANCE_CLAIM\n INSURANCE_CLAIM_PREAUTH\n ELIGIBILITY_STATUS\n CLAIM_STATUS\n PREAUTH_APPROVAL\n OTHER\n}\n\nmodel Payment {\n id Int @id @default(autoincrement())\n claimId Int? @unique\n patientId Int\n userId Int\n updatedById Int?\n npiProviderId Int?\n totalBilled Decimal @db.Decimal(10, 2)\n totalPaid Decimal @default(0.00) @db.Decimal(10, 2)\n totalAdjusted Decimal @default(0.00) @db.Decimal(10, 2)\n totalDue Decimal @db.Decimal(10, 2)\n mhPaidAmount Decimal? @db.Decimal(10, 2)\n copayment Decimal @default(0.00) @db.Decimal(10, 2)\n adjustment Decimal @default(0.00) @db.Decimal(10, 2)\n status PaymentStatus @default(PENDING)\n notes String?\n icn String?\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n\n claim Claim? @relation(fields: [claimId], references: [id], onDelete: Cascade)\n patient Patient @relation(fields: [patientId], references: [id], onDelete: Cascade)\n updatedBy User? @relation(\"PaymentUpdatedBy\", fields: [updatedById], references: [id])\n npiProvider NpiProvider? @relation(fields: [npiProviderId], references: [id])\n serviceLineTransactions ServiceLineTransaction[]\n serviceLines ServiceLine[]\n commissionBatchItems CommissionBatchItem[]\n\n @@index([claimId])\n @@index([patientId])\n @@index([createdAt])\n}\n\nmodel ServiceLineTransaction {\n id Int @id @default(autoincrement())\n paymentId Int\n serviceLineId Int\n transactionId String?\n paidAmount Decimal @db.Decimal(10, 2)\n adjustedAmount Decimal @default(0.00) @db.Decimal(10, 2)\n method PaymentMethod\n receivedDate DateTime\n payerName String?\n notes String?\n createdAt DateTime @default(now())\n\n payment Payment @relation(fields: [paymentId], references: [id], onDelete: Cascade)\n serviceLine ServiceLine @relation(fields: [serviceLineId], references: [id], onDelete: Cascade)\n\n @@index([paymentId])\n @@index([serviceLineId])\n}\n\nenum PaymentStatus {\n PENDING\n PARTIALLY_PAID\n PAID\n OVERPAID\n DENIED\n VOID\n}\n\nenum PaymentMethod {\n EFT\n CHECK\n CASH\n CARD\n OTHER\n}\n\n// Database management page\nmodel DatabaseBackup {\n id Int @id @default(autoincrement())\n userId Int\n createdAt DateTime @default(now())\n\n user User @relation(fields: [userId], references: [id], onDelete: Cascade)\n\n @@index([userId])\n @@index([createdAt])\n}\n\nmodel BackupDestination {\n id Int @id @default(autoincrement())\n userId Int\n path String\n isActive Boolean @default(true)\n createdAt DateTime @default(now())\n\n user User @relation(fields: [userId], references: [id])\n}\n\nmodel Notification {\n id Int @id @default(autoincrement())\n userId Int\n type NotificationTypes\n message String\n createdAt DateTime @default(now())\n read Boolean @default(false)\n\n user User @relation(fields: [userId], references: [id], onDelete: Cascade)\n\n @@index([userId])\n @@index([createdAt])\n}\n\nenum NotificationTypes {\n BACKUP\n CLAIM\n PAYMENT\n ETC\n}\n\n// Cron job execution log\nmodel CronJobLog {\n id Int @id @default(autoincrement())\n jobName String // e.g. \"local-backup\", \"usb-backup\"\n status String // \"success\" | \"failed\" | \"skipped\"\n startedAt DateTime\n completedAt DateTime?\n durationMs Int?\n errorMessage String?\n\n @@index([jobName])\n @@index([startedAt])\n @@index([status])\n}\n\nmodel CloudFolder {\n id Int @id @default(autoincrement())\n userId Int\n name String\n parentId Int?\n patientId Int?\n parent CloudFolder? @relation(\"FolderChildren\", fields: [parentId], references: [id], onDelete: Cascade)\n children CloudFolder[] @relation(\"FolderChildren\")\n user User @relation(fields: [userId], references: [id])\n patient Patient? @relation(\"PatientCloudFolder\", fields: [patientId], references: [id], onDelete: SetNull)\n files CloudFile[]\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n\n @@unique([userId, parentId, name]) // prevents sibling folder name duplicates\n @@index([parentId])\n @@index([patientId])\n}\n\nmodel CloudFile {\n id Int @id @default(autoincrement())\n userId Int\n name String\n mimeType String?\n fileSize BigInt @db.BigInt\n folderId Int? // optional: null => root\n isComplete Boolean @default(false) // upload completed?\n totalChunks Int? // optional: expected number of chunks\n diskPath String? // relative path on disk under uploads/\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n user User @relation(fields: [userId], references: [id])\n folder CloudFolder? @relation(fields: [folderId], references: [id], onDelete: SetNull)\n\n chunks CloudFileChunk[]\n\n @@index([folderId])\n}\n\nmodel CloudFileChunk {\n id Int @id @default(autoincrement())\n fileId Int\n seq Int\n data Bytes\n createdAt DateTime @default(now())\n\n file CloudFile @relation(fields: [fileId], references: [id], onDelete: Cascade)\n\n @@unique([fileId, seq])\n @@index([fileId, seq])\n}\n\n// patient-connection-\nenum CommunicationChannel {\n sms\n voice\n}\n\nenum CommunicationDirection {\n outbound\n inbound\n}\n\nenum CommunicationStatus {\n queued\n sent\n delivered\n failed\n completed\n busy\n no_answer\n}\n\nenum CommunicationProvider {\n twilio\n telnyx\n}\n\nmodel Communication {\n id Int @id @default(autoincrement())\n patientId Int\n userId Int?\n\n channel CommunicationChannel\n direction CommunicationDirection\n status CommunicationStatus\n // Which platform produced twilioSid — twilio for dial-pad-originated calls,\n // telnyx for everything else (SMS, inbound/AI voice, staff-triggered outbound calls).\n provider CommunicationProvider @default(twilio)\n\n body String?\n callDuration Int?\n // Provider SID — Twilio MessageSid/CallSid, or Telnyx message/call id. See `provider`.\n twilioSid String?\n\n createdAt DateTime @default(now())\n\n // Relations\n patient Patient @relation(fields: [patientId], references: [id])\n user User? @relation(fields: [userId], references: [id])\n\n @@map(\"communications\")\n}\n\nmodel PatientDocument {\n id Int @id @default(autoincrement())\n patientId Int\n filename String\n originalName String\n mimeType String\n fileSize BigInt\n filePath String\n uploadedAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n patient Patient @relation(fields: [patientId], references: [id], onDelete: Cascade)\n\n @@index([patientId])\n @@index([uploadedAt])\n}\n\nmodel TwilioSettings {\n id Int @id @default(autoincrement())\n userId Int @unique\n accountSid String\n authToken String\n phoneNumber String\n // Vestigial — inbound voice moved to Telnyx (TelnyxSettings.greetingMessage). No longer\n // read/written; kept to avoid a destructive migration for a cosmetic cleanup.\n greetingMessage String?\n templates Json?\n\n user User @relation(fields: [userId], references: [id], onDelete: Cascade)\n\n @@map(\"twilio_settings\")\n}\n\nmodel TelnyxSettings {\n id Int @id @default(autoincrement())\n userId Int @unique\n apiKey String\n // Telnyx account SID (Mission Control Portal), required to place outbound\n // TeXML calls via POST /texml/Accounts/{accountSid}/Calls — separate from apiKey.\n accountSid String?\n phoneNumber String\n texmlApplicationId String?\n messagingProfileId String?\n webhookPublicKey String?\n greetingMessage String?\n\n user User @relation(fields: [userId], references: [id], onDelete: Cascade)\n\n @@map(\"telnyx_settings\")\n}\n\nmodel AiSettings {\n id Int @id @default(autoincrement())\n userId Int @unique\n apiKey String\n aiEnabled Boolean @default(true)\n openAiKey String @default(\"\")\n openAiEnabled Boolean @default(false)\n claudeAiKey String @default(\"\")\n claudeAiEnabled Boolean @default(false)\n claudeAiModel String @default(\"claude-haiku-4-5-20251001\")\n openAiModel String @default(\"gpt-5.2\")\n googleAiModel String @default(\"gemini-2.5-flash\")\n dentalMgmtKey String @default(\"\")\n dentalMgmtEnabled Boolean @default(false)\n afterHoursEnabled Boolean @default(true)\n openPhoneReply Boolean @default(false)\n\n user User @relation(fields: [userId], references: [id], onDelete: Cascade)\n\n @@map(\"ai_settings\")\n}\n\nmodel OfficeHours {\n id Int @id @default(autoincrement())\n userId Int @unique\n data Json\n\n user User @relation(fields: [userId], references: [id], onDelete: Cascade)\n\n @@map(\"office_hours\")\n}\n\nmodel OfficeContact {\n id Int @id @default(autoincrement())\n userId Int @unique\n /// Legal (registered) business name — ADA claim form items 48 and 56\n legalName String?\n /// Dental office name as the public knows it (DBA)\n officeName String?\n receptionistName String?\n dentistName String?\n phoneNumber String?\n email String?\n fax String?\n streetAddress String?\n city String?\n state String?\n zipCode String?\n /// Office (billing) NPI — ADA claim form items 48-51\n billingName String?\n billingNpi String?\n billingLicense String?\n billingTaxId String?\n\n user User @relation(fields: [userId], references: [id], onDelete: Cascade)\n\n @@map(\"office_contact\")\n}\n\nmodel InsuranceContact {\n id Int @id @default(autoincrement())\n userId Int\n name String\n phoneNumber String?\n createdAt DateTime @default(now())\n\n user User @relation(fields: [userId], references: [id], onDelete: Cascade)\n\n @@map(\"insurance_contact\")\n}\n\nmodel ProcedureTimeslot {\n id Int @id @default(autoincrement())\n userId Int @unique\n data Json\n\n user User @relation(fields: [userId], references: [id], onDelete: Cascade)\n\n @@map(\"procedure_timeslot\")\n}\n\nmodel PatientConversation {\n id Int @id @default(autoincrement())\n patientId Int @unique\n userId Int\n stage String @default(\"initial\")\n aiHandoff Boolean @default(true)\n updatedAt DateTime @updatedAt\n\n patient Patient @relation(fields: [patientId], references: [id], onDelete: Cascade)\n user User @relation(fields: [userId], references: [id], onDelete: Cascade)\n\n @@map(\"patient_conversation\")\n}\n\n// Snapshot of the MassHealth Service History table, replaced on each eligibility check\nmodel PatientServiceHistory {\n id Int @id @default(autoincrement())\n patientId Int\n procedureCode String\n description String?\n toothQuadArchSurface String?\n placeOfService String?\n serviceDate String? // as shown by the portal, e.g. 10/15/2026\n createdAt DateTime @default(now())\n\n patient Patient @relation(fields: [patientId], references: [id], onDelete: Cascade)\n\n @@index([patientId])\n @@map(\"patient_service_history\")\n}\n\nmodel LabRxTemplate {\n id Int @id @default(autoincrement())\n userId Int\n name String\n labName String?\n labPhone String?\n labFax String?\n labAddress String?\n labAccount String?\n caseType String?\n material String?\n instructions String?\n sortOrder Int @default(0)\n createdAt DateTime @default(now())\n updatedAt DateTime @updatedAt\n\n user User @relation(fields: [userId], references: [id], onDelete: Cascade)\n\n @@index([userId])\n @@map(\"lab_rx_template\")\n}\n\n// Commission tracking\nmodel CommissionBatch {\n id Int @id @default(autoincrement())\n npiProviderId Int\n totalCollection Decimal @db.Decimal(14, 2)\n commissionAmount Decimal @db.Decimal(14, 2)\n notes String?\n createdAt DateTime @default(now())\n\n npiProvider NpiProvider @relation(fields: [npiProviderId], references: [id])\n items CommissionBatchItem[]\n\n @@index([npiProviderId])\n}\n\nmodel CommissionBatchItem {\n id Int @id @default(autoincrement())\n commissionBatchId Int\n paymentId Int\n collectionAmount Decimal @db.Decimal(14, 2)\n\n commissionBatch CommissionBatch @relation(fields: [commissionBatchId], references: [id], onDelete: Cascade)\n payment Payment @relation(fields: [paymentId], references: [id])\n\n @@unique([commissionBatchId, paymentId])\n @@index([paymentId])\n}\n\nmodel SeleniumSettings {\n id Int @id @default(autoincrement())\n userId Int @unique\n paymentGroupId String @default(\"\")\n\n user User @relation(fields: [userId], references: [id], onDelete: Cascade)\n\n @@map(\"selenium_settings\")\n}\n" } config.runtimeDataModel = JSON.parse("{\"models\":{\"User\":{\"fields\":[{\"name\":\"id\",\"kind\":\"scalar\",\"type\":\"Int\"},{\"name\":\"username\",\"kind\":\"scalar\",\"type\":\"String\"},{\"name\":\"password\",\"kind\":\"scalar\",\"type\":\"String\"},{\"name\":\"autoBackupEnabled\",\"kind\":\"scalar\",\"type\":\"Boolean\"},{\"name\":\"autoBackupHour\",\"kind\":\"scalar\",\"type\":\"Int\"},{\"name\":\"usbBackupEnabled\",\"kind\":\"scalar\",\"type\":\"Boolean\"},{\"name\":\"usbBackupHour\",\"kind\":\"scalar\",\"type\":\"Int\"},{\"name\":\"autoMhCheckEnabled\",\"kind\":\"scalar\",\"type\":\"Boolean\"},{\"name\":\"autoMhCheckDayOfWeek\",\"kind\":\"scalar\",\"type\":\"Int\"},{\"name\":\"autoMhCheckHour\",\"kind\":\"scalar\",\"type\":\"Int\"},{\"name\":\"patients\",\"kind\":\"object\",\"type\":\"Patient\",\"relationName\":\"PatientToUser\"},{\"name\":\"appointments\",\"kind\":\"object\",\"type\":\"Appointment\",\"relationName\":\"AppointmentToUser\"},{\"name\":\"staff\",\"kind\":\"object\",\"type\":\"Staff\",\"relationName\":\"StaffToUser\"},{\"name\":\"npiProviders\",\"kind\":\"object\",\"type\":\"NpiProvider\",\"relationName\":\"NpiProviderToUser\"},{\"name\":\"claims\",\"kind\":\"object\",\"type\":\"Claim\",\"relationName\":\"ClaimToUser\"},{\"name\":\"insuranceCredentials\",\"kind\":\"object\",\"type\":\"InsuranceCredential\",\"relationName\":\"InsuranceCredentialToUser\"},{\"name\":\"shoppingVendors\",\"kind\":\"object\",\"type\":\"ShoppingVendor\",\"relationName\":\"ShoppingVendorToUser\"},{\"name\":\"updatedPayments\",\"kind\":\"object\",\"type\":\"Payment\",\"relationName\":\"PaymentUpdatedBy\"},{\"name\":\"backups\",\"kind\":\"object\",\"type\":\"DatabaseBackup\",\"relationName\":\"DatabaseBackupToUser\"},{\"name\":\"backupDestinations\",\"kind\":\"object\",\"type\":\"BackupDestination\",\"relationName\":\"BackupDestinationToUser\"},{\"name\":\"notifications\",\"kind\":\"object\",\"type\":\"Notification\",\"relationName\":\"NotificationToUser\"},{\"name\":\"cloudFolders\",\"kind\":\"object\",\"type\":\"CloudFolder\",\"relationName\":\"CloudFolderToUser\"},{\"name\":\"cloudFiles\",\"kind\":\"object\",\"type\":\"CloudFile\",\"relationName\":\"CloudFileToUser\"},{\"name\":\"communications\",\"kind\":\"object\",\"type\":\"Communication\",\"relationName\":\"CommunicationToUser\"},{\"name\":\"twilioSettings\",\"kind\":\"object\",\"type\":\"TwilioSettings\",\"relationName\":\"TwilioSettingsToUser\"},{\"name\":\"telnyxSettings\",\"kind\":\"object\",\"type\":\"TelnyxSettings\",\"relationName\":\"TelnyxSettingsToUser\"},{\"name\":\"aiSettings\",\"kind\":\"object\",\"type\":\"AiSettings\",\"relationName\":\"AiSettingsToUser\"},{\"name\":\"officeHours\",\"kind\":\"object\",\"type\":\"OfficeHours\",\"relationName\":\"OfficeHoursToUser\"},{\"name\":\"officeContact\",\"kind\":\"object\",\"type\":\"OfficeContact\",\"relationName\":\"OfficeContactToUser\"},{\"name\":\"procedureTimeslot\",\"kind\":\"object\",\"type\":\"ProcedureTimeslot\",\"relationName\":\"ProcedureTimeslotToUser\"},{\"name\":\"insuranceContacts\",\"kind\":\"object\",\"type\":\"InsuranceContact\",\"relationName\":\"InsuranceContactToUser\"},{\"name\":\"patientConversations\",\"kind\":\"object\",\"type\":\"PatientConversation\",\"relationName\":\"PatientConversationToUser\"},{\"name\":\"labRxTemplates\",\"kind\":\"object\",\"type\":\"LabRxTemplate\",\"relationName\":\"LabRxTemplateToUser\"},{\"name\":\"seleniumSettings\",\"kind\":\"object\",\"type\":\"SeleniumSettings\",\"relationName\":\"SeleniumSettingsToUser\"}],\"dbName\":null},\"Patient\":{\"fields\":[{\"name\":\"id\",\"kind\":\"scalar\",\"type\":\"Int\"},{\"name\":\"firstName\",\"kind\":\"scalar\",\"type\":\"String\"},{\"name\":\"lastName\",\"kind\":\"scalar\",\"type\":\"String\"},{\"name\":\"dateOfBirth\",\"kind\":\"scalar\",\"type\":\"DateTime\"},{\"name\":\"gender\",\"kind\":\"scalar\",\"type\":\"String\"},{\"name\":\"phone\",\"kind\":\"scalar\",\"type\":\"String\"},{\"name\":\"email\",\"kind\":\"scalar\",\"type\":\"String\"},{\"name\":\"address\",\"kind\":\"scalar\",\"type\":\"String\"},{\"name\":\"city\",\"kind\":\"scalar\",\"type\":\"String\"},{\"name\":\"state\",\"kind\":\"scalar\",\"type\":\"String\"},{\"name\":\"zipCode\",\"kind\":\"scalar\",\"type\":\"String\"},{\"name\":\"insuranceProvider\",\"kind\":\"scalar\",\"type\":\"String\"},{\"name\":\"insuranceId\",\"kind\":\"scalar\",\"type\":\"String\"},{\"name\":\"groupNumber\",\"kind\":\"scalar\",\"type\":\"String\"},{\"name\":\"policyHolder\",\"kind\":\"scalar\",\"type\":\"String\"},{\"name\":\"policyHolderPatientId\",\"kind\":\"scalar\",\"type\":\"Int\"},{\"name\":\"policyHolderRelationship\",\"kind\":\"scalar\",\"type\":\"String\"},{\"name\":\"allergies\",\"kind\":\"scalar\",\"type\":\"String\"},{\"name\":\"medicalConditions\",\"kind\":\"scalar\",\"type\":\"String\"},{\"name\":\"preferredLanguage\",\"kind\":\"scalar\",\"type\":\"String\"},{\"name\":\"status\",\"kind\":\"enum\",\"type\":\"PatientStatus\"},{\"name\":\"remainingBenefit\",\"kind\":\"scalar\",\"type\":\"String\"},{\"name\":\"thirdPartyInsurance\",\"kind\":\"scalar\",\"type\":\"String\"},{\"name\":\"userId\",\"kind\":\"scalar\",\"type\":\"Int\"},{\"name\":\"createdAt\",\"kind\":\"scalar\",\"type\":\"DateTime\"},{\"name\":\"updatedAt\",\"kind\":\"scalar\",\"type\":\"DateTime\"},{\"name\":\"user\",\"kind\":\"object\",\"type\":\"User\",\"relationName\":\"PatientToUser\"},{\"name\":\"appointments\",\"kind\":\"object\",\"type\":\"Appointment\",\"relationName\":\"AppointmentToPatient\"},{\"name\":\"procedures\",\"kind\":\"object\",\"type\":\"AppointmentProcedure\",\"relationName\":\"AppointmentProcedureToPatient\"},{\"name\":\"claims\",\"kind\":\"object\",\"type\":\"Claim\",\"relationName\":\"ClaimToPatient\"},{\"name\":\"groups\",\"kind\":\"object\",\"type\":\"PdfGroup\",\"relationName\":\"PatientToPdfGroup\"},{\"name\":\"payment\",\"kind\":\"object\",\"type\":\"Payment\",\"relationName\":\"PatientToPayment\"},{\"name\":\"communications\",\"kind\":\"object\",\"type\":\"Communication\",\"relationName\":\"CommunicationToPatient\"},{\"name\":\"documents\",\"kind\":\"object\",\"type\":\"PatientDocument\",\"relationName\":\"PatientToPatientDocument\"},{\"name\":\"conversation\",\"kind\":\"object\",\"type\":\"PatientConversation\",\"relationName\":\"PatientToPatientConversation\"},{\"name\":\"cloudFolders\",\"kind\":\"object\",\"type\":\"CloudFolder\",\"relationName\":\"PatientCloudFolder\"},{\"name\":\"serviceHistory\",\"kind\":\"object\",\"type\":\"PatientServiceHistory\",\"relationName\":\"PatientToPatientServiceHistory\"}],\"dbName\":null},\"Appointment\":{\"fields\":[{\"name\":\"id\",\"kind\":\"scalar\",\"type\":\"Int\"},{\"name\":\"patientId\",\"kind\":\"scalar\",\"type\":\"Int\"},{\"name\":\"userId\",\"kind\":\"scalar\",\"type\":\"Int\"},{\"name\":\"staffId\",\"kind\":\"scalar\",\"type\":\"Int\"},{\"name\":\"npiProviderId\",\"kind\":\"scalar\",\"type\":\"Int\"},{\"name\":\"title\",\"kind\":\"scalar\",\"type\":\"String\"},{\"name\":\"date\",\"kind\":\"scalar\",\"type\":\"DateTime\"},{\"name\":\"startTime\",\"kind\":\"scalar\",\"type\":\"String\"},{\"name\":\"endTime\",\"kind\":\"scalar\",\"type\":\"String\"},{\"name\":\"type\",\"kind\":\"scalar\",\"type\":\"String\"},{\"name\":\"typeLocked\",\"kind\":\"scalar\",\"type\":\"Boolean\"},{\"name\":\"notes\",\"kind\":\"scalar\",\"type\":\"String\"},{\"name\":\"procedureCodeNotes\",\"kind\":\"scalar\",\"type\":\"String\"},{\"name\":\"status\",\"kind\":\"scalar\",\"type\":\"String\"},{\"name\":\"movedByAi\",\"kind\":\"scalar\",\"type\":\"Boolean\"},{\"name\":\"createdAt\",\"kind\":\"scalar\",\"type\":\"DateTime\"},{\"name\":\"eligibilityStatus\",\"kind\":\"enum\",\"type\":\"PatientStatus\"},{\"name\":\"patient\",\"kind\":\"object\",\"type\":\"Patient\",\"relationName\":\"AppointmentToPatient\"},{\"name\":\"user\",\"kind\":\"object\",\"type\":\"User\",\"relationName\":\"AppointmentToUser\"},{\"name\":\"staff\",\"kind\":\"object\",\"type\":\"Staff\",\"relationName\":\"AppointmentToStaff\"},{\"name\":\"npiProvider\",\"kind\":\"object\",\"type\":\"NpiProvider\",\"relationName\":\"AppointmentToNpiProvider\"},{\"name\":\"procedures\",\"kind\":\"object\",\"type\":\"AppointmentProcedure\",\"relationName\":\"AppointmentToAppointmentProcedure\"},{\"name\":\"claims\",\"kind\":\"object\",\"type\":\"Claim\",\"relationName\":\"AppointmentToClaim\"},{\"name\":\"files\",\"kind\":\"object\",\"type\":\"AppointmentFile\",\"relationName\":\"AppointmentToAppointmentFile\"}],\"dbName\":null},\"AppointmentFile\":{\"fields\":[{\"name\":\"id\",\"kind\":\"scalar\",\"type\":\"Int\"},{\"name\":\"appointmentId\",\"kind\":\"scalar\",\"type\":\"Int\"},{\"name\":\"filename\",\"kind\":\"scalar\",\"type\":\"String\"},{\"name\":\"mimeType\",\"kind\":\"scalar\",\"type\":\"String\"},{\"name\":\"filePath\",\"kind\":\"scalar\",\"type\":\"String\"},{\"name\":\"appointment\",\"kind\":\"object\",\"type\":\"Appointment\",\"relationName\":\"AppointmentToAppointmentFile\"}],\"dbName\":null},\"Staff\":{\"fields\":[{\"name\":\"id\",\"kind\":\"scalar\",\"type\":\"Int\"},{\"name\":\"userId\",\"kind\":\"scalar\",\"type\":\"Int\"},{\"name\":\"name\",\"kind\":\"scalar\",\"type\":\"String\"},{\"name\":\"email\",\"kind\":\"scalar\",\"type\":\"String\"},{\"name\":\"role\",\"kind\":\"scalar\",\"type\":\"String\"},{\"name\":\"phone\",\"kind\":\"scalar\",\"type\":\"String\"},{\"name\":\"createdAt\",\"kind\":\"scalar\",\"type\":\"DateTime\"},{\"name\":\"user\",\"kind\":\"object\",\"type\":\"User\",\"relationName\":\"StaffToUser\"},{\"name\":\"appointments\",\"kind\":\"object\",\"type\":\"Appointment\",\"relationName\":\"AppointmentToStaff\"},{\"name\":\"claims\",\"kind\":\"object\",\"type\":\"Claim\",\"relationName\":\"ClaimStaff\"}],\"dbName\":null},\"NpiProvider\":{\"fields\":[{\"name\":\"id\",\"kind\":\"scalar\",\"type\":\"Int\"},{\"name\":\"userId\",\"kind\":\"scalar\",\"type\":\"Int\"},{\"name\":\"npiNumber\",\"kind\":\"scalar\",\"type\":\"String\"},{\"name\":\"providerName\",\"kind\":\"scalar\",\"type\":\"String\"},{\"name\":\"licenseNumber\",\"kind\":\"scalar\",\"type\":\"String\"},{\"name\":\"sortOrder\",\"kind\":\"scalar\",\"type\":\"Int\"},{\"name\":\"createdAt\",\"kind\":\"scalar\",\"type\":\"DateTime\"},{\"name\":\"user\",\"kind\":\"object\",\"type\":\"User\",\"relationName\":\"NpiProviderToUser\"},{\"name\":\"claims\",\"kind\":\"object\",\"type\":\"Claim\",\"relationName\":\"ClaimToNpiProvider\"},{\"name\":\"payments\",\"kind\":\"object\",\"type\":\"Payment\",\"relationName\":\"NpiProviderToPayment\"},{\"name\":\"commissionBatches\",\"kind\":\"object\",\"type\":\"CommissionBatch\",\"relationName\":\"CommissionBatchToNpiProvider\"},{\"name\":\"appointmentProcedures\",\"kind\":\"object\",\"type\":\"AppointmentProcedure\",\"relationName\":\"AppointmentProcedureToNpiProvider\"},{\"name\":\"appointments\",\"kind\":\"object\",\"type\":\"Appointment\",\"relationName\":\"AppointmentToNpiProvider\"}],\"dbName\":null},\"AppointmentProcedure\":{\"fields\":[{\"name\":\"id\",\"kind\":\"scalar\",\"type\":\"Int\"},{\"name\":\"appointmentId\",\"kind\":\"scalar\",\"type\":\"Int\"},{\"name\":\"patientId\",\"kind\":\"scalar\",\"type\":\"Int\"},{\"name\":\"npiProviderId\",\"kind\":\"scalar\",\"type\":\"Int\"},{\"name\":\"procedureCode\",\"kind\":\"scalar\",\"type\":\"String\"},{\"name\":\"procedureLabel\",\"kind\":\"scalar\",\"type\":\"String\"},{\"name\":\"fee\",\"kind\":\"scalar\",\"type\":\"Decimal\"},{\"name\":\"category\",\"kind\":\"scalar\",\"type\":\"String\"},{\"name\":\"toothNumber\",\"kind\":\"scalar\",\"type\":\"String\"},{\"name\":\"toothSurface\",\"kind\":\"scalar\",\"type\":\"String\"},{\"name\":\"oralCavityArea\",\"kind\":\"scalar\",\"type\":\"String\"},{\"name\":\"source\",\"kind\":\"enum\",\"type\":\"ProcedureSource\"},{\"name\":\"comboKey\",\"kind\":\"scalar\",\"type\":\"String\"},{\"name\":\"createdAt\",\"kind\":\"scalar\",\"type\":\"DateTime\"},{\"name\":\"appointment\",\"kind\":\"object\",\"type\":\"Appointment\",\"relationName\":\"AppointmentToAppointmentProcedure\"},{\"name\":\"patient\",\"kind\":\"object\",\"type\":\"Patient\",\"relationName\":\"AppointmentProcedureToPatient\"},{\"name\":\"npiProvider\",\"kind\":\"object\",\"type\":\"NpiProvider\",\"relationName\":\"AppointmentProcedureToNpiProvider\"}],\"dbName\":null},\"Claim\":{\"fields\":[{\"name\":\"id\",\"kind\":\"scalar\",\"type\":\"Int\"},{\"name\":\"patientId\",\"kind\":\"scalar\",\"type\":\"Int\"},{\"name\":\"appointmentId\",\"kind\":\"scalar\",\"type\":\"Int\"},{\"name\":\"userId\",\"kind\":\"scalar\",\"type\":\"Int\"},{\"name\":\"staffId\",\"kind\":\"scalar\",\"type\":\"Int\"},{\"name\":\"patientName\",\"kind\":\"scalar\",\"type\":\"String\"},{\"name\":\"memberId\",\"kind\":\"scalar\",\"type\":\"String\"},{\"name\":\"dateOfBirth\",\"kind\":\"scalar\",\"type\":\"DateTime\"},{\"name\":\"remarks\",\"kind\":\"scalar\",\"type\":\"String\"},{\"name\":\"missingTeethStatus\",\"kind\":\"enum\",\"type\":\"MissingTeethStatus\"},{\"name\":\"missingTeeth\",\"kind\":\"scalar\",\"type\":\"Json\"},{\"name\":\"serviceDate\",\"kind\":\"scalar\",\"type\":\"DateTime\"},{\"name\":\"insuranceProvider\",\"kind\":\"scalar\",\"type\":\"String\"},{\"name\":\"createdAt\",\"kind\":\"scalar\",\"type\":\"DateTime\"},{\"name\":\"updatedAt\",\"kind\":\"scalar\",\"type\":\"DateTime\"},{\"name\":\"status\",\"kind\":\"enum\",\"type\":\"ClaimStatus\"},{\"name\":\"claimNumber\",\"kind\":\"scalar\",\"type\":\"String\"},{\"name\":\"preAuthNumber\",\"kind\":\"scalar\",\"type\":\"String\"},{\"name\":\"npiProviderId\",\"kind\":\"scalar\",\"type\":\"Int\"},{\"name\":\"patient\",\"kind\":\"object\",\"type\":\"Patient\",\"relationName\":\"ClaimToPatient\"},{\"name\":\"appointment\",\"kind\":\"object\",\"type\":\"Appointment\",\"relationName\":\"AppointmentToClaim\"},{\"name\":\"user\",\"kind\":\"object\",\"type\":\"User\",\"relationName\":\"ClaimToUser\"},{\"name\":\"staff\",\"kind\":\"object\",\"type\":\"Staff\",\"relationName\":\"ClaimStaff\"},{\"name\":\"npiProvider\",\"kind\":\"object\",\"type\":\"NpiProvider\",\"relationName\":\"ClaimToNpiProvider\"},{\"name\":\"serviceLines\",\"kind\":\"object\",\"type\":\"ServiceLine\",\"relationName\":\"ClaimToServiceLine\"},{\"name\":\"claimFiles\",\"kind\":\"object\",\"type\":\"ClaimFile\",\"relationName\":\"ClaimToClaimFile\"},{\"name\":\"payment\",\"kind\":\"object\",\"type\":\"Payment\",\"relationName\":\"ClaimToPayment\"}],\"dbName\":null},\"ServiceLine\":{\"fields\":[{\"name\":\"id\",\"kind\":\"scalar\",\"type\":\"Int\"},{\"name\":\"claimId\",\"kind\":\"scalar\",\"type\":\"Int\"},{\"name\":\"paymentId\",\"kind\":\"scalar\",\"type\":\"Int\"},{\"name\":\"procedureCode\",\"kind\":\"scalar\",\"type\":\"String\"},{\"name\":\"procedureDate\",\"kind\":\"scalar\",\"type\":\"DateTime\"},{\"name\":\"quad\",\"kind\":\"scalar\",\"type\":\"String\"},{\"name\":\"arch\",\"kind\":\"scalar\",\"type\":\"String\"},{\"name\":\"toothNumber\",\"kind\":\"scalar\",\"type\":\"String\"},{\"name\":\"toothSurface\",\"kind\":\"scalar\",\"type\":\"String\"},{\"name\":\"icn\",\"kind\":\"scalar\",\"type\":\"String\"},{\"name\":\"paidCode\",\"kind\":\"scalar\",\"type\":\"String\"},{\"name\":\"allowedAmount\",\"kind\":\"scalar\",\"type\":\"Decimal\"},{\"name\":\"totalBilled\",\"kind\":\"scalar\",\"type\":\"Decimal\"},{\"name\":\"totalPaid\",\"kind\":\"scalar\",\"type\":\"Decimal\"},{\"name\":\"totalAdjusted\",\"kind\":\"scalar\",\"type\":\"Decimal\"},{\"name\":\"totalDue\",\"kind\":\"scalar\",\"type\":\"Decimal\"},{\"name\":\"status\",\"kind\":\"enum\",\"type\":\"ServiceLineStatus\"},{\"name\":\"claim\",\"kind\":\"object\",\"type\":\"Claim\",\"relationName\":\"ClaimToServiceLine\"},{\"name\":\"payment\",\"kind\":\"object\",\"type\":\"Payment\",\"relationName\":\"PaymentToServiceLine\"},{\"name\":\"serviceLineTransactions\",\"kind\":\"object\",\"type\":\"ServiceLineTransaction\",\"relationName\":\"ServiceLineToServiceLineTransaction\"}],\"dbName\":null},\"ClaimFile\":{\"fields\":[{\"name\":\"id\",\"kind\":\"scalar\",\"type\":\"Int\"},{\"name\":\"claimId\",\"kind\":\"scalar\",\"type\":\"Int\"},{\"name\":\"filename\",\"kind\":\"scalar\",\"type\":\"String\"},{\"name\":\"mimeType\",\"kind\":\"scalar\",\"type\":\"String\"},{\"name\":\"filePath\",\"kind\":\"scalar\",\"type\":\"String\"},{\"name\":\"claim\",\"kind\":\"object\",\"type\":\"Claim\",\"relationName\":\"ClaimToClaimFile\"}],\"dbName\":null},\"InsuranceCredential\":{\"fields\":[{\"name\":\"id\",\"kind\":\"scalar\",\"type\":\"Int\"},{\"name\":\"userId\",\"kind\":\"scalar\",\"type\":\"Int\"},{\"name\":\"siteKey\",\"kind\":\"scalar\",\"type\":\"String\"},{\"name\":\"username\",\"kind\":\"scalar\",\"type\":\"String\"},{\"name\":\"password\",\"kind\":\"scalar\",\"type\":\"String\"},{\"name\":\"user\",\"kind\":\"object\",\"type\":\"User\",\"relationName\":\"InsuranceCredentialToUser\"}],\"dbName\":null},\"ShoppingVendor\":{\"fields\":[{\"name\":\"id\",\"kind\":\"scalar\",\"type\":\"Int\"},{\"name\":\"userId\",\"kind\":\"scalar\",\"type\":\"Int\"},{\"name\":\"vendorName\",\"kind\":\"scalar\",\"type\":\"String\"},{\"name\":\"websiteUrl\",\"kind\":\"scalar\",\"type\":\"String\"},{\"name\":\"loginUsername\",\"kind\":\"scalar\",\"type\":\"String\"},{\"name\":\"loginPassword\",\"kind\":\"scalar\",\"type\":\"String\"},{\"name\":\"user\",\"kind\":\"object\",\"type\":\"User\",\"relationName\":\"ShoppingVendorToUser\"}],\"dbName\":null},\"PdfGroup\":{\"fields\":[{\"name\":\"id\",\"kind\":\"scalar\",\"type\":\"Int\"},{\"name\":\"title\",\"kind\":\"scalar\",\"type\":\"String\"},{\"name\":\"titleKey\",\"kind\":\"enum\",\"type\":\"PdfTitleKey\"},{\"name\":\"createdAt\",\"kind\":\"scalar\",\"type\":\"DateTime\"},{\"name\":\"patientId\",\"kind\":\"scalar\",\"type\":\"Int\"},{\"name\":\"patient\",\"kind\":\"object\",\"type\":\"Patient\",\"relationName\":\"PatientToPdfGroup\"},{\"name\":\"pdfs\",\"kind\":\"object\",\"type\":\"PdfFile\",\"relationName\":\"PdfFileToPdfGroup\"}],\"dbName\":null},\"PdfFile\":{\"fields\":[{\"name\":\"id\",\"kind\":\"scalar\",\"type\":\"Int\"},{\"name\":\"filename\",\"kind\":\"scalar\",\"type\":\"String\"},{\"name\":\"pdfData\",\"kind\":\"scalar\",\"type\":\"Bytes\"},{\"name\":\"uploadedAt\",\"kind\":\"scalar\",\"type\":\"DateTime\"},{\"name\":\"groupId\",\"kind\":\"scalar\",\"type\":\"Int\"},{\"name\":\"group\",\"kind\":\"object\",\"type\":\"PdfGroup\",\"relationName\":\"PdfFileToPdfGroup\"}],\"dbName\":null},\"Payment\":{\"fields\":[{\"name\":\"id\",\"kind\":\"scalar\",\"type\":\"Int\"},{\"name\":\"claimId\",\"kind\":\"scalar\",\"type\":\"Int\"},{\"name\":\"patientId\",\"kind\":\"scalar\",\"type\":\"Int\"},{\"name\":\"userId\",\"kind\":\"scalar\",\"type\":\"Int\"},{\"name\":\"updatedById\",\"kind\":\"scalar\",\"type\":\"Int\"},{\"name\":\"npiProviderId\",\"kind\":\"scalar\",\"type\":\"Int\"},{\"name\":\"totalBilled\",\"kind\":\"scalar\",\"type\":\"Decimal\"},{\"name\":\"totalPaid\",\"kind\":\"scalar\",\"type\":\"Decimal\"},{\"name\":\"totalAdjusted\",\"kind\":\"scalar\",\"type\":\"Decimal\"},{\"name\":\"totalDue\",\"kind\":\"scalar\",\"type\":\"Decimal\"},{\"name\":\"mhPaidAmount\",\"kind\":\"scalar\",\"type\":\"Decimal\"},{\"name\":\"copayment\",\"kind\":\"scalar\",\"type\":\"Decimal\"},{\"name\":\"adjustment\",\"kind\":\"scalar\",\"type\":\"Decimal\"},{\"name\":\"status\",\"kind\":\"enum\",\"type\":\"PaymentStatus\"},{\"name\":\"notes\",\"kind\":\"scalar\",\"type\":\"String\"},{\"name\":\"icn\",\"kind\":\"scalar\",\"type\":\"String\"},{\"name\":\"createdAt\",\"kind\":\"scalar\",\"type\":\"DateTime\"},{\"name\":\"updatedAt\",\"kind\":\"scalar\",\"type\":\"DateTime\"},{\"name\":\"claim\",\"kind\":\"object\",\"type\":\"Claim\",\"relationName\":\"ClaimToPayment\"},{\"name\":\"patient\",\"kind\":\"object\",\"type\":\"Patient\",\"relationName\":\"PatientToPayment\"},{\"name\":\"updatedBy\",\"kind\":\"object\",\"type\":\"User\",\"relationName\":\"PaymentUpdatedBy\"},{\"name\":\"npiProvider\",\"kind\":\"object\",\"type\":\"NpiProvider\",\"relationName\":\"NpiProviderToPayment\"},{\"name\":\"serviceLineTransactions\",\"kind\":\"object\",\"type\":\"ServiceLineTransaction\",\"relationName\":\"PaymentToServiceLineTransaction\"},{\"name\":\"serviceLines\",\"kind\":\"object\",\"type\":\"ServiceLine\",\"relationName\":\"PaymentToServiceLine\"},{\"name\":\"commissionBatchItems\",\"kind\":\"object\",\"type\":\"CommissionBatchItem\",\"relationName\":\"CommissionBatchItemToPayment\"}],\"dbName\":null},\"ServiceLineTransaction\":{\"fields\":[{\"name\":\"id\",\"kind\":\"scalar\",\"type\":\"Int\"},{\"name\":\"paymentId\",\"kind\":\"scalar\",\"type\":\"Int\"},{\"name\":\"serviceLineId\",\"kind\":\"scalar\",\"type\":\"Int\"},{\"name\":\"transactionId\",\"kind\":\"scalar\",\"type\":\"String\"},{\"name\":\"paidAmount\",\"kind\":\"scalar\",\"type\":\"Decimal\"},{\"name\":\"adjustedAmount\",\"kind\":\"scalar\",\"type\":\"Decimal\"},{\"name\":\"method\",\"kind\":\"enum\",\"type\":\"PaymentMethod\"},{\"name\":\"receivedDate\",\"kind\":\"scalar\",\"type\":\"DateTime\"},{\"name\":\"payerName\",\"kind\":\"scalar\",\"type\":\"String\"},{\"name\":\"notes\",\"kind\":\"scalar\",\"type\":\"String\"},{\"name\":\"createdAt\",\"kind\":\"scalar\",\"type\":\"DateTime\"},{\"name\":\"payment\",\"kind\":\"object\",\"type\":\"Payment\",\"relationName\":\"PaymentToServiceLineTransaction\"},{\"name\":\"serviceLine\",\"kind\":\"object\",\"type\":\"ServiceLine\",\"relationName\":\"ServiceLineToServiceLineTransaction\"}],\"dbName\":null},\"DatabaseBackup\":{\"fields\":[{\"name\":\"id\",\"kind\":\"scalar\",\"type\":\"Int\"},{\"name\":\"userId\",\"kind\":\"scalar\",\"type\":\"Int\"},{\"name\":\"createdAt\",\"kind\":\"scalar\",\"type\":\"DateTime\"},{\"name\":\"user\",\"kind\":\"object\",\"type\":\"User\",\"relationName\":\"DatabaseBackupToUser\"}],\"dbName\":null},\"BackupDestination\":{\"fields\":[{\"name\":\"id\",\"kind\":\"scalar\",\"type\":\"Int\"},{\"name\":\"userId\",\"kind\":\"scalar\",\"type\":\"Int\"},{\"name\":\"path\",\"kind\":\"scalar\",\"type\":\"String\"},{\"name\":\"isActive\",\"kind\":\"scalar\",\"type\":\"Boolean\"},{\"name\":\"createdAt\",\"kind\":\"scalar\",\"type\":\"DateTime\"},{\"name\":\"user\",\"kind\":\"object\",\"type\":\"User\",\"relationName\":\"BackupDestinationToUser\"}],\"dbName\":null},\"Notification\":{\"fields\":[{\"name\":\"id\",\"kind\":\"scalar\",\"type\":\"Int\"},{\"name\":\"userId\",\"kind\":\"scalar\",\"type\":\"Int\"},{\"name\":\"type\",\"kind\":\"enum\",\"type\":\"NotificationTypes\"},{\"name\":\"message\",\"kind\":\"scalar\",\"type\":\"String\"},{\"name\":\"createdAt\",\"kind\":\"scalar\",\"type\":\"DateTime\"},{\"name\":\"read\",\"kind\":\"scalar\",\"type\":\"Boolean\"},{\"name\":\"user\",\"kind\":\"object\",\"type\":\"User\",\"relationName\":\"NotificationToUser\"}],\"dbName\":null},\"CronJobLog\":{\"fields\":[{\"name\":\"id\",\"kind\":\"scalar\",\"type\":\"Int\"},{\"name\":\"jobName\",\"kind\":\"scalar\",\"type\":\"String\"},{\"name\":\"status\",\"kind\":\"scalar\",\"type\":\"String\"},{\"name\":\"startedAt\",\"kind\":\"scalar\",\"type\":\"DateTime\"},{\"name\":\"completedAt\",\"kind\":\"scalar\",\"type\":\"DateTime\"},{\"name\":\"durationMs\",\"kind\":\"scalar\",\"type\":\"Int\"},{\"name\":\"errorMessage\",\"kind\":\"scalar\",\"type\":\"String\"}],\"dbName\":null},\"CloudFolder\":{\"fields\":[{\"name\":\"id\",\"kind\":\"scalar\",\"type\":\"Int\"},{\"name\":\"userId\",\"kind\":\"scalar\",\"type\":\"Int\"},{\"name\":\"name\",\"kind\":\"scalar\",\"type\":\"String\"},{\"name\":\"parentId\",\"kind\":\"scalar\",\"type\":\"Int\"},{\"name\":\"patientId\",\"kind\":\"scalar\",\"type\":\"Int\"},{\"name\":\"parent\",\"kind\":\"object\",\"type\":\"CloudFolder\",\"relationName\":\"FolderChildren\"},{\"name\":\"children\",\"kind\":\"object\",\"type\":\"CloudFolder\",\"relationName\":\"FolderChildren\"},{\"name\":\"user\",\"kind\":\"object\",\"type\":\"User\",\"relationName\":\"CloudFolderToUser\"},{\"name\":\"patient\",\"kind\":\"object\",\"type\":\"Patient\",\"relationName\":\"PatientCloudFolder\"},{\"name\":\"files\",\"kind\":\"object\",\"type\":\"CloudFile\",\"relationName\":\"CloudFileToCloudFolder\"},{\"name\":\"createdAt\",\"kind\":\"scalar\",\"type\":\"DateTime\"},{\"name\":\"updatedAt\",\"kind\":\"scalar\",\"type\":\"DateTime\"}],\"dbName\":null},\"CloudFile\":{\"fields\":[{\"name\":\"id\",\"kind\":\"scalar\",\"type\":\"Int\"},{\"name\":\"userId\",\"kind\":\"scalar\",\"type\":\"Int\"},{\"name\":\"name\",\"kind\":\"scalar\",\"type\":\"String\"},{\"name\":\"mimeType\",\"kind\":\"scalar\",\"type\":\"String\"},{\"name\":\"fileSize\",\"kind\":\"scalar\",\"type\":\"BigInt\"},{\"name\":\"folderId\",\"kind\":\"scalar\",\"type\":\"Int\"},{\"name\":\"isComplete\",\"kind\":\"scalar\",\"type\":\"Boolean\"},{\"name\":\"totalChunks\",\"kind\":\"scalar\",\"type\":\"Int\"},{\"name\":\"diskPath\",\"kind\":\"scalar\",\"type\":\"String\"},{\"name\":\"createdAt\",\"kind\":\"scalar\",\"type\":\"DateTime\"},{\"name\":\"updatedAt\",\"kind\":\"scalar\",\"type\":\"DateTime\"},{\"name\":\"user\",\"kind\":\"object\",\"type\":\"User\",\"relationName\":\"CloudFileToUser\"},{\"name\":\"folder\",\"kind\":\"object\",\"type\":\"CloudFolder\",\"relationName\":\"CloudFileToCloudFolder\"},{\"name\":\"chunks\",\"kind\":\"object\",\"type\":\"CloudFileChunk\",\"relationName\":\"CloudFileToCloudFileChunk\"}],\"dbName\":null},\"CloudFileChunk\":{\"fields\":[{\"name\":\"id\",\"kind\":\"scalar\",\"type\":\"Int\"},{\"name\":\"fileId\",\"kind\":\"scalar\",\"type\":\"Int\"},{\"name\":\"seq\",\"kind\":\"scalar\",\"type\":\"Int\"},{\"name\":\"data\",\"kind\":\"scalar\",\"type\":\"Bytes\"},{\"name\":\"createdAt\",\"kind\":\"scalar\",\"type\":\"DateTime\"},{\"name\":\"file\",\"kind\":\"object\",\"type\":\"CloudFile\",\"relationName\":\"CloudFileToCloudFileChunk\"}],\"dbName\":null},\"Communication\":{\"fields\":[{\"name\":\"id\",\"kind\":\"scalar\",\"type\":\"Int\"},{\"name\":\"patientId\",\"kind\":\"scalar\",\"type\":\"Int\"},{\"name\":\"userId\",\"kind\":\"scalar\",\"type\":\"Int\"},{\"name\":\"channel\",\"kind\":\"enum\",\"type\":\"CommunicationChannel\"},{\"name\":\"direction\",\"kind\":\"enum\",\"type\":\"CommunicationDirection\"},{\"name\":\"status\",\"kind\":\"enum\",\"type\":\"CommunicationStatus\"},{\"name\":\"provider\",\"kind\":\"enum\",\"type\":\"CommunicationProvider\"},{\"name\":\"body\",\"kind\":\"scalar\",\"type\":\"String\"},{\"name\":\"callDuration\",\"kind\":\"scalar\",\"type\":\"Int\"},{\"name\":\"twilioSid\",\"kind\":\"scalar\",\"type\":\"String\"},{\"name\":\"createdAt\",\"kind\":\"scalar\",\"type\":\"DateTime\"},{\"name\":\"patient\",\"kind\":\"object\",\"type\":\"Patient\",\"relationName\":\"CommunicationToPatient\"},{\"name\":\"user\",\"kind\":\"object\",\"type\":\"User\",\"relationName\":\"CommunicationToUser\"}],\"dbName\":\"communications\"},\"PatientDocument\":{\"fields\":[{\"name\":\"id\",\"kind\":\"scalar\",\"type\":\"Int\"},{\"name\":\"patientId\",\"kind\":\"scalar\",\"type\":\"Int\"},{\"name\":\"filename\",\"kind\":\"scalar\",\"type\":\"String\"},{\"name\":\"originalName\",\"kind\":\"scalar\",\"type\":\"String\"},{\"name\":\"mimeType\",\"kind\":\"scalar\",\"type\":\"String\"},{\"name\":\"fileSize\",\"kind\":\"scalar\",\"type\":\"BigInt\"},{\"name\":\"filePath\",\"kind\":\"scalar\",\"type\":\"String\"},{\"name\":\"uploadedAt\",\"kind\":\"scalar\",\"type\":\"DateTime\"},{\"name\":\"updatedAt\",\"kind\":\"scalar\",\"type\":\"DateTime\"},{\"name\":\"patient\",\"kind\":\"object\",\"type\":\"Patient\",\"relationName\":\"PatientToPatientDocument\"}],\"dbName\":null},\"TwilioSettings\":{\"fields\":[{\"name\":\"id\",\"kind\":\"scalar\",\"type\":\"Int\"},{\"name\":\"userId\",\"kind\":\"scalar\",\"type\":\"Int\"},{\"name\":\"accountSid\",\"kind\":\"scalar\",\"type\":\"String\"},{\"name\":\"authToken\",\"kind\":\"scalar\",\"type\":\"String\"},{\"name\":\"phoneNumber\",\"kind\":\"scalar\",\"type\":\"String\"},{\"name\":\"greetingMessage\",\"kind\":\"scalar\",\"type\":\"String\"},{\"name\":\"templates\",\"kind\":\"scalar\",\"type\":\"Json\"},{\"name\":\"user\",\"kind\":\"object\",\"type\":\"User\",\"relationName\":\"TwilioSettingsToUser\"}],\"dbName\":\"twilio_settings\"},\"TelnyxSettings\":{\"fields\":[{\"name\":\"id\",\"kind\":\"scalar\",\"type\":\"Int\"},{\"name\":\"userId\",\"kind\":\"scalar\",\"type\":\"Int\"},{\"name\":\"apiKey\",\"kind\":\"scalar\",\"type\":\"String\"},{\"name\":\"accountSid\",\"kind\":\"scalar\",\"type\":\"String\"},{\"name\":\"phoneNumber\",\"kind\":\"scalar\",\"type\":\"String\"},{\"name\":\"texmlApplicationId\",\"kind\":\"scalar\",\"type\":\"String\"},{\"name\":\"messagingProfileId\",\"kind\":\"scalar\",\"type\":\"String\"},{\"name\":\"webhookPublicKey\",\"kind\":\"scalar\",\"type\":\"String\"},{\"name\":\"greetingMessage\",\"kind\":\"scalar\",\"type\":\"String\"},{\"name\":\"user\",\"kind\":\"object\",\"type\":\"User\",\"relationName\":\"TelnyxSettingsToUser\"}],\"dbName\":\"telnyx_settings\"},\"AiSettings\":{\"fields\":[{\"name\":\"id\",\"kind\":\"scalar\",\"type\":\"Int\"},{\"name\":\"userId\",\"kind\":\"scalar\",\"type\":\"Int\"},{\"name\":\"apiKey\",\"kind\":\"scalar\",\"type\":\"String\"},{\"name\":\"aiEnabled\",\"kind\":\"scalar\",\"type\":\"Boolean\"},{\"name\":\"openAiKey\",\"kind\":\"scalar\",\"type\":\"String\"},{\"name\":\"openAiEnabled\",\"kind\":\"scalar\",\"type\":\"Boolean\"},{\"name\":\"claudeAiKey\",\"kind\":\"scalar\",\"type\":\"String\"},{\"name\":\"claudeAiEnabled\",\"kind\":\"scalar\",\"type\":\"Boolean\"},{\"name\":\"claudeAiModel\",\"kind\":\"scalar\",\"type\":\"String\"},{\"name\":\"openAiModel\",\"kind\":\"scalar\",\"type\":\"String\"},{\"name\":\"googleAiModel\",\"kind\":\"scalar\",\"type\":\"String\"},{\"name\":\"dentalMgmtKey\",\"kind\":\"scalar\",\"type\":\"String\"},{\"name\":\"dentalMgmtEnabled\",\"kind\":\"scalar\",\"type\":\"Boolean\"},{\"name\":\"afterHoursEnabled\",\"kind\":\"scalar\",\"type\":\"Boolean\"},{\"name\":\"openPhoneReply\",\"kind\":\"scalar\",\"type\":\"Boolean\"},{\"name\":\"user\",\"kind\":\"object\",\"type\":\"User\",\"relationName\":\"AiSettingsToUser\"}],\"dbName\":\"ai_settings\"},\"OfficeHours\":{\"fields\":[{\"name\":\"id\",\"kind\":\"scalar\",\"type\":\"Int\"},{\"name\":\"userId\",\"kind\":\"scalar\",\"type\":\"Int\"},{\"name\":\"data\",\"kind\":\"scalar\",\"type\":\"Json\"},{\"name\":\"user\",\"kind\":\"object\",\"type\":\"User\",\"relationName\":\"OfficeHoursToUser\"}],\"dbName\":\"office_hours\"},\"OfficeContact\":{\"fields\":[{\"name\":\"id\",\"kind\":\"scalar\",\"type\":\"Int\"},{\"name\":\"userId\",\"kind\":\"scalar\",\"type\":\"Int\"},{\"name\":\"legalName\",\"kind\":\"scalar\",\"type\":\"String\"},{\"name\":\"officeName\",\"kind\":\"scalar\",\"type\":\"String\"},{\"name\":\"receptionistName\",\"kind\":\"scalar\",\"type\":\"String\"},{\"name\":\"dentistName\",\"kind\":\"scalar\",\"type\":\"String\"},{\"name\":\"phoneNumber\",\"kind\":\"scalar\",\"type\":\"String\"},{\"name\":\"email\",\"kind\":\"scalar\",\"type\":\"String\"},{\"name\":\"fax\",\"kind\":\"scalar\",\"type\":\"String\"},{\"name\":\"streetAddress\",\"kind\":\"scalar\",\"type\":\"String\"},{\"name\":\"city\",\"kind\":\"scalar\",\"type\":\"String\"},{\"name\":\"state\",\"kind\":\"scalar\",\"type\":\"String\"},{\"name\":\"zipCode\",\"kind\":\"scalar\",\"type\":\"String\"},{\"name\":\"billingName\",\"kind\":\"scalar\",\"type\":\"String\"},{\"name\":\"billingNpi\",\"kind\":\"scalar\",\"type\":\"String\"},{\"name\":\"billingLicense\",\"kind\":\"scalar\",\"type\":\"String\"},{\"name\":\"billingTaxId\",\"kind\":\"scalar\",\"type\":\"String\"},{\"name\":\"user\",\"kind\":\"object\",\"type\":\"User\",\"relationName\":\"OfficeContactToUser\"}],\"dbName\":\"office_contact\"},\"InsuranceContact\":{\"fields\":[{\"name\":\"id\",\"kind\":\"scalar\",\"type\":\"Int\"},{\"name\":\"userId\",\"kind\":\"scalar\",\"type\":\"Int\"},{\"name\":\"name\",\"kind\":\"scalar\",\"type\":\"String\"},{\"name\":\"phoneNumber\",\"kind\":\"scalar\",\"type\":\"String\"},{\"name\":\"createdAt\",\"kind\":\"scalar\",\"type\":\"DateTime\"},{\"name\":\"user\",\"kind\":\"object\",\"type\":\"User\",\"relationName\":\"InsuranceContactToUser\"}],\"dbName\":\"insurance_contact\"},\"ProcedureTimeslot\":{\"fields\":[{\"name\":\"id\",\"kind\":\"scalar\",\"type\":\"Int\"},{\"name\":\"userId\",\"kind\":\"scalar\",\"type\":\"Int\"},{\"name\":\"data\",\"kind\":\"scalar\",\"type\":\"Json\"},{\"name\":\"user\",\"kind\":\"object\",\"type\":\"User\",\"relationName\":\"ProcedureTimeslotToUser\"}],\"dbName\":\"procedure_timeslot\"},\"PatientConversation\":{\"fields\":[{\"name\":\"id\",\"kind\":\"scalar\",\"type\":\"Int\"},{\"name\":\"patientId\",\"kind\":\"scalar\",\"type\":\"Int\"},{\"name\":\"userId\",\"kind\":\"scalar\",\"type\":\"Int\"},{\"name\":\"stage\",\"kind\":\"scalar\",\"type\":\"String\"},{\"name\":\"aiHandoff\",\"kind\":\"scalar\",\"type\":\"Boolean\"},{\"name\":\"updatedAt\",\"kind\":\"scalar\",\"type\":\"DateTime\"},{\"name\":\"patient\",\"kind\":\"object\",\"type\":\"Patient\",\"relationName\":\"PatientToPatientConversation\"},{\"name\":\"user\",\"kind\":\"object\",\"type\":\"User\",\"relationName\":\"PatientConversationToUser\"}],\"dbName\":\"patient_conversation\"},\"PatientServiceHistory\":{\"fields\":[{\"name\":\"id\",\"kind\":\"scalar\",\"type\":\"Int\"},{\"name\":\"patientId\",\"kind\":\"scalar\",\"type\":\"Int\"},{\"name\":\"procedureCode\",\"kind\":\"scalar\",\"type\":\"String\"},{\"name\":\"description\",\"kind\":\"scalar\",\"type\":\"String\"},{\"name\":\"toothQuadArchSurface\",\"kind\":\"scalar\",\"type\":\"String\"},{\"name\":\"placeOfService\",\"kind\":\"scalar\",\"type\":\"String\"},{\"name\":\"serviceDate\",\"kind\":\"scalar\",\"type\":\"String\"},{\"name\":\"createdAt\",\"kind\":\"scalar\",\"type\":\"DateTime\"},{\"name\":\"patient\",\"kind\":\"object\",\"type\":\"Patient\",\"relationName\":\"PatientToPatientServiceHistory\"}],\"dbName\":\"patient_service_history\"},\"LabRxTemplate\":{\"fields\":[{\"name\":\"id\",\"kind\":\"scalar\",\"type\":\"Int\"},{\"name\":\"userId\",\"kind\":\"scalar\",\"type\":\"Int\"},{\"name\":\"name\",\"kind\":\"scalar\",\"type\":\"String\"},{\"name\":\"labName\",\"kind\":\"scalar\",\"type\":\"String\"},{\"name\":\"labPhone\",\"kind\":\"scalar\",\"type\":\"String\"},{\"name\":\"labFax\",\"kind\":\"scalar\",\"type\":\"String\"},{\"name\":\"labAddress\",\"kind\":\"scalar\",\"type\":\"String\"},{\"name\":\"labAccount\",\"kind\":\"scalar\",\"type\":\"String\"},{\"name\":\"caseType\",\"kind\":\"scalar\",\"type\":\"String\"},{\"name\":\"material\",\"kind\":\"scalar\",\"type\":\"String\"},{\"name\":\"instructions\",\"kind\":\"scalar\",\"type\":\"String\"},{\"name\":\"sortOrder\",\"kind\":\"scalar\",\"type\":\"Int\"},{\"name\":\"createdAt\",\"kind\":\"scalar\",\"type\":\"DateTime\"},{\"name\":\"updatedAt\",\"kind\":\"scalar\",\"type\":\"DateTime\"},{\"name\":\"user\",\"kind\":\"object\",\"type\":\"User\",\"relationName\":\"LabRxTemplateToUser\"}],\"dbName\":\"lab_rx_template\"},\"CommissionBatch\":{\"fields\":[{\"name\":\"id\",\"kind\":\"scalar\",\"type\":\"Int\"},{\"name\":\"npiProviderId\",\"kind\":\"scalar\",\"type\":\"Int\"},{\"name\":\"totalCollection\",\"kind\":\"scalar\",\"type\":\"Decimal\"},{\"name\":\"commissionAmount\",\"kind\":\"scalar\",\"type\":\"Decimal\"},{\"name\":\"notes\",\"kind\":\"scalar\",\"type\":\"String\"},{\"name\":\"createdAt\",\"kind\":\"scalar\",\"type\":\"DateTime\"},{\"name\":\"npiProvider\",\"kind\":\"object\",\"type\":\"NpiProvider\",\"relationName\":\"CommissionBatchToNpiProvider\"},{\"name\":\"items\",\"kind\":\"object\",\"type\":\"CommissionBatchItem\",\"relationName\":\"CommissionBatchToCommissionBatchItem\"}],\"dbName\":null},\"CommissionBatchItem\":{\"fields\":[{\"name\":\"id\",\"kind\":\"scalar\",\"type\":\"Int\"},{\"name\":\"commissionBatchId\",\"kind\":\"scalar\",\"type\":\"Int\"},{\"name\":\"paymentId\",\"kind\":\"scalar\",\"type\":\"Int\"},{\"name\":\"collectionAmount\",\"kind\":\"scalar\",\"type\":\"Decimal\"},{\"name\":\"commissionBatch\",\"kind\":\"object\",\"type\":\"CommissionBatch\",\"relationName\":\"CommissionBatchToCommissionBatchItem\"},{\"name\":\"payment\",\"kind\":\"object\",\"type\":\"Payment\",\"relationName\":\"CommissionBatchItemToPayment\"}],\"dbName\":null},\"SeleniumSettings\":{\"fields\":[{\"name\":\"id\",\"kind\":\"scalar\",\"type\":\"Int\"},{\"name\":\"userId\",\"kind\":\"scalar\",\"type\":\"Int\"},{\"name\":\"paymentGroupId\",\"kind\":\"scalar\",\"type\":\"String\"},{\"name\":\"user\",\"kind\":\"object\",\"type\":\"User\",\"relationName\":\"SeleniumSettingsToUser\"}],\"dbName\":\"selenium_settings\"}},\"enums\":{},\"types\":{}}") diff --git a/packages/db/generated/prisma/package.json b/packages/db/generated/prisma/package.json index 2407d0d5..5140efbd 100644 --- a/packages/db/generated/prisma/package.json +++ b/packages/db/generated/prisma/package.json @@ -1,5 +1,5 @@ { - "name": "prisma-client-01b48bd0456d48936b7527399127242418a65188285f81893df198fb01f65dfc", + "name": "prisma-client-c7b726f8dec2423c71eb4d61965ee1e9b83a8a9a3265ebe2cf951adace1b60b4", "main": "index.js", "types": "index.d.ts", "browser": "default.js", diff --git a/packages/db/generated/prisma/schema.prisma b/packages/db/generated/prisma/schema.prisma index 0829d490..328fae79 100755 --- a/packages/db/generated/prisma/schema.prisma +++ b/packages/db/generated/prisma/schema.prisma @@ -365,6 +365,7 @@ enum PdfTitleKey { INSURANCE_CLAIM_PREAUTH ELIGIBILITY_STATUS CLAIM_STATUS + PREAUTH_APPROVAL OTHER } diff --git a/packages/db/prisma/migrations/20261105000000_add_pdf_title_key_preauth_approval/migration.sql b/packages/db/prisma/migrations/20261105000000_add_pdf_title_key_preauth_approval/migration.sql new file mode 100644 index 00000000..e173580a --- /dev/null +++ b/packages/db/prisma/migrations/20261105000000_add_pdf_title_key_preauth_approval/migration.sql @@ -0,0 +1,2 @@ +-- AlterEnum +ALTER TYPE "PdfTitleKey" ADD VALUE 'PREAUTH_APPROVAL'; diff --git a/packages/db/prisma/schema.prisma b/packages/db/prisma/schema.prisma index 078431ad..b65311ce 100755 --- a/packages/db/prisma/schema.prisma +++ b/packages/db/prisma/schema.prisma @@ -366,6 +366,7 @@ enum PdfTitleKey { INSURANCE_CLAIM_PREAUTH ELIGIBILITY_STATUS CLAIM_STATUS + PREAUTH_APPROVAL OTHER } diff --git a/packages/db/shared/.prisma-zod-generator-manifest.json b/packages/db/shared/.prisma-zod-generator-manifest.json index 7f91a4d2..82e20111 100755 --- a/packages/db/shared/.prisma-zod-generator-manifest.json +++ b/packages/db/shared/.prisma-zod-generator-manifest.json @@ -1,7 +1,7 @@ { "version": "1.0", "generatorVersion": "1.0.0", - "generatedAt": "2026-11-05T03:16:03.000Z", + "generatedAt": "2026-11-06T03:35:54.009Z", "outputPath": "/home/ee/Desktop/DentalManagement09/packages/db/shared", "files": [ "schemas/enums/TransactionIsolationLevel.schema.ts", diff --git a/packages/db/shared/schemas/enums/PdfTitleKey.schema.ts b/packages/db/shared/schemas/enums/PdfTitleKey.schema.ts index 289b7f7d..22c66adc 100644 --- a/packages/db/shared/schemas/enums/PdfTitleKey.schema.ts +++ b/packages/db/shared/schemas/enums/PdfTitleKey.schema.ts @@ -1,5 +1,5 @@ import * as z from 'zod'; -export const PdfTitleKeySchema = z.enum(['INSURANCE_CLAIM', 'INSURANCE_CLAIM_PREAUTH', 'ELIGIBILITY_STATUS', 'CLAIM_STATUS', 'OTHER']) +export const PdfTitleKeySchema = z.enum(['INSURANCE_CLAIM', 'INSURANCE_CLAIM_PREAUTH', 'ELIGIBILITY_STATUS', 'CLAIM_STATUS', 'PREAUTH_APPROVAL', 'OTHER']) export type PdfTitleKey = z.infer; \ No newline at end of file