public async Task <Result <string> > Handle(AfyaMobileFamilyScreeningEncounterCommand request, CancellationToken cancellationToken)
        {
            string afyaMobileId            = string.Empty;
            string indexClientAfyaMobileId = string.Empty;

            using (var trans = _htsUnitOfWork.Context.Database.BeginTransaction())
            {
                try
                {
                    RegisterPersonService   registerPersonService   = new RegisterPersonService(_unitOfWork);
                    EncounterTestingService encounterTestingService = new EncounterTestingService(_unitOfWork, _htsUnitOfWork);

                    for (int j = 0; j < request.INTERNAL_PATIENT_ID.Count; j++)
                    {
                        if (request.INTERNAL_PATIENT_ID[j].IDENTIFIER_TYPE == "AFYA_MOBILE_ID")
                        {
                            afyaMobileId = request.INTERNAL_PATIENT_ID[j].ID;
                        }

                        if (request.INTERNAL_PATIENT_ID[j].IDENTIFIER_TYPE == "INDEX_CLIENT_AFYAMOBILE_ID")
                        {
                            indexClientAfyaMobileId = request.INTERNAL_PATIENT_ID[j].ID;
                        }
                    }

                    var afyaMobileMessage = await registerPersonService.AddAfyaMobileInbox(DateTime.Now, request.MESSAGE_HEADER.MESSAGE_TYPE, afyaMobileId, JsonConvert.SerializeObject(request), false);

                    var indexClientIdentifiers = await registerPersonService.getPersonIdentifiers(indexClientAfyaMobileId, 10);

                    if (indexClientIdentifiers.Count > 0)
                    {
                        //Get Index client
                        var indexClient = await registerPersonService.GetPatientByPersonId(indexClientIdentifiers[0].PersonId);

                        var partnetPersonIdentifiers = await registerPersonService.getPersonIdentifiers(afyaMobileId, 10);

                        if (partnetPersonIdentifiers.Count > 0)
                        {
                            DateTime screeningDate = DateTime.Now;
                            try
                            {
                                screeningDate = DateTime.ParseExact(request.SCREENING_ENCOUNTER.FAMILY_SCREENING.SCREENING_DATE, "yyyyMMdd", null);
                            }
                            catch (Exception e)
                            {
                                Log.Error($"Could not parse family screening SCREENING_DATE: {request.SCREENING_ENCOUNTER.FAMILY_SCREENING.SCREENING_DATE} as a valid date: Incorrect format, date should be in the following format yyyyMMdd");
                                throw new Exception($"Could not parse family screening SCREENING_DATE: {request.SCREENING_ENCOUNTER.FAMILY_SCREENING.SCREENING_DATE} as a valid date: Incorrect format, date should be in the following format yyyyMMdd");
                            }
                            int      hivStatus   = request.SCREENING_ENCOUNTER.FAMILY_SCREENING.HIV_STATUS;
                            int      eligible    = request.SCREENING_ENCOUNTER.FAMILY_SCREENING.ELIGIBLE_FOR_HTS;
                            DateTime bookingDate = DateTime.Now;
                            try
                            {
                                bookingDate = DateTime.ParseExact(request.SCREENING_ENCOUNTER.FAMILY_SCREENING.BOOKING_DATE, "yyyyMMdd", null);
                            }
                            catch (Exception e)
                            {
                                Log.Error($"Could not parse family screening BOOKING_DATE: {request.SCREENING_ENCOUNTER.FAMILY_SCREENING.BOOKING_DATE} as a valid date: Incorrect format, date should be in the following format yyyyMMdd");
                                throw new Exception($"Could not parse family screening BOOKING_DATE: {request.SCREENING_ENCOUNTER.FAMILY_SCREENING.BOOKING_DATE} as a valid date: Incorrect format, date should be in the following format yyyyMMdd. Exception: {e.Message}");
                            }
                            string remarks = request.SCREENING_ENCOUNTER.FAMILY_SCREENING.REMARKS;

                            var familyScreenings = await _unitOfWork.Repository <LookupItemView>().Get(x => x.MasterName == "FamilyScreening")
                                                   .ToListAsync();

                            List <Screening> familyScreeningList = new List <Screening>();
                            for (int j = 0; j < familyScreenings.Count; j++)
                            {
                                if (familyScreenings[j].ItemName == "EligibleTesting")
                                {
                                    Screening screening = new Screening()
                                    {
                                        ScreeningCategoryId = familyScreenings[j].ItemId,
                                        ScreeningTypeId     = familyScreenings[j].MasterId,
                                        ScreeningValueId    = eligible
                                    };
                                    familyScreeningList.Add(screening);
                                }
                                else if (familyScreenings[j].ItemName == "ScreeningHivStatus")
                                {
                                    Screening screening = new Screening()
                                    {
                                        ScreeningCategoryId = familyScreenings[j].ItemId,
                                        ScreeningTypeId     = familyScreenings[j].MasterId,
                                        ScreeningValueId    = hivStatus
                                    };
                                    familyScreeningList.Add(screening);
                                }
                            }

                            var patientMasterVisitEntity = await _unitOfWork.Repository <PatientMasterVisit>()
                                                           .Get(x => x.PatientId == indexClient.Id && x.ServiceId == 2).ToListAsync();

                            int patientMasterVisitId = patientMasterVisitEntity.OrderBy(x => x.Id).FirstOrDefault().Id;

                            var familyScreeningReturnValue = await encounterTestingService.AddPartnerScreening(partnetPersonIdentifiers[0].PersonId, indexClient.Id, patientMasterVisitId, null,
                                                                                                               screeningDate, bookingDate, familyScreeningList, 1);

                            var stringParnerObject = Newtonsoft.Json.JsonConvert.SerializeObject(new
                            {
                                familyId     = partnetPersonIdentifiers[0].PersonId,
                                familyTraced = true
                            });

                            var partnerScreeningDone =
                                await registerPersonService.AddAppStateStore(indexClient.PersonId, indexClient.Id, 10,
                                                                             null, null, stringParnerObject);

                            var familyHivStatus = await _unitOfWork.Repository <LookupItemView>()
                                                  .Get(x => x.MasterName == "ScreeningHivStatus" && x.ItemId == hivStatus).ToListAsync();

                            if (familyHivStatus.Count > 0 && familyHivStatus[0].ItemName == "Positive")
                            {
                                var stringFamilyScreenedPositiveObject = Newtonsoft.Json.JsonConvert.SerializeObject(new
                                {
                                    familyId     = partnetPersonIdentifiers[0].PersonId,
                                    familyTraced = true
                                });

                                var hasFamiyBeenScreenedPositive = await registerPersonService.AddAppStateStore(indexClient.PersonId, indexClient.Id, 14,
                                                                                                                null, null, stringFamilyScreenedPositiveObject);
                            }
                        }
                        else
                        {
                            //update message has been processed
                            await registerPersonService.UpdateAfyaMobileInbox(afyaMobileMessage.Id, afyaMobileId, true, DateTime.Now, $"Family member with afyamobileid: {afyaMobileId} could not be found", false);

                            return(Result <string> .Invalid($"Family member with afyamobileid: {afyaMobileId} could not be found"));
                        }
                    }
                    else
                    {
                        //update message has been processed
                        await registerPersonService.UpdateAfyaMobileInbox(afyaMobileMessage.Id, afyaMobileId, true, DateTime.Now, $"Index client with afyamobileid: {indexClientAfyaMobileId} could not be found for family member: {afyaMobileId}", false);

                        return(Result <string> .Invalid($"Index client with afyamobileid: {indexClientAfyaMobileId} could not be found for family member: {afyaMobileId}"));
                    }

                    //update message has been processed
                    await registerPersonService.UpdateAfyaMobileInbox(afyaMobileMessage.Id, afyaMobileId, true, DateTime.Now, $"Successfully synchronized family screening for clientid: {indexClientAfyaMobileId} and  partnerid: {afyaMobileId}", true);

                    trans.Commit();
                    return(Result <string> .Valid($"Successfully synchronized family screening for afyamobileId: {afyaMobileId}"));
                }
                catch (Exception ex)
                {
                    trans.Rollback();
                    Log.Error($"Failed to synchronize family screening for clientId: {afyaMobileId} " + ex.Message + " " + ex.InnerException);
                    return(Result <string> .Invalid($"Failed to synchronize family screening for clientId: {afyaMobileId} " + ex.Message + " " + ex.InnerException));
                }
            }
        }
