@@ -325,8 +325,72 @@ const createMetRequirementAndNewCase = async (
325325 const patientLastName = patient . name ?. [ 0 ] . family || '' ;
326326 const patientDOB = patient . birthDate || '' ;
327327 let message = '' ;
328- const case_number = uid ( ) ;
329328
329+ // Check if case already exists
330+ const existingCase = await remsCaseCollection . findOne ( {
331+ patientFirstName : patientFirstName ,
332+ patientLastName : patientLastName ,
333+ patientDOB : patientDOB ,
334+ drugCode : drug ?. code
335+ } ) ;
336+
337+ if ( existingCase ) {
338+ // Case already exists - update the existing requirement instead of creating new case
339+ console . log ( `Case ${ existingCase . case_number } already exists, updating requirement ${ requirement . name } ` ) ;
340+
341+ // Find and update the existing MetRequirement
342+ const matchedMetReq = await metRequirementsCollection
343+ . findOne ( {
344+ stakeholderId : reqStakeholderReference ,
345+ requirementName : requirement . name ,
346+ drugName : drug ?. name
347+ } )
348+ . exec ( ) ;
349+
350+ if ( matchedMetReq ) {
351+ // Update existing MetRequirement
352+ matchedMetReq . completed = true ;
353+ matchedMetReq . completedQuestionnaire = questionnaireResponse ;
354+ await matchedMetReq . save ( ) ;
355+
356+ // Update the case's metRequirements array
357+ const metReqArray = existingCase . metRequirements || [ ] ;
358+ let foundUncompleted = false ;
359+
360+ for ( let i = 0 ; i < metReqArray . length ; i ++ ) {
361+ const req = existingCase . metRequirements [ i ] ;
362+ if ( req ?. requirementName === matchedMetReq . requirementName ) {
363+ metReqArray [ i ] . completed = true ;
364+ req ! . completed = true ;
365+ await remsCaseCollection . updateOne (
366+ { _id : existingCase . _id } ,
367+ { $set : { metRequirements : metReqArray } }
368+ ) ;
369+ }
370+ if ( ! req ?. completed ) {
371+ foundUncompleted = true ;
372+ }
373+ }
374+
375+ // Update case status if all requirements are now complete
376+ if ( ! foundUncompleted && existingCase . status === 'Pending' ) {
377+ existingCase . status = 'Approved' ;
378+ await existingCase . save ( ) ;
379+ }
380+
381+ return {
382+ returnedRemsRequestDoc : existingCase
383+ } ;
384+ } else {
385+ message = 'ERROR: MetRequirement not found for existing case' ;
386+ console . log ( message ) ;
387+ throw new Error ( message ) ;
388+ }
389+ }
390+
391+ // No existing case - create new one
392+ const case_number = uid ( ) ;
393+
330394 // create new rems request and add the created metReq to it
331395 let remsRequestCompletedStatus = 'Approved' ;
332396 const dispenseStatusDefault = 'Pending' ;
0 commit comments