From 2ee45f1b135339c7e2bd6b0d72a6b867796f87c8 Mon Sep 17 00:00:00 2001 From: Gitead Date: Thu, 26 Nov 2026 12:52:31 -0500 Subject: [PATCH] feat: Claim Again button in Claim/Preauth Details reopens the claim form prefilled from that claim Copies service date, procedure lines, remarks, missing teeth, staff, NPI provider, insurance type and attachments; submitting through an insurance button creates a new claim. MH/CCA routes read carried attachments from disk by ClaimFile id. Co-Authored-By: Claude Opus 5.5 --- apps/Backend/src/routes/claims.ts | 4 +- .../src/routes/insuranceStatusCCAClaim.ts | 3 +- .../src/routes/insuranceStatusCCAPreAuth.ts | 3 +- .../src/utils/appointmentAttachments.ts | 26 +++ .../src/components/claims/claim-form.tsx | 161 +++++++++++++++++- .../components/claims/claim-view-modal.tsx | 16 +- .../claims/claims-of-patient-table.tsx | 5 +- .../components/claims/claims-recent-table.tsx | 4 + apps/Frontend/src/pages/claims-page.tsx | 23 ++- packages/db/types/claim-types.d.ts | 2 + packages/db/types/claim-types.ts | 4 + 11 files changed, 243 insertions(+), 8 deletions(-) diff --git a/apps/Backend/src/routes/claims.ts b/apps/Backend/src/routes/claims.ts index 17e1dfb7..ff6d029d 100755 --- a/apps/Backend/src/routes/claims.ts +++ b/apps/Backend/src/routes/claims.ts @@ -21,7 +21,7 @@ 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, autoLinkAppointmentFiles } from "../utils/appointmentAttachments"; +import { appendAppointmentFiles, appendClaimFilesById, autoLinkAppointmentFiles } from "../utils/appointmentAttachments"; import { buildPreAuthClaimDetails } from "../utils/preAuthClaim"; const router = Router(); @@ -378,6 +378,7 @@ router.post( if (!claimData.skipAppointmentAttachmentMerge) { await appendAppointmentFiles(filesForQueue, claimData.appointmentId); } + await appendClaimFilesById(filesForQueue, claimData.carriedClaimFileIds); const job = await seleniumQueue.add("claim-submit", { jobType: "claim-submit", @@ -580,6 +581,7 @@ router.post( // Include X-rays etc. already attached to the appointment await appendAppointmentFiles(filesForQueue, claimData.appointmentId); + await appendClaimFilesById(filesForQueue, claimData.carriedClaimFileIds); const job = await seleniumQueue.add("claim-pre-auth", { jobType: "claim-pre-auth", diff --git a/apps/Backend/src/routes/insuranceStatusCCAClaim.ts b/apps/Backend/src/routes/insuranceStatusCCAClaim.ts index 52441163..ca378fab 100644 --- a/apps/Backend/src/routes/insuranceStatusCCAClaim.ts +++ b/apps/Backend/src/routes/insuranceStatusCCAClaim.ts @@ -2,7 +2,7 @@ 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, appendClaimFilesById } from "../utils/appointmentAttachments"; const router = Router(); const upload = multer({ storage: multer.memoryStorage() }); @@ -65,6 +65,7 @@ router.post( if (!claimData.skipAppointmentAttachmentMerge) { await appendAppointmentFiles(filesForQueue, claimData.appointmentId); } + await appendClaimFilesById(filesForQueue, claimData.carriedClaimFileIds); const enrichedPayload = { claim: { diff --git a/apps/Backend/src/routes/insuranceStatusCCAPreAuth.ts b/apps/Backend/src/routes/insuranceStatusCCAPreAuth.ts index 8f921695..6739baa3 100644 --- a/apps/Backend/src/routes/insuranceStatusCCAPreAuth.ts +++ b/apps/Backend/src/routes/insuranceStatusCCAPreAuth.ts @@ -2,7 +2,7 @@ import { Router, Request, Response } from "express"; import { storage } from "../storage"; import { enqueueSeleniumJob } from "../queue/jobRunner"; import multer from "multer"; -import { appendAppointmentFiles, autoLinkAppointmentFiles } from "../utils/appointmentAttachments"; +import { appendAppointmentFiles, appendClaimFilesById, autoLinkAppointmentFiles } from "../utils/appointmentAttachments"; import { buildPreAuthClaimDetails } from "../utils/preAuthClaim"; const router = Router(); @@ -59,6 +59,7 @@ router.post( })); // Include X-rays etc. already attached to the appointment await appendAppointmentFiles(filesForQueue, claimData.appointmentId); + await appendClaimFilesById(filesForQueue, claimData.carriedClaimFileIds); const enrichedPayload = { claim: { diff --git a/apps/Backend/src/utils/appointmentAttachments.ts b/apps/Backend/src/utils/appointmentAttachments.ts index f066d302..722b4853 100644 --- a/apps/Backend/src/utils/appointmentAttachments.ts +++ b/apps/Backend/src/utils/appointmentAttachments.ts @@ -26,6 +26,32 @@ export async function appendAppointmentFiles( } } +// "Claim Again": include attachments of an earlier claim, looked up by ClaimFile id +// (the path comes from the database, never from the request) and read from disk. +export async function appendClaimFilesById( + filesForQueue: QueuedFile[], + claimFileIds: unknown, +): Promise { + if (!Array.isArray(claimFileIds)) return; + const ids = claimFileIds.map(Number).filter((id) => Number.isInteger(id) && id > 0); + if (!ids.length) return; + const { prisma: db } = await import("@repo/db/client"); + const rows = await db.claimFile.findMany({ where: { id: { in: ids } } }); + const seenNames = new Set(filesForQueue.map((f) => f.originalname)); + const root = path.resolve(process.cwd()); + for (const f of rows) { + if (!f.filePath || seenNames.has(f.filename)) continue; + const absPath = path.resolve(root, `.${path.sep}${f.filePath.replace(/^[\\/]+/, "")}`); + if (!absPath.startsWith(root + path.sep) || !fs.existsSync(absPath)) continue; + filesForQueue.push({ + originalname: f.filename, + bufferBase64: fs.readFileSync(absPath).toString("base64"), + mimetype: f.mimeType || "application/octet-stream", + }); + 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) { diff --git a/apps/Frontend/src/components/claims/claim-form.tsx b/apps/Frontend/src/components/claims/claim-form.tsx index 999b3516..b1f78826 100755 --- a/apps/Frontend/src/components/claims/claim-form.tsx +++ b/apps/Frontend/src/components/claims/claim-form.tsx @@ -38,6 +38,7 @@ import { ClaimFileMeta, ClaimFormData, ClaimPreAuthData, + ClaimWithServiceLines, InputServiceLine, MissingTeethStatus, NpiProvider, @@ -106,6 +107,8 @@ interface ClaimFormProps { onHandleForUnitedUcardSeleniumClaim: (data: ClaimFormData) => void; onClose: () => void; isLicensed?: boolean; + /** "Claim Again": prefill the form from this earlier claim/preauth. Submitting creates a new claim. */ + claimAgainSource?: ClaimWithServiceLines | null; } export function ClaimForm({ @@ -132,6 +135,7 @@ export function ClaimForm({ onSubmit, onClose, isLicensed = false, + claimAgainSource = null, }: ClaimFormProps) { const { toast } = useToast(); const { user } = useAuth(); @@ -305,6 +309,9 @@ export function ClaimForm({ setAppointmentStaffId(Number(appointment.staffId)); } + // Claim Again keeps the earlier claim's service date + if (claimAgainSource) return; + // appointment.date is expected to be either "YYYY-MM-DD" or an ISO string. const rawDate = appointment?.date ?? appointment?.day ?? ""; if (!rawDate) return; @@ -355,6 +362,8 @@ export function ClaimForm({ useEffect(() => { if (!appointmentId) return; if (proceduresOnly) return; + // Claim Again prefills from the chosen claim and submits a new one, not the appointment's + if (claimAgainSource) return; let cancelled = false; (async () => { @@ -498,7 +507,8 @@ export function ClaimForm({ setExistingAppointmentFiles(data.appointmentFiles); } - if (existingClaimId) return; // existing claim takes priority for the rest + // existing claim (or the Claim Again source) takes priority for the rest + if (existingClaimId || claimAgainSource) return; const mappedLines = (data.procedures || []).map((p: any) => ({ procedureCode: p.procedureCode, @@ -862,6 +872,80 @@ export function ClaimForm({ } }, [patient]); + // Claim Again: once the patient has loaded (so the patient sync above doesn't overwrite it), + // fill the form from the earlier claim. Member ID / DOB / name come from the patient record, + // falling back to the earlier claim's values when the patient record has none. + const claimAgainAppliedRef = useRef(false); + useEffect(() => { + if (!claimAgainSource || !patient || claimAgainAppliedRef.current) return; + claimAgainAppliedRef.current = true; + const src = claimAgainSource; + + const claimDate = src.serviceDate ? String(src.serviceDate).split("T")[0] ?? "" : ""; + if (claimDate) { + try { + setServiceDateValue(parseLocalDate(claimDate)); + setServiceDate(claimDate); + } catch {} + } + + const blankLine = (date: string): InputServiceLine => ({ + procedureCode: "", + procedureDate: date, + quad: "", + arch: "", + toothNumber: "", + toothSurface: "", + totalBilled: new Decimal(0), + totalAdjusted: new Decimal(0), + totalPaid: new Decimal(0), + }); + + setForm((prev) => { + const date = claimDate || prev.serviceDate; + const lines: InputServiceLine[] = (src.serviceLines ?? []).map((sl) => ({ + procedureCode: sl.procedureCode ?? "", + procedureDate: date, + quad: sl.quad ?? "", + arch: sl.arch ?? "", + toothNumber: sl.toothNumber ?? "", + toothSurface: sl.toothSurface ?? "", + totalBilled: new Decimal(Number(sl.totalBilled ?? 0)), + totalAdjusted: new Decimal(0), + totalPaid: new Decimal(0), + })); + // keep the usual blank rows so more procedures can be added + while (lines.length < 10) lines.push(blankLine(date)); + + return { + ...prev, + serviceDate: date, + serviceLines: lines, + memberId: prev.memberId || src.memberId || "", + dateOfBirth: prev.dateOfBirth || normalizeToIsoDateString(src.dateOfBirth as any), + remarks: src.remarks ?? "", + missingTeethStatus: (src.missingTeethStatus as MissingTeethStatus) ?? "No_missing", + missingTeeth: ((src.missingTeeth as Record) ?? {}) as MissingMapStrict, + insuranceProvider: src.insuranceProvider ?? "", + insuranceSiteKey: deriveInsuranceSiteKey(src.insuranceProvider) || prev.insuranceSiteKey, + ...(src.staffId ? { staffId: src.staffId } : {}), + ...(src.npiProvider?.npiNumber + ? { npiProvider: { npiNumber: src.npiProvider.npiNumber, providerName: src.npiProvider.providerName } } + : {}), + }; + }); + }, [claimAgainSource, patient]); + + // Claim Again: restore the earlier claim's staff once the staff list has loaded + const claimAgainStaffAppliedRef = useRef(false); + useEffect(() => { + if (!claimAgainSource?.staffId || claimAgainStaffAppliedRef.current) return; + if (staffMembersRaw.length === 0) return; + claimAgainStaffAppliedRef.current = true; + const matched = staffMembersRaw.find((s) => Number(s.id) === Number(claimAgainSource.staffId)); + if (matched) setStaff(matched); + }, [claimAgainSource, staffMembersRaw]); + // Handle patient field changes (to make inputs controlled and editable) const updatePatientField = (field: keyof Patient, value: any) => { setPatient((prev) => (prev ? { ...prev, [field]: value } : null)); @@ -970,15 +1054,26 @@ export function ClaimForm({ // Merges attachments already saved on the appointment (e.g. via the Schedule editor) with // any newly uploaded in this claim-form session, so Selenium submission always gets every // file — not just ones uploaded through this form's own file picker in the current session. + // Claim Again: attachments of the earlier claim, sent along unless the user removes them. + const [carriedClaimFiles, setCarriedClaimFiles] = useState(() => + (claimAgainSource?.claimFiles ?? []).filter((f) => !!f?.filename), + ); const mergeWithExistingAttachments = useCallback( (newFiles: ClaimFileMeta[]): ClaimFileMeta[] => { const byFilename = new Map(); + for (const f of carriedClaimFiles) { + byFilename.set(f.filename, { filename: f.filename, mimeType: f.mimeType ?? "", ...(f.filePath ? { filePath: f.filePath } : {}) }); + } for (const f of existingAppointmentFiles) byFilename.set(f.filename, f); for (const f of newFiles) byFilename.set(f.filename, f); return Array.from(byFilename.values()); }, - [existingAppointmentFiles], + [existingAppointmentFiles, carriedClaimFiles], ); + // MH and CCA send file contents to the portal, so the backend reads these from disk by id + const carriedClaimFileIds = carriedClaimFiles + .map((f) => Number(f.id)) + .filter((id) => Number.isFinite(id) && id > 0); // NO validation here — the upload zone handles validation, toasts, max files, sizes, etc. const handleFilesChange = useCallback((files: File[]) => { @@ -1075,6 +1170,7 @@ export function ClaimForm({ insuranceSiteKey: "MH", claimId: createdClaim.id, uploadedFiles, + carriedClaimFileIds, // Only skip the backend's appointment-attachment fallback merge when this automated // submission already supplied its own files — otherwise files saved directly on the // appointment (e.g. a screenshot attached via the Schedule editor) would never reach @@ -1146,6 +1242,7 @@ export function ClaimForm({ insuranceSiteKey: "MH", appointmentId: appointmentId ?? 0, claimFiles: mergeWithExistingAttachments(preAuthFilesMeta), + carriedClaimFileIds, }); // 5. Close form @@ -1214,6 +1311,7 @@ export function ClaimForm({ appointmentId: appointmentIdToUse, insuranceSiteKey: "CCA", claimId: createdClaim.id, + carriedClaimFileIds, skipAppointmentAttachmentMerge: !!autoSubmit && !!uploadedFiles?.length, }); @@ -1711,6 +1809,7 @@ export function ClaimForm({ insuranceSiteKey: "CCA", appointmentId: appointmentId ?? 0, claimFiles: mergeWithExistingAttachments(preAuthFilesMeta), + carriedClaimFileIds, }); onClose(); @@ -2822,6 +2921,35 @@ export function ClaimForm({ ))} )} + {carriedClaimFiles.length > 0 && ( +
+

+ Attachments from the earlier claim (sent again): +

+
    + {carriedClaimFiles.map((file) => ( +
  • + {file.filename} + +
  • + ))} +
+
+ )} {/* Missing Teeth */} @@ -3431,6 +3559,35 @@ export function ClaimForm({ ))} )} + {carriedClaimFiles.length > 0 && ( +
+

+ Attachments from the earlier claim (sent again): +

+
    + {carriedClaimFiles.map((file) => ( +
  • + {file.filename} + +
  • + ))} +
+
+ )} {/* Missing Teeth */} diff --git a/apps/Frontend/src/components/claims/claim-view-modal.tsx b/apps/Frontend/src/components/claims/claim-view-modal.tsx index 9b4bfbd9..789fcb16 100755 --- a/apps/Frontend/src/components/claims/claim-view-modal.tsx +++ b/apps/Frontend/src/components/claims/claim-view-modal.tsx @@ -9,7 +9,7 @@ import { Button } from "@/components/ui/button"; 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 { FileText, Paperclip, Printer, RotateCcw } from "lucide-react"; import { toast } from "@/hooks/use-toast"; import { openPendingTab, showAdaClaimForm } from "@/utils/adaClaimForm"; import { CheckPreauthButton } from "./check-preauth-button"; @@ -26,6 +26,8 @@ type ClaimViewModalProps = { onClose: () => void; claim: ClaimWithServiceLines | null; onEditClaim: (claim: ClaimWithServiceLines) => void; + /** Opens the claim form prefilled from this claim (shown only when provided). */ + onClaimAgain?: (claim: ClaimWithServiceLines) => void; }; export default function ClaimViewModal({ @@ -34,6 +36,7 @@ export default function ClaimViewModal({ onClose, claim, onEditClaim, + onClaimAgain, }: ClaimViewModalProps) { // Normalizer: supports both ClaimFile[] and nested-create shape { create: ClaimFile[] } const getClaimFilesArray = ( @@ -394,6 +397,17 @@ export default function ClaimViewModal({ )} {claim.id != null && } + {onClaimAgain && ( + + )}