示例#2
0
        public async Task <Result <string> > Handle(AfyaMobileSynchronizeHtsTestsCommand request, CancellationToken cancellationToken)
        {
            string afyaMobileId = String.Empty;

            using (var trans = _htsUnitOfWork.Context.Database.BeginTransaction())
            {
                RegisterPersonService   registerPersonService   = new RegisterPersonService(_unitOfWork);
                EncounterTestingService encounterTestingService = new EncounterTestingService(_unitOfWork, _htsUnitOfWork);

                try
                {
                    //Person Identifier
                    for (int j = 0; j < request.INTERNAL_PATIENT_ID.Count; j++)
                    {
                        if (request.INTERNAL_PATIENT_ID[j].IDENTIFIER_TYPE == "AFYA_MOBILE_ID" && request.INTERNAL_PATIENT_ID[j].ASSIGNING_AUTHORITY == "AFYAMOBILE")
                        {
                            afyaMobileId = request.INTERNAL_PATIENT_ID[j].ID;
                        }
                    }
                    var afyaMobileMessage = await registerPersonService.AddAfyaMobileInbox(DateTime.Now, request.MESSAGE_HEADER.MESSAGE_TYPE, afyaMobileId, JsonConvert.SerializeObject(request), false);

                    //check if person already exists
                    var identifiers = await registerPersonService.getPersonIdentifiers(afyaMobileId, 10);

                    if (identifiers.Count > 0)
                    {
                        var person = await registerPersonService.GetPerson(identifiers[0].PersonId);

                        var patient = await registerPersonService.GetPatientByPersonId(identifiers[0].PersonId);

                        int             pnsAccepted        = request.HIV_TESTS.SUMMARY.PNS_ACCEPTED;
                        int             pnsDeclineReason   = request.HIV_TESTS.SUMMARY.PNS_DECLINE_REASON;
                        List <NewTests> screeningTests     = request.HIV_TESTS.SCREENING;
                        List <NewTests> confirmatoryTests  = request.HIV_TESTS.CONFIRMATORY;
                        int             coupleDiscordant   = request.HIV_TESTS.SUMMARY.COUPLE_DISCORDANT;
                        int             finalResultGiven   = request.HIV_TESTS.SUMMARY.FINAL_RESULT_GIVEN;
                        int             roundOneTestResult = request.HIV_TESTS.SUMMARY.SCREENING_RESULT;
                        int?            roundTwoTestResult = request.HIV_TESTS.SUMMARY.CONFIRMATORY_RESULT;
                        int?            finalResult        = request.HIV_TESTS.SUMMARY.FINAL_RESULT;
                        var             encounterNumber    = request.PLACER_DETAIL.ENCOUNTER_NUMBER;
                        int             providerId         = request.PLACER_DETAIL.PROVIDER_ID;

                        //Get Consent to screen partners itemId
                        var consentPartnerType = await _unitOfWork.Repository <LookupItemView>()
                                                 .Get(x => x.MasterName == "ConsentType" && x.ItemName == "ConsentToListPartners")
                                                 .FirstOrDefaultAsync();

                        int consentListPartnersTypeId = consentPartnerType != null ? consentPartnerType.ItemId : 0;

                        var resultPlacerGet = await registerPersonService.GetInteropPlacerValue(7, 4, encounterNumber);

                        if (resultPlacerGet.Count > 0)
                        {
                            var getHtsEncounter = await encounterTestingService.GetHtsEncounter(resultPlacerGet[0].EntityId);

                            var getPatientEncounter = await encounterTestingService.GetPatientEncounterById(getHtsEncounter.PatientEncounterID);

                            var getPatientConsents = await encounterTestingService.GetPatientConsent(patient.Id, getPatientEncounter.PatientMasterVisitId, 2, consentListPartnersTypeId);

                            if (getPatientConsents.Count > 0)
                            {
                                getPatientConsents[0].ConsentValue  = pnsAccepted;
                                getPatientConsents[0].ConsentDate   = getPatientEncounter.EncounterStartTime;
                                getPatientConsents[0].DeclineReason = pnsDeclineReason;

                                await encounterTestingService.UpdatePatientConsent(getPatientConsents[0]);


                                var hasConsentedToListPartners = await _unitOfWork.Repository <LookupItemView>()
                                                                 .Get(x => x.ItemId == pnsAccepted && x.MasterName == "YesNoNA").ToListAsync();

                                if (hasConsentedToListPartners.Count > 0)
                                {
                                    if (hasConsentedToListPartners[0].ItemName == "Yes")
                                    {
                                        var listPartners = await registerPersonService.AddAppStateStore(person.Id, patient.Id, 3,
                                                                                                        getPatientEncounter.PatientMasterVisitId, getPatientEncounter.Id, null);
                                    }
                                }
                            }
                            else
                            {
                                //add consent to list partners
                                var partnersConsent = await encounterTestingService.addPatientConsent(patient.Id,
                                                                                                      getPatientEncounter.PatientMasterVisitId, 2, pnsAccepted, consentListPartnersTypeId, getPatientEncounter.EncounterStartTime, providerId,
                                                                                                      pnsDeclineReason);

                                var hasConsentedToListPartners = await _unitOfWork.Repository <LookupItemView>()
                                                                 .Get(x => x.ItemId == pnsAccepted && x.MasterName == "YesNoNA").ToListAsync();

                                if (hasConsentedToListPartners.Count > 0)
                                {
                                    if (hasConsentedToListPartners[0].ItemName == "Yes")
                                    {
                                        var listPartners = await registerPersonService.AddAppStateStore(person.Id, patient.Id, 3,
                                                                                                        getPatientEncounter.PatientMasterVisitId, getPatientEncounter.Id, null);
                                    }
                                }
                            }

                            //Screening Tests
                            var updatedScreeningTests = await encounterTestingService.UpdateTesting(getHtsEncounter.Id, screeningTests, providerId, 1);

                            //Confirmatory Tests
                            var updatedConfirmatoryTests = await encounterTestingService.UpdateTesting(getHtsEncounter.Id, confirmatoryTests, providerId, 2);

                            getHtsEncounter.CoupleDiscordant = coupleDiscordant;
                            getHtsEncounter.FinalResultGiven = finalResultGiven;

                            await encounterTestingService.updateHtsEncounter(getHtsEncounter.Id, getHtsEncounter);

                            var getHtsEncounterResults = await encounterTestingService.GetHtsEncounterResultByEncounterId(getHtsEncounter.Id);

                            if (getHtsEncounterResults.Count > 0)
                            {
                                getHtsEncounterResults[0].RoundOneTestResult = roundOneTestResult;
                                getHtsEncounterResults[0].RoundTwoTestResult = roundTwoTestResult;
                                getHtsEncounterResults[0].FinalResult        = finalResult;

                                var updatedHtsEncounterResult = await encounterTestingService.UpdateHtsEncounterResult(getHtsEncounterResults[0]);

                                // add state for positive person
                                var clientFinalResultsList = await _unitOfWork.Repository <LookupItemView>()
                                                             .Get(x => x.ItemId == finalResult && x.MasterName == "HIVFinalResults").ToListAsync();

                                if (clientFinalResultsList.Count > 0 &&
                                    clientFinalResultsList[0].ItemName == "Positive")
                                {
                                    var isClientPositiveState = await registerPersonService.AddAppStateStore(person.Id, patient.Id, 4,
                                                                                                             getPatientEncounter.PatientMasterVisitId, getPatientEncounter.Id, null);
                                }
                            }
                            else
                            {
                                var htsEncounterResult = await encounterTestingService.addHtsEncounterResult(getHtsEncounter.Id, roundOneTestResult, roundTwoTestResult, finalResult);


                                // add state for positive person
                                var clientFinalResultsList = await _unitOfWork.Repository <LookupItemView>()
                                                             .Get(x => x.ItemId == finalResult && x.MasterName == "HIVFinalResults").ToListAsync();

                                if (clientFinalResultsList.Count > 0 &&
                                    clientFinalResultsList[0].ItemName == "Positive")
                                {
                                    var isClientPositiveState = await registerPersonService.AddAppStateStore(person.Id, patient.Id, 4,
                                                                                                             getPatientEncounter.PatientMasterVisitId, getPatientEncounter.Id, null);
                                }
                            }
                        }
                        else
                        {
                            //update message has been processed
                            await registerPersonService.UpdateAfyaMobileInbox(afyaMobileMessage.Id, afyaMobileId, true, DateTime.Now, $"HTS PRE-TEST with encounter number: {encounterNumber} could not be found", false);

                            Result <string> .Invalid($"HTS PRE-TEST with encounter number: {encounterNumber} could not be found");
                        }
                    }
                    else
                    {
                        //update message has been processed
                        await registerPersonService.UpdateAfyaMobileInbox(afyaMobileMessage.Id, afyaMobileId, true, DateTime.Now, $"Person with afyaMobileId: {afyaMobileId} could not be found", false);

                        return(Result <string> .Invalid($"Person with afyaMobileId: {afyaMobileId} could not be found"));
                    }

                    //update message has been processed
                    await registerPersonService.UpdateAfyaMobileInbox(afyaMobileMessage.Id, afyaMobileId, true, DateTime.Now, $"Successfully synchronized HTS tests for afyamobileid: {afyaMobileId}", true);

                    trans.Commit();
                    return(Result <string> .Valid($"Successfully synchronized HTS tests for afyamobileid: {afyaMobileId}"));
                }
                catch (Exception ex)
                {
                    trans.Rollback();
                    Log.Error($"Failed to synchronize Hts tests for clientid: {afyaMobileId} " + ex.Message + " " + ex.InnerException);
                    return(Result <string> .Invalid($"Failed to synchronize Hts tests for clientid: {afyaMobileId} " + ex.Message + " " + ex.InnerException));
                }
            }
        }
