feat: Check DDMA Payments reads Plan Pays from DDMA claim status, fills app payments and saves a PDF

Adds a Check DDMA Payments card (date range, Go, auto-check schedule) above
Check MH Payments. Go logs into DDMA (with OTP), searches Check Claim Status by
service date range, reads claim numbers and Plan Pays across pages, matches
them to app claims to fill the paid amount, creates patient + payment for
unmatched paid claims, and saves the results page as a PDF in
uploads/DDMAPayment.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-26 22:11:36 -05:00
co-authored by Claude Opus 5.5
parent 2ee45f1b13
commit 432150b7a7
158 changed files with 2944 additions and 191 deletions
@@ -18,9 +18,17 @@ interface DdmaOtpModalProps {
onClose: () => void;
onSubmit: (otp: string) => Promise<void> | void;
isSubmitting: boolean;
/** What the OTP is for, shown in the description. Defaults to "eligibility check". */
purpose?: string;
}
function DdmaOtpModal({ open, onClose, onSubmit, isSubmitting }: DdmaOtpModalProps) {
export function DdmaOtpModal({
open,
onClose,
onSubmit,
isSubmitting,
purpose = "eligibility check",
}: DdmaOtpModalProps) {
const [otp, setOtp] = useState("");
useEffect(() => {
@@ -45,8 +53,8 @@ function DdmaOtpModal({ open, onClose, onSubmit, isSubmitting }: DdmaOtpModalPro
</button>
</div>
<p className="text-sm text-slate-500 mb-4">
We need the one-time password (OTP) sent by the Delta Dental MA portal to complete this
eligibility check.
We need the one-time password (OTP) sent by the Delta Dental MA portal to complete this{" "}
{purpose}.
</p>
<form onSubmit={handleSubmit} className="space-y-4">
<div className="space-y-2">
@@ -0,0 +1,193 @@
import {
Dialog,
DialogContent,
DialogDescription,
DialogHeader,
DialogTitle,
} from "@/components/ui/dialog";
import { Button } from "@/components/ui/button";
import { FileText } from "lucide-react";
import { apiRequest } from "@/lib/queryClient";
import { toast } from "@/hooks/use-toast";
export type DdmaMatchOutcome =
| "updated"
| "unchanged"
| "created"
| "not_paid_yet"
| "no_claim"
| "no_payment";
export interface DdmaClaimPayment {
claimNumber: string;
dateOfService: string;
provider: string;
patientName: string;
planPays: number | null;
planPaysText: string;
status: string;
match?: {
outcome: DdmaMatchOutcome;
appClaimId?: number;
paymentId?: number;
appPatientName?: string;
previousPaid?: number | null;
patientCreated?: boolean;
patientId?: number;
};
}
export interface DdmaClaimPaymentsResult {
fromDate?: string;
toDate?: string;
claims: DdmaClaimPayment[];
summary?: Partial<Record<DdmaMatchOutcome, number>>;
/** Saved PDF of the DDMA claims results page */
pdfFilename?: string | null;
}
async function openDdmaPdf(filename: string) {
// Open the tab first (synchronously) so the browser doesn't block it as a popup
const tab = window.open("", "_blank");
try {
const res = await apiRequest(
"GET",
`/api/payments/ddma-payment-pdf/${encodeURIComponent(filename)}`
);
if (!res.ok) throw new Error(`Server error (${res.status})`);
const blob = await res.blob();
const url = URL.createObjectURL(blob);
if (tab) tab.location.href = url;
else window.open(url, "_blank");
} catch (e: any) {
tab?.close();
toast({ title: "Could not open PDF", description: e?.message, variant: "destructive" });
}
}
interface Props {
result: DdmaClaimPaymentsResult | null;
onClose: () => void;
}
function formatIsoDate(value: string) {
const m = /^(\d{4})-(\d{2})-(\d{2})$/.exec(value ?? "");
return m ? `${m[2]}/${m[3]}/${m[1]}` : value;
}
const currency = new Intl.NumberFormat("en-US", { style: "currency", currency: "USD" });
function MatchCell({ c }: { c: DdmaClaimPayment }) {
const m = c.match;
if (!m) return <span className="text-gray-400">—</span>;
switch (m.outcome) {
case "updated":
return (
<span className="text-green-700">
Paid filled
{m.previousPaid != null && (
<span className="text-gray-500"> (was {currency.format(m.previousPaid)})</span>
)}
</span>
);
case "unchanged":
return <span className="text-gray-600">Already filled</span>;
case "created":
return (
<span className="text-blue-700">
{m.patientCreated ? "New patient + payment created" : "Payment created (existing patient)"}
</span>
);
case "not_paid_yet":
return <span className="text-amber-700">Not paid yet</span>;
case "no_payment":
return <span className="text-red-700">Claim found, no payment record</span>;
case "no_claim":
default:
return <span className="text-red-700">No matching claim in app</span>;
}
}
export default function DdmaClaimPaymentsDialog({ result, onClose }: Props) {
const claims = result?.claims ?? [];
const total = claims.reduce((sum, c) => sum + (c.planPays ?? 0), 0);
const s = result?.summary ?? {};
return (
<Dialog open={!!result} onOpenChange={(open) => !open && onClose()}>
<DialogContent className="max-w-5xl">
<DialogHeader>
<DialogTitle>DDMA Claim Payments</DialogTitle>
<DialogDescription>
{result?.fromDate && result?.toDate
? `Service dates ${formatIsoDate(result.fromDate)} – ${formatIsoDate(result.toDate)}. `
: ""}
{claims.length} claim(s), Plan Pays total {currency.format(total)}.
</DialogDescription>
</DialogHeader>
{result?.pdfFilename && (
<div>
<Button
variant="outline"
size="sm"
onClick={() => openDdmaPdf(result.pdfFilename!)}
>
<FileText className="h-4 w-4 mr-2" />
View PDF
</Button>
</div>
)}
{claims.length > 0 && (
<div className="flex flex-wrap gap-x-4 gap-y-1 text-sm">
<span className="text-green-700">{s.updated ?? 0} filled</span>
<span className="text-gray-600">{s.unchanged ?? 0} already filled</span>
<span className="text-blue-700">{s.created ?? 0} created</span>
<span className="text-amber-700">{s.not_paid_yet ?? 0} not paid yet</span>
<span className="text-red-700">
{(s.no_claim ?? 0) + (s.no_payment ?? 0)} not matched
</span>
</div>
)}
{claims.length === 0 ? (
<p className="text-sm text-gray-500 py-6 text-center">
No DDMA claims found in this date range.
</p>
) : (
<div className="max-h-[60vh] overflow-auto border rounded-md">
<table className="w-full text-sm">
<thead className="bg-gray-50 sticky top-0">
<tr className="text-left">
<th className="px-3 py-2 font-medium">Date of Service</th>
<th className="px-3 py-2 font-medium">Patient</th>
<th className="px-3 py-2 font-medium">Claim Number</th>
<th className="px-3 py-2 font-medium text-right">Plan Pays</th>
<th className="px-3 py-2 font-medium">DDMA Status</th>
<th className="px-3 py-2 font-medium">In App</th>
</tr>
</thead>
<tbody>
{claims.map((c) => (
<tr key={c.claimNumber} className="border-t">
<td className="px-3 py-1.5 whitespace-nowrap">{formatIsoDate(c.dateOfService)}</td>
<td className="px-3 py-1.5">{c.patientName}</td>
<td className="px-3 py-1.5 font-mono">{c.claimNumber}</td>
<td className="px-3 py-1.5 text-right tabular-nums">
{c.planPays != null ? currency.format(c.planPays) : c.planPaysText}
</td>
<td className="px-3 py-1.5">{c.status}</td>
<td className="px-3 py-1.5">
<MatchCell c={c} />
</td>
</tr>
))}
</tbody>
</table>
</div>
)}
</DialogContent>
</Dialog>
);
}
@@ -681,6 +681,9 @@ export default function PaymentsRecentTable({
<TableCell>
{payment.claim?.claimNumber ? (
<span className="text-sm font-mono">{payment.claim.claimNumber}</span>
) : payment.notes?.startsWith("DDMA import") && payment.icn ? (
// Created by Check DDMA Payments (no claim in app) — claim number kept on icn
<span className="text-sm font-mono">{payment.icn}</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>
) : (
+371 -2
View File
@@ -9,7 +9,13 @@ import {
import { Button } from "@/components/ui/button";
import { Switch } from "@/components/ui/switch";
import { Label } from "@/components/ui/label";
import { DollarSign, CalendarIcon } from "lucide-react";
import { DollarSign, CalendarIcon, LoaderCircleIcon } from "lucide-react";
import { DdmaOtpModal } from "@/components/insurance-status/ddma-buton-modal";
import DdmaClaimPaymentsDialog, {
DdmaClaimPaymentsResult,
} from "@/components/payments/ddma-claim-payments-dialog";
import { socket } from "@/lib/socket";
import { formatLocalDate } from "@/utils/dateUtils";
import {
Select,
SelectContent,
@@ -29,7 +35,8 @@ 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";
import { apiRequest, queryClient } from "@/lib/queryClient";
import { QK_PAYMENTS_RECENT_BASE } from "@/components/payments/payments-recent-table";
import { toast } from "@/hooks/use-toast";
import PaymentEditModal from "@/components/payments/payment-edit-modal";
@@ -64,6 +71,12 @@ export default function PaymentsPage() {
const [autoMhCheckHour, setAutoMhCheckHour] = useState(13);
const [autoMhCheckLoaded, setAutoMhCheckLoaded] = useState(false);
// Auto DDMA check schedule
const [autoDdmaCheckEnabled, setAutoDdmaCheckEnabled] = useState(false);
const [autoDdmaCheckDay, setAutoDdmaCheckDay] = useState(1);
const [autoDdmaCheckHour, setAutoDdmaCheckHour] = useState(13);
const [autoDdmaCheckLoaded, setAutoDdmaCheckLoaded] = useState(false);
// Check Payments Online date range
const [mhFromDate, setMhFromDate] = useState<Date | undefined>(undefined);
const [mhToDate, setMhToDate] = useState<Date | undefined>(undefined);
@@ -72,6 +85,21 @@ export default function PaymentsPage() {
const [fromCalendarOpen, setFromCalendarOpen] = useState(false);
const [toCalendarOpen, setToCalendarOpen] = useState(false);
// Check DDMA Payments date range
const [ddmaFromDate, setDdmaFromDate] = useState<Date | undefined>(undefined);
const [ddmaToDate, setDdmaToDate] = useState<Date | undefined>(undefined);
const [ddmaFromText, setDdmaFromText] = useState("");
const [ddmaToText, setDdmaToText] = useState("");
const [ddmaFromCalendarOpen, setDdmaFromCalendarOpen] = useState(false);
const [ddmaToCalendarOpen, setDdmaToCalendarOpen] = useState(false);
// DDMA payment check run (selenium login + OTP)
const [ddmaCheckRunning, setDdmaCheckRunning] = useState(false);
const [ddmaOtpOpen, setDdmaOtpOpen] = useState(false);
const [ddmaOtpSubmitting, setDdmaOtpSubmitting] = useState(false);
const ddmaSessionIdRef = useRef<string | null>(null);
const [ddmaResult, setDdmaResult] = useState<DdmaClaimPaymentsResult | null>(null);
// for auto-open from appointment redirect
const [location] = useLocation();
const [initialPatientForModal, setInitialPatientForModal] =
@@ -205,6 +233,163 @@ export default function PaymentsPage() {
}
};
// Load auto DDMA check setting on mount
useEffect(() => {
(async () => {
try {
const res = await apiRequest("GET", "/api/database-management/auto-ddma-check-setting");
if (res.ok) {
const data = await res.json();
setAutoDdmaCheckEnabled(data.autoDdmaCheckEnabled ?? false);
setAutoDdmaCheckDay(data.autoDdmaCheckDayOfWeek ?? 1);
setAutoDdmaCheckHour(data.autoDdmaCheckHour ?? 13);
}
} catch {}
setAutoDdmaCheckLoaded(true);
})();
}, []);
const saveAutoDdmaCheckSetting = async (
enabled: boolean,
day: number,
hour: number
) => {
try {
const res = await apiRequest("PUT", "/api/database-management/auto-ddma-check-setting", {
autoDdmaCheckEnabled: enabled,
autoDdmaCheckDayOfWeek: day,
autoDdmaCheckHour: hour,
});
if (!res.ok) {
toast({ title: "Failed to save auto DDMA check setting", variant: "destructive" });
}
} catch {
toast({ title: "Failed to save auto DDMA check setting", variant: "destructive" });
}
};
// Start DDMA payment check: opens the DDMA portal and logs in (OTP via modal)
const startDdmaPaymentCheck = async () => {
if (!ddmaFromDate || !ddmaToDate) {
toast({ title: "Please select both From and To dates", variant: "destructive" });
return;
}
setDdmaCheckRunning(true);
ddmaSessionIdRef.current = null;
try {
const res = await apiRequest("POST", "/api/payments/ddma-payment-check", {
fromDate: formatLocalDate(ddmaFromDate),
toDate: formatLocalDate(ddmaToDate),
socketId: socket.id,
});
const body = await res.json();
if (!res.ok) throw new Error(body.message || `Server error (${res.status})`);
const jobId: string = body.jobId;
if (!jobId) throw new Error("No jobId returned from server");
toast({ title: "Check DDMA Payments", description: "Opening DDMA and logging in…" });
const onSessionStarted = (data: any) => {
if (String(data?.jobId) !== String(jobId)) return;
ddmaSessionIdRef.current = data.session_id ?? null;
};
const onOtpRequired = (data: any) => {
if (String(data?.jobId) !== String(jobId)) return;
if (data.session_id) ddmaSessionIdRef.current = data.session_id;
setDdmaOtpOpen(true);
};
const onJobUpdate = (data: any) => {
if (String(data?.jobId) !== String(jobId)) return;
if (data.status === "active") return;
cleanup();
setDdmaCheckRunning(false);
setDdmaOtpOpen(false);
if (data.status === "completed") {
setDdmaResult({
fromDate: data.result?.fromDate,
toDate: data.result?.toDate,
claims: Array.isArray(data.result?.claims) ? data.result.claims : [],
summary: data.result?.summary,
pdfFilename: data.result?.pdfFilename ?? null,
});
// Payments may have been filled — refresh the payments table
queryClient.invalidateQueries({ queryKey: QK_PAYMENTS_RECENT_BASE });
} else if (data.status === "failed") {
toast({
title: "DDMA Payment Check Failed",
description: data.error ?? "DDMA payment check failed.",
variant: "destructive",
});
}
};
const safetyTimer = setTimeout(() => {
cleanup();
setDdmaCheckRunning(false);
setDdmaOtpOpen(false);
toast({
title: "DDMA Payment Check",
description: "Timed out waiting for the DDMA login to finish.",
variant: "destructive",
});
}, 6 * 60 * 1000);
function cleanup() {
clearTimeout(safetyTimer);
socket.off("selenium:ddma_session_started", onSessionStarted);
socket.off("selenium:otp_required", onOtpRequired);
socket.off("job:update", onJobUpdate);
}
socket.on("selenium:ddma_session_started", onSessionStarted);
socket.on("selenium:otp_required", onOtpRequired);
socket.on("job:update", onJobUpdate);
} catch (e: any) {
setDdmaCheckRunning(false);
toast({
title: "DDMA Payment Check Failed",
description: e?.message ?? "Failed to start DDMA payment check",
variant: "destructive",
});
}
};
const submitDdmaPaymentOtp = async (otp: string) => {
const sessionId = ddmaSessionIdRef.current;
if (!sessionId) {
toast({
title: "Session not ready",
description: "Cannot submit OTP — DDMA session ID is not available yet.",
variant: "destructive",
});
return;
}
try {
setDdmaOtpSubmitting(true);
const resp = await apiRequest("POST", "/api/insurance-status-ddma/selenium/submit-otp", {
session_id: sessionId,
otp,
socketId: socket.id,
});
const data = await resp.json();
if (!resp.ok || data.error) throw new Error(data.error || "Failed to submit OTP");
setDdmaOtpOpen(false);
} catch (err: any) {
toast({
title: "Failed to submit OTP",
description: err?.message || "Error forwarding OTP to selenium agent",
variant: "destructive",
});
} finally {
setDdmaOtpSubmitting(false);
}
};
return (
<div>
{/* Header */}
@@ -293,6 +478,190 @@ export default function PaymentsPage() {
</Card>
</div>
{/* Check DDMA Payments */}
<Card className="mb-6">
<CardHeader>
<CardTitle>Check DDMA Payments</CardTitle>
<CardDescription>
Select a date range and check DDMA payment status online
</CardDescription>
</CardHeader>
<CardContent>
<div className="flex flex-wrap items-center gap-4">
{/* From date picker */}
<div className="flex items-center gap-2">
<span className="text-sm font-medium text-gray-600 whitespace-nowrap">From:</span>
<div className="flex items-center gap-1">
<input
type="text"
placeholder="MM/DD/YYYY"
className="border rounded-md px-2 py-1.5 text-sm w-[110px] focus:outline-none focus:ring-2 focus:ring-ring"
value={ddmaFromText}
onChange={(e) => {
const formatted = formatDateInput(e.target.value);
setDdmaFromText(formatted);
if (formatted === "") { setDdmaFromDate(undefined); return; }
if (/^\d{2}\/\d{2}\/\d{4}$/.test(formatted)) {
const parsed = new Date(formatted);
if (!isNaN(parsed.getTime())) setDdmaFromDate(parsed);
}
}}
/>
<Popover open={ddmaFromCalendarOpen} onOpenChange={setDdmaFromCalendarOpen}>
<PopoverTrigger asChild>
<Button type="button" variant="outline" size="icon" className="h-8 w-8 shrink-0">
<CalendarIcon className="h-4 w-4" />
</Button>
</PopoverTrigger>
<PopoverContent className="w-auto p-0" align="start">
<Calendar
mode="single"
selected={ddmaFromDate}
onSelect={(d) => {
setDdmaFromDate(d);
setDdmaFromText(d ? d.toLocaleDateString("en-US", { month: "2-digit", day: "2-digit", year: "numeric" }) : "");
setDdmaFromCalendarOpen(false);
}}
onClose={() => setDdmaFromCalendarOpen(false)}
/>
</PopoverContent>
</Popover>
</div>
</div>
{/* To date picker */}
<div className="flex items-center gap-2">
<span className="text-sm font-medium text-gray-600 whitespace-nowrap">To:</span>
<div className="flex items-center gap-1">
<input
type="text"
placeholder="MM/DD/YYYY"
className="border rounded-md px-2 py-1.5 text-sm w-[110px] focus:outline-none focus:ring-2 focus:ring-ring"
value={ddmaToText}
onChange={(e) => {
const formatted = formatDateInput(e.target.value);
setDdmaToText(formatted);
if (formatted === "") { setDdmaToDate(undefined); return; }
if (/^\d{2}\/\d{2}\/\d{4}$/.test(formatted)) {
const parsed = new Date(formatted);
if (!isNaN(parsed.getTime())) setDdmaToDate(parsed);
}
}}
/>
<Popover open={ddmaToCalendarOpen} onOpenChange={setDdmaToCalendarOpen}>
<PopoverTrigger asChild>
<Button type="button" variant="outline" size="icon" className="h-8 w-8 shrink-0">
<CalendarIcon className="h-4 w-4" />
</Button>
</PopoverTrigger>
<PopoverContent className="w-auto p-0" align="start">
<Calendar
mode="single"
selected={ddmaToDate}
onSelect={(d) => {
setDdmaToDate(d);
setDdmaToText(d ? d.toLocaleDateString("en-US", { month: "2-digit", day: "2-digit", year: "numeric" }) : "");
setDdmaToCalendarOpen(false);
}}
onClose={() => setDdmaToCalendarOpen(false)}
/>
</PopoverContent>
</Popover>
</div>
</div>
{/* DDMA Payment Check button */}
<Button
variant="default"
disabled={ddmaCheckRunning}
onClick={startDdmaPaymentCheck}
>
{ddmaCheckRunning ? (
<>
<LoaderCircleIcon className="h-4 w-4 mr-2 animate-spin" />
Processing...
</>
) : (
"Go"
)}
</Button>
<DdmaOtpModal
open={ddmaOtpOpen}
onClose={() => setDdmaOtpOpen(false)}
onSubmit={submitDdmaPaymentOtp}
isSubmitting={ddmaOtpSubmitting}
purpose="payment check"
/>
<DdmaClaimPaymentsDialog result={ddmaResult} onClose={() => setDdmaResult(null)} />
{/* Auto check DDMA payment toggle */}
{autoDdmaCheckLoaded && (
<div className="flex flex-wrap items-center gap-3 ml-2 pl-4 border-l border-gray-200">
<div className="flex items-center gap-2">
<Switch
id="auto-ddma-check"
checked={autoDdmaCheckEnabled}
onCheckedChange={(checked) => {
setAutoDdmaCheckEnabled(checked);
saveAutoDdmaCheckSetting(checked, autoDdmaCheckDay, autoDdmaCheckHour);
}}
/>
<Label htmlFor="auto-ddma-check" className="text-sm font-medium whitespace-nowrap cursor-pointer">
Auto Check DDMA Payment
</Label>
</div>
{autoDdmaCheckEnabled && (
<>
<Select
value={String(autoDdmaCheckDay)}
onValueChange={(v) => {
const day = Number(v);
setAutoDdmaCheckDay(day);
saveAutoDdmaCheckSetting(autoDdmaCheckEnabled, day, autoDdmaCheckHour);
}}
>
<SelectTrigger className="w-[140px]">
<SelectValue placeholder="Day" />
</SelectTrigger>
<SelectContent>
{DAYS_OF_WEEK.map((d) => (
<SelectItem key={d.value} value={String(d.value)}>
{d.label}
</SelectItem>
))}
</SelectContent>
</Select>
<Select
value={String(autoDdmaCheckHour)}
onValueChange={(v) => {
const hour = Number(v);
setAutoDdmaCheckHour(hour);
saveAutoDdmaCheckSetting(autoDdmaCheckEnabled, autoDdmaCheckDay, hour);
}}
>
<SelectTrigger className="w-[130px]">
<SelectValue placeholder="Time" />
</SelectTrigger>
<SelectContent>
{HOURS.map((h) => (
<SelectItem key={h.value} value={String(h.value)}>
{h.label}
</SelectItem>
))}
</SelectContent>
</Select>
</>
)}
</div>
)}
</div>
</CardContent>
</Card>
{/* Check Payments Online */}
<Card className="mb-6">
<CardHeader>