feat: payment PDF extraction, import, and remittance tracking

- Add Upload Payment Documents section with Extract & Download (Excel)
  and Extract & Import (database) buttons
- PDF extractor (pdfplumber) parses MassHealth RA PDFs: two-pass
  strategy joins summary-page ICN/patient map with detail-page
  procedure data (CDT code, paid code, tooth, date, allowed amount)
- RA cover-page summary (Payee ID, RA #, Payment Amount, etc.)
  included as separate Excel sheet; numeric values written as numbers
- Backend PDF import route groups rows by Member #, finds/creates
  patient, creates Payment + ServiceLines with ICN per procedure
- Add icn, paidCode, allowedAmount fields to ServiceLine schema
- Payments table: status simplified to Paid in Full / Balance;
  adjustment auto-computed on mhPaidAmount/copayment change;
  Paid in Full and Revert buttons with confirmation dialogs
- Edit Payment modal: shows ICN, Paid Code, Allowed Amount per line
- PDF Import badge distinguishes from OCR imports in payments table

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
Gitead
2026-05-07 12:53:50 -04:00
parent e204d30ff6
commit dd0df4a435
76 changed files with 1570 additions and 96 deletions

View File

@@ -85,6 +85,7 @@
"vaul": "^1.1.2",
"wouter": "^3.7.0",
"ws": "^8.18.0",
"xlsx": "^0.18.5",
"zod": "^3.24.2",
"zod-validation-error": "^3.4.0"
},

View File

