feat: CCA Check Preauth approval PDF, merge patients, attachment picker across records

- CCA Check Preauth: searches Authorization Search by auth number, clicks View Auth on the
  result row and saves the PortalAuthReport PDF to the patient's Approval folder
- Merge Patients button above the eligibility page search (admin only): moves appointments,
  claims, payments, PDFs, documents and Cloud Storage folders onto the kept record, fills its
  blank fields, deletes the other records, all in one transaction
- Appointment attachment picker lists files from all of the patient's folders and from the
  patient's other records (same first + last name), labeled by record

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-09 09:58:57 -05:00
co-authored by Claude Opus 5.5
parent 1968e3bfcc
commit 0db69a34b6
8 changed files with 633 additions and 15 deletions
@@ -18,7 +18,8 @@ interface ServerAttachmentsPickerModalProps {
onFilesSelected: (files: File[]) => void;
}
type PickerFile = CloudFile & { folderName?: string };
// recordLabel: which of the patient's records (e.g. "CCA (#269)") the file is from, when there are several
type PickerFile = CloudFile & { folderName?: string; recordLabel?: string };
function fileIcon(mime: string | undefined | null) {
if (mime?.startsWith("image/")) return ImageIcon;
@@ -159,12 +160,12 @@ export function ServerAttachmentsPickerModal({
</h3>
<p className="text-sm text-muted-foreground mt-1">
{showAllFolders
? "Files saved in any of this patient's folders (Approval, Eligibility, Attachments, ...)."
? "Files saved in any of this patient's folders (Approval, Eligibility, Attachments, ...), including the patient's other records."
: patientId
? "Previously saved screenshots and files for this patient."
: "Recently saved screenshots and files across all patients."}
</p>
{folderNames.length > 1 && (
{folderNames.length > 0 && (
<div className="flex flex-wrap gap-2 mt-3">
{[null, ...folderNames].map((name) => (
<Button
@@ -219,6 +220,11 @@ export function ServerAttachmentsPickerModal({
{showAllFolders && file.folderName && (
<p className="text-[11px] text-muted-foreground truncate">{file.folderName}</p>
)}
{showAllFolders && file.recordLabel && (
<p className="text-[11px] text-muted-foreground truncate" title={file.recordLabel}>
{file.recordLabel}
</p>
)}
</div>
{isSelected && (
<div className="absolute top-1 right-1 bg-primary text-primary-foreground rounded-full p-0.5">
@@ -0,0 +1,146 @@
import { useEffect, useState } from "react";
import { useMutation } from "@tanstack/react-query";
import { Loader2 } from "lucide-react";
import {
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
} from "@/components/ui/dialog";
import { Button } from "@/components/ui/button";
import { Checkbox } from "@/components/ui/checkbox";
import { apiRequest, queryClient } from "@/lib/queryClient";
import { useToast } from "@/hooks/use-toast";
import { formatDateToHumanReadable } from "@/utils/dateUtils";
import { Patient } from "@repo/db/types";
import { QK_PATIENTS_BASE } from "./patient-table";
interface MergePatientsModalProps {
open: boolean;
onClose: () => void;
// Records to choose from: the patients currently listed by the search
patients: Patient[];
}
export function MergePatientsModal({ open, onClose, patients }: MergePatientsModalProps) {
const { toast } = useToast();
const [selectedIds, setSelectedIds] = useState<Set<number>>(new Set());
const [keepId, setKeepId] = useState<number | null>(null);
// Start with every listed record ticked (a search like "shah" usually lists just the duplicates)
useEffect(() => {
if (!open) return;
const ids = patients.map((p) => Number(p.id));
setSelectedIds(new Set(ids));
setKeepId(ids[0] ?? null);
}, [open, patients]);
const mergeMutation = useMutation({
mutationFn: async () => {
const mergeIds = [...selectedIds].filter((id) => id !== keepId);
const res = await apiRequest("POST", "/api/patients/merge", { keepId, mergeIds });
const json = await res.json().catch(() => ({}));
if (!res.ok) throw new Error(json.message || "Failed to merge patients");
return json as Patient;
},
onSuccess: (patient) => {
queryClient.invalidateQueries({ queryKey: QK_PATIENTS_BASE });
toast({
title: "Patients merged",
description: `All records are now PID-${String(patient.id).padStart(4, "0")} ${patient.firstName} ${patient.lastName}.`,
});
onClose();
},
onError: (err: any) => {
toast({ title: "Merge failed", description: err?.message, variant: "destructive" });
},
});
const toggle = (id: number) => {
setSelectedIds((prev) => {
const next = new Set(prev);
if (next.has(id)) {
next.delete(id);
if (keepId === id) setKeepId([...next][0] ?? null);
} else {
next.add(id);
if (keepId === null) setKeepId(id);
}
return next;
});
};
const mergeCount = [...selectedIds].filter((id) => id !== keepId).length;
const canMerge = keepId !== null && selectedIds.has(keepId) && mergeCount > 0;
return (
<Dialog open={open} onOpenChange={(o) => !o && !mergeMutation.isPending && onClose()}>
<DialogContent className="max-w-2xl">
<DialogHeader>
<DialogTitle>Merge Patients</DialogTitle>
<DialogDescription>
Tick the records that are the same patient and choose the one to keep. Appointments,
claims, payments, documents and files from the other records move to it, its blank
fields are filled from them, and the other records are deleted. This can't be undone.
</DialogDescription>
</DialogHeader>
{patients.length < 2 ? (
<p className="text-sm text-muted-foreground py-6 text-center">
Search for the patient first so their records are listed (e.g. "shah"), then click Merge.
</p>
) : (
<div className="border rounded-md divide-y max-h-[50vh] overflow-y-auto">
{patients.map((p) => {
const id = Number(p.id);
const selected = selectedIds.has(id);
return (
<div key={id} className={`flex items-center gap-3 p-3 ${selected ? "" : "opacity-60"}`}>
<Checkbox checked={selected} onCheckedChange={() => toggle(id)} />
<div className="flex-1 min-w-0">
<div className="text-sm font-medium">
{p.firstName} {p.lastName}{" "}
<span className="text-gray-500 font-normal">PID-{String(id).padStart(4, "0")}</span>
</div>
<div className="text-xs text-gray-500">
DOB {formatDateToHumanReadable(p.dateOfBirth ?? undefined)} · {p.insuranceProvider || "No insurance"}
{p.insuranceId ? ` · ${p.insuranceId}` : ""}
</div>
</div>
<label className="flex items-center gap-1.5 text-sm cursor-pointer">
<input
type="radio"
name="merge-keep"
checked={keepId === id}
disabled={!selected}
onChange={() => setKeepId(id)}
/>
Keep
</label>
</div>
);
})}
</div>
)}
<DialogFooter>
<Button variant="ghost" onClick={onClose} disabled={mergeMutation.isPending}>
Cancel
</Button>
<Button
variant="destructive"
disabled={!canMerge || mergeMutation.isPending}
onClick={() => mergeMutation.mutate()}
>
{mergeMutation.isPending && <Loader2 className="h-4 w-4 mr-2 animate-spin" />}
{canMerge
? `Merge ${mergeCount} record${mergeCount > 1 ? "s" : ""} into PID-${String(keepId).padStart(4, "0")}`
: "Merge"}
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
);
}
@@ -8,7 +8,7 @@ import {
TableRow,
} from "@/components/ui/table";
import { Button } from "@/components/ui/button";
import { Delete, Edit, Eye, FileCheck, Scan, Upload, X, FileText, Download, Trash2, Camera, RefreshCw } from "lucide-react";
import { Delete, Edit, Eye, FileCheck, Scan, Upload, X, FileText, Download, Trash2, Camera, RefreshCw, Merge } from "lucide-react";
import { Avatar, AvatarFallback } from "@/components/ui/avatar";
import {
Pagination,
@@ -39,6 +39,7 @@ import { Checkbox } from "@/components/ui/checkbox";
import { formatDateToHumanReadable } from "@/utils/dateUtils";
import { Patient, UpdatePatient } from "@repo/db/types";
import { PatientFinancialsModal } from "./patient-financial-modal";
import { MergePatientsModal } from "./merge-patients-modal";
import { getPageNumbers } from "@/utils/pageNumberGenerator";
import {
uploadDocument,
@@ -72,6 +73,8 @@ interface PatientTableProps {
allowCheckbox?: boolean;
allowNewClaim?: boolean;
allowFinancial?: boolean;
// Merge Patients button above the search (admin only, since merging deletes records)
allowMerge?: boolean;
showEligibilityColumns?: boolean;
onNewClaim?: (patientId: number) => void;
onSelectPatient?: (patient: Patient | null) => void;
@@ -92,6 +95,7 @@ export function PatientTable({
allowCheckbox,
allowNewClaim,
allowFinancial,
allowMerge,
showEligibilityColumns,
onNewClaim,
onSelectPatient,
@@ -110,6 +114,7 @@ export function PatientTable({
const [isViewPatientOpen, setIsViewPatientOpen] = useState(false);
const [isDeletePatientOpen, setIsDeletePatientOpen] = useState(false);
const [isFinancialsOpen, setIsFinancialsOpen] = useState(false);
const [isMergeOpen, setIsMergeOpen] = useState(false);
const [modalPatientId, setModalPatientId] = useState<number | null>(null);
const [currentPage, setCurrentPage] = useState(1);
@@ -975,6 +980,28 @@ export function PatientTable({
)}
<div className="overflow-x-auto">
{allowMerge && isAdmin && (
<div className="flex justify-end mb-2">
<Button
variant="outline"
size="sm"
onClick={() => setIsMergeOpen(true)}
className="flex items-center space-x-1"
title="Merge duplicate records of the same patient (search for the patient first)"
>
<Merge className="h-4 w-4" />
<span>Merge Patients</span>
</Button>
</div>
)}
<MergePatientsModal
open={isMergeOpen}
onClose={() => {
setIsMergeOpen(false);
handleClearSelection();
}}
patients={patientsData?.patients ?? []}
/>
<PatientSearch
onSearch={(criteria) => {
setSearchCriteria(criteria);
@@ -1512,6 +1512,7 @@ export default function InsuranceStatusPage() {
allowDelete={true}
allowCheckbox={true}
allowEdit={true}
allowMerge={true}
showEligibilityColumns={true}
onSelectPatient={setSelectedPatient}
/>