@@ -0,0 +1,382 @@
/**
* Processor for "ddma-payment-check" jobs.
*
* 1. Start a session on the Python agent (POST /ddma-payment-check)
* 2. Emit selenium:ddma_session_started → frontend stores session_id for OTP
* 3. Poll agent status (emits selenium:otp_required when OTP is needed)
* 4. Match each DDMA claim number to a claim in the app and fill its
* payment's paid amount (mhPaidAmount — the "MH Paid" column, which the
* payments table and commission report use as the insurance-paid amount).
* Only claims DDMA marks "Paid" are filled; "Processed" etc. are not paid yet.
*/
import { prisma } from "@repo/db/client" ;
import { io } from "../../socket" ;
import { forwardToSeleniumDdmaPaymentAgent } from "../../services/seleniumDdmaInsuranceEligibilityClient" ;
import { pollUntilDone } from "./ddmaEligibilityProcessor" ;
function log ( tag : string , msg : string , ctx? : any ) {
console . log ( ` ${ new Date ( ) . toISOString ( ) } [ ${ tag } ] ${ msg } ` , ctx ? ? "" ) ;
}
function emitToSocket ( socketId : string | undefined , event : string , payload : any ) {
if ( ! socketId || ! io ) return ;
try {
const socket = io . sockets . sockets . get ( socketId ) ;
if ( socket ) socket . emit ( event , payload ) ;
} catch ( err : any ) {
log ( "ddma-payment-processor" , ` emit failed for ${ event } ` , { err : err?.message } ) ;
}
}
export interface DdmaPaymentProcessorInput {
enrichedPayload : any ;
userId : number ;
socketId? : string ;
}
export interface DdmaClaimPayment {
claimNumber : string ;
dateOfService : string ;
provider : string ;
patientName : string ;
planPays : number | null ;
planPaysText : string ;
status : string ;
}
export type DdmaMatchOutcome =
| "updated" // payment paid amount set from Plan Pays
| "unchanged" // payment already had this amount
| "created" // no claim in the app — patient + payment created (like MH PDF import)
| "not_paid_yet" // DDMA status is not "Paid"
| "no_claim" // no claim in the app with this claim number (and not paid, so nothing created)
| "no_payment" ; // claim found but it has no payment record
export interface DdmaClaimMatch {
outcome : DdmaMatchOutcome ;
appClaimId? : number ;
paymentId? : number ;
appPatientName? : string ;
previousPaid? : number | null ;
/** For "created": whether the patient was newly created or an existing one was reused */
patientCreated? : boolean ;
patientId? : number ;
}
export type DdmaMatchedClaim = DdmaClaimPayment & { match : DdmaClaimMatch } ;
export interface DdmaPaymentProcessorResult {
message : string ;
fromDate? : string ;
toDate? : string ;
claims : DdmaMatchedClaim [ ] ;
summary : Record < DdmaMatchOutcome , number > ;
/** Saved results page PDF in uploads/DDMAPayment (view via /api/payments/ddma-payment-pdf/:filename) */
pdfFilename : string | null ;
}
const digitsOnly = ( s : string | null | undefined ) = > ( s ? ? "" ) . replace ( /\D/g , "" ) ;
const DDMA_PAYER = "Delta Dental MA" ;
const isPaid = ( c : DdmaClaimPayment ) = >
( c . status ? ? "" ) . trim ( ) . toLowerCase ( ) === "paid" && c . planPays != null ;
/** "NATHAN ZHANG" → { firstName: "NATHAN", lastName: "ZHANG" } (DDMA shows First Last) */
function splitDdmaName ( full : string ) : { firstName : string ; lastName : string } {
const parts = ( full ? ? "" ) . replace ( /\s+/g , " " ) . trim ( ) . split ( " " ) . filter ( Boolean ) ;
if ( parts . length === 0 ) return { firstName : "" , lastName : "" } ;
if ( parts . length === 1 ) return { firstName : "" , lastName : parts [ 0 ] ! } ;
return { firstName : parts [ 0 ] ! , lastName : parts.slice ( 1 ) . join ( " " ) } ;
}
/** "2026-11-09" → Date at UTC midnight (for @db.Date columns) */
function isoToDate ( iso : string ) : Date {
const m = /^(\d{4})-(\d{2})-(\d{2})$/ . exec ( iso ? ? "" ) ;
return m ? new Date ( Date . UTC ( + m [ 1 ] ! , + m [ 2 ] ! - 1 , + m [ 3 ] ! ) ) : new Date ( ) ;
}
/**
* No claim in the app for this DDMA claim number — create the records the same
* way the MH PDF import does: find-or-create the patient, then a payment (no
* claim) with one service line and a DDMA transaction for the Plan Pays amount.
* The DDMA claim number is stored on payment.icn (shown in the Claim No. column)
* and on the service line, so the next run finds this payment instead of
* creating another one.
*/
async function createDdmaPayment (
c : DdmaClaimPayment ,
userId : number ,
npiProviders : { id : number ; providerName : string } [ ]
) : Promise < DdmaClaimMatch > {
const { firstName , lastName } = splitDdmaName ( c . patientName ) ;
const paid = c . planPays ? ? 0 ;
const providerKey = ( c . provider ? ? "" ) . trim ( ) . toLowerCase ( ) ;
const npiProviderId =
npiProviders . find ( ( p ) = > p . providerName . trim ( ) . toLowerCase ( ) === providerKey ) ? . id ? ? null ;
return prisma . $transaction ( async ( tx : typeof prisma ) = > {
// 1. Find patient by name (prefer one already on Delta Dental MA), else create
const candidates = await tx . patient . findMany ( {
where : {
firstName : { equals : firstName , mode : "insensitive" } ,
lastName : { equals : lastName , mode : "insensitive" } ,
} ,
orderBy : { id : "asc" } ,
} ) ;
let patient =
candidates . find ( ( p : any ) = > /delta/i . test ( p . insuranceProvider ? ? "" ) ) ? ? candidates [ 0 ] ? ? null ;
let patientCreated = false ;
if ( ! patient ) {
patient = await tx . patient . create ( {
data : {
firstName ,
lastName ,
insuranceProvider : DDMA_PAYER ,
gender : "" ,
phone : "" ,
userId ,
} ,
} ) ;
patientCreated = true ;
} else if ( ! patient . insuranceProvider ) {
patient = await tx . patient . update ( {
where : { id : patient.id } ,
data : { insuranceProvider : DDMA_PAYER } ,
} ) ;
}
// 2. Payment — DDMA doesn't show the billed amount, so billed = Plan Pays
const payment = await tx . payment . create ( {
data : {
patientId : patient.id ,
userId ,
npiProviderId ,
totalBilled : paid ,
totalPaid : paid ,
totalAdjusted : 0 ,
totalDue : 0 ,
mhPaidAmount : paid ,
adjustment : 0 ,
status : paid > 0 ? "PAID" : "PENDING" ,
icn : c.claimNumber ,
notes : ` DDMA import claim ${ c . claimNumber } ` ,
updatedById : userId ,
} ,
} ) ;
// 3. One service line for the claim + a DDMA transaction for the paid amount
const line = await tx . serviceLine . create ( {
data : {
paymentId : payment.id ,
icn : c.claimNumber ,
procedureCode : "" ,
procedureDate : isoToDate ( c . dateOfService ) ,
totalBilled : paid ,
totalPaid : paid ,
totalAdjusted : 0 ,
totalDue : 0 ,
status : paid > 0 ? "PAID" : "UNPAID" ,
} ,
} ) ;
if ( paid > 0 ) {
await tx . serviceLineTransaction . create ( {
data : {
paymentId : payment.id ,
serviceLineId : line.id ,
transactionId : c.claimNumber ,
paidAmount : paid ,
method : "EFT" ,
receivedDate : new Date ( ) ,
payerName : DDMA_PAYER ,
notes : ` DDMA claim ${ c . claimNumber } ` ,
} ,
} ) ;
}
log ( "ddma-payment-processor" , "created patient/payment for unmatched claim" , {
claimNumber : c.claimNumber ,
patientId : patient.id ,
patientCreated ,
paymentId : payment.id ,
paid ,
} ) ;
return {
outcome : "created" as const ,
paymentId : payment.id ,
patientId : patient.id ,
patientCreated ,
appPatientName : ` ${ patient . firstName } ${ patient . lastName } ` . trim ( ) ,
} ;
} ) ;
}
/**
* Match DDMA claims to app claims by claim number and fill the payment's paid
* amount. Same math as PATCH /api/payments/:id/mh-paid-amount:
* adjustment = max(0, totalBilled − paid − copayment)
* The amount is set (not added), so re-running the check is safe.
* Paid claims with no match get a new patient/payment (createDdmaPayment).
*/
async function applyDdmaPayments (
claims : DdmaClaimPayment [ ] ,
userId : number
) : Promise < DdmaMatchedClaim [ ] > {
const variants = new Set < string > ( ) ;
for ( const c of claims ) {
const raw = ( c . claimNumber ? ? "" ) . trim ( ) ;
if ( raw ) variants . add ( raw ) ;
const d = digitsOnly ( raw ) ;
if ( d ) variants . add ( d ) ;
}
if ( variants . size === 0 ) return [ ] ;
const appClaims = await prisma . claim . findMany ( {
where : { claimNumber : { in : [ . . . variants ] } } ,
include : { payment : true } ,
orderBy : { id : "desc" } ,
} ) ;
const byNumber = new Map < string , ( typeof appClaims ) [ number ] > ( ) ;
for ( const ac of appClaims ) {
const key = digitsOnly ( ac . claimNumber ) ;
if ( key && ! byNumber . has ( key ) ) byNumber . set ( key , ac ) ;
}
// Payments created by earlier DDMA runs (no claim; claim number stored on icn)
const importedPayments = await prisma . payment . findMany ( {
where : { claimId : null , icn : { in : [ . . . variants ] } } ,
include : { patient : true } ,
orderBy : { id : "desc" } ,
} ) ;
const importedByNumber = new Map < string , ( typeof importedPayments ) [ number ] > ( ) ;
for ( const p of importedPayments ) {
const key = digitsOnly ( p . icn ) ;
if ( key && ! importedByNumber . has ( key ) ) importedByNumber . set ( key , p ) ;
}
const npiProviders = await prisma . npiProvider . findMany ( {
select : { id : true , providerName : true } ,
} ) ;
const out : DdmaMatchedClaim [ ] = [ ] ;
for ( const c of claims ) {
const key = digitsOnly ( c . claimNumber ) ;
const appClaim = byNumber . get ( key ) ;
let base : Partial < DdmaClaimMatch > ;
let payment : any ;
if ( appClaim ) {
base = { appClaimId : appClaim.id , appPatientName : appClaim.patientName } ;
payment = appClaim . payment ;
if ( ! payment ) {
out . push ( { . . . c , match : { . . . base , outcome : "no_payment" } } ) ;
continue ;
}
} else if ( importedByNumber . has ( key ) ) {
payment = importedByNumber . get ( key ) ! ;
base = {
appPatientName : payment.patient
? ` ${ payment . patient . firstName } ${ payment . patient . lastName } ` . trim ( )
: undefined ,
} ;
} else {
// Not in the app at all — create patient + payment, like the MH import
if ( ! isPaid ( c ) ) {
out . push ( { . . . c , match : { outcome : "no_claim" } } ) ;
continue ;
}
try {
out . push ( { . . . c , match : await createDdmaPayment ( c , userId , npiProviders ) } ) ;
} catch ( err : any ) {
log ( "ddma-payment-processor" , "create failed" , {
claimNumber : c.claimNumber ,
err : err?.message ,
} ) ;
out . push ( { . . . c , match : { outcome : "no_claim" } } ) ;
}
continue ;
}
const previousPaid = payment . mhPaidAmount != null ? Number ( payment . mhPaidAmount ) : null ;
const withPayment = { . . . base , paymentId : payment.id , previousPaid } ;
if ( ! isPaid ( c ) ) {
out . push ( { . . . c , match : { . . . withPayment , outcome : "not_paid_yet" } } ) ;
continue ;
}
const planPays = c . planPays ! ; // isPaid() guarantees non-null
if ( previousPaid != null && Math . abs ( previousPaid - planPays ) < 0.005 ) {
out . push ( { . . . c , match : { . . . withPayment , outcome : "unchanged" } } ) ;
continue ;
}
const totalBilled = Number ( payment . totalBilled ) ;
const copayment = Number ( payment . copayment ? ? 0 ) ;
const adjustment = Math . max ( 0 , totalBilled - planPays - copayment ) ;
await prisma . payment . update ( {
where : { id : payment.id } ,
data : { mhPaidAmount : planPays , adjustment , updatedById : userId } ,
} ) ;
log ( "ddma-payment-processor" , "payment updated" , {
paymentId : payment.id ,
claimNumber : c.claimNumber ,
planPays ,
previousPaid ,
} ) ;
out . push ( { . . . c , match : { . . . withPayment , outcome : "updated" } } ) ;
}
return out ;
}
export async function runDdmaPaymentProcessor (
input : DdmaPaymentProcessorInput ,
jobId : string
) : Promise < DdmaPaymentProcessorResult > {
const { enrichedPayload , socketId , userId } = input ;
log ( "ddma-payment-processor" , "starting Python agent session" , {
fromDate : enrichedPayload?.fromDate ,
toDate : enrichedPayload?.toDate ,
} ) ;
const agentResp = await forwardToSeleniumDdmaPaymentAgent ( enrichedPayload ) ;
if ( ! agentResp ? . session_id ) {
throw new Error ( "Python agent did not return a session_id for DDMA payment check" ) ;
}
const sessionId = agentResp . session_id as string ;
emitToSocket ( socketId , "selenium:ddma_session_started" , { session_id : sessionId , jobId } ) ;
const seleniumResult = await pollUntilDone ( sessionId , socketId , jobId ) ;
if ( ! seleniumResult || seleniumResult . status === "error" ) {
throw new Error ( seleniumResult ? . message ? ? "DDMA payment session returned an error result" ) ;
}
const ddmaClaims : DdmaClaimPayment [ ] = Array . isArray ( seleniumResult . claims )
? seleniumResult . claims
: [ ] ;
const claims = await applyDdmaPayments ( ddmaClaims , userId ) ;
const summary : Record < DdmaMatchOutcome , number > = {
updated : 0 ,
unchanged : 0 ,
created : 0 ,
not_paid_yet : 0 ,
no_claim : 0 ,
no_payment : 0 ,
} ;
for ( const c of claims ) summary [ c . match . outcome ] ++ ;
log ( "ddma-payment-processor" , "done" , { claimCount : claims.length , summary } ) ;
return {
message : ` Found ${ claims . length } DDMA claim(s); ${ summary . updated } payment(s) updated, ${ summary . created } created ` ,
fromDate : seleniumResult.fromDate ,
toDate : seleniumResult.toDate ,
claims ,
summary ,
pdfFilename : seleniumResult.pdfFilename ? ? null ,
} ;
}