@@ -504,6 +504,10 @@ export default function PaymentEditModal({
<span className="bg-gray-100 text-gray-800 px-2 py-0.5 rounded-full font-medium">
Claim #{payment.claimId.toString().padStart(4, "0")}
</span>
) : payment.notes?.startsWith("PDF import") ? (
<span className="bg-blue-100 text-blue-800 px-2 py-0.5 rounded-full font-medium">
PDF Import
</span>
) : (
<span className="bg-gray-100 text-gray-800 px-2 py-0.5 rounded-full font-medium">
OCR Imported Payment
@@ -628,6 +632,28 @@ export default function PaymentEditModal({
{line.procedureCode}
</span>
</p>
{(line as any).icn && (
<p>
<span className="text-gray-500">ICN:</span>{" "}
<span className="font-medium font-mono text-xs">
{(line as any).icn}
</span>
</p>
)}
{(line as any).paidCode && (line as any).paidCode !== line.procedureCode && (
<p>
<span className="text-gray-500">Paid Code:</span>{" "}
<span className="font-medium">{(line as any).paidCode}</span>
</p>
)}
{(line as any).allowedAmount != null && (
<p>
<span className="text-gray-500">Allowed:</span>{" "}
<span className="font-medium text-blue-600">
${Number((line as any).allowedAmount).toFixed(2)}
</span>
</p>
)}
{(line as any).quad && (
<p>
<span className="text-gray-500">Quad:</span>{" "}

View File

@@ -0,0 +1,267 @@
import * as React from "react";
import * as XLSX from "xlsx";
import {
Card,
CardContent,
CardDescription,
CardHeader,
CardTitle,
} from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { FileText, X, Download, DatabaseIcon } from "lucide-react";
import { useMutation } from "@tanstack/react-query";
import { apiRequest, queryClient } from "@/lib/queryClient";
import { toast } from "@/hooks/use-toast";
import { QK_PAYMENTS_RECENT_BASE } from "@/components/payments/payments-recent-table";
import {
MultipleFileUploadZone,
MultipleFileUploadZoneHandle,
} from "../file-upload/multiple-file-upload-zone";
type Row = Record<string, string>;
type Header = Record<string, string>;
const COLUMNS: { key: string; label: string }[] = [
{ key: "Patient Name", label: "Patient Name" },
{ key: "Member #", label: "Member #" },
{ key: "ICN", label: "ICN" },
{ key: "Submitted Code", label: "Submitted Code" },
{ key: "Paid Code", label: "Paid Code" },
{ key: "Tooth", label: "Tooth" },
{ key: "Date of Service", label: "Date of Service" },
{ key: "Submitted Amount", label: "Submitted ($)" },
{ key: "Allowed Amount", label: "Allowed ($)" },
{ key: "Paid Amount", label: "Paid ($)" },
];
const SUMMARY_FIELDS = [
"Source File",
"Payee ID",
"Business NPI",
"Run #",
"RA #",
"RA Date",
"Claim Detail Amount",
"Claim Adjustment Amount",
"Misc. Adjustment Amount",
"Payment Amount",
];
// Convert a string value to a number if it looks numeric, otherwise keep as string.
// Handles: "36.00" → 36, "$14,369.00" → 14369, "($3,107.39)" → -3107.39
function toExcelValue(val: string): string | number {
if (!val) return "";
const stripped = val
.replace(/\$/g, "")
.replace(/,/g, "")
.replace(/^\((.+)\)$/, "-$1") // (3,107.39) → -3107.39
.trim();
const num = Number(stripped);
return stripped !== "" && !isNaN(num) ? num : val;
}
function downloadExcel(rows: Row[], headers: Header[], sourceFileName: string) {
const wb = XLSX.utils.book_new();
// Sheet 1 — RA Summary (one row per uploaded PDF)
if (headers.length > 0) {
const summaryData = headers.map((h) => {
const out: Record<string, string | number> = {};
SUMMARY_FIELDS.forEach((f) => { out[f] = toExcelValue(h[f] ?? ""); });
return out;
});
const wsSummary = XLSX.utils.json_to_sheet(summaryData, {
header: SUMMARY_FIELDS,
});
XLSX.utils.book_append_sheet(wb, wsSummary, "RA Summary");
}
// Sheet 2 — Payment Data (one row per ICN)
const data = rows.map((row) => {
const out: Record<string, string | number> = {};
COLUMNS.forEach(({ key, label }) => { out[label] = toExcelValue(row[key] ?? ""); });
return out;
});
const wsData = XLSX.utils.json_to_sheet(data, {
header: COLUMNS.map((c) => c.label),
});
XLSX.utils.book_append_sheet(wb, wsData, "Payment Data");
const name = sourceFileName.replace(/\.pdf$/i, "") || "payment_extract";
XLSX.writeFile(wb, `${name}.xlsx`);
}
export default function PaymentUploadDocumentsBlock() {
const MAX_FILES = 10;
const ACCEPTED_FILE_TYPES = "application/pdf";
const uploadZoneRef = React.useRef<MultipleFileUploadZoneHandle | null>(null);
const [filesForUI, setFilesForUI] = React.useState<File[]>([]);
const [isUploading] = React.useState(false);
const [error, setError] = React.useState<string | null>(null);
// ── shared extract helper ────────────────────────────────────────────────
const extractData = async (files: File[]): Promise<{ rows: Row[]; headers: Header[] }> => {
const formData = new FormData();
files.forEach((file) => formData.append("files", file, file.name));
const res = await apiRequest("POST", "/api/payment-pdf/extract", formData);
if (!res.ok) {
const err = await res.json().catch(() => ({}));
throw new Error(err?.error || "Failed to extract PDF data");
}
const data = (await res.json()) as { rows: Row[]; headers: Header[] };
return { rows: data.rows ?? [], headers: data.headers ?? [] };
};
const getFiles = () => {
const files = uploadZoneRef.current?.getFiles() ?? [];
if (!files.length) {
setError("Please upload at least one PDF file.");
return null;
}
setError(null);
return files;
};
// ── Extract & Download ───────────────────────────────────────────────────
const downloadMutation = useMutation({
mutationFn: async (files: File[]) => {
const { rows, headers } = await extractData(files);
return { rows, headers, sourceName: files[0]?.name ?? "payment_extract" };
},
onSuccess: ({ rows, headers, sourceName }) => {
if (rows.length === 0) {
toast({ title: "No data", description: "No rows were extracted from the PDF.", variant: "destructive" });
return;
}
downloadExcel(rows, headers, sourceName);
toast({ title: "Downloaded", description: `${rows.length} rows exported to Excel.` });
},
onError: (err: any) => {
toast({ title: "Error", description: err.message, variant: "destructive" });
},
});
// ── Extract & Import ─────────────────────────────────────────────────────
const importMutation = useMutation({
mutationFn: async (files: File[]) => {
const { rows } = await extractData(files);
if (rows.length === 0) throw new Error("No rows extracted from the PDF.");
const res = await apiRequest("POST", "/api/payment-pdf/import", { rows });
if (!res.ok) {
const err = await res.json().catch(() => ({}));
throw new Error(err?.error || "Import failed");
}
return res.json();
},
onSuccess: async (data) => {
toast({
title: "Imported",
description: `${data.paymentIds?.length ?? 0} payment(s) created successfully.`,
});
await queryClient.invalidateQueries({ queryKey: QK_PAYMENTS_RECENT_BASE });
},
onError: (err: any) => {
toast({ title: "Error", description: err.message, variant: "destructive" });
},
});
const handleZoneFilesChange = React.useCallback((files: File[]) => {
setFilesForUI(files);
setError(null);
}, []);
const removeUploadedFile = React.useCallback((index: number) => {
uploadZoneRef.current?.removeFile(index);
}, []);
const busy = downloadMutation.isPending || importMutation.isPending;
return (
<div className="mb-8">
<Card>
<CardHeader>
<CardTitle>Upload Payment Documents</CardTitle>
<CardDescription>
Upload up to 10 MassHealth remittance PDFs. Extract and download as
Excel, or import directly into the database.
</CardDescription>
</CardHeader>
<CardContent>
<div className="bg-gray-100 p-4 rounded-md space-y-4">
<MultipleFileUploadZone
ref={uploadZoneRef}
isUploading={isUploading}
acceptedFileTypes={ACCEPTED_FILE_TYPES}
maxFiles={MAX_FILES}
onFilesChange={handleZoneFilesChange}
/>
{filesForUI.length > 0 && (
<div>
<p className="text-sm text-gray-600 mb-2">
Uploaded ({filesForUI.length}/{MAX_FILES})
</p>
<ul className="space-y-2 max-h-48 overflow-auto">
{filesForUI.map((file, idx) => (
<li
key={`${file.name}-${file.size}-${idx}`}
className="flex items-center justify-between border rounded-md p-2 bg-white"
>
<div className="flex items-center gap-3">
<FileText className="h-6 w-6 text-blue-500" />
<div className="text-left">
<p className="font-medium text-blue-700 truncate">{file.name}</p>
<p className="text-sm text-gray-500">
{(file.size / 1024 / 1024).toFixed(2)} MB
</p>
</div>
</div>
<Button variant="ghost" size="sm" onClick={() => removeUploadedFile(idx)}>
<X className="h-4 w-4" />
</Button>
</li>
))}
</ul>
</div>
)}
</div>
<div className="mt-4 flex gap-3">
{/* Extract & Download */}
<Button
className="flex-1 h-12 gap-2 bg-blue-600 hover:bg-blue-700 text-white"
type="button"
disabled={busy || !filesForUI.length}
onClick={() => {
const files = getFiles();
if (files) downloadMutation.mutate(files);
}}
>
<Download className="h-4 w-4" />
{downloadMutation.isPending ? "Extracting…" : "Extract & Download"}
</Button>
{/* Extract & Import */}
<Button
className="flex-1 h-12 gap-2 bg-teal-600 hover:bg-teal-700 text-white"
type="button"
disabled={busy || !filesForUI.length}
onClick={() => {
const files = getFiles();
if (files) importMutation.mutate(files);
}}
>
<DatabaseIcon className="h-4 w-4" />
{importMutation.isPending ? "Importing…" : "Extract & Import"}
</Button>
</div>
{error && <p className="mt-3 text-sm text-red-600">{error}</p>}
</CardContent>
</Card>
</div>
);
}

View File

@@ -103,8 +103,6 @@ export default function PaymentsRecentTable({
const [editingMhPaidValue, setEditingMhPaidValue] = useState<string>("");
const [editingCopaymentId, setEditingCopaymentId] = useState<number | null>(null);
const [editingCopaymentValue, setEditingCopaymentValue] = useState<string>("");
const [editingAdjustmentId, setEditingAdjustmentId] = useState<number | null>(null);
const [editingAdjustmentValue, setEditingAdjustmentValue] = useState<string>("");
const [isRevertOpen, setIsRevertOpen] = useState(false);
const [revertPaymentId, setRevertPaymentId] = useState<number | null>(null);
@@ -394,6 +392,12 @@ export default function PaymentsRecentTable({
const [isUnvoidOpen, setIsUnvoidOpen] = useState(false);
const [unvoidPaymentId, setUnvoidPaymentId] = useState<number | null>(null);
const [isPaidInFullOpen, setIsPaidInFullOpen] = useState(false);
const [paidInFullPaymentId, setPaidInFullPaymentId] = useState<number | null>(null);
const [isRevertPaidOpen, setIsRevertPaidOpen] = useState(false);
const [revertPaidPaymentId, setRevertPaidPaymentId] = useState<number | null>(null);
const handleConfirmVoid = () => {
if (!voidPaymentId) return;
handleVoid(voidPaymentId);
@@ -408,6 +412,20 @@ export default function PaymentsRecentTable({
setIsUnvoidOpen(false);
};
const handleConfirmPaidInFull = () => {
if (!paidInFullPaymentId) return;
updatePaymentStatusMutation.mutate({ paymentId: paidInFullPaymentId, status: "PAID" });
setPaidInFullPaymentId(null);
setIsPaidInFullOpen(false);
};
const handleConfirmRevertPaid = () => {
if (!revertPaidPaymentId) return;
updatePaymentStatusMutation.mutate({ paymentId: revertPaidPaymentId, status: "PENDING" });
setRevertPaidPaymentId(null);
setIsRevertPaidOpen(false);
};
// Pagination
useEffect(() => {
if (onPageChange) onPageChange(currentPage);
@@ -660,9 +678,13 @@ export default function PaymentsRecentTable({
</TableCell>
)}
<TableCell>
<span className="text-sm font-mono">
{payment.claim?.claimNumber ?? <span className="text-gray-400"></span>}
</span>
{payment.claim?.claimNumber ? (
<span className="text-sm font-mono">{payment.claim.claimNumber}</span>
) : payment.notes?.startsWith("PDF import") ? (
<span className="text-xs font-medium bg-blue-100 text-blue-800 px-2 py-0.5 rounded-full">PDF Import</span>
) : (
<span className="text-gray-400"></span>
)}
</TableCell>
<TableCell>
@@ -717,37 +739,19 @@ export default function PaymentsRecentTable({
<TableCell>
<div className="flex items-center gap-2">
{(() => {
// VOID and DENIED are manual decisions — show as-is
if (payment.status === "VOID" || payment.status === "DENIED" || payment.status === "OVERPAID") {
const { label, color, icon } = getStatusInfo(payment.status);
return (
<span className={`px-2 py-1 text-xs font-medium rounded-full ${color}`}>
<span className="flex items-center">{icon}{label}</span>
</span>
);
}
// Compute status from numbers
if (totalDue === 0) {
return (
<span className="px-2 py-1 text-xs font-medium rounded-full bg-teal-100 text-teal-800">
<span className="flex items-center"><CheckCircle className="h-3 w-3 mr-1" />Paid in Full</span>
</span>
);
}
if (totalCollected > 0) {
return (
<span className="px-2 py-1 text-xs font-medium rounded-full bg-blue-100 text-blue-800">
<span className="flex items-center"><DollarSign className="h-3 w-3 mr-1" />Partially Paid</span>
</span>
);
}
return (
<span className="px-2 py-1 text-xs font-medium rounded-full bg-red-100 text-red-800">
<span className="flex items-center"><Clock className="h-3 w-3 mr-1" />Pending</span>
</span>
);
})()}
{payment.status === "VOID" ? (
<span className="px-2 py-1 text-xs font-medium rounded-full bg-gray-100 text-gray-800 flex items-center">
<Ban className="h-3 w-3 mr-1" />Void
</span>
) : payment.status === "PAID" ? (
<span className="px-2 py-1 text-xs font-medium rounded-full bg-teal-100 text-teal-800 flex items-center">
<CheckCircle className="h-3 w-3 mr-1" />Paid in Full
</span>
) : (
<span className="px-2 py-1 text-xs font-medium rounded-full bg-yellow-100 text-yellow-800 flex items-center">
<Clock className="h-3 w-3 mr-1" />Balance
</span>
)}
</div>
</TableCell>
@@ -875,50 +879,11 @@ export default function PaymentsRecentTable({
)}
</TableCell>
{/* Adjustment */}
{/* Adjustment — auto-computed: totalBilled - mhPaid - copayment */}
<TableCell>
{editingAdjustmentId === payment.id ? (
<input
type="number"
min="0"
step="0.01"
autoFocus
className="w-24 border border-blue-400 rounded px-1 py-0.5 text-sm focus:outline-none focus:ring-2 focus:ring-blue-300"
value={editingAdjustmentValue}
onChange={(e) => setEditingAdjustmentValue(e.target.value)}
onKeyDown={(e) => {
if (e.key === "Enter") e.currentTarget.blur();
else if (e.key === "Escape") setEditingAdjustmentId(null);
}}
onBlur={async () => {
const val = parseFloat(editingAdjustmentValue);
if (!isNaN(val) && val >= 0) {
try {
const res = await apiRequest("PATCH", `/api/payments/${payment.id}/adjustment`, { adjustment: val });
if (res.ok) {
await queryClient.invalidateQueries({ queryKey: QK_PAYMENTS_RECENT_BASE });
} else {
toast({ title: "Error", description: "Failed to save adjustment.", variant: "destructive" });
}
} catch {
toast({ title: "Error", description: "Failed to save adjustment.", variant: "destructive" });
}
}
setEditingAdjustmentId(null);
}}
/>
) : (
<span
className="text-sm font-medium text-orange-700 cursor-pointer hover:underline hover:text-orange-900"
title="Click to edit"
onClick={() => {
setEditingAdjustmentId(payment.id);
setEditingAdjustmentValue(Number(payment.adjustment ?? 0).toFixed(2));
}}
>
${Number(payment.adjustment ?? 0).toFixed(2)}
</span>
)}
<span className="text-sm font-medium text-orange-700">
${adjustment.toFixed(2)}
</span>
</TableCell>
<TableCell className="text-right">
@@ -949,6 +914,38 @@ export default function PaymentsRecentTable({
</Button>
)}
{/* Paid in Full — only when not already paid or voided */}
{payment.status !== "PAID" &&
payment.status !== "VOID" &&
payment.status !== "DENIED" && (
<Button
variant="default"
size="sm"
className="bg-teal-600 hover:bg-teal-700 text-white"
onClick={() => {
setPaidInFullPaymentId(payment.id);
setIsPaidInFullOpen(true);
}}
>
Paid in Full
</Button>
)}
{/* Revert — only when already Paid in Full */}
{payment.status === "PAID" && (
<Button
variant="outline"
size="sm"
className="border-teal-400 text-teal-700 hover:bg-teal-50"
onClick={() => {
setRevertPaidPaymentId(payment.id);
setIsRevertPaidOpen(true);
}}
>
Revert
</Button>
)}
{/* Show Void unless already voided or denied */}
{payment.status !== "VOID" &&
payment.status !== "DENIED" && (
@@ -1010,6 +1007,28 @@ export default function PaymentsRecentTable({
onCancel={() => setIsRevertOpen(false)}
/>
{/* Revert Paid in Full Confirmation Dialog */}
<ConfirmationDialog
isOpen={isRevertPaidOpen}
title="Revert Paid in Full?"
message="This will revert the status back to Balance. The amounts stay unchanged. Continue?"
confirmLabel="Revert"
confirmColor="bg-yellow-600 hover:bg-yellow-700"
onConfirm={handleConfirmRevertPaid}
onCancel={() => setIsRevertPaidOpen(false)}
/>
{/* Paid in Full Confirmation Dialog */}
<ConfirmationDialog
isOpen={isPaidInFullOpen}
title="Mark as Paid in Full?"
message="This will set the status to Paid in Full and close the balance for this payment. Continue?"
confirmLabel="Paid in Full"
confirmColor="bg-teal-600 hover:bg-teal-700"
onConfirm={handleConfirmPaidInFull}
onCancel={() => setIsPaidInFullOpen(false)}
/>
{/* NEW: Void Confirmation Dialog */}
<ConfirmationDialog
isOpen={isVoidOpen}

View File

@@ -24,6 +24,7 @@ import { Calendar } from "@/components/ui/calendar";
import PaymentsRecentTable from "@/components/payments/payments-recent-table";
import PaymentsOfPatientModal from "@/components/payments/payments-of-patient-table";
import PaymentOCRBlock from "@/components/payments/payment-ocr-block";
import PaymentUploadDocumentsBlock from "@/components/payments/payment-upload-documents-block";
import { useLocation } from "wouter";
import { Patient, PaymentWithExtras } from "@repo/db/types";
import { apiRequest } from "@/lib/queryClient";
@@ -330,6 +331,9 @@ export default function PaymentsPage() {
}}
/>
{/* Upload Payment Documents Section */}
<PaymentUploadDocumentsBlock />
{/* OCR Image Upload Section*/}
<PaymentOCRBlock />