• Rahul Mehata
  • NEWBIE
  • 0 Points
  • Member since 2016

  • Chatter
    Feed
  • 0
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 2
    Questions
  • 14
    Replies
My apex class is
public with sharing class CandidatePatientHandler implements TriggerInterFace {
  
  static String PATIENT_ROLE = 'Patient';
  static String CARE_COORDINATOR_ROLE = 'Care Coordinator';

  public List<HealthCloudGA__CandidatePatient__c>  lstCandidatePaitentsToUpdate;

  public void bulkAfter(){

    lstCandidatePaitentsToUpdate = new List<HealthCloudGA__CandidatePatient__c>();
    
    //New list of Patient Candidates
    List<HealthCloudGA__CandidatePatient__c> newAccountList = (List<HealthCloudGA__CandidatePatient__c>)Trigger.new;
    
    //Map of Old values of Patient Candidates.
    Map<Id, HealthCloudGA__CandidatePatient__c> oldMap = (Map<Id, HealthCloudGA__CandidatePatient__c>)Trigger.oldMap;
    
    //List of Candidate Patients who accepted the CCM Program.
    List<HealthCloudGA__CandidatePatient__c> lstOfAcceptedCandidatePatients = new List<HealthCloudGA__CandidatePatient__c>();
       
    //To cancel Recurring Tasks.
    Set<Id> setOfIdsOfCandidatePatients= new Set<Id>();
    
    //Store Account to create per Candidate Patients.
    Map<Id,Account> mapPatientToAccounts = new Map<Id,Account>();
    
    //Store Contact to create per Candidate Patients.
    Map<Id,Contact> mapPatienttoContacts = new Map<Id,Contact>();
      
    //Store Care Plan to create for each Candidate Patients.
    Map<Id,Case> mapPatientToCase = new Map<Id,Case>();
    
    //Store Care Coordinator and Patient in Team.
    Map<Id,List<CaseTeamMember>> mapPatientTocaseTeamMember = new Map<Id,List<CaseTeamMember>>();
    
    //List of all CaseTeamMembers to insert.Includes Care Coordinator and Patient himself.
    List<CaseTeamMember> lstCaseTeamMembers = new List<CaseTeamMember>();
    
    //List of goals to achieve in Care Plan of each Patient.
    //List<HealthCloudGA__CarePlanGoal__c> lstGoals = new List<HealthCloudGA__CarePlanGoal__c>();
    //List of problems.
    List<HealthCloudGA__CarePlanProblem__c> lstProblems = new List<HealthCloudGA__CarePlanProblem__c>();
       
    //List of Task for Care Coordinators.
    List<Task> lstOfTask = new List<Task>();
    List<Task> lstTasks = new List<Task>();
    
    //Map Contact to accountId.
    Map<Id,Id> mapAccountToContactId = new Map<Id,Id>();
    
    //Set to store Name of Practices of Patients.
    Set<String> setPractices = new Set<String>();
    
    //Map Practice to Care Coordinator Parctice.
    Map<String,Set<Id>> mapCareCordinatorPractices = new Map<String,Set<Id>>();
    
    //Store MemberIds in set.
    Set<Id> careCoordinatorIds = new Set<Id>();
    
    //Map to store Care Coordinator and number of patients assigned to him.
    Map<Id,Integer> mapCoordinatorToPatients = new Map<id,Integer>();

    //Map to store Patient Account and its care plan.
    Map<Id,Id> mapPatientAccountCarePlan = new Map<Id,Id>();

    //Map Medical record number to Account.
    Map<String,Account> mapMRNToAccount = new Map<String,Account>();
    
    Map<Id,Contact> mapExistingContacts = new Map<Id,Contact>();

    //Store Medical Record Numbers
    Set<String> medicalRecordNumbers = new Set<String>();

    //Store Practice Ids.
    Set<Id> AllPracticeIds = new Set<Id>();
    for(HealthCloudGA__CandidatePatient__c patient : newAccountList){
      if(patient.Practice__c != null){
        AllPracticeIds.add(patient.Practice__c);
      }
    }

    for(Account acc : [Select Id from Account where Parent.Enable_Care_Plan_Automation__c =: true and Id In:AllPracticeIds]){
      String accountId = acc.Id;
      setPractices.add(accountId );
      accountId = accountId.substring(0,15);
      setPractices.add(accountId);
    }
       
    for(HealthCloudGA__CandidatePatient__c patient : newAccountList){
      if(setPractices.contains(patient.Practice__c)){
      
        if(Trigger.IsInsert && patient.CCM_Status__c == 'Accepted' && patient.HealthCloudGA__AccountId__c == null){
          lstOfAcceptedCandidatePatients.add(patient);
        }
        else{
          if(Trigger.IsUpdate && patient.CCM_Status__c == 'Accepted' && 
            (patient.CCM_Status__c != oldMap.get(patient.Id).CCM_Status__c) && patient.HealthCloudGA__AccountId__c == null){
            
            lstOfAcceptedCandidatePatients.add(patient);
          }
          else {
            if(Trigger.IsUpdate && patient.CCM_Status__c != 'Accepted' && 
              (patient.CCM_Status__c != oldMap.get(patient.Id).CCM_Status__c)){
              
              setOfIdsOfCandidatePatients.add(patient.HealthCloudGA__AccountId__c );
            }
          }
        }
        if(patient.HealthCloudGA__MedicalRecordNumber__c != null){
          medicalRecordNumbers.add(patient.HealthCloudGA__MedicalRecordNumber__c);
        }
      } 
    }
      
    if(setOfIdsOfCandidatePatients.size()>0){
      List<Case> lstCases = [Select Id from case where AccountId In:setOfIdsOfCandidatePatients];
      List<Task> lstTasksToCancel = [Select Id,RecurrenceEndDateOnly 
        from task where whatId IN: lstCases and RecurrenceEndDateOnly != null];
      
      for(Task tsk : lstTasksToCancel){
          tsk.RecurrenceStartDateOnly = Date.Today().addDays(-1);
          tsk.RecurrenceEndDateOnly = Date.Today();
      }
      update lstTasksToCancel;
    }
    
    if(lstOfAcceptedCandidatePatients.size()>0){

      //Store Field names of Candidate patient to map with fields of Contact.
      Map<String,String> mapNonEditableToContact = new Map<String,String>{
        'HealthCloudGA__FamilyName1__c'=>'LastName',
        'HealthCloudGA__GivenName1__c'=>'FirstName',
        'HealthCloudGA__BirthDate__c'=>'Birthdate',
        'Insurance_Id__c'=>'Insurance_Id__c',
        'Primary_Phone__c'=>'Phone',
        'Email__c'=>'Email',
        'HealthCloudGA__Address1City__c'=>'MailingCity',
        'HealthCloudGA__Address1State__c'=>'MailingState',
        'HealthCloudGA__Address1PostalCode__c'=>'MailingPostalCode'
      };
    
      //Store medical number and account having that Medical number.
      for(Account acc : [Select Id,
                                Name,
                                HealthCloudGA__MedicalRecordNumber__c,
                                Description,HealthCloudGA__PrimaryContact__c 
                                from Account 
                                where HealthCloudGA__MedicalRecordNumber__c In: medicalRecordNumbers]){

          mapMRNToAccount.put(acc.HealthCloudGA__MedicalRecordNumber__c,acc);
      }

      //Store Field names of Candidate patient to map with fields of Contact.
      Map<String,String> mapFieldsToMapWithContact = new Map<String,String>{
        'Practice__c'=>'Practice__c',
        'HealthCloudGA__MedicalRecordNumber__c'=>'HealthCloudGA__MedicalRecordNumber__c',
        'HealthCloudGA__FamilyName1__c'=>'LastName',
        'HealthCloudGA__GivenName1__c'=>'FirstName',
        'HealthCloudGA__BirthDate__c'=>'Birthdate',
        'Last_Appointment__c'=>'Last_Appointment__c',
        'Next_Appointment__C'=>'Next_Appointment__C',
        'Advanced_Directive__c'=>'Advanced_Directive__c',
        'Insurance_Id__c'=>'Insurance_Id__c',
        'Primary_Phone__c'=>'Phone',
        'Email__c'=>'Email',
        'Advanced_Directive_Date__c'=>'Advanced_Directive_Date__c',
        'HealthCloudGA__Address1City__c'=>'MailingCity',
        'HealthCloudGA__Address1State__c'=>'MailingState',
        'HealthCloudGA__Address1PostalCode__c'=>'MailingPostalCode',
        'CCM_Status__c'=>'CCM_Status__c',
        'Wellness__c'=>'Wellness__c',
        'Pneumococcal_Prevar__c'=>'Pneumococcal_Prevar__c',
        'Pneumococcal_Pneumovax__c'=>'Pneumococcal_Pneumovax__c',
        'Colonoscopy__c'=>'Colonoscopy__c',
        'FOBT__c'=>'FOBT__c',
        'Mammogram__c'=>'Mammogram__c',
        'Fall_Risk__C'=>'Fall_Risk__C',
        'Depression_Screening__c'=>'Depression_Screening__c',
        'CAD_IVD__c'=>'CAD_IVD__c',
        'HF_Beta_Blocker__c'=>'HF_Beta_Blocker__c',
        'CAD_DM_HF__c'=>'CAD_DM_HF__c',
        'CAD_DM_Statin__c'=>'CAD_DM_Statin__c',
        'Diabetes_A1C__c'=>'Diabetes_A1C__c',
        'BMI_plan__c'=>'BMI_plan__c',
        'Tobacco_Use__c'=>'Tobacco_Use__c',
        'HTN_BP__c'=>'HTN_BP__c',
        'Diabetic__c'=>'Diabetic__c'
      };
           
      //Store Field names of Candidate patient to map with fields of Account.  
      Map<String,String> mapFieldsToMapWithAccount = new Map<String,String>{
        'HealthCloudGA__Name__c'=>'Name',
        'Comment__c'=>'Description',
        'HealthCloudGA__MedicalRecordNumber__c'=>'HealthCloudGA__MedicalRecordNumber__c',
        'CCM_Status__c'=>'CCM_Status__c'
      };

      //Store Field names of Candidate patient to map with fields of Account.  
      Map<String,String> mapNonEditableFieldsToMapWithAccount = new Map<String,String>{
        'HealthCloudGA__Name__c'=>'Name',
        'Comment__c'=>'Description'
      };

      //Store Field names of TemplateGoal to map with Goal.
      Map<String,String> mapFieldsToMapWithGoal = new Map<String,String>{
        'HealthCloudGA__Description__c'=>'HealthCloudGA__Description__c',
        'HealthCloudGA__Priority__c'=>'HealthCloudGA__Priority__c',
        'Name'=>'Name'
      };

      //Store Field names of TemplateProblem to map with Problem.
      Map<String,String> mapFieldsToMapWithProblem = new Map<String,String>{
        'HealthCloudGA__CarePlanTemplate__c'=>'HealthCloudGA__CarePlanTemplate__c',
        'HealthCloudGA__Description__c'=>'HealthCloudGA__Description__c',
        'HealthCloudGA__Priority__c'=>'HealthCloudGA__Priority__c',
        'Name'=>'Name'
      };

      //Store Field names of TemplateTask to map with Task.
      Map<String,String> mapFieldsToMapWithTask = new Map<String,String>{
        'HealthCloudGA__Priority__c'=>'Priority',
        'HealthCloudGA__Status__c'=>'Status',
        'HealthCloudGA__Subject__c'=>'Subject',
        'HealthCloudGA__Type__c'=>'Type'
      };
          
      //get Care Coordinators of Practices.
      Map<String,String> mapPracticeIdToName = new Map<String,String>();
      if(setPractices.size()>0){
        for(AccountTeamMember practice : 
          [Select Id,UserId,Account.Name,AccountId
          from AccountTeamMember 
          where AccountId In:setPractices /*and TeamMemberRole =: CARE_COORDINATOR_ROLE*/]){

          String accountId = practice.AccountId;
          mapPracticeIdToName.put(accountId,practice.Account.Name);
          
          Set<ID> setOfCareCoordinatorIds = mapCareCordinatorPractices.get(accountId);
          
          if(setOfCareCoordinatorIds == null){
            accountId = accountId.substring(0,15);
            mapPracticeIdToName.put(accountId,practice.Account.Name);
            setOfCareCoordinatorIds = mapCareCordinatorPractices.get(accountId);
            if(setOfCareCoordinatorIds == null){
              setOfCareCoordinatorIds = new Set<ID>();
            }
          }
          setOfCareCoordinatorIds.add(practice.UserId);
          mapCareCordinatorPractices.put(accountId,setOfCareCoordinatorIds);
          careCoordinatorIds.add(practice.UserId);
        }
        system.debug('mapPracticeIdToName'+mapPracticeIdToName);
      }

      //Get Care coordinators and patients assigned to them.
      Map<String,Map<Id,Integer>> mapPracticeToCareCoordinators = new Map<String,Map<Id,Integer>>();

      AggregateResult[] Results = [SELECT MemberId,
                                  Parent.Contact.Practice__c,
                                  Count(Id) Total 
                                  FROM CaseTeamMember 
                                  where MemberId In:careCoordinatorIds 
                                  and TeamRole.Name ='Care Coordinator' 
                                  group by MemberId,Parent.Contact.Practice__c];
           
      if(Results !=null){
        for(AggregateResult result : Results ){

          Map<Id,Integer> mapCoordinatorToNoOfPatients = mapPracticeToCareCoordinators.get((String)result.get('Practice__c'));
          if(mapCoordinatorToNoOfPatients == null){

            mapCoordinatorToNoOfPatients = new Map<Id,Integer>();
          }
          mapCoordinatorToNoOfPatients.put((ID)result.get('MemberId'),(Integer)result.get('Total'));

          mapPracticeToCareCoordinators.put((String)result.get('Practice__c'),mapCoordinatorToNoOfPatients);
        }
      }
      
      //Create Account and contact for each patient
      for(HealthCloudGA__CandidatePatient__c patient : lstOfAcceptedCandidatePatients){
        Account acc = new Account();
        if(!mapMRNToAccount.keySet().contains(patient.HealthCloudGA__MedicalRecordNumber__c)){          
          for(String str : mapFieldsToMapWithAccount.keySet()){
            acc.put(mapFieldsToMapWithAccount.get(str),patient.get(str));
          }
        }
        else{
          acc = mapMRNToAccount.get(patient.HealthCloudGA__MedicalRecordNumber__c);
          for(String str : mapNonEditableFieldsToMapWithAccount.keySet()){
            acc.put(mapNonEditableFieldsToMapWithAccount.get(str),patient.get(str));
          }
        }
        mapPatientToAccounts.put(patient.Id,acc);
      }
      
      //Insert all accounts
      if(mapPatientToAccounts.values().size()>0){
        upsert mapPatientToAccounts.values();
      }
      
      for(Contact con : [Select Id,AccountId from Contact where AccountId In :mapPatientToAccounts.values()]){
        mapAccountToContactId.put(con.AccountId,con.Id);
      }
      
      //Set AccountId on contact.
      
      for(HealthCloudGA__CandidatePatient__c patient : lstOfAcceptedCandidatePatients){
          Contact con = new Contact();
          Account acc = mapPatientToAccounts.get(patient.Id);
          if(!mapMRNToAccount.keySet().contains(patient.HealthCloudGA__MedicalRecordNumber__c)){
            for(String str : mapFieldsToMapWithContact.keySet()){
              con.put(mapFieldsToMapWithContact.get(str),patient.get(str));
            }
          }
          else{
            for(String str : mapNonEditableToContact.keySet()){
              con.put(mapNonEditableToContact.get(str),patient.get(str));
            }
          }
          Id conId = mapAccountToContactId.get(acc.Id);
          if(conId != null){
            con.Id = conId;
            mapPatienttoContacts.put(patient.Id,con);
         }
      }
      
      //update Contact.
      if(mapPatienttoContacts.values().size()>0){
          try{
                update mapPatienttoContacts.values();
          }
          catch(DMLException e){
          }
      }
      
      //CaseTeamRole for Patient.
      CaseTeamRole PatientRole = [select Id from CaseTeamRole where Name =:PATIENT_ROLE];
      
      //CaseTeamRole for Care Coordinator.
      CaseTeamRole CareCoordinatorRole = [select Id from CaseTeamRole where Name =:CARE_COORDINATOR_ROLE];

      //AccountTeamRole for Care Coordinator.
      //AccountTeamRole practiceCareCoordinatorRole = [select Id from AccountTeamRole where Name =:CARE_COORDINATOR_ROLE];
      
      //Get last Date of current month
      Integer numberOfDays = Date.daysInMonth(Date.today().year(), Date.today().month());
      Date lastDayOfMonth = Date.newInstance(Date.today().year(), Date.today().month(), numberOfDays);
      
      //Create Care Plan and Care Team.
      for(HealthCloudGA__CandidatePatient__c patient : lstOfAcceptedCandidatePatients){
        Account acc = mapPatientToAccounts.get(patient.Id);
        Contact con = mapPatienttoContacts.get(patient.Id);
        Case cs = new Case();
        cs.AccountId = acc.Id;
        cs.ContactId = con.Id;
        cs.Status = 'New';
        cs.Priority = 'Low';
        mapPatientToCase.put(patient.Id,cs);
        
        List<CaseTeamMember> lstCaseTeamMember = new List<CaseTeamMember>();
        CaseTeamMember casemember = new CaseTeamMember();
        if(con.Id != null){
            casemember.MemberId = con.Id;
            casemember.TeamRoleId = PatientRole.Id;
            lstCaseTeamMember.add(casemember);
        }
        
        //Get Care Coordinator for Patient who has least number of patients assigned.
        Integer i = 0;
        String CareCoordinatorId = '';
        /**
         * Check for Care Coordinators in Map.
         * Map will return null in case of new Practice(Care Coordinators in this practice don't have a single patient assigned.)
         */
        if(mapPracticeToCareCoordinators.get(Patient.Practice__c) != null){
          CareCoordinatorId = getCareCoordinator(mapPracticeToCareCoordinators.get(Patient.Practice__c),mapCareCordinatorPractices.get(Patient.Practice__c));
        }
        /**
         * If Care Coordinators in this practice don't have a single patient assigned to them assign this patient to first Care 
         * Coordinator.
         */
        else{
          if(mapCareCordinatorPractices.get(Patient.Practice__c) != null){
            for(String coordinatorId : mapCareCordinatorPractices.get(Patient.Practice__c)){
              CareCoordinatorId = coordinatorId;
              Map<Id,Integer> mapCoordinatorTocount = new Map<Id,Integer>();
              mapPracticeToCareCoordinators.put(Patient.Practice__c,mapCoordinatorTocount);
              break;
            }
          }
        }
        if(CareCoordinatorId != ''){
          casemember = new CaseTeamMember();
          casemember.MemberId = CareCoordinatorId;
          casemember.TeamRoleId = CareCoordinatorRole.Id;
          lstCaseTeamMember.add(casemember);
        }  
        mapPatientTocaseTeamMember.put(patient.Id,lstCaseTeamMember);
      }
      
      Map<Id,Id> mapCarePlanToPatient = new Map<Id,Id>();
      
      //Insert Care Plan for each patient who accept CCM Program.
      if(mapPatientToCase.values().size()>0){
        insert mapPatientToCase.values();
        for(Case cs : mapPatientToCase.values()){
          mapCarePlanToPatient.put(cs.Id,cs.AccountId);
        }
      }
      
      //Assign Care Coordinator for each patient who accept CCM Program.
      for(HealthCloudGA__CandidatePatient__c patient : lstOfAcceptedCandidatePatients){
        case cs = mapPatientToCase.get(patient.Id);
        for(CaseTeamMember teamMember : mapPatientTocaseTeamMember.get(patient.Id)){
          teamMember.ParentId = cs.Id;
          lstCaseTeamMembers.add(teamMember);
        }
      }
      
      //Insert Case Team Members.
      if(lstCaseTeamMembers.size()>0){
        insert lstCaseTeamMembers;
      }
           
      //Get Care Plan Template.
      HealthCloudGA__CarePlanTemplate__c template = [Select Id,
        (Select Id,Name,HealthCloudGA__Active__c,HealthCloudGA__CarePlanTemplate__c,HealthCloudGA__Description__c,
        HealthCloudGA__Priority__c,HealthCloudGA__SortOrder__c
        from HealthCloudGA__CarePlanTemplateProblems__r)
        from HealthCloudGA__CarePlanTemplate__c where Name =:Label.Care_Plan_Template];

      //Get Care Plan Template Problems.                                              
      Map<Id, HealthCloudGA__CarePlanTemplateProblem__c> mapProblem = new Map<Id, HealthCloudGA__CarePlanTemplateProblem__c>(
        [Select Id, (Select ID,Name,HealthCloudGA__Active__c,HealthCloudGA__CarePlanTemplateProblem__c,
        HealthCloudGA__Description__c, HealthCloudGA__Priority__c,HealthCloudGA__SortOrder__c 
        From HealthCloudGA__CarePlanTemplateGoals__r)
        from HealthCloudGA__CarePlanTemplateProblem__c where ID In :template.HealthCloudGA__CarePlanTemplateProblems__r]);
          
      //Prblem to goals                                                              
      Map<Id,List<HealthCloudGA__CarePlanTemplateGoal__c>> mapProblemToGoals = 
        new Map<Id,List<HealthCloudGA__CarePlanTemplateGoal__c>>();

      Map<Id,List<HealthCloudGA__CarePlanTemplateTask__c>> mapGoalToTasks = 
        new Map<Id,List<HealthCloudGA__CarePlanTemplateTask__c>>();

      Map<String,HealthCloudGA__CarePlanProblem__c> maptemplateProblemToProblem = 
        new Map<String,HealthCloudGA__CarePlanProblem__c>();

      Map<String,HealthCloudGA__CarePlanGoal__c> maptemplateGoalToGoal = 
        new Map<String,HealthCloudGA__CarePlanGoal__c>();

      //Store Template Goal Id.
      Set<Id> setGoalIds = new Set<Id>();
      
      //Store Problem and related Goals.
      for(HealthCloudGA__CarePlanTemplateProblem__c  problem : mapProblem.values() ){
        for(HealthCloudGA__CarePlanTemplateGoal__c goal : problem.HealthCloudGA__CarePlanTemplateGoals__r){
          
          setGoalIds.add(goal.Id);
        }
      }

      Map<Id, HealthCloudGA__CarePlanTemplateGoal__c> mapGoals = new Map<Id, HealthCloudGA__CarePlanTemplateGoal__c>(
        [Select id, (Select Id,HealthCloudGA__Active__c,HealthCloudGA__AssignedTo__c,
          HealthCloudGA__CarePlanTemplateGoal__c, HealthCloudGA__Description__c, HealthCloudGA__Offset__c,
          HealthCloudGA__Priority__c,HealthCloudGA__SortOrder__c,HealthCloudGA__Status__c, HealthCloudGA__Subject__c,
          HealthCloudGA__Type__c 
          from HealthCloudGA__CarePlanTemplateTasks__r)
          from HealthCloudGA__CarePlanTemplateGoal__c
          where id IN : setGoalIds]); 

      //Add Goal, problems, tasks for Care Coordinator.                     
      if(template != null){
        for(Case cs : mapPatientToCase.values()){
          //Create Problem here
          for(HealthCloudGA__CarePlanTemplateProblem__c problem : template.HealthCloudGA__CarePlanTemplateProblems__r){
            HealthCloudGA__CarePlanProblem__c prblm = new HealthCloudGA__CarePlanProblem__c();
            
            // set problem for case with fields of template problem
            for(String key : mapFieldsToMapWithProblem.keySet()){
              prblm.put(mapFieldsToMapWithProblem.get(key),problem.get(key));
            }
            prblm.HealthCloudGA__CarePlan__c = cs.Id;
            lstProblems.add(prblm);
            maptemplateProblemToProblem.put(problem.Id+''+cs.Id,prblm);
          }
        }
      }
      
      //Add Problems.
      if(maptemplateProblemToProblem.values().Size()>0){
        insert maptemplateProblemToProblem.Values();
      }

      for(Case cs : mapPatientToCase.values()){
        mapPatientAccountCarePlan.put(cs.AccountId,cs.Id);

        for(HealthCloudGA__CarePlanTemplateProblem__c problem : template.HealthCloudGA__CarePlanTemplateProblems__r){
          HealthCloudGA__CarePlanProblem__c problems = maptemplateProblemToProblem.get(problem.Id+''+cs.Id);
          
          HealthCloudGA__CarePlanTemplateProblem__c problemDb = mapProblem.get(problem.id); 

          for(HealthCloudGA__CarePlanTemplateGoal__c goal : problemDb.HealthCloudGA__CarePlanTemplateGoals__r){
            
            HealthCloudGA__CarePlanGoal__c carePlanGoal = new HealthCloudGA__CarePlanGoal__c();
            
            // template goal to normal goal tied to case problem 
            for(String key : mapFieldsToMapWithGoal.keySet()){
              carePlanGoal.put(mapFieldsToMapWithGoal.get(key),goal.get(key));
            }
            carePlanGoal.HealthCloudGA__CarePlan__c = cs.Id;
            carePlanGoal.HealthCloudGA__CarePlanProblem__c = problems .Id;
            maptemplateGoalToGoal.put(goal.Id+''+problemDb.Id+''+cs.Id,carePlanGoal);
          }
        } 
      }
      
      if(maptemplateGoalToGoal.values().size()>0){
        insert maptemplateGoalToGoal.values();
      }
      
      for(Case cs : mapPatientToCase.values()){
        for(HealthCloudGA__CarePlanTemplateProblem__c problem : template.HealthCloudGA__CarePlanTemplateProblems__r){
          HealthCloudGA__CarePlanTemplateProblem__c problemDb = mapProblem.get(problem.Id);
          
          if(problemDb == null) continue;

          for(HealthCloudGA__CarePlanTemplateGoal__c goal : problemDb.HealthCloudGA__CarePlanTemplateGoals__r){
            HealthCloudGA__CarePlanGoal__c carePlanGoal = maptemplateGoalToGoal.get(goal.Id+''+problemDb.Id+''+cs.Id);

            HealthCloudGA__CarePlanTemplateGoal__c goalDb = mapGoals.get(goal.id);

            if(goalDb == null) continue;
            for(HealthCloudGA__CarePlanTemplateTask__c tk : goalDb.HealthCloudGA__CarePlanTemplateTasks__r){
              Task tsk = new Task();
              for(String key : mapFieldsToMapWithTask.keySet()){
                tsk.put(mapFieldsToMapWithTask.get(key),tk.get(key));
              }
              tsk.HealthCloudGA__CarePlanProblem__c = maptemplateProblemToProblem.get(problem.Id+''+cs.Id).id;
              tsk.HealthCloudGA__CarePlanGoal__c = maptemplateGoalToGoal.get(goal.id+''+problemDb.Id+''+cs.Id).Id;

              tsk.WhatId = cs.Id;
              //tsk.ActivityDate = lastDayOfMonth;
              tsk.whoId = cs.ContactId;
              tsk.Patient__c = mapCarePlanToPatient.get(cs.Id);
              
              // template task should recur with due date as end of the month
              tsk.RecurrenceInterval = 1;
              //tsk.RecurrenceRegeneratedType = 'RecurrenceRegenerateAfterDueDate';
              tsk.RecurrenceEndDateOnly = Date.today().addMonths(1);
              tsk.RecurrenceStartDateOnly = Date.today();
              tsk.RecurrenceType = 'RecursMonthly';
              tsk.RecurrenceDayOfMonth = 1;
              tsk.IsRecurrence = true;
              lstOfTask.add(tsk);
            }
          }
        } 
      }
          
      if(lstOfTask.size()>0){
        insert lstOfTask; 
      }
      
      //Update Candidate Pateint with Account.
      Map<Id,Id> mapAccountToPractice = new Map<Id,Id>();
      for(HealthCloudGA__CandidatePatient__c patient : lstOfAcceptedCandidatePatients){
        if(mapPatientToAccounts.get(patient.Id) != null){
          HealthCloudGA__CandidatePatient__c  patients = patient.clone(true,false);
          Id AccountId = mapPatientToAccounts.get(patient.Id).Id;
          patients.HealthCloudGA__AccountId__c = AccountId;
          patients.Practice_Name__c = mapPracticeIdToName.get(patient.Practice__c);
          lstCandidatePaitentsToUpdate.add(patients);
          mapAccountToPractice.put(AccountId,patient.Practice__c);
        }
      }
      //Update Account with Care Plan.
      List<Account> lstAccountToUpdate = new List<Account>();
      for(String accId : mapPatientAccountCarePlan.keySet()){
          Account acc = new Account();
          acc.Id = accId;
          acc.HealthCloudGA__CarePlan__c = mapPatientAccountCarePlan.get(accId);
          acc.ParentId = mapAccountToPractice.get(accId);
          lstAccountToUpdate.add(acc);
      }
      if(lstAccountToUpdate.size()>0){
        update lstAccountToUpdate;
      }
    }  
  }
  /**
   * Get Care Coordinator for Patient.
   * @param: mapCoordinatorToCount-Map of Care Coordinator to its count(Number of patients assigned to him.).
   * @param: CoordinatorIdSet-Set of all Coordinators in Patient's practice.
   */
  public static String getCareCoordinator(Map<Id,Integer> mapCoordinatorToCount,Set<Id> CoordinatorIdSet){
    String CareCoordinatorId = '';
    Integer i;
    /**
     * Itreting Set of Care Coordinators Id because if any care coordinator doesnt have single patient assigned to him it will not be 
     * present in aggregate result 'mapCoordinatorToCount'.
     */
    for(String coordinatorId : CoordinatorIdSet){
      i = mapCoordinatorToCount.get(coordinatorId);
      break;
    }
    for(String coordinatorId : CoordinatorIdSet){
      if(mapCoordinatorToCount.get(coordinatorId) == null){
        CareCoordinatorId = coordinatorId;
        break;
      }
      else
        if(mapCoordinatorToCount.get(coordinatorId)<=i){
          i = mapCoordinatorToCount.get(coordinatorId);
          CareCoordinatorId = coordinatorId;
      }
    }
    if(mapCoordinatorToCount.get(CareCoordinatorId) == null){
      mapCoordinatorToCount.put(CareCoordinatorId,1);
    }
    else{
      mapCoordinatorToCount.put(CareCoordinatorId,mapCoordinatorToCount.get(CareCoordinatorId)+1);
    }
    return CareCoordinatorId;
  }
    
  public void bulkBefore(){}
  public void beforeInsert(SObject so){}
  public void beforeUpdate(SObject oldSo, SObject so){}
  public void beforeDelete(SObject so){}
  public void afterInsert(SObject so){}
  public void afterUpdate(SObject oldSo, SObject so){}
  public void afterDelete(SObject so){}
  public void afterUndelete(SObject so){} 
  public void andFinally(){
    if(lstCandidatePaitentsToUpdate.size()>0){
      update lstCandidatePaitentsToUpdate;
    }  
  }

}
I am not able to cover the below lines in test class. please help.
Contact con = new contact();
          con.id= rel.From_Individual__c;
          con.firstname= rel.From_Individual__r.firstname;
          con.lastname= rel.From_Individual__r.lastname;
          con.email= rel.From_Individual__r.email;
          conListForAdvisor.add(con);
        }
        if(conListForAdvisor.size()>0){
          update relationListForAdvisor;
          update conListForAdvisor;
        }
        for(Event ev : newEvents){
            System.debug(ev);
          if(ev.eventName != null && ev.eventName != ''){
            cEvent = new Event__c();

            String parishRegion = getCRSRegion(University);
            cEvent.Name = ev.eventName;
            cEvent.Status__c = 'Completed';
            cEvent.Description__c = ev.eventDescription;
            if(ev.eventCheckAllThatApply != null) {
              cEvent.Check_all_that_apply_to_your_campus__c = 
              String.valueOf(ev.eventCheckAllThatApply).remove('(').remove(')').replace(',',';');
            }
            if(ev.eventNuberAttended != null && ev.eventNuberAttended != ''){
              cEvent.Number_Attended__c = Decimal.ValueOf(ev.eventNuberAttended);
            }
            if(ev.eventLetters != null && ev.eventLetters != ''){
              cEvent.If_you_hand_wrote_letters_please_list__c = Decimal.ValueOf(ev.eventLetters);
              /*if(Decimal.ValueOf(ev.eventLetters) > 0 ){
                cEvent.Action__c = 'EN - Directing a LETTER WRITING campaign';
              }*/
            }
            
            String evSelectedOptions = '';
            for(String s: ev.eventCheckAllThatApply) {
              evSelectedOptions += s + ' ';
            }
            //evSelectedOptions.addAll(ev.eventCheckAllThatApply);
            System.debug('>>>evSelectedOptions: ' + evSelectedOptions);

            if(evSelectedOptions.contains('Chapter meetings')) {
              cEvent.Action__c = 'ED - Coordinating a MEETING';
            }
            else if(evSelectedOptions.contains('Legislative Visit')) {
              cEvent.Action__c = 'EN - Facilitating a CONGRESSIONAL VISIT';
            }
            else {
              cEvent.Action__c = 'ED - Providing general OUTREACH';
            } 
            
            cEvent.Category__c = catagory;
            String campaignName = ''; // hold the program initiative to attach the event to
            cEvent.Parish_or_School__c = University;
            cEvent.Primary_Institution__c = University;
            

            cEvent.CRS_Region__c = 'Replicator; ' + parishRegion;
            if(ev.eventDate != null && ev.eventDate !=''){
              cEvent.Start_Date__c = date.ValueOf(ev.eventDate);
              cEvent.End_Date__c = date.ValueOf(ev.eventDate);
              cEvent.Event_Date_Time__c = cEvent.End_Date__c;
            }
            cEvent.Association_if_other__c = ''; // reset after the field has been used.            
            lstEvents.add(cEvent);
          }

        }
        if(lstEvents.size() > 0){

          insert lstEvents;
          for(Event__c events : lstEvents){
            eventIds.add(events.Id);
          }
          eventId = lstEvents[0].Id;
        }
