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
+26
View File
@@ -380,6 +380,32 @@ router.delete(
}
}
);
// POST /api/patients/merge
// Body: { keepId, mergeIds } — moves the mergeIds records' appointments, claims, payments,
// documents and Cloud Storage folders onto keepId, then deletes them.
router.post("/merge", async (req: Request, res: Response): Promise<any> => {
// Merging deletes records, so like delete it's admin-only
if (req.user!.username !== "admin") {
return res.status(403).json({ message: "Forbidden: Only admin users can merge patients." });
}
const keepId = Number(req.body?.keepId);
const mergeIds: number[] = Array.isArray(req.body?.mergeIds)
? req.body.mergeIds.map(Number).filter((id: number) => Number.isInteger(id) && id > 0 && id !== keepId)
: [];
if (!Number.isInteger(keepId) || keepId <= 0 || mergeIds.length === 0) {
return res.status(400).json({ message: "Choose the record to keep and at least one other record to merge." });
}
try {
const patient = await storage.mergePatients(keepId, [...new Set(mergeIds)]);
return res.json(patient);
} catch (error: any) {
console.error("Merge patients error:", error);
return res.status(500).json({ message: error?.message || "Failed to merge patients" });
}
});
// Get appointments for a specific patient
router.get(
"/:patientId/appointments",
@@ -165,7 +165,7 @@ export interface IStorage {
listRecentAttachmentFiles(limit?: number): Promise<CloudFile[]>;
listPatientAllCloudFiles(
patientId: number
): Promise<(CloudFile & { folderName: string })[]>;
): Promise<(CloudFile & { folderName: string; recordLabel: string })[]>;
}
/* ------------------------------- Implementation ------------------------------- */
@@ -679,17 +679,55 @@ export const cloudStorageStorage: IStorage = {
// 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 [];
// The same person may have several patient records (e.g. one per insurance, MassHealth
// then CCA): include every record with the same first + last name.
const patient = await db.patient.findUnique({
where: { id: patientId },
select: { firstName: true, lastName: true },
});
if (!patient) return [];
const records = await db.patient.findMany({
where: {
firstName: { equals: patient.firstName.trim(), mode: "insensitive" },
lastName: { equals: patient.lastName.trim(), mode: "insensitive" },
},
select: { id: true, insuranceProvider: true },
});
if (!records.some((r: { id: number }) => r.id === patientId)) {
records.push({ id: patientId, insuranceProvider: null });
}
const folderNames = new Map<number, string>([[patientFolder.id, patientFolder.name]]);
let frontier = [patientFolder.id];
// A record can own more than one patient folder, so take all of them
const patientFolders = await db.cloudFolder.findMany({
where: { patientId: { in: records.map((r: { id: number }) => r.id) } },
select: { id: true, name: true, patientId: true },
});
if (patientFolders.length === 0) return [];
// With several records, label each file with the record it belongs to
const multipleRecords = new Set(patientFolders.map((f: { patientId: number | null }) => f.patientId)).size > 1;
const recordLabel = (id: number | null) => {
if (!multipleRecords || id == null) return "";
const r = records.find((x: { id: number }) => x.id === id);
return `${r?.insuranceProvider || "No insurance"} (#${id})`;
};
const folderNames = new Map<number, string>();
const folderRecords = new Map<number, string>();
patientFolders.forEach((f: { id: number; name: string; patientId: number | null }) => {
folderNames.set(f.id, f.name);
folderRecords.set(f.id, recordLabel(f.patientId));
});
let frontier = patientFolders.map((f: { id: number }) => f.id);
while (frontier.length > 0) {
const children = await db.cloudFolder.findMany({
where: { parentId: { in: frontier } },
select: { id: true, name: true },
select: { id: true, name: true, parentId: true },
});
children.forEach((c: { id: number; name: string; parentId: number | null }) => {
folderNames.set(c.id, c.name);
folderRecords.set(c.id, folderRecords.get(c.parentId as number) ?? "");
});
children.forEach((c: { id: number; name: string }) => folderNames.set(c.id, c.name));
frontier = children.map((c: { id: number }) => c.id);
}
@@ -710,7 +748,8 @@ export const cloudStorageStorage: IStorage = {
return files.map((f: any) => ({
...serializeFile(f),
folderName: folderNames.get(f.folderId as number) ?? "",
})) as unknown as (CloudFile & { folderName: string })[];
recordLabel: folderRecords.get(f.folderId as number) ?? "",
})) as unknown as (CloudFile & { folderName: string; recordLabel: string })[];
},
async listRecentAttachmentFiles(limit: number = 20) {
@@ -28,6 +28,7 @@ export interface IStorage {
updatePatient(id: number, patient: UpdatePatient): Promise<Patient>;
touchPatient(id: number): Promise<void>;
deletePatient(id: number): Promise<void>;
mergePatients(keepId: number, mergeIds: number[]): Promise<Patient>;
searchPatients(args: {
filters: any;
limit: number;
@@ -203,6 +204,114 @@ export const patientsStorage: IStorage = {
}
},
// Moves everything belonging to the mergeIds records onto keepId, fills keepId's blank fields
// from them, then deletes them. All in one transaction: a failure leaves every record as it was.
async mergePatients(keepId: number, mergeIds: number[]): Promise<Patient> {
const ids = mergeIds.filter((id) => id !== keepId);
if (ids.length === 0) throw new Error("Choose at least one other record to merge");
return db.$transaction(
async (tx) => {
const keep = await tx.patient.findUnique({ where: { id: keepId } });
if (!keep) throw new Error(`Patient ${keepId} not found`);
const others = await tx.patient.findMany({ where: { id: { in: ids } }, orderBy: { id: "desc" } });
if (others.length !== ids.length) throw new Error("One of the records to merge was not found");
// 1) Fill the kept record's blank fields from the merged records (newest record first)
const isBlank = (v: unknown) =>
v === null || v === undefined || (typeof v === "string" && v.trim() === "");
const fillable = [
"gender", "phone", "email", "address", "city", "state", "zipCode", "insuranceProvider",
"insuranceId", "groupNumber", "policyHolder", "policyHolderPatientId",
"policyHolderRelationship", "allergies", "medicalConditions", "remainingBenefit",
"thirdPartyInsurance",
] as const;
const fill: Record<string, unknown> = {};
for (const field of fillable) {
if (!isBlank((keep as any)[field])) continue;
const source = others.find((o) => !isBlank((o as any)[field]));
if (source) fill[field] = (source as any)[field];
}
// 1900-01-01 is the placeholder DOB for records created without one
const hasRealDob = (d: Date | null) => !!d && d.getUTCFullYear() > 1900;
if (!hasRealDob(keep.dateOfBirth)) {
const source = others.find((o) => hasRealDob(o.dateOfBirth));
if (source) fill.dateOfBirth = source.dateOfBirth;
}
if (fill.policyHolderPatientId !== undefined && ids.includes(fill.policyHolderPatientId as number)) {
fill.policyHolderPatientId = keepId;
}
// 2) Re-point everything that belongs to the merged records
const move = { where: { patientId: { in: ids } }, data: { patientId: keepId } };
await tx.appointment.updateMany(move);
await tx.appointmentProcedure.updateMany(move);
await tx.claim.updateMany(move);
await tx.payment.updateMany(move);
await tx.pdfGroup.updateMany(move);
await tx.communication.updateMany(move);
await tx.patientDocument.updateMany(move);
await tx.patient.updateMany({
where: { policyHolderPatientId: { in: ids } },
data: { policyHolderPatientId: keepId },
});
// One-per-patient data: keep the kept record's own when it has one
if (!(await tx.patientConversation.findUnique({ where: { patientId: keepId } }))) {
const conv = await tx.patientConversation.findFirst({ where: { patientId: { in: ids } } });
if (conv) await tx.patientConversation.update({ where: { id: conv.id }, data: { patientId: keepId } });
}
// Service history is a snapshot from the last MassHealth check, not something to combine
if ((await tx.patientServiceHistory.count({ where: { patientId: keepId } })) === 0) {
const latest = await tx.patientServiceHistory.findFirst({
where: { patientId: { in: ids } },
orderBy: { createdAt: "desc" },
});
if (latest) {
await tx.patientServiceHistory.updateMany({
where: { patientId: latest.patientId },
data: { patientId: keepId },
});
}
}
// 3) Cloud Storage: fold every patient folder of these records into one,
// merging same-name subfolders (Approval, Claims, ...) rather than duplicating them
const roots = await tx.cloudFolder.findMany({
where: { patientId: { in: [keepId, ...ids] } },
orderBy: { id: "asc" },
});
const target = roots.find((r) => r.patientId === keepId) ?? roots[0];
const mergeFolderInto = async (srcId: number, dstId: number) => {
const children = await tx.cloudFolder.findMany({ where: { parentId: srcId } });
for (const child of children) {
const same = await tx.cloudFolder.findFirst({ where: { parentId: dstId, name: child.name } });
if (same) {
await mergeFolderInto(child.id, same.id);
await tx.cloudFolder.delete({ where: { id: child.id } });
} else {
await tx.cloudFolder.update({ where: { id: child.id }, data: { parentId: dstId } });
}
}
await tx.cloudFile.updateMany({ where: { folderId: srcId }, data: { folderId: dstId } });
};
if (target) {
for (const root of roots) {
if (root.id === target.id) continue;
await mergeFolderInto(root.id, target.id);
await tx.cloudFolder.delete({ where: { id: root.id } });
}
await tx.cloudFolder.update({ where: { id: target.id }, data: { patientId: keepId } });
}
// 4) Remove the merged records (anything left on them is only data the kept record replaces)
await tx.patient.deleteMany({ where: { id: { in: ids } } });
const merged = await tx.patient.update({ where: { id: keepId }, data: fill as any });
return merged as unknown as Patient;
},
{ timeout: 60_000 }
);
},
async searchPatients({
filters,
limit,