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));
                }
            }
        }
        public async Task <Result <string> > Handle(SynchronizePartnersCommand request, CancellationToken cancellationToken)
        {
            using (_htsUnitOfWork)
                using (_unitOfWork)
                {
                    string afyaMobileId            = string.Empty;
                    string indexClientAfyaMobileId = string.Empty;

                    RegisterPersonService   registerPersonService   = new RegisterPersonService(_unitOfWork);
                    EncounterTestingService encounterTestingService = new EncounterTestingService(_unitOfWork, _htsUnitOfWork);

                    var facilityId = request.MESSAGE_HEADER.SENDING_FACILITY;
                    for (int i = 0; i < request.PARTNERS.Count; i++)
                    {
                        for (int j = 0; j < request.PARTNERS[i].PATIENT_IDENTIFICATION.INTERNAL_PATIENT_ID.Count; j++)
                        {
                            if (request.PARTNERS[i].PATIENT_IDENTIFICATION.INTERNAL_PATIENT_ID[j].IDENTIFIER_TYPE ==
                                "AFYA_MOBILE_ID")
                            {
                                afyaMobileId = request.PARTNERS[i].PATIENT_IDENTIFICATION.INTERNAL_PATIENT_ID[j].ID;
                            }

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

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

                        try
                        {
                            string   firstName       = request.PARTNERS[i].PATIENT_IDENTIFICATION.PATIENT_NAME.FIRST_NAME;
                            string   middleName      = request.PARTNERS[i].PATIENT_IDENTIFICATION.PATIENT_NAME.MIDDLE_NAME;
                            string   lastName        = request.PARTNERS[i].PATIENT_IDENTIFICATION.PATIENT_NAME.LAST_NAME;
                            int      sex             = request.PARTNERS[i].PATIENT_IDENTIFICATION.SEX;
                            DateTime dateOfBirth     = DateTime.ParseExact(request.PARTNERS[i].PATIENT_IDENTIFICATION.DATE_OF_BIRTH, "yyyyMMdd", null);
                            int      providerId      = request.PARTNERS[i].PATIENT_IDENTIFICATION.USER_ID;
                            int      maritalStatusId = request.PARTNERS[i].PATIENT_IDENTIFICATION.MARITAL_STATUS;
                            string   mobileNumber    = request.PARTNERS[i].PATIENT_IDENTIFICATION.PHONE_NUMBER;
                            string   landmark        = request.PARTNERS[i].PATIENT_IDENTIFICATION.PATIENT_ADDRESS.PHYSICAL_ADDRESS
                                                       .LANDMARK;
                            int relationshipType = request.PARTNERS[i].PATIENT_IDENTIFICATION.RELATIONSHIP_TYPE;

                            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();
                            }

                            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)
                                {
                                    await registerPersonService.UpdatePerson(partnetPersonIdentifiers[0].PersonId, firstName, middleName, lastName, sex, dateOfBirth, clientFacility.FacilityID);

                                    //update maritalstatus id
                                    await registerPersonService.UpdateMaritalStatus(partnetPersonIdentifiers[0].PersonId, maritalStatusId);

                                    if (!string.IsNullOrWhiteSpace(mobileNumber))
                                    {
                                        await registerPersonService.UpdatePersonContact(partnetPersonIdentifiers[0].PersonId, null, mobileNumber);
                                    }
                                    if (!string.IsNullOrWhiteSpace(landmark))
                                    {
                                        await registerPersonService.UpdatePersonLocation(partnetPersonIdentifiers[0].PersonId, landmark);
                                    }

                                    var getPersonRelationship = await registerPersonService.GetPersonRelationshipByPatientIdPersonId(indexClient.Id, partnetPersonIdentifiers[0].PersonId);

                                    if (getPersonRelationship != null)
                                    {
                                        getPersonRelationship.RelationshipTypeId = relationshipType;
                                        var updatedRelationship = await registerPersonService.UpdatePersonRelationship(getPersonRelationship);
                                    }
                                    else
                                    {
                                        //Add PersonRelationship
                                        var personRelationship = await registerPersonService.addPersonRelationship(partnetPersonIdentifiers[0].PersonId, indexClient.Id, relationshipType, providerId);
                                    }

                                    /***
                                     * Encounter
                                     */

                                    if (request.PARTNERS[i].ENCOUNTER != null)
                                    {
                                        if (request.PARTNERS[i].ENCOUNTER.PARTNER_SCREENING != null)
                                        {
                                            int      pnsAccepted          = request.PARTNERS[i].ENCOUNTER.PARTNER_SCREENING.PNS_ACCEPTED;
                                            DateTime screeningDate        = DateTime.ParseExact(request.PARTNERS[i].ENCOUNTER.PARTNER_SCREENING.SCREENING_DATE, "yyyyMMdd", null);
                                            int      ipvScreeningDone     = request.PARTNERS[i].ENCOUNTER.PARTNER_SCREENING.IPV_SCREENING_DONE;
                                            int      hurtByPartner        = request.PARTNERS[i].ENCOUNTER.PARTNER_SCREENING.HURT_BY_PARTNER;
                                            int      threatByPartner      = request.PARTNERS[i].ENCOUNTER.PARTNER_SCREENING.THREAT_BY_PARTNER;
                                            int      sexualAbuseByPartner = request.PARTNERS[i].ENCOUNTER.PARTNER_SCREENING.SEXUAL_ABUSE_BY_PARTNER;
                                            int      ipvOutcome           = request.PARTNERS[i].ENCOUNTER.PARTNER_SCREENING.IPV_OUTCOME;
                                            string   partnerOccupation    = request.PARTNERS[i].ENCOUNTER.PARTNER_SCREENING.PARTNER_OCCUPATION;
                                            int      partnerRelationship  = request.PARTNERS[i].ENCOUNTER.PARTNER_SCREENING.PARTNER_RELATIONSHIP;
                                            int      livingWithClient     = request.PARTNERS[i].ENCOUNTER.PARTNER_SCREENING.LIVING_WITH_CLIENT;
                                            int      hivStatus            = request.PARTNERS[i].ENCOUNTER.PARTNER_SCREENING.HIV_STATUS;
                                            int      pnsApproach          = request.PARTNERS[i].ENCOUNTER.PARTNER_SCREENING.PNS_APPROACH;
                                            int      eligibleForHts       = request.PARTNERS[i].ENCOUNTER.PARTNER_SCREENING.ELIGIBLE_FOR_HTS;
                                            DateTime bookingDate          = DateTime.ParseExact(request.PARTNERS[i].ENCOUNTER.PARTNER_SCREENING.BOOKING_DATE, "yyyyMMdd", null);

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

                                            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 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 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.PARTNERS[i].ENCOUNTER.TRACING.Count; j++)
                                        {
                                            DateTime tracingDate        = DateTime.ParseExact(request.PARTNERS[i].ENCOUNTER.TRACING[j].TRACING_DATE, "yyyyMMdd", null);
                                            int      mode               = request.PARTNERS[i].ENCOUNTER.TRACING[j].TRACING_MODE;
                                            int      outcome            = request.PARTNERS[i].ENCOUNTER.TRACING[j].TRACING_OUTCOME;
                                            int      consent            = request.PARTNERS[i].ENCOUNTER.TRACING[j].CONSENT;
                                            DateTime?tracingBookingDate = null;
                                            if (!string.IsNullOrWhiteSpace(request.PARTNERS[i].ENCOUNTER.TRACING[j].BOOKING_DATE))
                                            {
                                                tracingBookingDate = DateTime.ParseExact(request.PARTNERS[i].ENCOUNTER.TRACING[j].BOOKING_DATE, "yyyyMMdd", null);
                                            }
                                            int?   reasonnotcontacted      = request.PARTNERS[i].ENCOUNTER.TRACING[j].REASONNOTCONTACTED;
                                            string reasonnotcontactedother = request.PARTNERS[i].ENCOUNTER.TRACING[j].REASONNOTCONTACTEDOTHER;

                                            var tracingOutcome = await encounterTestingService.addTracing(partnetPersonIdentifiers[0].PersonId, tracingType,
                                                                                                          tracingDate, mode, outcome, providerId, null, consent, tracingBookingDate, null, reasonnotcontacted, reasonnotcontactedother);
                                        }
                                    }

                                    // update message as processed
                                    await registerPersonService.UpdateAfyaMobileInbox(afyaMobileMessage.Id, indexClientAfyaMobileId, true, DateTime.Now, "success");
                                }
                                else
                                {
                                    //Register Partner
                                    var person = await registerPersonService.RegisterPerson(firstName, middleName, lastName, sex, providerId, clientFacility.FacilityID, dateOfBirth);

                                    //Add afyamobile Id as an Id of the partner
                                    var personIdentifier = await registerPersonService.addPersonIdentifiers(person.Id, 10, afyaMobileId, providerId);

                                    //Add partner marital status
                                    var partnerMaritalStatus = await registerPersonService.AddMaritalStatus(person.Id, maritalStatusId, providerId);

                                    //add partner contacts
                                    if (!string.IsNullOrWhiteSpace(mobileNumber))
                                    {
                                        var partnerContacts = await registerPersonService.addPersonContact(person.Id, null,
                                                                                                           mobileNumber, null, null, providerId);
                                    }
                                    //add partner location
                                    if (!string.IsNullOrWhiteSpace(landmark))
                                    {
                                        var partnerLocation =
                                            await registerPersonService.addPersonLocation(person.Id, 0, 0, 0, " ", landmark,
                                                                                          providerId);
                                    }

                                    //Add PersonRelationship
                                    var personRelationship = await registerPersonService.addPersonRelationship(person.Id, indexClient.Id, relationshipType, providerId);


                                    /***
                                     * Encounter
                                     */

                                    if (request.PARTNERS[i].ENCOUNTER != null)
                                    {
                                        if (request.PARTNERS[i].ENCOUNTER.PARTNER_SCREENING != null)
                                        {
                                            int      pnsAccepted          = request.PARTNERS[i].ENCOUNTER.PARTNER_SCREENING.PNS_ACCEPTED;
                                            DateTime screeningDate        = DateTime.ParseExact(request.PARTNERS[i].ENCOUNTER.PARTNER_SCREENING.SCREENING_DATE, "yyyyMMdd", null);
                                            int      ipvScreeningDone     = request.PARTNERS[i].ENCOUNTER.PARTNER_SCREENING.IPV_SCREENING_DONE;
                                            int      hurtByPartner        = request.PARTNERS[i].ENCOUNTER.PARTNER_SCREENING.HURT_BY_PARTNER;
                                            int      threatByPartner      = request.PARTNERS[i].ENCOUNTER.PARTNER_SCREENING.THREAT_BY_PARTNER;
                                            int      sexualAbuseByPartner = request.PARTNERS[i].ENCOUNTER.PARTNER_SCREENING.SEXUAL_ABUSE_BY_PARTNER;
                                            int      ipvOutcome           = request.PARTNERS[i].ENCOUNTER.PARTNER_SCREENING.IPV_OUTCOME;
                                            string   partnerOccupation    = request.PARTNERS[i].ENCOUNTER.PARTNER_SCREENING.PARTNER_OCCUPATION;
                                            int      partnerRelationship  = request.PARTNERS[i].ENCOUNTER.PARTNER_SCREENING.PARTNER_RELATIONSHIP;
                                            int      livingWithClient     = request.PARTNERS[i].ENCOUNTER.PARTNER_SCREENING.LIVING_WITH_CLIENT;
                                            int      hivStatus            = request.PARTNERS[i].ENCOUNTER.PARTNER_SCREENING.HIV_STATUS;
                                            int      pnsApproach          = request.PARTNERS[i].ENCOUNTER.PARTNER_SCREENING.PNS_APPROACH;
                                            int      eligibleForHts       = request.PARTNERS[i].ENCOUNTER.PARTNER_SCREENING.ELIGIBLE_FOR_HTS;
                                            DateTime bookingDate          = DateTime.ParseExact(request.PARTNERS[i].ENCOUNTER.PARTNER_SCREENING.BOOKING_DATE, "yyyyMMdd", null);

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

                                            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 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(person.Id, indexClient.Id, patientMasterVisitId, partnerOccupation,
                                                                                                                       screeningDate, bookingDate, newScreenings, providerId);
                                        }

                                        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.PARTNERS[i].ENCOUNTER.TRACING.Count; j++)
                                        {
                                            DateTime tracingDate        = DateTime.ParseExact(request.PARTNERS[i].ENCOUNTER.TRACING[j].TRACING_DATE, "yyyyMMdd", null);
                                            int      mode               = request.PARTNERS[i].ENCOUNTER.TRACING[j].TRACING_MODE;
                                            int      outcome            = request.PARTNERS[i].ENCOUNTER.TRACING[j].TRACING_OUTCOME;
                                            int      consent            = request.PARTNERS[i].ENCOUNTER.TRACING[j].CONSENT;
                                            DateTime?tracingBookingDate = null;
                                            if (!string.IsNullOrWhiteSpace(request.PARTNERS[i].ENCOUNTER.TRACING[j].BOOKING_DATE))
                                            {
                                                tracingBookingDate = DateTime.ParseExact(request.PARTNERS[i].ENCOUNTER.TRACING[j].BOOKING_DATE, "yyyyMMdd", null);
                                            }
                                            int?   reasonnotContacted      = request.PARTNERS[i].ENCOUNTER.TRACING[j].REASONNOTCONTACTED;
                                            string reasonnotContactedOther = request.PARTNERS[i].ENCOUNTER.TRACING[j].REASONNOTCONTACTEDOTHER;
                                            var    tracingOutcome          = await encounterTestingService.addTracing(person.Id, tracingType,
                                                                                                                      tracingDate, mode, outcome, providerId, null, consent, tracingBookingDate, null, reasonnotContacted, reasonnotContactedOther);
                                        }
                                    }
                                }
                            }

                            // update message as processed
                            await registerPersonService.UpdateAfyaMobileInbox(afyaMobileMessage.Id, indexClientAfyaMobileId, true, DateTime.Now, "success");

                            return(Result <string> .Valid(afyaMobileId));
                        }
                        catch (Exception e)
                        {
                            Log.Error(e.Message);
                            Log.Error(e.InnerException.ToString());
                            // update message as processed
                            await registerPersonService.UpdateAfyaMobileInbox(afyaMobileMessage.Id, indexClientAfyaMobileId, false, DateTime.Now, e.Message + " " + e.InnerException.ToString());

                            return(Result <string> .Invalid(e.Message));
                        }
                    }

                    return(Result <string> .Valid(afyaMobileId));
                }
        }