示例#3
0
        public async Task <Result <string> > Handle(AfyaMobileSynchronizeClientsCommand request, CancellationToken cancellationToken)
        {
            string afyaMobileId = String.Empty;

            using (var trans = _unitOfWork.Context.Database.BeginTransaction())
            {
                RegisterPersonService   registerPersonService = new RegisterPersonService(_unitOfWork);
                LookupLogic             lookupLogic           = new LookupLogic(_unitOfWork);
                PersonOccupationService pocc = new PersonOccupationService(_unitOfWork);
                EducationLevelService   educationLevelService = new EducationLevelService(_unitOfWork);

                for (int i = 0; i < request.CLIENTS.Count; i++)
                {
                    for (int j = 0; j < request.CLIENTS[i].PATIENT_IDENTIFICATION.INTERNAL_PATIENT_ID.Count; j++)
                    {
                        if (request.CLIENTS[i].PATIENT_IDENTIFICATION.INTERNAL_PATIENT_ID[j].IDENTIFIER_TYPE == "AFYA_MOBILE_ID" &&
                            request.CLIENTS[i].PATIENT_IDENTIFICATION.INTERNAL_PATIENT_ID[j].ASSIGNING_AUTHORITY == "AFYAMOBILE")
                        {
                            afyaMobileId = request.CLIENTS[i].PATIENT_IDENTIFICATION.INTERNAL_PATIENT_ID[j].ID;
                        }
                    }
                }
                var afyaMobileMessage = await registerPersonService.AddAfyaMobileInbox(DateTime.Now, request.MESSAGE_HEADER.MESSAGE_TYPE, afyaMobileId, JsonConvert.SerializeObject(request), false);

                try
                {
                    var facilityId = request.MESSAGE_HEADER.SENDING_FACILITY;

                    for (int i = 0; i < request.CLIENTS.Count; i++)
                    {
                        string firstName  = request.CLIENTS[i].PATIENT_IDENTIFICATION.PATIENT_NAME.FIRST_NAME;
                        string middleName = string.IsNullOrWhiteSpace(request.CLIENTS[i].PATIENT_IDENTIFICATION.PATIENT_NAME.MIDDLE_NAME) ? "" : request.CLIENTS[i].PATIENT_IDENTIFICATION.PATIENT_NAME.MIDDLE_NAME;
                        string lastName   = request.CLIENTS[i].PATIENT_IDENTIFICATION.PATIENT_NAME.LAST_NAME;
                        string nickName   = (request.CLIENTS[i].PATIENT_IDENTIFICATION.PATIENT_NAME.NICK_NAME == null) ? "" : request.CLIENTS[i].PATIENT_IDENTIFICATION.PATIENT_NAME.NICK_NAME.ToString();
                        int    sex        = request.CLIENTS[i].PATIENT_IDENTIFICATION.SEX;

                        //Try to parse dateOfBirth
                        DateTime dateOfBirth = DateTime.Now;
                        try
                        {
                            dateOfBirth = DateTime.ParseExact(request.CLIENTS[i].PATIENT_IDENTIFICATION.DATE_OF_BIRTH, "yyyyMMdd", null);
                        }
                        catch (Exception e)
                        {
                            Log.Error($"Could not parse DateOfBirth: {request.CLIENTS[i].PATIENT_IDENTIFICATION.DATE_OF_BIRTH} as a valid date. Incorrect format, date should be in the following format yyyyMMdd");
                            throw new Exception($"Could not parse DateOfBirth: {request.CLIENTS[i].PATIENT_IDENTIFICATION.DATE_OF_BIRTH} as a valid date. Incorrect format, date should be in the following format yyyyMMdd");
                        }
                        string dobPrecision = request.CLIENTS[i].PATIENT_IDENTIFICATION.DATE_OF_BIRTH_PRECISION;

                        //Try to parse DateOfEnrollment
                        DateTime dateEnrollment = DateTime.Now;
                        try
                        {
                            dateEnrollment = DateTime.ParseExact(request.CLIENTS[i].PATIENT_IDENTIFICATION.REGISTRATION_DATE, "yyyyMMdd", null);
                        }
                        catch (Exception e)
                        {
                            Log.Error($"Could not parse DateOfEnrollment: {request.CLIENTS[i].PATIENT_IDENTIFICATION.REGISTRATION_DATE} as a valid date: Incorrect format, date should be in the following format yyyyMMdd");
                            throw new Exception($"Could not parse DateOfEnrollment: {request.CLIENTS[i].PATIENT_IDENTIFICATION.REGISTRATION_DATE} as a valid date: Incorrect format, date should be in the following format yyyyMMdd");
                        }

                        int    maritalStatusId = request.CLIENTS[i].PATIENT_IDENTIFICATION.MARITAL_STATUS;
                        string landmark        = request.CLIENTS[i].PATIENT_IDENTIFICATION.PATIENT_ADDRESS.PHYSICAL_ADDRESS
                                                 .LANDMARK;

                        int ward      = request.CLIENTS[i].PATIENT_IDENTIFICATION.PATIENT_ADDRESS.PHYSICAL_ADDRESS.WARD;
                        int county    = request.CLIENTS[i].PATIENT_IDENTIFICATION.PATIENT_ADDRESS.PHYSICAL_ADDRESS.COUNTY;
                        int subcounty = request.CLIENTS[i].PATIENT_IDENTIFICATION.PATIENT_ADDRESS.PHYSICAL_ADDRESS.SUB_COUNTY;

                        string educationlevel   = (request.CLIENTS[i].PATIENT_IDENTIFICATION.EDUCATIONLEVEL == null) ? "" : request.CLIENTS[i].PATIENT_IDENTIFICATION.EDUCATIONLEVEL.ToString();
                        string educationoutcome = (request.CLIENTS[i].PATIENT_IDENTIFICATION.EDUCATIONOUTCOME == null) ? "" : request.CLIENTS[i].PATIENT_IDENTIFICATION.EDUCATIONOUTCOME.ToString();
                        string occupation       = (request.CLIENTS[i].PATIENT_IDENTIFICATION.OCCUPATION == null) ? "" : request.CLIENTS[i].PATIENT_IDENTIFICATION.OCCUPATION.ToString();
                        string physicalAddress  = request.CLIENTS[i].PATIENT_IDENTIFICATION.PATIENT_ADDRESS.POSTAL_ADDRESS;
                        string mobileNumber     = request.CLIENTS[i].PATIENT_IDENTIFICATION.PHONE_NUMBER;
                        string enrollmentNo     = string.Empty;
                        int    userId           = request.CLIENTS[i].PATIENT_IDENTIFICATION.USER_ID;

                        string maritalStatusName = String.Empty;
                        string gender            = String.Empty;

                        var maritalStatusList = await lookupLogic.GetLookupNameByGroupNameItemId(maritalStatusId, "HTSMaritalStatus");

                        var genderList = await lookupLogic.GetLookupNameByGroupNameItemId(sex, "Gender");

                        if (maritalStatusList.Count > 0)
                        {
                            maritalStatusName = maritalStatusList[0].ItemName;
                        }
                        if (genderList.Count > 0)
                        {
                            gender = genderList[0].ItemName;
                        }

                        for (int j = 0; j < request.CLIENTS[i].PATIENT_IDENTIFICATION.INTERNAL_PATIENT_ID.Count; j++)
                        {
                            if (request.CLIENTS[i].PATIENT_IDENTIFICATION.INTERNAL_PATIENT_ID[j].ASSIGNING_AUTHORITY ==
                                "HTS" && request.CLIENTS[i].PATIENT_IDENTIFICATION.INTERNAL_PATIENT_ID[j].IDENTIFIER_TYPE == "HTS_SERIAL")
                            {
                                enrollmentNo = request.CLIENTS[i].PATIENT_IDENTIFICATION.INTERNAL_PATIENT_ID[j].ID;
                            }

                            if (request.CLIENTS[i].PATIENT_IDENTIFICATION.INTERNAL_PATIENT_ID[j].IDENTIFIER_TYPE == "AFYA_MOBILE_ID" &&
                                request.CLIENTS[i].PATIENT_IDENTIFICATION.INTERNAL_PATIENT_ID[j].ASSIGNING_AUTHORITY == "AFYAMOBILE")
                            {
                                afyaMobileId = request.CLIENTS[i].PATIENT_IDENTIFICATION.INTERNAL_PATIENT_ID[j].ID;
                            }
                        }

                        Facility clientFacility = await _unitOfWork.Repository <Facility>().Get(x => x.PosID == facilityId).FirstOrDefaultAsync();

                        if (clientFacility == null)
                        {
                            clientFacility = await _unitOfWork.Repository <Facility>().Get(x => x.DeleteFlag == 0).FirstOrDefaultAsync();
                        }

                        //check if person already exists
                        var identifiers = await registerPersonService.getPersonIdentifiers(afyaMobileId, 10);

                        if (identifiers.Count > 0)
                        {
                            var registeredPerson = await registerPersonService.GetPerson(identifiers[0].PersonId);

                            if (registeredPerson != null)
                            {
                                var updatedPerson = await registerPersonService.UpdatePerson(identifiers[0].PersonId,
                                                                                             firstName, middleName, lastName, sex, dateOfBirth, clientFacility.FacilityID, registrationDate : dateEnrollment, NickName : nickName);
                            }
                            else
                            {
                                var person = await registerPersonService.RegisterPerson(firstName, middleName, lastName,
                                                                                        sex, userId, clientFacility.FacilityID, dateOfBirth, nickName : nickName);
                            }

                            var patient = await registerPersonService.GetPatientByPersonId(identifiers[0].PersonId);

                            if (patient != null)
                            {
                                var updatedPatient = await registerPersonService.UpdatePatient(patient.Id, dateOfBirth, facilityId);
                            }
                            else
                            {
                                //Add Person to mst_patient
                                var mstResult = await registerPersonService.InsertIntoBlueCard(firstName, lastName,
                                                                                               middleName, dateEnrollment, " ", 283, maritalStatusName, physicalAddress, mobileNumber, gender, dobPrecision, dateOfBirth, userId, facilityId);

                                if (mstResult.Count > 0)
                                {
                                    patient = await registerPersonService.AddPatient(identifiers[0].PersonId, userId, facilityId);

                                    // Person is enrolled state
                                    var enrollmentAppState = await registerPersonService.AddAppStateStore(identifiers[0].PersonId, patient.Id, 7, null, null);

                                    // Enroll patient
                                    var patientIdentifier = await registerPersonService.EnrollPatient(enrollmentNo, patient.Id, 2, userId, dateEnrollment);

                                    //Add PersonIdentifiers
                                    var personIdentifier = await registerPersonService.addPersonIdentifiers(identifiers[0].PersonId, 10, afyaMobileId, userId);
                                }
                            }

                            var updatedPersonPopulations = await registerPersonService.UpdatePersonPopulation(identifiers[0].PersonId,
                                                                                                              request.CLIENTS[i].PATIENT_IDENTIFICATION.KEY_POP, userId);

                            //Location
                            if (!string.IsNullOrWhiteSpace(landmark) || (county > 0) || (subcounty > 0) || (ward > 0))
                            {
                                var updatedLocation = await registerPersonService.UpdatePersonLocation(identifiers[0].PersonId, landmark, ward, county, subcounty, userId);
                            }

                            if (!string.IsNullOrWhiteSpace(educationlevel))
                            {
                                var personeducation = await educationLevelService.UpdatePersonEducation(identifiers[0].PersonId, educationlevel, educationoutcome, userId);
                            }
                            if (!string.IsNullOrWhiteSpace(occupation))
                            {
                                var personoccupation = await pocc.Update(identifiers[0].PersonId, occupation, userId);
                            }

                            if (!string.IsNullOrWhiteSpace(mobileNumber) || !string.IsNullOrWhiteSpace(physicalAddress))
                            {
                                //add Person Contact
                                var personContact =
                                    await registerPersonService.UpdatePersonContact(identifiers[0].PersonId,
                                                                                    physicalAddress, mobileNumber);
                            }

                            // update message as processed
                            await registerPersonService.UpdateAfyaMobileInbox(afyaMobileMessage.Id, afyaMobileId, true, DateTime.Now, "success", true);
                        }
                        else
                        {
                            // Add Person
                            var person = await registerPersonService.RegisterPerson(firstName, middleName, lastName, sex,
                                                                                    userId, clientFacility.FacilityID, dateOfBirth, nickName : nickName);

                            //Add Person to mst_patient
                            var mstResult = await registerPersonService.InsertIntoBlueCard(firstName, lastName, middleName, dateEnrollment, " ", 283, maritalStatusName, physicalAddress, mobileNumber, gender, dobPrecision, dateOfBirth, userId, facilityId);

                            if (mstResult.Count > 0)
                            {
                                //Add PersonIdentifiers
                                var personIdentifier = await registerPersonService.addPersonIdentifiers(person.Id, 10, afyaMobileId, userId);

                                // Add Patient
                                var patient = await registerPersonService.AddPatient(person.Id, userId, mstResult[0].Ptn_Pk, facilityId);

                                // Person is enrolled state
                                var enrollmentAppState = await registerPersonService.AddAppStateStore(person.Id, patient.Id, 7, null, null);

                                // Enroll patient
                                var patientIdentifier = await registerPersonService.EnrollPatient(enrollmentNo, patient.Id, 2, userId, dateEnrollment);

                                // Add Marital Status
                                var maritalStatus = await registerPersonService.AddMaritalStatus(person.Id, maritalStatusId, userId);

                                // Add Person Key pop
                                var population = await registerPersonService.addPersonPopulation(person.Id, request.CLIENTS[i].PATIENT_IDENTIFICATION.KEY_POP, userId);

                                // Add Person Location
                                if (!string.IsNullOrWhiteSpace(landmark) || (county > 0) || (subcounty > 0) || (ward > 0))
                                {
                                    var personLocation = await registerPersonService.UpdatePersonLocation(person.Id, landmark, ward, county, subcounty, userId);
                                }

                                if (!string.IsNullOrWhiteSpace(educationlevel))
                                {
                                    var personeducation = await educationLevelService.UpdatePersonEducation(person.Id, educationlevel, educationoutcome, userId);
                                }
                                if (!string.IsNullOrWhiteSpace(occupation))
                                {
                                    var personoccupation = await pocc.Update(person.Id, occupation, userId);
                                }


                                if (!string.IsNullOrWhiteSpace(mobileNumber) || !string.IsNullOrWhiteSpace(physicalAddress))
                                {
                                    //add Person Contact
                                    var personContact = await registerPersonService.addPersonContact(person.Id, physicalAddress,
                                                                                                     mobileNumber, string.Empty, string.Empty, userId);
                                }

                                //update message has been processed
                                await registerPersonService.UpdateAfyaMobileInbox(afyaMobileMessage.Id, afyaMobileId, true, DateTime.Now, $"Successfully synchronized demographics for afyamobileid: {afyaMobileId}", true);
                            }
                        }
                    }

                    //update message has been processed
                    await registerPersonService.UpdateAfyaMobileInbox(afyaMobileMessage.Id, afyaMobileId, true, DateTime.Now, $"Successfully synchronized demographics for afyamobileid: {afyaMobileId}", true);

                    trans.Commit();
                    return(Result <string> .Valid($"Successfully synchronized demographics for afyamobileid: {afyaMobileId}"));
                }
                catch (Exception ex)
                {
                    trans.Rollback();
                    Log.Error($"Error syncronizing afyamobileid: {afyaMobileId}. Exception Message: {ex.Message},  Inner Exception {ex.InnerException}");
                    return(Result <string> .Invalid($"Failed to synchronize clientId: {afyaMobileId} " + ex.Message + " " + ex.InnerException));
                }
            }
        }
        public async Task <Result <string> > Handle(AfyaMobileSynchronizeReferralCommand request, CancellationToken cancellationToken)
        {
            string afyaMobileId = String.Empty;

            using (var trans = _htsUnitOfWork.Context.Database.BeginTransaction())
            {
                RegisterPersonService   registerPersonService   = new RegisterPersonService(_unitOfWork);
                EncounterTestingService encounterTestingService = new EncounterTestingService(_unitOfWork, _htsUnitOfWork);

                try
                {
                    //Person Identifier
                    for (int j = 0; j < request.INTERNAL_PATIENT_ID.Count; j++)
                    {
                        if (request.INTERNAL_PATIENT_ID[j].IDENTIFIER_TYPE == "AFYA_MOBILE_ID" && request.INTERNAL_PATIENT_ID[j].ASSIGNING_AUTHORITY == "AFYAMOBILE")
                        {
                            afyaMobileId = request.INTERNAL_PATIENT_ID[j].ID;
                        }
                    }
                    var afyaMobileMessage = await registerPersonService.AddAfyaMobileInbox(DateTime.Now, request.MESSAGE_HEADER.MESSAGE_TYPE, afyaMobileId, JsonConvert.SerializeObject(request), false);

                    //check if person already exists
                    var identifiers = await registerPersonService.getPersonIdentifiers(afyaMobileId, 10);

                    if (identifiers.Count > 0)
                    {
                        // var person = await registerPersonService.GetPerson(identifiers[0].PersonId);
                        var patient = await registerPersonService.GetPatientByPersonId(identifiers[0].PersonId);

                        //add referral
                        int      providerId       = request.PLACER_DETAIL.PROVIDER_ID;
                        DateTime?dateToBeEnrolled = null;
                        try
                        {
                            dateToBeEnrolled = DateTime.ParseExact(request.REFERRAL.DATE_TO_BE_ENROLLED, "yyyyMMdd", null);
                        }
                        catch (Exception e)
                        {
                            Log.Error($"Could not parse Referral DATE_TO_BE_ENROLLED: {request.REFERRAL.DATE_TO_BE_ENROLLED} as a valid date: Incorrect format, date should be in the following format yyyyMMdd");
                            throw new Exception($"Could not parse Referral DATE_TO_BE_ENROLLED: {request.REFERRAL.DATE_TO_BE_ENROLLED} as a valid date: Incorrect format, date should be in the following format yyyyMMdd");
                        }

                        string facilityReferred = request.REFERRAL.REFERRED_TO;
                        var    referralReason   = await _unitOfWork.Repository <LookupItemView>()
                                                  .Get(x => x.MasterName == "ReferralReason" &&
                                                       x.ItemName == "CCCEnrollment").ToListAsync();

                        var searchFacility = await encounterTestingService.SearchFacility(facilityReferred);

                        var previousReferrals = await encounterTestingService.GetReferralByPersonId(identifiers[0].PersonId);

                        var facility = await encounterTestingService.GetCurrentFacility();

                        int MFLCode = 0;
                        if (searchFacility.Count > 0)
                        {
                            MFLCode = Convert.ToInt32(searchFacility[0].MFLCode);

                            if (previousReferrals.Count > 0)
                            {
                                previousReferrals[0].ToFacility =
                                    Convert.ToInt32(searchFacility[0].MFLCode);
                                previousReferrals[0].OtherFacility = "";
                                previousReferrals[0].ExpectedDate  = dateToBeEnrolled.Value;

                                await encounterTestingService.UpdateReferral(previousReferrals[0]);
                            }
                            else
                            {
                                if (facility.Count > 0)
                                {
                                    await encounterTestingService.AddReferral(identifiers[0].PersonId,
                                                                              facility[0].FacilityID, 2, MFLCode,
                                                                              referralReason[0].ItemId, providerId, dateToBeEnrolled.Value, "");
                                }
                            }
                        }
                        else
                        {
                            searchFacility = await encounterTestingService.SearchFacility("Other");

                            MFLCode = Convert.ToInt32(searchFacility[0].MFLCode);

                            await encounterTestingService.AddReferral(identifiers[0].PersonId, facility[0].FacilityID,
                                                                      2, MFLCode, referralReason[0].ItemId, providerId, dateToBeEnrolled.Value, facilityReferred);
                        }

                        var clientHasBeenReferredState =
                            await registerPersonService.AddAppStateStore(identifiers[0].PersonId, patient.Id, 5, null,
                                                                         null);
                    }
                    else
                    {
                        //update message has been processed
                        await registerPersonService.UpdateAfyaMobileInbox(afyaMobileMessage.Id, afyaMobileId, true, DateTime.Now, $"Person with afyaMobileId: {afyaMobileId} could not be found", false);

                        return(Result <string> .Invalid($"Person with afyaMobileId: {afyaMobileId} could not be found"));
                    }

                    //update message has been processed
                    await registerPersonService.UpdateAfyaMobileInbox(afyaMobileMessage.Id, afyaMobileId, true, DateTime.Now, $"Successfully synchronized HTS Referral for afyamobileid: {afyaMobileId}", true);

                    trans.Commit();
                    return(Result <string> .Valid($"Successfully synchronized HTS Referral for afyamobileid: {afyaMobileId}"));
                }
                catch (Exception ex)
                {
                    trans.Rollback();
                    Log.Error($"Failed to synchronize Hts Referral for clientid: {afyaMobileId} " + ex.Message + " " + ex.InnerException);
                    return(Result <string> .Invalid($"Failed to synchronize Hts Referral for clientid: {afyaMobileId} " + ex.Message + " " + ex.InnerException));
                }
            }
        }
        public async Task <Result <string> > Handle(AfyaMobilePartnerTracingEncounterCommand request, CancellationToken cancellationToken)
        {
            string afyaMobileId            = string.Empty;
            string indexClientAfyaMobileId = string.Empty;

            using (var trans = _htsUnitOfWork.Context.Database.BeginTransaction())
            {
                RegisterPersonService   registerPersonService   = new RegisterPersonService(_unitOfWork);
                EncounterTestingService encounterTestingService = new EncounterTestingService(_unitOfWork, _htsUnitOfWork);

                try
                {
                    for (int j = 0; j < request.INTERNAL_PATIENT_ID.Count; j++)
                    {
                        if (request.INTERNAL_PATIENT_ID[j].IDENTIFIER_TYPE == "AFYA_MOBILE_ID")
                        {
                            afyaMobileId = request.INTERNAL_PATIENT_ID[j].ID;
                        }

                        if (request.INTERNAL_PATIENT_ID[j].IDENTIFIER_TYPE == "INDEX_CLIENT_AFYAMOBILE_ID")
                        {
                            indexClientAfyaMobileId = request.INTERNAL_PATIENT_ID[j].ID;
                        }
                    }

                    var afyaMobileMessage = await registerPersonService.AddAfyaMobileInbox(DateTime.Now, request.MESSAGE_HEADER.MESSAGE_TYPE, afyaMobileId, JsonConvert.SerializeObject(request), false);

                    var indexClientIdentifiers = await registerPersonService.getPersonIdentifiers(indexClientAfyaMobileId, 10);

                    if (indexClientIdentifiers.Count > 0)
                    {
                        //Get Index client
                        var indexClient = await registerPersonService.GetPatientByPersonId(indexClientIdentifiers[0].PersonId);

                        var partnetPersonIdentifiers = await registerPersonService.getPersonIdentifiers(afyaMobileId, 10);

                        if (partnetPersonIdentifiers.Count > 0)
                        {
                            var tracingLookup = await _unitOfWork.Repository <LookupItemView>()
                                                .Get(x => x.MasterName == "TracingType" && x.ItemName == "Family").ToListAsync();

                            int tracingType = tracingLookup.FirstOrDefault().ItemId;

                            for (int j = 0; j < request.PARTNERTRACING.TRACING.Count; j++)
                            {
                                DateTime tracingDate = DateTime.Now;
                                try
                                {
                                    tracingDate = DateTime.ParseExact(request.PARTNERTRACING.TRACING[j].TRACING_DATE, "yyyyMMdd", null);
                                }
                                catch (Exception e)
                                {
                                    Log.Error($"Could not parse partner tracing SCREENING_DATE: {request.PARTNERTRACING.TRACING[j].TRACING_DATE} as a valid date: Incorrect format, date should be in the following format yyyyMMdd");
                                    throw new Exception($"Could not parse partner tracing SCREENING_DATE: {request.PARTNERTRACING.TRACING[j].TRACING_DATE} as a valid date: Incorrect format, date should be in the following format yyyyMMdd");
                                }
                                int      mode               = request.PARTNERTRACING.TRACING[j].TRACING_MODE;
                                int      outcome            = request.PARTNERTRACING.TRACING[j].TRACING_OUTCOME;
                                int      consent            = request.PARTNERTRACING.TRACING[j].CONSENT;
                                DateTime?tracingBookingDate = null;
                                if (!string.IsNullOrWhiteSpace(request.PARTNERTRACING.TRACING[j].BOOKING_DATE))
                                {
                                    try
                                    {
                                        tracingBookingDate = DateTime.ParseExact(request.PARTNERTRACING.TRACING[j].BOOKING_DATE, "yyyyMMdd", null);
                                    }
                                    catch (Exception e)
                                    {
                                        Log.Error($"Could not parse partner tracing BOOKING_DATE: {request.PARTNERTRACING.TRACING[j].BOOKING_DATE} as a valid date: Incorrect format, date should be in the following format yyyyMMdd");
                                        throw new Exception($"Could not parse partner tracing BOOKING_DATE: {request.PARTNERTRACING.TRACING[j].BOOKING_DATE} as a valid date: Incorrect format, date should be in the following format yyyyMMdd");
                                    }
                                }
                                int?   reasonnotcontacted      = request.PARTNERTRACING.TRACING[j].REASONNOTCONTACTED;
                                string reasonnotcontactedother = request.PARTNERTRACING.TRACING[j].REASONNOTCONTACTEDOTHER;
                                var    tracingOutcome          = await encounterTestingService.addTracing(partnetPersonIdentifiers[0].PersonId, tracingType,
                                                                                                          tracingDate, mode, outcome, 1, null, consent, tracingBookingDate, null, reasonnotcontacted, reasonnotcontactedother);
                            }

                            var stringParnerObject = Newtonsoft.Json.JsonConvert.SerializeObject(new
                            {
                                partnerId = partnetPersonIdentifiers[0].PersonId,
                                pnsTraced = true
                            });

                            var partnerScreeningDone =
                                await registerPersonService.AddAppStateStore(indexClient.PersonId, indexClient.Id, 9,
                                                                             null, null, stringParnerObject);
                        }
                        else
                        {
                            //update message has been processed
                            await registerPersonService.UpdateAfyaMobileInbox(afyaMobileMessage.Id, afyaMobileId, true, DateTime.Now, $"Partner with afyamobileid: {afyaMobileId} could not be found", false);

                            return(Result <string> .Invalid($"Partner with afyamobileid: {afyaMobileId} could not be found"));
                        }
                    }
                    else
                    {
                        //update message has been processed
                        await registerPersonService.UpdateAfyaMobileInbox(afyaMobileMessage.Id, afyaMobileId, true, DateTime.Now, $"Index clientid: {indexClientAfyaMobileId} for partnerid: {afyaMobileId} not found", false);

                        return(Result <string> .Invalid($"Index clientid: {indexClientAfyaMobileId} for partnerid: {afyaMobileId} not found"));
                    }

                    //update message has been processed
                    await registerPersonService.UpdateAfyaMobileInbox(afyaMobileMessage.Id, afyaMobileId, true, DateTime.Now, $"Successfully synchronized partner tracing for clientid: {indexClientAfyaMobileId} and partnerid: {afyaMobileId}", true);

                    trans.Commit();
                    return(Result <string> .Valid($"Successfully synchronized partner tracing for afyamobileid: {afyaMobileId}"));
                }
                catch (Exception ex)
                {
                    trans.Rollback();
                    Log.Error($"Failed to synchronize partner tracing for clientId: {afyaMobileId} " + ex.Message + " " + ex.InnerException);
                    return(Result <string> .Invalid($"Failed to synchronize partner tracing for clientId: {afyaMobileId} " + ex.Message + " " + ex.InnerException));
                }
            }
        }
        public async Task <Result <string> > Handle(AfyaMobilePartnerScreeningEncounterCommand request, CancellationToken cancellationToken)
        {
            string afyaMobileId            = string.Empty;
            string indexClientAfyaMobileId = string.Empty;

            using (var trans = _htsUnitOfWork.Context.Database.BeginTransaction())
            {
                try
                {
                    RegisterPersonService   registerPersonService   = new RegisterPersonService(_unitOfWork);
                    EncounterTestingService encounterTestingService = new EncounterTestingService(_unitOfWork, _htsUnitOfWork);

                    for (int j = 0; j < request.INTERNAL_PATIENT_ID.Count; j++)
                    {
                        if (request.INTERNAL_PATIENT_ID[j].IDENTIFIER_TYPE == "AFYA_MOBILE_ID")
                        {
                            afyaMobileId = request.INTERNAL_PATIENT_ID[j].ID;
                        }

                        if (request.INTERNAL_PATIENT_ID[j].IDENTIFIER_TYPE == "INDEX_CLIENT_AFYAMOBILE_ID")
                        {
                            indexClientAfyaMobileId = request.INTERNAL_PATIENT_ID[j].ID;
                        }
                    }

                    var afyaMobileMessage = await registerPersonService.AddAfyaMobileInbox(DateTime.Now, request.MESSAGE_HEADER.MESSAGE_TYPE, afyaMobileId, JsonConvert.SerializeObject(request), false);

                    int      pnsAccepted   = request.SCREENING.PARTNER_SCREENING.PNS_ACCEPTED;
                    DateTime screeningDate = DateTime.Now;
                    try
                    {
                        screeningDate = DateTime.ParseExact(request.SCREENING.PARTNER_SCREENING.SCREENING_DATE, "yyyyMMdd", null);
                    }
                    catch (Exception e)
                    {
                        Log.Error($"Could not parse partner screening SCREENING_DATE: {request.SCREENING.PARTNER_SCREENING.SCREENING_DATE} as a valid date: Incorrect format, date should be in the following format yyyyMMdd");
                        throw new Exception($"Could not parse partner screening SCREENING_DATE: {request.SCREENING.PARTNER_SCREENING.SCREENING_DATE} as a valid date: Incorrect format, date should be in the following format yyyyMMdd");
                    }

                    int      ipvScreeningDone     = request.SCREENING.PARTNER_SCREENING.IPV_SCREENING_DONE;
                    int      hurtByPartner        = request.SCREENING.PARTNER_SCREENING.HURT_BY_PARTNER;
                    int      threatByPartner      = request.SCREENING.PARTNER_SCREENING.THREAT_BY_PARTNER;
                    int      sexualAbuseByPartner = request.SCREENING.PARTNER_SCREENING.SEXUAL_ABUSE_BY_PARTNER;
                    int      ipvOutcome           = request.SCREENING.PARTNER_SCREENING.IPV_OUTCOME;
                    string   partnerOccupation    = request.SCREENING.PARTNER_SCREENING.PARTNER_OCCUPATION;
                    int      partnerRelationship  = request.SCREENING.PARTNER_SCREENING.PARTNER_RELATIONSHIP;
                    int      livingWithClient     = request.SCREENING.PARTNER_SCREENING.LIVING_WITH_CLIENT;
                    int      hivStatus            = request.SCREENING.PARTNER_SCREENING.HIV_STATUS;
                    int      pnsApproach          = request.SCREENING.PARTNER_SCREENING.PNS_APPROACH;
                    int      eligibleForHts       = request.SCREENING.PARTNER_SCREENING.ELIGIBLE_FOR_HTS;
                    DateTime bookingDate          = DateTime.Now;
                    try
                    {
                        bookingDate = DateTime.ParseExact(request.SCREENING.PARTNER_SCREENING.BOOKING_DATE, "yyyyMMdd", null);
                    }
                    catch (Exception e)
                    {
                        Log.Error($"Could not parse partner screening BOOKING_DATE: {request.SCREENING.PARTNER_SCREENING.BOOKING_DATE} as a valid date: Incorrect format, date should be in the following format yyyyMMdd");
                        throw new Exception($"Could not parse partner screening BOOKING_DATE: {request.SCREENING.PARTNER_SCREENING.BOOKING_DATE} as a valid date: Incorrect format, date should be in the following format yyyyMMdd");
                    }

                    var pnsScreeningOptions = await _unitOfWork.Repository <LookupItemView>().Get(x => x.MasterName == "PnsScreening").ToListAsync();

                    int providerId = 1;

                    List <Screening> newScreenings = new List <Screening>();
                    for (int j = 0; j < pnsScreeningOptions.Count; j++)
                    {
                        if (pnsScreeningOptions[j].ItemName == "EligibleTesting")
                        {
                            Screening screening = new Screening()
                            {
                                ScreeningCategoryId = pnsScreeningOptions[j].ItemId,
                                ScreeningTypeId     = pnsScreeningOptions[j].MasterId,
                                ScreeningValueId    = eligibleForHts
                            };
                            newScreenings.Add(screening);
                        }
                        else if (pnsScreeningOptions[j].ItemName == "PNSApproach")
                        {
                            Screening screening = new Screening()
                            {
                                ScreeningCategoryId = pnsScreeningOptions[j].ItemId,
                                ScreeningTypeId     = pnsScreeningOptions[j].MasterId,
                                ScreeningValueId    = pnsApproach
                            };
                            newScreenings.Add(screening);
                        }
                        else if (pnsScreeningOptions[j].ItemName == "HIVStatus")
                        {
                            Screening screening = new Screening()
                            {
                                ScreeningCategoryId = pnsScreeningOptions[j].ItemId,
                                ScreeningTypeId     = pnsScreeningOptions[j].MasterId,
                                ScreeningValueId    = hivStatus
                            };
                            newScreenings.Add(screening);
                        }
                        else if (pnsScreeningOptions[j].ItemName == "LivingWithClient")
                        {
                            Screening screening = new Screening()
                            {
                                ScreeningCategoryId = pnsScreeningOptions[j].ItemId,
                                ScreeningTypeId     = pnsScreeningOptions[j].MasterId,
                                ScreeningValueId    = livingWithClient
                            };
                            newScreenings.Add(screening);
                        }
                        else if (pnsScreeningOptions[j].ItemName == "PnsRelationship")
                        {
                            Screening screening = new Screening()
                            {
                                ScreeningCategoryId = pnsScreeningOptions[j].ItemId,
                                ScreeningTypeId     = pnsScreeningOptions[j].MasterId,
                                ScreeningValueId    = partnerRelationship
                            };
                            newScreenings.Add(screening);
                        }
                        else if (pnsScreeningOptions[j].ItemName == "IPVOutcome")
                        {
                            Screening screening = new Screening()
                            {
                                ScreeningCategoryId = pnsScreeningOptions[j].ItemId,
                                ScreeningTypeId     = pnsScreeningOptions[j].MasterId,
                                ScreeningValueId    = ipvOutcome
                            };
                            newScreenings.Add(screening);
                        }
                        else if (pnsScreeningOptions[j].ItemName == "PnsForcedSexual")
                        {
                            Screening screening = new Screening()
                            {
                                ScreeningCategoryId = pnsScreeningOptions[j].ItemId,
                                ScreeningTypeId     = pnsScreeningOptions[j].MasterId,
                                ScreeningValueId    = sexualAbuseByPartner
                            };
                            newScreenings.Add(screening);
                        }
                        else if (pnsScreeningOptions[j].ItemName == "PnsThreatenedHurt")
                        {
                            Screening screening = new Screening()
                            {
                                ScreeningCategoryId = pnsScreeningOptions[j].ItemId,
                                ScreeningTypeId     = pnsScreeningOptions[j].MasterId,
                                ScreeningValueId    = threatByPartner
                            };
                            newScreenings.Add(screening);
                        }
                        else if (pnsScreeningOptions[j].ItemName == "PnsPhysicallyHurt")
                        {
                            Screening screening = new Screening()
                            {
                                ScreeningCategoryId = pnsScreeningOptions[j].ItemId,
                                ScreeningTypeId     = pnsScreeningOptions[j].MasterId,
                                ScreeningValueId    = hurtByPartner
                            };
                            newScreenings.Add(screening);
                        }
                    }

                    var indexClientIdentifiers = await registerPersonService.getPersonIdentifiers(indexClientAfyaMobileId, 10);

                    if (indexClientIdentifiers.Count > 0)
                    {
                        //Get Index client
                        var indexClient = await registerPersonService.GetPatientByPersonId(indexClientIdentifiers[0].PersonId);

                        var partnetPersonIdentifiers = await registerPersonService.getPersonIdentifiers(afyaMobileId, 10);

                        if (partnetPersonIdentifiers.Count > 0)
                        {
                            var patientMasterVisitEntity = await _unitOfWork.Repository <PatientMasterVisit>()
                                                           .Get(x => x.PatientId == indexClient.Id && x.ServiceId == 2).ToListAsync();

                            int patientMasterVisitId = patientMasterVisitEntity.OrderBy(x => x.Id).FirstOrDefault().Id;


                            var partnHtsScreenings = await encounterTestingService.AddPartnerScreening(
                                partnetPersonIdentifiers[0].PersonId, indexClient.Id, patientMasterVisitId,
                                partnerOccupation,
                                screeningDate, bookingDate, newScreenings, providerId);

                            var stringParnerObject = Newtonsoft.Json.JsonConvert.SerializeObject(new
                            {
                                partnerId   = partnetPersonIdentifiers[0].PersonId,
                                pnsScreened = true
                            });

                            var partnerScreeningDone =
                                await registerPersonService.AddAppStateStore(indexClient.PersonId, indexClient.Id, 8,
                                                                             null, null, stringParnerObject);
                        }
                        else
                        {
                            //update message has been processed
                            await registerPersonService.UpdateAfyaMobileInbox(afyaMobileMessage.Id, afyaMobileId, true, DateTime.Now, $"Partner with afyamobileid: {afyaMobileId} could not be found", false);

                            return(Result <string> .Invalid($"Partner with afyamobileid: {afyaMobileId} could not be found"));
                        }
                    }
                    else
                    {
                        //update message has been processed
                        await registerPersonService.UpdateAfyaMobileInbox(afyaMobileMessage.Id, afyaMobileId, true, DateTime.Now, $"Index clientid: {indexClientAfyaMobileId} for partnerid: {afyaMobileId} not found", false);

                        return(Result <string> .Invalid($"Index clientid: {indexClientAfyaMobileId} for partnerid: {afyaMobileId} not found"));
                    }

                    //update message has been processed
                    await registerPersonService.UpdateAfyaMobileInbox(afyaMobileMessage.Id, afyaMobileId, true, DateTime.Now, $"Successfully synchronized partner screening for afyamobileid: {afyaMobileId}", true);

                    trans.Commit();
                    return(Result <string> .Valid($"Successfully synchronized partner screening for afyamobileid: {afyaMobileId}"));
                }
                catch (Exception ex)
                {
                    trans.Rollback();
                    Log.Error($"Failed to synchronize partner screening for clientId: {afyaMobileId} " + ex.Message + " " + ex.InnerException);
                    return(Result <string> .Invalid($"Failed to synchronize partner screening for clientId: {afyaMobileId} " + ex.Message + " " + ex.InnerException));
                }
            }
        }