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 <noreply@anthropic.com>
This commit is contained in:
2026-11-26 12:52:31 -05:00
co-authored by Claude Opus 5.5
parent 3410a2a0c4
commit 2ee45f1b13
11 changed files with 243 additions and 8 deletions
+3 -1
View File
@@ -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",
@@ -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: {
@@ -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: {
@@ -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<void> {
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) {
@@ -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<string, "X" | "O">) ?? {}) 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<ClaimFileMeta[]>(() =>
(claimAgainSource?.claimFiles ?? []).filter((f) => !!f?.filename),
);
const mergeWithExistingAttachments = useCallback(
(newFiles: ClaimFileMeta[]): ClaimFileMeta[] => {
const byFilename = new Map<string, ClaimFileMeta>();
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({
))}
</ul>
)}
{carriedClaimFiles.length > 0 && (
<div className="space-y-1">
<p className="text-sm font-medium text-gray-700">
Attachments from the earlier claim (sent again):
</p>
<ul className="text-sm text-gray-700 space-y-1">
{carriedClaimFiles.map((file) => (
<li
key={file.id ?? file.filename}
className="flex items-center justify-between bg-white border rounded px-2 py-1"
>
<span className="truncate">{file.filename}</span>
<button
type="button"
className="ml-2 text-gray-500 hover:text-red-600"
aria-label={`Remove ${file.filename}`}
onClick={() =>
setCarriedClaimFiles((prev) =>
prev.filter((f) => f !== file),
)
}
>
<X className="h-4 w-4" />
</button>
</li>
))}
</ul>
</div>
)}
</div>
{/* Missing Teeth */}
@@ -3431,6 +3559,35 @@ export function ClaimForm({
))}
</ul>
)}
{carriedClaimFiles.length > 0 && (
<div className="space-y-1">
<p className="text-sm font-medium text-gray-700">
Attachments from the earlier claim (sent again):
</p>
<ul className="text-sm text-gray-700 space-y-1">
{carriedClaimFiles.map((file) => (
<li
key={file.id ?? file.filename}
className="flex items-center justify-between bg-white border rounded px-2 py-1"
>
<span className="truncate">{file.filename}</span>
<button
type="button"
className="ml-2 text-gray-500 hover:text-red-600"
aria-label={`Remove ${file.filename}`}
onClick={() =>
setCarriedClaimFiles((prev) =>
prev.filter((f) => f !== file),
)
}
>
<X className="h-4 w-4" />
</button>
</li>
))}
</ul>
</div>
)}
</div>
{/* Missing Teeth */}
@@ -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({
</Button>
)}
{claim.id != null && <CheckPreauthButton claimId={claim.id} onCompleted={closeAfterPreauthCheck} />}
{onClaimAgain && (
<Button
variant="outline"
onClick={() => {
onOpenChange(false);
onClaimAgain(claim);
}}
>
<RotateCcw className="mr-2 h-4 w-4" /> Claim Again
</Button>
)}
<Button
onClick={() => {
onOpenChange(false);
@@ -8,14 +8,16 @@ import {
CardHeader,
CardTitle,
} from "../ui/card";
import { Patient } from "@repo/db/types";
import { ClaimWithServiceLines, Patient } from "@repo/db/types";
interface ClaimsOfPatientModalProps {
onNewClaim?: (patientId: number) => void;
onClaimAgain?: (claim: ClaimWithServiceLines) => void;
}
export default function ClaimsOfPatientModal({
onNewClaim,
onClaimAgain,
}: ClaimsOfPatientModalProps) {
const [selectedPatient, setSelectedPatient] = useState<Patient | null>(null);
const [isModalOpen, setIsModalOpen] = useState(false);
@@ -52,6 +54,7 @@ export default function ClaimsOfPatientModal({
allowEdit
allowDelete
onPageChange={setClaimsPage}
onClaimAgain={onClaimAgain}
/>
</CardContent>
</Card>
@@ -53,6 +53,8 @@ interface ClaimsRecentTableProps {
onSelectClaim?: (claim: Claim | null) => void;
onPageChange?: (page: number) => void;
patientId?: number;
/** Shows "Claim Again" in the details window; opens the claim form prefilled from that claim. */
onClaimAgain?: (claim: ClaimWithServiceLines) => void;
}
// 🔑 exported base key
@@ -74,6 +76,7 @@ export default function ClaimsRecentTable({
onSelectClaim,
onPageChange,
patientId,
onClaimAgain,
}: ClaimsRecentTableProps) {
const { toast } = useToast();
const dispatch = useAppDispatch();
@@ -605,6 +608,7 @@ export default function ClaimsRecentTable({
onClose={() => setIsViewClaimOpen(false)}
onOpenChange={(open) => setIsViewClaimOpen(open)}
onEditClaim={(claim) => handleEditClaim(claim)}
onClaimAgain={onClaimAgain}
claim={currentClaim}
/>
)}
+22 -1
View File
@@ -33,6 +33,7 @@ import ClaimsOfPatientModal from "@/components/claims/claims-of-patient-table";
import { PreauthCheckHost } from "@/components/claims/check-preauth-button";
import {
Claim,
ClaimWithServiceLines,
UpdatePatient,
} from "@repo/db/types";
import ClaimDocumentsUploadMultiple from "@/components/claims/claim-document-upload-modal";
@@ -44,6 +45,8 @@ import { useLicense } from "@/hooks/use-license";
export default function ClaimsPage() {
const [isClaimFormOpen, setIsClaimFormOpen] = useState(false);
const [selectedPatientId, setSelectedPatientId] = useState<number | null>(null);
// "Claim Again" from the Claim/Preauth Details window: the claim the form is prefilled from
const [claimAgainSource, setClaimAgainSource] = useState<ClaimWithServiceLines | null>(null);
const [chatbotAutoSubmitSiteKey, setChatbotAutoSubmitSiteKey] = useState<string | undefined>(undefined);
// Mirrors chatbotAutoSubmitSiteKey but survives closeClaim(), which resets the state
// synchronously right after the selenium job is kicked off — well before the job's async
@@ -242,6 +245,20 @@ export default function ClaimsPage() {
setIsClaimFormOpen(true);
};
// "Claim Again": reopen the claim form filled from an earlier claim/preauth; the user can edit
// it and pick an insurance button, which submits a new claim through that portal.
const handleClaimAgain = (claim: ClaimWithServiceLines) => {
if (!claim.patientId) {
toast({ title: "Cannot claim again", description: "This claim has no patient.", variant: "destructive" });
return;
}
setClaimAgainSource(claim);
setSelectedPatientId(claim.patientId);
setSelectedAppointmentId(claim.appointmentId ?? null);
setChatbotInitialTab(claim.status === "PREAUTH" ? "preauth" : undefined);
setIsClaimFormOpen(true);
};
// if ?newPatient=<id> is present, open claim form directly
useEffect(() => {
if (!newPatient) return;
@@ -1252,6 +1269,7 @@ export default function ClaimsPage() {
const closeClaim = () => {
setSelectedPatientId(null);
setSelectedAppointmentId(null);
setClaimAgainSource(null);
setChatbotAutoSubmitSiteKey(undefined);
setChatbotInitialTab(undefined);
setChatbotAutoSubmitPreauthSiteKey(undefined);
@@ -1371,7 +1389,7 @@ export default function ClaimsPage() {
</div>
{/* Recent Claims by Patients also handles new claims */}
<ClaimsOfPatientModal onNewClaim={handleNewClaim} />
<ClaimsOfPatientModal onNewClaim={handleNewClaim} onClaimAgain={handleClaimAgain} />
{/* Check PreAuth OTP popup; here so it outlives the Claim/Preauth Details window */}
<PreauthCheckHost />
@@ -1389,6 +1407,7 @@ export default function ClaimsPage() {
allowEdit={true}
allowView={true}
allowDelete={true}
onClaimAgain={handleClaimAgain}
/>
</CardContent>
</Card>
@@ -1508,6 +1527,7 @@ export default function ClaimsPage() {
{/* Claim Form Modal */}
{isClaimFormOpen && selectedPatientId !== null && (
<ClaimForm
key={claimAgainSource ? `again-${claimAgainSource.id}` : "new"}
patientId={selectedPatientId}
appointmentId={selectedAppointmentId ?? undefined}
autoSubmit={mode === "direct" || !!chatbotAutoSubmitSiteKey}
@@ -1531,6 +1551,7 @@ export default function ClaimsPage() {
onHandleForTuftsSCOSeleniumClaim={handleTuftsSCOClaimSubmitSelenium}
onHandleForUnitedUcardSeleniumClaim={handleUnitedUcardClaimSubmitSelenium}
isLicensed={isLicensed}
claimAgainSource={claimAgainSource}
/>
)}
+2
View File
@@ -108,6 +108,7 @@ export interface ClaimFormData {
serviceLines: InputServiceLine[];
claimId?: number;
claimFiles?: ClaimFileMeta[];
carriedClaimFileIds?: number[];
}
export interface ClaimPreAuthData {
patientId: number;
@@ -130,5 +131,6 @@ export interface ClaimPreAuthData {
appointmentId?: number;
serviceLines: InputServiceLine[];
claimFiles?: ClaimFileMeta[];
carriedClaimFileIds?: number[];
}
//# sourceMappingURL=claim-types.d.ts.map
+4
View File
@@ -113,6 +113,8 @@ export interface ClaimFormData {
serviceLines: InputServiceLine[];
claimId?: number;
claimFiles?: ClaimFileMeta[];
// "Claim Again": ClaimFile ids of the earlier claim to send with the submission
carriedClaimFileIds?: number[];
}
export interface ClaimPreAuthData {
@@ -136,4 +138,6 @@ export interface ClaimPreAuthData {
appointmentId?: number;
serviceLines: InputServiceLine[];
claimFiles?: ClaimFileMeta[];
// "Claim Again": ClaimFile ids of the earlier claim to send with the submission
carriedClaimFileIds?: number[];
}