My apex class is
public with sharing class CandidatePatientHandler implements TriggerInterFace {
  
  static String PATIENT_ROLE = 'Patient';
  static String CARE_COORDINATOR_ROLE = 'Care Coordinator';

  public List<HealthCloudGA__CandidatePatient__c>  lstCandidatePaitentsToUpdate;

  public void bulkAfter(){

    lstCandidatePaitentsToUpdate = new List<HealthCloudGA__CandidatePatient__c>();
    
    //New list of Patient Candidates
    List<HealthCloudGA__CandidatePatient__c> newAccountList = (List<HealthCloudGA__CandidatePatient__c>)Trigger.new;
    
    //Map of Old values of Patient Candidates.
    Map<Id, HealthCloudGA__CandidatePatient__c> oldMap = (Map<Id, HealthCloudGA__CandidatePatient__c>)Trigger.oldMap;
    
    //List of Candidate Patients who accepted the CCM Program.
    List<HealthCloudGA__CandidatePatient__c> lstOfAcceptedCandidatePatients = new List<HealthCloudGA__CandidatePatient__c>();
       
    //To cancel Recurring Tasks.
    Set<Id> setOfIdsOfCandidatePatients= new Set<Id>();
    
    //Store Account to create per Candidate Patients.
    Map<Id,Account> mapPatientToAccounts = new Map<Id,Account>();
    
    //Store Contact to create per Candidate Patients.
    Map<Id,Contact> mapPatienttoContacts = new Map<Id,Contact>();
      
    //Store Care Plan to create for each Candidate Patients.
    Map<Id,Case> mapPatientToCase = new Map<Id,Case>();
    
    //Store Care Coordinator and Patient in Team.
    Map<Id,List<CaseTeamMember>> mapPatientTocaseTeamMember = new Map<Id,List<CaseTeamMember>>();
    
    //List of all CaseTeamMembers to insert.Includes Care Coordinator and Patient himself.
    List<CaseTeamMember> lstCaseTeamMembers = new List<CaseTeamMember>();
    
    //List of goals to achieve in Care Plan of each Patient.
    //List<HealthCloudGA__CarePlanGoal__c> lstGoals = new List<HealthCloudGA__CarePlanGoal__c>();
    //List of problems.
    List<HealthCloudGA__CarePlanProblem__c> lstProblems = new List<HealthCloudGA__CarePlanProblem__c>();
       
    //List of Task for Care Coordinators.
    List<Task> lstOfTask = new List<Task>();
    List<Task> lstTasks = new List<Task>();
    
    //Map Contact to accountId.
    Map<Id,Id> mapAccountToContactId = new Map<Id,Id>();
    
    //Set to store Name of Practices of Patients.
    Set<String> setPractices = new Set<String>();
    
    //Map Practice to Care Coordinator Parctice.
    Map<String,Set<Id>> mapCareCordinatorPractices = new Map<String,Set<Id>>();
    
    //Store MemberIds in set.
    Set<Id> careCoordinatorIds = new Set<Id>();
    
    //Map to store Care Coordinator and number of patients assigned to him.
    Map<Id,Integer> mapCoordinatorToPatients = new Map<id,Integer>();

    //Map to store Patient Account and its care plan.
    Map<Id,Id> mapPatientAccountCarePlan = new Map<Id,Id>();

    //Map Medical record number to Account.
    Map<String,Account> mapMRNToAccount = new Map<String,Account>();
    
    Map<Id,Contact> mapExistingContacts = new Map<Id,Contact>();

    //Store Medical Record Numbers
    Set<String> medicalRecordNumbers = new Set<String>();

    //Store Practice Ids.
    Set<Id> AllPracticeIds = new Set<Id>();
    for(HealthCloudGA__CandidatePatient__c patient : newAccountList){
      if(patient.Practice__c != null){
        AllPracticeIds.add(patient.Practice__c);
      }
    }

    for(Account acc : [Select Id from Account where Parent.Enable_Care_Plan_Automation__c =: true and Id In:AllPracticeIds]){
      String accountId = acc.Id;
      setPractices.add(accountId );
      accountId = accountId.substring(0,15);
      setPractices.add(accountId);
    }
       
    for(HealthCloudGA__CandidatePatient__c patient : newAccountList){
      if(setPractices.contains(patient.Practice__c)){
      
        if(Trigger.IsInsert && patient.CCM_Status__c == 'Accepted' && patient.HealthCloudGA__AccountId__c == null){
          lstOfAcceptedCandidatePatients.add(patient);
        }
        else{
          if(Trigger.IsUpdate && patient.CCM_Status__c == 'Accepted' && 
            (patient.CCM_Status__c != oldMap.get(patient.Id).CCM_Status__c) && patient.HealthCloudGA__AccountId__c == null){
            
            lstOfAcceptedCandidatePatients.add(patient);
          }
          else {
            if(Trigger.IsUpdate && patient.CCM_Status__c != 'Accepted' && 
              (patient.CCM_Status__c != oldMap.get(patient.Id).CCM_Status__c)){
              
              setOfIdsOfCandidatePatients.add(patient.HealthCloudGA__AccountId__c );
            }
          }
        }
        if(patient.HealthCloudGA__MedicalRecordNumber__c != null){
          medicalRecordNumbers.add(patient.HealthCloudGA__MedicalRecordNumber__c);
        }
      } 
    }
      
    if(setOfIdsOfCandidatePatients.size()>0){
      List<Case> lstCases = [Select Id from case where AccountId In:setOfIdsOfCandidatePatients];
      List<Task> lstTasksToCancel = [Select Id,RecurrenceEndDateOnly 
        from task where whatId IN: lstCases and RecurrenceEndDateOnly != null];
      
      for(Task tsk : lstTasksToCancel){
          tsk.RecurrenceStartDateOnly = Date.Today().addDays(-1);
          tsk.RecurrenceEndDateOnly = Date.Today();
      }
      update lstTasksToCancel;
    }
    
    if(lstOfAcceptedCandidatePatients.size()>0){

      //Store Field names of Candidate patient to map with fields of Contact.
      Map<String,String> mapNonEditableToContact = new Map<String,String>{
        'HealthCloudGA__FamilyName1__c'=>'LastName',
        'HealthCloudGA__GivenName1__c'=>'FirstName',
        'HealthCloudGA__BirthDate__c'=>'Birthdate',
        'Insurance_Id__c'=>'Insurance_Id__c',
        'Primary_Phone__c'=>'Phone',
        'Email__c'=>'Email',
        'HealthCloudGA__Address1City__c'=>'MailingCity',
        'HealthCloudGA__Address1State__c'=>'MailingState',
        'HealthCloudGA__Address1PostalCode__c'=>'MailingPostalCode'
      };
    
      //Store medical number and account having that Medical number.
      for(Account acc : [Select Id,
                                Name,
                                HealthCloudGA__MedicalRecordNumber__c,
                                Description,HealthCloudGA__PrimaryContact__c 
                                from Account 
                                where HealthCloudGA__MedicalRecordNumber__c In: medicalRecordNumbers]){

          mapMRNToAccount.put(acc.HealthCloudGA__MedicalRecordNumber__c,acc);
      }

      //Store Field names of Candidate patient to map with fields of Contact.
      Map<String,String> mapFieldsToMapWithContact = new Map<String,String>{
        'Practice__c'=>'Practice__c',
        'HealthCloudGA__MedicalRecordNumber__c'=>'HealthCloudGA__MedicalRecordNumber__c',
        'HealthCloudGA__FamilyName1__c'=>'LastName',
        'HealthCloudGA__GivenName1__c'=>'FirstName',
        'HealthCloudGA__BirthDate__c'=>'Birthdate',
        'Last_Appointment__c'=>'Last_Appointment__c',
        'Next_Appointment__C'=>'Next_Appointment__C',
        'Advanced_Directive__c'=>'Advanced_Directive__c',
        'Insurance_Id__c'=>'Insurance_Id__c',
        'Primary_Phone__c'=>'Phone',
        'Email__c'=>'Email',
        'Advanced_Directive_Date__c'=>'Advanced_Directive_Date__c',
        'HealthCloudGA__Address1City__c'=>'MailingCity',
        'HealthCloudGA__Address1State__c'=>'MailingState',
        'HealthCloudGA__Address1PostalCode__c'=>'MailingPostalCode',
        'CCM_Status__c'=>'CCM_Status__c',
        'Wellness__c'=>'Wellness__c',
        'Pneumococcal_Prevar__c'=>'Pneumococcal_Prevar__c',
        'Pneumococcal_Pneumovax__c'=>'Pneumococcal_Pneumovax__c',
        'Colonoscopy__c'=>'Colonoscopy__c',
        'FOBT__c'=>'FOBT__c',
        'Mammogram__c'=>'Mammogram__c',
        'Fall_Risk__C'=>'Fall_Risk__C',
        'Depression_Screening__c'=>'Depression_Screening__c',
        'CAD_IVD__c'=>'CAD_IVD__c',
        'HF_Beta_Blocker__c'=>'HF_Beta_Blocker__c',
        'CAD_DM_HF__c'=>'CAD_DM_HF__c',
        'CAD_DM_Statin__c'=>'CAD_DM_Statin__c',
        'Diabetes_A1C__c'=>'Diabetes_A1C__c',
        'BMI_plan__c'=>'BMI_plan__c',
        'Tobacco_Use__c'=>'Tobacco_Use__c',
        'HTN_BP__c'=>'HTN_BP__c',
        'Diabetic__c'=>'Diabetic__c'
      };
           
      //Store Field names of Candidate patient to map with fields of Account.  
      Map<String,String> mapFieldsToMapWithAccount = new Map<String,String>{
        'HealthCloudGA__Name__c'=>'Name',
        'Comment__c'=>'Description',
        'HealthCloudGA__MedicalRecordNumber__c'=>'HealthCloudGA__MedicalRecordNumber__c',
        'CCM_Status__c'=>'CCM_Status__c'
      };

      //Store Field names of Candidate patient to map with fields of Account.  
      Map<String,String> mapNonEditableFieldsToMapWithAccount = new Map<String,String>{
        'HealthCloudGA__Name__c'=>'Name',
        'Comment__c'=>'Description'
      };

      //Store Field names of TemplateGoal to map with Goal.
      Map<String,String> mapFieldsToMapWithGoal = new Map<String,String>{
        'HealthCloudGA__Description__c'=>'HealthCloudGA__Description__c',
        'HealthCloudGA__Priority__c'=>'HealthCloudGA__Priority__c',
        'Name'=>'Name'
      };

      //Store Field names of TemplateProblem to map with Problem.
      Map<String,String> mapFieldsToMapWithProblem = new Map<String,String>{
        'HealthCloudGA__CarePlanTemplate__c'=>'HealthCloudGA__CarePlanTemplate__c',
        'HealthCloudGA__Description__c'=>'HealthCloudGA__Description__c',
        'HealthCloudGA__Priority__c'=>'HealthCloudGA__Priority__c',
        'Name'=>'Name'
      };

      //Store Field names of TemplateTask to map with Task.
      Map<String,String> mapFieldsToMapWithTask = new Map<String,String>{
        'HealthCloudGA__Priority__c'=>'Priority',
        'HealthCloudGA__Status__c'=>'Status',
        'HealthCloudGA__Subject__c'=>'Subject',
        'HealthCloudGA__Type__c'=>'Type'
      };
          
      //get Care Coordinators of Practices.
      Map<String,String> mapPracticeIdToName = new Map<String,String>();
      if(setPractices.size()>0){
        for(AccountTeamMember practice : 
          [Select Id,UserId,Account.Name,AccountId
          from AccountTeamMember 
          where AccountId In:setPractices /*and TeamMemberRole =: CARE_COORDINATOR_ROLE*/]){

          String accountId = practice.AccountId;
          mapPracticeIdToName.put(accountId,practice.Account.Name);
          
          Set<ID> setOfCareCoordinatorIds = mapCareCordinatorPractices.get(accountId);
          
          if(setOfCareCoordinatorIds == null){
            accountId = accountId.substring(0,15);
            mapPracticeIdToName.put(accountId,practice.Account.Name);
            setOfCareCoordinatorIds = mapCareCordinatorPractices.get(accountId);
            if(setOfCareCoordinatorIds == null){
              setOfCareCoordinatorIds = new Set<ID>();
            }
          }
          setOfCareCoordinatorIds.add(practice.UserId);
          mapCareCordinatorPractices.put(accountId,setOfCareCoordinatorIds);
          careCoordinatorIds.add(practice.UserId);
        }
        system.debug('mapPracticeIdToName'+mapPracticeIdToName);
      }

      //Get Care coordinators and patients assigned to them.
      Map<String,Map<Id,Integer>> mapPracticeToCareCoordinators = new Map<String,Map<Id,Integer>>();

      AggregateResult[] Results = [SELECT MemberId,
                                  Parent.Contact.Practice__c,
                                  Count(Id) Total 
                                  FROM CaseTeamMember 
                                  where MemberId In:careCoordinatorIds 
                                  and TeamRole.Name ='Care Coordinator' 
                                  group by MemberId,Parent.Contact.Practice__c];
           
      if(Results !=null){
        for(AggregateResult result : Results ){

          Map<Id,Integer> mapCoordinatorToNoOfPatients = mapPracticeToCareCoordinators.get((String)result.get('Practice__c'));
          if(mapCoordinatorToNoOfPatients == null){

            mapCoordinatorToNoOfPatients = new Map<Id,Integer>();
          }
          mapCoordinatorToNoOfPatients.put((ID)result.get('MemberId'),(Integer)result.get('Total'));

          mapPracticeToCareCoordinators.put((String)result.get('Practice__c'),mapCoordinatorToNoOfPatients);
        }
      }
      
      //Create Account and contact for each patient
      for(HealthCloudGA__CandidatePatient__c patient : lstOfAcceptedCandidatePatients){
        Account acc = new Account();
        if(!mapMRNToAccount.keySet().contains(patient.HealthCloudGA__MedicalRecordNumber__c)){          
          for(String str : mapFieldsToMapWithAccount.keySet()){
            acc.put(mapFieldsToMapWithAccount.get(str),patient.get(str));
          }
        }
        else{
          acc = mapMRNToAccount.get(patient.HealthCloudGA__MedicalRecordNumber__c);
          for(String str : mapNonEditableFieldsToMapWithAccount.keySet()){
            acc.put(mapNonEditableFieldsToMapWithAccount.get(str),patient.get(str));
          }
        }
        mapPatientToAccounts.put(patient.Id,acc);
      }
      
      //Insert all accounts
      if(mapPatientToAccounts.values().size()>0){
        upsert mapPatientToAccounts.values();
      }
      
      for(Contact con : [Select Id,AccountId from Contact where AccountId In :mapPatientToAccounts.values()]){
        mapAccountToContactId.put(con.AccountId,con.Id);
      }
      
      //Set AccountId on contact.
      
      for(HealthCloudGA__CandidatePatient__c patient : lstOfAcceptedCandidatePatients){
          Contact con = new Contact();
          Account acc = mapPatientToAccounts.get(patient.Id);
          if(!mapMRNToAccount.keySet().contains(patient.HealthCloudGA__MedicalRecordNumber__c)){
            for(String str : mapFieldsToMapWithContact.keySet()){
              con.put(mapFieldsToMapWithContact.get(str),patient.get(str));
            }
          }
          else{
            for(String str : mapNonEditableToContact.keySet()){
              con.put(mapNonEditableToContact.get(str),patient.get(str));
            }
          }
          Id conId = mapAccountToContactId.get(acc.Id);
          if(conId != null){
            con.Id = conId;
            mapPatienttoContacts.put(patient.Id,con);
         }
      }
      
      //update Contact.
      if(mapPatienttoContacts.values().size()>0){
          try{
                update mapPatienttoContacts.values();
          }
          catch(DMLException e){
          }
      }
      
      //CaseTeamRole for Patient.
      CaseTeamRole PatientRole = [select Id from CaseTeamRole where Name =:PATIENT_ROLE];
      
      //CaseTeamRole for Care Coordinator.
      CaseTeamRole CareCoordinatorRole = [select Id from CaseTeamRole where Name =:CARE_COORDINATOR_ROLE];

      //AccountTeamRole for Care Coordinator.
      //AccountTeamRole practiceCareCoordinatorRole = [select Id from AccountTeamRole where Name =:CARE_COORDINATOR_ROLE];
      
      //Get last Date of current month
      Integer numberOfDays = Date.daysInMonth(Date.today().year(), Date.today().month());
      Date lastDayOfMonth = Date.newInstance(Date.today().year(), Date.today().month(), numberOfDays);
      
      //Create Care Plan and Care Team.
      for(HealthCloudGA__CandidatePatient__c patient : lstOfAcceptedCandidatePatients){
        Account acc = mapPatientToAccounts.get(patient.Id);
        Contact con = mapPatienttoContacts.get(patient.Id);
        Case cs = new Case();
        cs.AccountId = acc.Id;
        cs.ContactId = con.Id;
        cs.Status = 'New';
        cs.Priority = 'Low';
        mapPatientToCase.put(patient.Id,cs);
        
        List<CaseTeamMember> lstCaseTeamMember = new List<CaseTeamMember>();
        CaseTeamMember casemember = new CaseTeamMember();
        if(con.Id != null){
            casemember.MemberId = con.Id;
            casemember.TeamRoleId = PatientRole.Id;
            lstCaseTeamMember.add(casemember);
        }
        
        //Get Care Coordinator for Patient who has least number of patients assigned.
        Integer i = 0;
        String CareCoordinatorId = '';
        /**
         * Check for Care Coordinators in Map.
         * Map will return null in case of new Practice(Care Coordinators in this practice don't have a single patient assigned.)
         */
        if(mapPracticeToCareCoordinators.get(Patient.Practice__c) != null){
          CareCoordinatorId = getCareCoordinator(mapPracticeToCareCoordinators.get(Patient.Practice__c),mapCareCordinatorPractices.get(Patient.Practice__c));
        }
        /**
         * If Care Coordinators in this practice don't have a single patient assigned to them assign this patient to first Care 
         * Coordinator.
         */
        else{
          if(mapCareCordinatorPractices.get(Patient.Practice__c) != null){
            for(String coordinatorId : mapCareCordinatorPractices.get(Patient.Practice__c)){
              CareCoordinatorId = coordinatorId;
              Map<Id,Integer> mapCoordinatorTocount = new Map<Id,Integer>();
              mapPracticeToCareCoordinators.put(Patient.Practice__c,mapCoordinatorTocount);
              break;
            }
          }
        }
        if(CareCoordinatorId != ''){
          casemember = new CaseTeamMember();
          casemember.MemberId = CareCoordinatorId;
          casemember.TeamRoleId = CareCoordinatorRole.Id;
          lstCaseTeamMember.add(casemember);
        }  
        mapPatientTocaseTeamMember.put(patient.Id,lstCaseTeamMember);
      }
      
      Map<Id,Id> mapCarePlanToPatient = new Map<Id,Id>();
      
      //Insert Care Plan for each patient who accept CCM Program.
      if(mapPatientToCase.values().size()>0){
        insert mapPatientToCase.values();
        for(Case cs : mapPatientToCase.values()){
          mapCarePlanToPatient.put(cs.Id,cs.AccountId);
        }
      }
      
      //Assign Care Coordinator for each patient who accept CCM Program.
      for(HealthCloudGA__CandidatePatient__c patient : lstOfAcceptedCandidatePatients){
        case cs = mapPatientToCase.get(patient.Id);
        for(CaseTeamMember teamMember : mapPatientTocaseTeamMember.get(patient.Id)){
          teamMember.ParentId = cs.Id;
          lstCaseTeamMembers.add(teamMember);
        }
      }
      
      //Insert Case Team Members.
      if(lstCaseTeamMembers.size()>0){
        insert lstCaseTeamMembers;
      }
           
      //Get Care Plan Template.
      HealthCloudGA__CarePlanTemplate__c template = [Select Id,
        (Select Id,Name,HealthCloudGA__Active__c,HealthCloudGA__CarePlanTemplate__c,HealthCloudGA__Description__c,
        HealthCloudGA__Priority__c,HealthCloudGA__SortOrder__c
        from HealthCloudGA__CarePlanTemplateProblems__r)
        from HealthCloudGA__CarePlanTemplate__c where Name =:Label.Care_Plan_Template];

      //Get Care Plan Template Problems.                                              
      Map<Id, HealthCloudGA__CarePlanTemplateProblem__c> mapProblem = new Map<Id, HealthCloudGA__CarePlanTemplateProblem__c>(
        [Select Id, (Select ID,Name,HealthCloudGA__Active__c,HealthCloudGA__CarePlanTemplateProblem__c,
        HealthCloudGA__Description__c, HealthCloudGA__Priority__c,HealthCloudGA__SortOrder__c 
        From HealthCloudGA__CarePlanTemplateGoals__r)
        from HealthCloudGA__CarePlanTemplateProblem__c where ID In :template.HealthCloudGA__CarePlanTemplateProblems__r]);
          
      //Prblem to goals                                                              
      Map<Id,List<HealthCloudGA__CarePlanTemplateGoal__c>> mapProblemToGoals = 
        new Map<Id,List<HealthCloudGA__CarePlanTemplateGoal__c>>();

      Map<Id,List<HealthCloudGA__CarePlanTemplateTask__c>> mapGoalToTasks = 
        new Map<Id,List<HealthCloudGA__CarePlanTemplateTask__c>>();

      Map<String,HealthCloudGA__CarePlanProblem__c> maptemplateProblemToProblem = 
        new Map<String,HealthCloudGA__CarePlanProblem__c>();

      Map<String,HealthCloudGA__CarePlanGoal__c> maptemplateGoalToGoal = 
        new Map<String,HealthCloudGA__CarePlanGoal__c>();

      //Store Template Goal Id.
      Set<Id> setGoalIds = new Set<Id>();
      
      //Store Problem and related Goals.
      for(HealthCloudGA__CarePlanTemplateProblem__c  problem : mapProblem.values() ){
        for(HealthCloudGA__CarePlanTemplateGoal__c goal : problem.HealthCloudGA__CarePlanTemplateGoals__r){
          
          setGoalIds.add(goal.Id);
        }
      }

      Map<Id, HealthCloudGA__CarePlanTemplateGoal__c> mapGoals = new Map<Id, HealthCloudGA__CarePlanTemplateGoal__c>(
        [Select id, (Select Id,HealthCloudGA__Active__c,HealthCloudGA__AssignedTo__c,
          HealthCloudGA__CarePlanTemplateGoal__c, HealthCloudGA__Description__c, HealthCloudGA__Offset__c,
          HealthCloudGA__Priority__c,HealthCloudGA__SortOrder__c,HealthCloudGA__Status__c, HealthCloudGA__Subject__c,
          HealthCloudGA__Type__c 
          from HealthCloudGA__CarePlanTemplateTasks__r)
          from HealthCloudGA__CarePlanTemplateGoal__c
          where id IN : setGoalIds]); 

      //Add Goal, problems, tasks for Care Coordinator.                     
      if(template != null){
        for(Case cs : mapPatientToCase.values()){
          //Create Problem here
          for(HealthCloudGA__CarePlanTemplateProblem__c problem : template.HealthCloudGA__CarePlanTemplateProblems__r){
            HealthCloudGA__CarePlanProblem__c prblm = new HealthCloudGA__CarePlanProblem__c();
            
            // set problem for case with fields of template problem
            for(String key : mapFieldsToMapWithProblem.keySet()){
              prblm.put(mapFieldsToMapWithProblem.get(key),problem.get(key));
            }
            prblm.HealthCloudGA__CarePlan__c = cs.Id;
            lstProblems.add(prblm);
            maptemplateProblemToProblem.put(problem.Id+''+cs.Id,prblm);
          }
        }
      }
      
      //Add Problems.
      if(maptemplateProblemToProblem.values().Size()>0){
        insert maptemplateProblemToProblem.Values();
      }

      for(Case cs : mapPatientToCase.values()){
        mapPatientAccountCarePlan.put(cs.AccountId,cs.Id);

        for(HealthCloudGA__CarePlanTemplateProblem__c problem : template.HealthCloudGA__CarePlanTemplateProblems__r){
          HealthCloudGA__CarePlanProblem__c problems = maptemplateProblemToProblem.get(problem.Id+''+cs.Id);
          
          HealthCloudGA__CarePlanTemplateProblem__c problemDb = mapProblem.get(problem.id); 

          for(HealthCloudGA__CarePlanTemplateGoal__c goal : problemDb.HealthCloudGA__CarePlanTemplateGoals__r){
            
            HealthCloudGA__CarePlanGoal__c carePlanGoal = new HealthCloudGA__CarePlanGoal__c();
            
            // template goal to normal goal tied to case problem 
            for(String key : mapFieldsToMapWithGoal.keySet()){
              carePlanGoal.put(mapFieldsToMapWithGoal.get(key),goal.get(key));
            }
            carePlanGoal.HealthCloudGA__CarePlan__c = cs.Id;
            carePlanGoal.HealthCloudGA__CarePlanProblem__c = problems .Id;
            maptemplateGoalToGoal.put(goal.Id+''+problemDb.Id+''+cs.Id,carePlanGoal);
          }
        } 
      }
      
      if(maptemplateGoalToGoal.values().size()>0){
        insert maptemplateGoalToGoal.values();
      }
      
      for(Case cs : mapPatientToCase.values()){
        for(HealthCloudGA__CarePlanTemplateProblem__c problem : template.HealthCloudGA__CarePlanTemplateProblems__r){
          HealthCloudGA__CarePlanTemplateProblem__c problemDb = mapProblem.get(problem.Id);
          
          if(problemDb == null) continue;

          for(HealthCloudGA__CarePlanTemplateGoal__c goal : problemDb.HealthCloudGA__CarePlanTemplateGoals__r){
            HealthCloudGA__CarePlanGoal__c carePlanGoal = maptemplateGoalToGoal.get(goal.Id+''+problemDb.Id+''+cs.Id);

            HealthCloudGA__CarePlanTemplateGoal__c goalDb = mapGoals.get(goal.id);

            if(goalDb == null) continue;
            for(HealthCloudGA__CarePlanTemplateTask__c tk : goalDb.HealthCloudGA__CarePlanTemplateTasks__r){
              Task tsk = new Task();
              for(String key : mapFieldsToMapWithTask.keySet()){
                tsk.put(mapFieldsToMapWithTask.get(key),tk.get(key));
              }
              tsk.HealthCloudGA__CarePlanProblem__c = maptemplateProblemToProblem.get(problem.Id+''+cs.Id).id;
              tsk.HealthCloudGA__CarePlanGoal__c = maptemplateGoalToGoal.get(goal.id+''+problemDb.Id+''+cs.Id).Id;

              tsk.WhatId = cs.Id;
              //tsk.ActivityDate = lastDayOfMonth;
              tsk.whoId = cs.ContactId;
              tsk.Patient__c = mapCarePlanToPatient.get(cs.Id);
              
              // template task should recur with due date as end of the month
              tsk.RecurrenceInterval = 1;
              //tsk.RecurrenceRegeneratedType = 'RecurrenceRegenerateAfterDueDate';
              tsk.RecurrenceEndDateOnly = Date.today().addMonths(1);
              tsk.RecurrenceStartDateOnly = Date.today();
              tsk.RecurrenceType = 'RecursMonthly';
              tsk.RecurrenceDayOfMonth = 1;
              tsk.IsRecurrence = true;
              lstOfTask.add(tsk);
            }
          }
        } 
      }
          
      if(lstOfTask.size()>0){
        insert lstOfTask; 
      }
      
      //Update Candidate Pateint with Account.
      Map<Id,Id> mapAccountToPractice = new Map<Id,Id>();
      for(HealthCloudGA__CandidatePatient__c patient : lstOfAcceptedCandidatePatients){
        if(mapPatientToAccounts.get(patient.Id) != null){
          HealthCloudGA__CandidatePatient__c  patients = patient.clone(true,false);
          Id AccountId = mapPatientToAccounts.get(patient.Id).Id;
          patients.HealthCloudGA__AccountId__c = AccountId;
          patients.Practice_Name__c = mapPracticeIdToName.get(patient.Practice__c);
          lstCandidatePaitentsToUpdate.add(patients);
          mapAccountToPractice.put(AccountId,patient.Practice__c);
        }
      }
      //Update Account with Care Plan.
      List<Account> lstAccountToUpdate = new List<Account>();
      for(String accId : mapPatientAccountCarePlan.keySet()){
          Account acc = new Account();
          acc.Id = accId;
          acc.HealthCloudGA__CarePlan__c = mapPatientAccountCarePlan.get(accId);
          acc.ParentId = mapAccountToPractice.get(accId);
          lstAccountToUpdate.add(acc);
      }
      if(lstAccountToUpdate.size()>0){
        update lstAccountToUpdate;
      }
    }  
  }
  /**
   * Get Care Coordinator for Patient.
   * @param: mapCoordinatorToCount-Map of Care Coordinator to its count(Number of patients assigned to him.).
   * @param: CoordinatorIdSet-Set of all Coordinators in Patient's practice.
   */
  public static String getCareCoordinator(Map<Id,Integer> mapCoordinatorToCount,Set<Id> CoordinatorIdSet){
    String CareCoordinatorId = '';
    Integer i;
    /**
     * Itreting Set of Care Coordinators Id because if any care coordinator doesnt have single patient assigned to him it will not be 
     * present in aggregate result 'mapCoordinatorToCount'.
     */
    for(String coordinatorId : CoordinatorIdSet){
      i = mapCoordinatorToCount.get(coordinatorId);
      break;
    }
    for(String coordinatorId : CoordinatorIdSet){
      if(mapCoordinatorToCount.get(coordinatorId) == null){
        CareCoordinatorId = coordinatorId;
        break;
      }
      else
        if(mapCoordinatorToCount.get(coordinatorId)<=i){
          i = mapCoordinatorToCount.get(coordinatorId);
          CareCoordinatorId = coordinatorId;
      }
    }
    if(mapCoordinatorToCount.get(CareCoordinatorId) == null){
      mapCoordinatorToCount.put(CareCoordinatorId,1);
    }
    else{
      mapCoordinatorToCount.put(CareCoordinatorId,mapCoordinatorToCount.get(CareCoordinatorId)+1);
    }
    return CareCoordinatorId;
  }
    
  public void bulkBefore(){}
  public void beforeInsert(SObject so){}
  public void beforeUpdate(SObject oldSo, SObject so){}
  public void beforeDelete(SObject so){}
  public void afterInsert(SObject so){}
  public void afterUpdate(SObject oldSo, SObject so){}
  public void afterDelete(SObject so){}
  public void afterUndelete(SObject so){} 
  public void andFinally(){
    if(lstCandidatePaitentsToUpdate.size()>0){
      update lstCandidatePaitentsToUpdate;
    }  
  }

}
I am not able to cover the below lines in test class. please help.
Contact con = new contact();
          con.id= rel.From_Individual__c;
          con.firstname= rel.From_Individual__r.firstname;
          con.lastname= rel.From_Individual__r.lastname;
          con.email= rel.From_Individual__r.email;
          conListForAdvisor.add(con);
        }
        if(conListForAdvisor.size()>0){
          update relationListForAdvisor;
          update conListForAdvisor;
        }
        for(Event ev : newEvents){
            System.debug(ev);
          if(ev.eventName != null && ev.eventName != ''){
            cEvent = new Event__c();

            String parishRegion = getCRSRegion(University);
            cEvent.Name = ev.eventName;
            cEvent.Status__c = 'Completed';
            cEvent.Description__c = ev.eventDescription;
            if(ev.eventCheckAllThatApply != null) {
              cEvent.Check_all_that_apply_to_your_campus__c = 
              String.valueOf(ev.eventCheckAllThatApply).remove('(').remove(')').replace(',',';');
            }
            if(ev.eventNuberAttended != null && ev.eventNuberAttended != ''){
              cEvent.Number_Attended__c = Decimal.ValueOf(ev.eventNuberAttended);
            }
            if(ev.eventLetters != null && ev.eventLetters != ''){
              cEvent.If_you_hand_wrote_letters_please_list__c = Decimal.ValueOf(ev.eventLetters);
              /*if(Decimal.ValueOf(ev.eventLetters) > 0 ){
                cEvent.Action__c = 'EN - Directing a LETTER WRITING campaign';
              }*/
            }
            
            String evSelectedOptions = '';
            for(String s: ev.eventCheckAllThatApply) {
              evSelectedOptions += s + ' ';
            }
            //evSelectedOptions.addAll(ev.eventCheckAllThatApply);
            System.debug('>>>evSelectedOptions: ' + evSelectedOptions);

            if(evSelectedOptions.contains('Chapter meetings')) {
              cEvent.Action__c = 'ED - Coordinating a MEETING';
            }
            else if(evSelectedOptions.contains('Legislative Visit')) {
              cEvent.Action__c = 'EN - Facilitating a CONGRESSIONAL VISIT';
            }
            else {
              cEvent.Action__c = 'ED - Providing general OUTREACH';
            } 
            
            cEvent.Category__c = catagory;
            String campaignName = ''; // hold the program initiative to attach the event to
            cEvent.Parish_or_School__c = University;
            cEvent.Primary_Institution__c = University;
            

            cEvent.CRS_Region__c = 'Replicator; ' + parishRegion;
            if(ev.eventDate != null && ev.eventDate !=''){
              cEvent.Start_Date__c = date.ValueOf(ev.eventDate);
              cEvent.End_Date__c = date.ValueOf(ev.eventDate);
              cEvent.Event_Date_Time__c = cEvent.End_Date__c;
            }
            cEvent.Association_if_other__c = ''; // reset after the field has been used.            
            lstEvents.add(cEvent);
          }

        }
        if(lstEvents.size() > 0){

          insert lstEvents;
          for(Event__c events : lstEvents){
            eventIds.add(events.Id);
          }
          eventId = lstEvents[0].Id;
        }
I created a validation rule for the standard probability stage in opportunities. What I need the rule to do is limit the users to entering percentages only divisible by 10 with three exceptions. 1) They can never use 50% for any stage. 2) The minimum is 10% unless the stage is 'closed lost' which has a probability of 0%. 3) The maximum is 90% unless the stage is 'closed won' which has a probability of 100%. I can get the error message to come up only when 100% is entered on a stage other then closed won. The system still allows 0% and 50%. Here is my rule:

OR(
AND(
!ISPICKVAL(StageName,"Closed Won"),
Probability<>0.50,
MOD(Probability*100,10)<>0)
,
AND(
!ISPICKVAL(StageName,"Closed Won"),
Probability=1)
)

Can someone help me and show me what I'm doing wrong?
Thanks