import path from "path"; import fs from "fs"; import { storage } from "../storage"; type QueuedFile = { originalname: string; bufferBase64: string; mimetype: string }; // Include attachments already saved on the appointment (e.g. X-rays added via "Select Procedures") // that weren't re-uploaded in this request — read straight from disk by filePath. export async function appendAppointmentFiles( filesForQueue: QueuedFile[], appointmentId: number | string | null | undefined, ): Promise { if (!appointmentId) return; const seenNames = new Set(filesForQueue.map((f) => f.originalname)); const apptFiles = await storage.getAppointmentFiles(Number(appointmentId)); for (const f of apptFiles) { if (!f.filePath || seenNames.has(f.filename)) continue; const absPath = path.join(process.cwd(), f.filePath); if (!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) { 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) } : {}), })), }); }