Exemplo n.º 3
0
        public async Task <Result <string> > Handle(SynchronizeFamilyCommand request, CancellationToken cancellationToken)
        {
            using (_htsUnitOfWork)
                using (_unitOfWork)
                {
                    try
                    {
                        string afyaMobileId            = string.Empty;
                        string indexClientAfyaMobileId = string.Empty;

                        RegisterPersonService   registerPersonService   = new RegisterPersonService(_unitOfWork);
                        EncounterTestingService encounterTestingService = new EncounterTestingService(_unitOfWork, _htsUnitOfWork);

                        var facilityId = request.MESSAGE_HEADER.SENDING_FACILITY;

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

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

                            string   firstName       = request.FAMILY[i].PATIENT_IDENTIFICATION.PATIENT_NAME.FIRST_NAME;
                            string   middleName      = request.FAMILY[i].PATIENT_IDENTIFICATION.PATIENT_NAME.MIDDLE_NAME;
                            string   lastName        = request.FAMILY[i].PATIENT_IDENTIFICATION.PATIENT_NAME.LAST_NAME;
                            int      sex             = request.FAMILY[i].PATIENT_IDENTIFICATION.SEX;
                            DateTime dateOfBirth     = DateTime.ParseExact(request.FAMILY[i].PATIENT_IDENTIFICATION.DATE_OF_BIRTH, "yyyyMMdd", null);
                            int      providerId      = request.FAMILY[i].PATIENT_IDENTIFICATION.USER_ID;
                            int      maritalStatusId = request.FAMILY[i].PATIENT_IDENTIFICATION.MARITAL_STATUS;
                            string   mobileNumber    = request.FAMILY[i].PATIENT_IDENTIFICATION.PHONE_NUMBER;
                            string   landmark        = request.FAMILY[i].PATIENT_IDENTIFICATION.PATIENT_ADDRESS.PHYSICAL_ADDRESS
                                                       .LANDMARK;
                            int relationshipType = request.FAMILY[i].PATIENT_IDENTIFICATION.RELATIONSHIP_TYPE;

                            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)
                                {
                                    await registerPersonService.UpdatePerson(partnetPersonIdentifiers[0].PersonId, firstName, middleName, lastName, sex, dateOfBirth);

                                    //update maritalstatus id
                                    await registerPersonService.UpdateMaritalStatus(partnetPersonIdentifiers[0].PersonId, maritalStatusId);

                                    if (!string.IsNullOrWhiteSpace(mobileNumber))
                                    {
                                        await registerPersonService.UpdatePersonContact(partnetPersonIdentifiers[0].PersonId, null, mobileNumber);
                                    }
                                    if (!string.IsNullOrWhiteSpace(landmark))
                                    {
                                        await registerPersonService.UpdatePersonLocation(partnetPersonIdentifiers[0].PersonId, landmark);
                                    }

                                    var getPersonRelationship = await registerPersonService.GetPersonRelationshipByPatientIdPersonId(indexClient.Id, partnetPersonIdentifiers[0].PersonId);

                                    if (getPersonRelationship != null)
                                    {
                                        getPersonRelationship.RelationshipTypeId = relationshipType;
                                        var updatedRelationship = await registerPersonService.UpdatePersonRelationship(getPersonRelationship);
                                    }
                                    else
                                    {
                                        //Add PersonRelationship
                                        var personRelationship = await registerPersonService.addPersonRelationship(partnetPersonIdentifiers[0].PersonId, indexClient.Id, relationshipType, providerId);
                                    }

                                    /***
                                     * Encounter
                                     */
                                    if (request.FAMILY[i].ENCOUNTER != null)
                                    {
                                        if (request.FAMILY[i].ENCOUNTER.FAMILY_SCREENING != null)
                                        {
                                            DateTime screeningDate = DateTime.ParseExact(request.FAMILY[i].ENCOUNTER.FAMILY_SCREENING.SCREENING_DATE, "yyyyMMdd", null);
                                            int      hivStatus     = request.FAMILY[i].ENCOUNTER.FAMILY_SCREENING.HIV_STATUS;
                                            int      eligible      = request.FAMILY[i].ENCOUNTER.FAMILY_SCREENING.ELIGIBLE_FOR_HTS;
                                            DateTime bookingDate   = DateTime.ParseExact(request.FAMILY[i].ENCOUNTER.FAMILY_SCREENING.BOOKING_DATE, "yyyyMMdd", null);
                                            string   remarks       = request.FAMILY[i].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, providerId);
                                        }

                                        for (int j = 0; j < request.FAMILY[i].ENCOUNTER.TRACING.Count; j++)
                                        {
                                            var lookupitem = await _unitOfWork.Repository <LookupItemView>()
                                                             .Get(x => x.MasterName == "TracingType" && x.ItemName == "Family").ToListAsync();

                                            int tracingType = lookupitem[0].ItemId;

                                            DateTime tracingDate = DateTime.ParseExact(request.FAMILY[i].ENCOUNTER.TRACING[j].TRACING_DATE, "yyyyMMdd", null);
                                            int      mode        = request.FAMILY[i].ENCOUNTER.TRACING[j].TRACING_MODE;
                                            int      outcome     = request.FAMILY[i].ENCOUNTER.TRACING[j].TRACING_OUTCOME;

                                            DateTime?reminderDate = null;
                                            if (!string.IsNullOrWhiteSpace(request.FAMILY[i].ENCOUNTER.TRACING[j].REMINDER_DATE))
                                            {
                                                reminderDate = DateTime.ParseExact(request.FAMILY[i].ENCOUNTER.TRACING[j].REMINDER_DATE, "yyyyMMdd", null);
                                            }
                                            DateTime?tracingBookingDate = null;
                                            if (!string.IsNullOrWhiteSpace(request.FAMILY[i].ENCOUNTER.TRACING[j].BOOKING_DATE))
                                            {
                                                tracingBookingDate = DateTime.ParseExact(request.FAMILY[i].ENCOUNTER.TRACING[j].BOOKING_DATE, "yyyyMMdd", null);
                                            }
                                            int consent = request.FAMILY[i].ENCOUNTER.TRACING[j].CONSENT;

                                            var trace = await encounterTestingService.addTracing(partnetPersonIdentifiers[0].PersonId, tracingType, tracingDate, mode, outcome,
                                                                                                 providerId, null, consent, tracingBookingDate, reminderDate);
                                        }
                                    }
                                }
                                else
                                {
                                    //Register family
                                    var person = await registerPersonService.RegisterPerson(firstName, middleName, lastName, sex, dateOfBirth, providerId);

                                    //Add afyamobile Id as an Id of the family
                                    var personIdentifier = await registerPersonService.addPersonIdentifiers(person.Id, 10, afyaMobileId, providerId);

                                    //Add family marital status
                                    var partnerMaritalStatus = await registerPersonService.AddMaritalStatus(person.Id, maritalStatusId, providerId);

                                    //add family contacts
                                    if (string.IsNullOrWhiteSpace(mobileNumber))
                                    {
                                        var partnerContacts = await registerPersonService.addPersonContact(person.Id, null, mobileNumber, null, null, providerId);
                                    }
                                    //add family location
                                    if (!string.IsNullOrWhiteSpace(landmark))
                                    {
                                        var partnerLocation = await registerPersonService.addPersonLocation(person.Id, 0, 0, 0, null, landmark, providerId);
                                    }
                                    //Add PersonRelationship
                                    var personRelationship = await registerPersonService.addPersonRelationship(person.Id, indexClient.Id, relationshipType, providerId);


                                    /***
                                     * Encounter
                                     */
                                    if (request.FAMILY[i].ENCOUNTER != null)
                                    {
                                        if (request.FAMILY[i].ENCOUNTER.FAMILY_SCREENING != null)
                                        {
                                            DateTime screeningDate = DateTime.ParseExact(request.FAMILY[i].ENCOUNTER.FAMILY_SCREENING.SCREENING_DATE, "yyyyMMdd", null);
                                            int      hivStatus     = request.FAMILY[i].ENCOUNTER.FAMILY_SCREENING.HIV_STATUS;
                                            int      eligible      = request.FAMILY[i].ENCOUNTER.FAMILY_SCREENING.ELIGIBLE_FOR_HTS;
                                            DateTime bookingDate   = DateTime.ParseExact(request.FAMILY[i].ENCOUNTER.FAMILY_SCREENING.BOOKING_DATE, "yyyyMMdd", null);
                                            string   remarks       = request.FAMILY[i].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(person.Id, indexClient.Id, patientMasterVisitId, null,
                                                                                                  screeningDate, bookingDate, familyScreeningList, providerId);
                                        }

                                        for (int j = 0; j < request.FAMILY[i].ENCOUNTER.TRACING.Count; j++)
                                        {
                                            var lookupitem = await _unitOfWork.Repository <LookupItemView>()
                                                             .Get(x => x.MasterName == "TracingType" && x.ItemName == "Family").ToListAsync();

                                            int tracingType = lookupitem[0].ItemId;

                                            DateTime tracingDate = DateTime.ParseExact(request.FAMILY[i].ENCOUNTER.TRACING[j].TRACING_DATE, "yyyyMMdd", null);
                                            int      mode        = request.FAMILY[i].ENCOUNTER.TRACING[j].TRACING_MODE;
                                            int      outcome     = request.FAMILY[i].ENCOUNTER.TRACING[j].TRACING_OUTCOME;

                                            DateTime?reminderDate = null;
                                            if (!string.IsNullOrWhiteSpace(request.FAMILY[i].ENCOUNTER.TRACING[j].REMINDER_DATE))
                                            {
                                                reminderDate = DateTime.ParseExact(request.FAMILY[i].ENCOUNTER.TRACING[j].REMINDER_DATE, "yyyyMMdd", null);
                                            }
                                            DateTime?tracingBookingDate = null;
                                            if (!string.IsNullOrWhiteSpace(request.FAMILY[i].ENCOUNTER.TRACING[j].BOOKING_DATE))
                                            {
                                                tracingBookingDate = DateTime.ParseExact(request.FAMILY[i].ENCOUNTER.TRACING[j].BOOKING_DATE, "yyyyMMdd", null);
                                            }
                                            int consent = request.FAMILY[i].ENCOUNTER.TRACING[j].CONSENT;

                                            var trace = await encounterTestingService.addTracing(person.Id, tracingType, tracingDate, mode, outcome,
                                                                                                 providerId, null, consent, tracingBookingDate, reminderDate);
                                        }
                                    }
                                }
                            }
                        }
                        return(Result <string> .Valid(afyaMobileId));
                    }
                    catch (Exception e)
                    {
                        return(Result <string> .Invalid(e.Message));
                    }
                }
        }
Exemplo n.º 4
0
        public async Task <Result <string> > Handle(SynchronizeFamilyCommand request, CancellationToken cancellationToken)
        {
            using (_htsUnitOfWork)
                using (_unitOfWork)
                {
                    string afyaMobileId            = string.Empty;
                    string indexClientAfyaMobileId = string.Empty;

                    RegisterPersonService   registerPersonService   = new RegisterPersonService(_unitOfWork);
                    EncounterTestingService encounterTestingService = new EncounterTestingService(_unitOfWork, _htsUnitOfWork);
                    PersonOccupationService pocc = new PersonOccupationService(_unitOfWork);
                    EducationLevelService   educationLevelService = new EducationLevelService(_unitOfWork);
                    var facilityId = request.MESSAGE_HEADER.SENDING_FACILITY;

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

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

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

                        try
                        {
                            string firstName  = request.FAMILY[i].PATIENT_IDENTIFICATION.PATIENT_NAME.FIRST_NAME;
                            string middleName = request.FAMILY[i].PATIENT_IDENTIFICATION.PATIENT_NAME.MIDDLE_NAME;
                            string lastName   = request.FAMILY[i].PATIENT_IDENTIFICATION.PATIENT_NAME.LAST_NAME;

                            int    sex      = request.FAMILY[i].PATIENT_IDENTIFICATION.SEX;
                            string nickName = (request.FAMILY[i].PATIENT_IDENTIFICATION.PATIENT_NAME.NICK_NAME == null) ? "" : request.FAMILY[i].PATIENT_IDENTIFICATION.PATIENT_NAME.NICK_NAME.ToString();

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

                            string   educationlevel   = (request.FAMILY[i].PATIENT_IDENTIFICATION.EDUCATIONLEVEL == null) ? "" : request.FAMILY[i].PATIENT_IDENTIFICATION.EDUCATIONLEVEL.ToString();
                            string   educationoutcome = (request.FAMILY[i].PATIENT_IDENTIFICATION.EDUCATIONOUTCOME == null) ? "" : request.FAMILY[i].PATIENT_IDENTIFICATION.EDUCATIONOUTCOME.ToString();
                            string   occupation       = (request.FAMILY[i].PATIENT_IDENTIFICATION.OCCUPATION == null) ? "" : request.FAMILY[i].PATIENT_IDENTIFICATION.OCCUPATION.ToString();
                            DateTime dateOfBirth      = DateTime.ParseExact(request.FAMILY[i].PATIENT_IDENTIFICATION.DATE_OF_BIRTH, "yyyyMMdd", null);
                            int      providerId       = request.FAMILY[i].PATIENT_IDENTIFICATION.USER_ID;
                            int      maritalStatusId  = request.FAMILY[i].PATIENT_IDENTIFICATION.MARITAL_STATUS;
                            string   mobileNumber     = request.FAMILY[i].PATIENT_IDENTIFICATION.PHONE_NUMBER;
                            string   landmark         = request.FAMILY[i].PATIENT_IDENTIFICATION.PATIENT_ADDRESS.PHYSICAL_ADDRESS
                                                        .LANDMARK;

                            int relationshipType = request.FAMILY[i].PATIENT_IDENTIFICATION.RELATIONSHIP_TYPE;
                            int Userid           = request.FAMILY[i].PATIENT_IDENTIFICATION.USER_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();
                            }

                            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)
                                {
                                    await registerPersonService.UpdatePerson(partnetPersonIdentifiers[0].PersonId, firstName, middleName, lastName, sex, dateOfBirth, clientFacility.FacilityID, NickName : nickName);

                                    //update maritalstatus id
                                    await registerPersonService.UpdateMaritalStatus(partnetPersonIdentifiers[0].PersonId, maritalStatusId);

                                    if (!string.IsNullOrWhiteSpace(mobileNumber))
                                    {
                                        await registerPersonService.UpdatePersonContact(partnetPersonIdentifiers[0].PersonId, null, mobileNumber);
                                    }
                                    if (!string.IsNullOrWhiteSpace(landmark) || (county > 0) || (subcounty > 0) || (ward > 0))
                                    {
                                        var personlocation = await registerPersonService.UpdatePersonLocation(partnetPersonIdentifiers[0].PersonId, landmark, ward, county, subcounty, Userid);
                                    }

                                    if (!string.IsNullOrWhiteSpace(educationlevel))
                                    {
                                        var personeducation = await educationLevelService.UpdatePersonEducation(partnetPersonIdentifiers[0].PersonId, educationlevel, educationoutcome, Userid);
                                    }
                                    if (!string.IsNullOrWhiteSpace(occupation))
                                    {
                                        var personoccupation = await pocc.Update(partnetPersonIdentifiers[0].PersonId, occupation, Userid);
                                    }
                                    var getPersonRelationship = await registerPersonService.GetPersonRelationshipByPatientIdPersonId(indexClient.Id, partnetPersonIdentifiers[0].PersonId);

                                    if (getPersonRelationship != null)
                                    {
                                        getPersonRelationship.RelationshipTypeId = relationshipType;
                                        var updatedRelationship = await registerPersonService.UpdatePersonRelationship(getPersonRelationship);
                                    }
                                    else
                                    {
                                        //Add PersonRelationship
                                        var personRelationship = await registerPersonService.addPersonRelationship(partnetPersonIdentifiers[0].PersonId, indexClient.Id, relationshipType, providerId);
                                    }

                                    /***
                                     * Encounter
                                     */
                                    if (request.FAMILY[i].ENCOUNTER != null)
                                    {
                                        if (request.FAMILY[i].ENCOUNTER.FAMILY_SCREENING != null)
                                        {
                                            DateTime screeningDate = DateTime.ParseExact(request.FAMILY[i].ENCOUNTER.FAMILY_SCREENING.SCREENING_DATE, "yyyyMMdd", null);
                                            int      hivStatus     = request.FAMILY[i].ENCOUNTER.FAMILY_SCREENING.HIV_STATUS;
                                            int      eligible      = request.FAMILY[i].ENCOUNTER.FAMILY_SCREENING.ELIGIBLE_FOR_HTS;
                                            DateTime bookingDate   = DateTime.ParseExact(request.FAMILY[i].ENCOUNTER.FAMILY_SCREENING.BOOKING_DATE, "yyyyMMdd", null);
                                            string   remarks       = request.FAMILY[i].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, providerId);
                                        }

                                        for (int j = 0; j < request.FAMILY[i].ENCOUNTER.TRACING.Count; j++)
                                        {
                                            var lookupitem = await _unitOfWork.Repository <LookupItemView>()
                                                             .Get(x => x.MasterName == "TracingType" && x.ItemName == "Family").ToListAsync();

                                            int tracingType = lookupitem[0].ItemId;

                                            DateTime tracingDate = DateTime.ParseExact(request.FAMILY[i].ENCOUNTER.TRACING[j].TRACING_DATE, "yyyyMMdd", null);
                                            int      mode        = request.FAMILY[i].ENCOUNTER.TRACING[j].TRACING_MODE;
                                            int      outcome     = request.FAMILY[i].ENCOUNTER.TRACING[j].TRACING_OUTCOME;

                                            DateTime?reminderDate = null;
                                            if (!string.IsNullOrWhiteSpace(request.FAMILY[i].ENCOUNTER.TRACING[j].REMINDER_DATE))
                                            {
                                                reminderDate = DateTime.ParseExact(request.FAMILY[i].ENCOUNTER.TRACING[j].REMINDER_DATE, "yyyyMMdd", null);
                                            }
                                            DateTime?tracingBookingDate = null;
                                            if (!string.IsNullOrWhiteSpace(request.FAMILY[i].ENCOUNTER.TRACING[j].BOOKING_DATE))
                                            {
                                                tracingBookingDate = DateTime.ParseExact(request.FAMILY[i].ENCOUNTER.TRACING[j].BOOKING_DATE, "yyyyMMdd", null);
                                            }
                                            int    consent                 = request.FAMILY[i].ENCOUNTER.TRACING[j].CONSENT;
                                            int?   ReasonNotContacted      = request.FAMILY[i].ENCOUNTER.TRACING[j].REASONNOTCONTACTED;
                                            string reasonnotcontactedOther = request.FAMILY[i].ENCOUNTER.TRACING[j].REASONNOTCONTACTEDOTHER;

                                            var trace = await encounterTestingService.addTracing(partnetPersonIdentifiers[0].PersonId, tracingType, tracingDate, mode, outcome,
                                                                                                 providerId, null, consent, tracingBookingDate, reminderDate, ReasonNotContacted, reasonnotcontactedOther);
                                        }
                                    }
                                }
                                else
                                {
                                    //Register family
                                    var person = await registerPersonService.RegisterPerson(firstName, middleName, lastName, sex, providerId, clientFacility.FacilityID, dateOfBirth, nickName : nickName);

                                    //Add afyamobile Id as an Id of the family
                                    var personIdentifier = await registerPersonService.addPersonIdentifiers(person.Id, 10, afyaMobileId, providerId);

                                    //Add family marital status
                                    var partnerMaritalStatus = await registerPersonService.AddMaritalStatus(person.Id, maritalStatusId, providerId);

                                    //add family contacts
                                    if (string.IsNullOrWhiteSpace(mobileNumber))
                                    {
                                        var partnerContacts = await registerPersonService.addPersonContact(person.Id, null, mobileNumber, null, null, providerId);
                                    }
                                    //add family location

                                    /*  if (!string.IsNullOrWhiteSpace(landmark))
                                     * {
                                     *     var partnerLocation = await registerPersonService.addPersonLocation(person.Id, 0, 0, 0, "", landmark, providerId);
                                     * }*/

                                    if (!string.IsNullOrWhiteSpace(landmark) || (county > 0) || (subcounty > 0) || (ward > 0))
                                    {
                                        var partnerLocation = await registerPersonService.UpdatePersonLocation(person.Id, landmark, ward, county, subcounty, Userid);
                                    }
                                    if (!string.IsNullOrWhiteSpace(educationlevel))
                                    {
                                        var partnereducation = await educationLevelService.UpdatePersonEducation(person.Id, educationlevel, educationoutcome, Userid);
                                    }
                                    if (!string.IsNullOrWhiteSpace(occupation))
                                    {
                                        var partneroccupation = await pocc.Update(person.Id, occupation, Userid);
                                    }
                                    //Add PersonRelationship
                                    var personRelationship = await registerPersonService.addPersonRelationship(person.Id, indexClient.Id, relationshipType, providerId);


                                    /***
                                     * Encounter
                                     */
                                    if (request.FAMILY[i].ENCOUNTER != null)
                                    {
                                        if (request.FAMILY[i].ENCOUNTER.FAMILY_SCREENING != null)
                                        {
                                            DateTime screeningDate = DateTime.ParseExact(request.FAMILY[i].ENCOUNTER.FAMILY_SCREENING.SCREENING_DATE, "yyyyMMdd", null);
                                            int      hivStatus     = request.FAMILY[i].ENCOUNTER.FAMILY_SCREENING.HIV_STATUS;
                                            int      eligible      = request.FAMILY[i].ENCOUNTER.FAMILY_SCREENING.ELIGIBLE_FOR_HTS;
                                            DateTime bookingDate   = DateTime.ParseExact(request.FAMILY[i].ENCOUNTER.FAMILY_SCREENING.BOOKING_DATE, "yyyyMMdd", null);
                                            string   remarks       = request.FAMILY[i].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(person.Id, indexClient.Id, patientMasterVisitId, null,
                                                                                                  screeningDate, bookingDate, familyScreeningList, providerId);
                                        }

                                        for (int j = 0; j < request.FAMILY[i].ENCOUNTER.TRACING.Count; j++)
                                        {
                                            var lookupitem = await _unitOfWork.Repository <LookupItemView>()
                                                             .Get(x => x.MasterName == "TracingType" && x.ItemName == "Family").ToListAsync();

                                            int tracingType = lookupitem[0].ItemId;

                                            DateTime tracingDate = DateTime.ParseExact(request.FAMILY[i].ENCOUNTER.TRACING[j].TRACING_DATE, "yyyyMMdd", null);
                                            int      mode        = request.FAMILY[i].ENCOUNTER.TRACING[j].TRACING_MODE;
                                            int      outcome     = request.FAMILY[i].ENCOUNTER.TRACING[j].TRACING_OUTCOME;

                                            DateTime?reminderDate = null;
                                            if (!string.IsNullOrWhiteSpace(request.FAMILY[i].ENCOUNTER.TRACING[j].REMINDER_DATE))
                                            {
                                                reminderDate = DateTime.ParseExact(request.FAMILY[i].ENCOUNTER.TRACING[j].REMINDER_DATE, "yyyyMMdd", null);
                                            }
                                            DateTime?tracingBookingDate = null;
                                            if (!string.IsNullOrWhiteSpace(request.FAMILY[i].ENCOUNTER.TRACING[j].BOOKING_DATE))
                                            {
                                                tracingBookingDate = DateTime.ParseExact(request.FAMILY[i].ENCOUNTER.TRACING[j].BOOKING_DATE, "yyyyMMdd", null);
                                            }
                                            int    consent                 = request.FAMILY[i].ENCOUNTER.TRACING[j].CONSENT;
                                            int?   reasonnotcontacted      = request.FAMILY[i].ENCOUNTER.TRACING[j].REASONNOTCONTACTED;
                                            string reasonnotcontactedother = request.FAMILY[i].ENCOUNTER.TRACING[j].REASONNOTCONTACTEDOTHER;

                                            var trace = await encounterTestingService.addTracing(person.Id, tracingType, tracingDate, mode, outcome,
                                                                                                 providerId, null, consent, tracingBookingDate, reminderDate, reasonnotcontacted, reasonnotcontactedother);
                                        }
                                    }
                                }
                            }

                            // update message as processed
                            await registerPersonService.UpdateAfyaMobileInbox(afyaMobileMessage.Id, indexClientAfyaMobileId, true, DateTime.Now, "success");

                            return(Result <string> .Valid(afyaMobileId));
                        }
                        catch (Exception e)
                        {
                            Log.Error(e.Message);
                            Log.Error(e.InnerException.ToString());
                            // update message as processed
                            await registerPersonService.UpdateAfyaMobileInbox(afyaMobileMessage.Id, indexClientAfyaMobileId, false, DateTime.Now, e.Message + " " + e.InnerException.ToString());

                            return(Result <string> .Invalid(e.Message));
                        }
                    }

                    return(Result <string> .Valid(afyaMobileId));
                }
        }
        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));
                }
            }
        }