コード例 #1
0
        public async Task <Result <AddUpdatePersonContactResponse> > Handle(AddUpdatePersonContactCommand request, CancellationToken cancellationToken)
        {
            try
            {
                RegisterPersonService registerPersonService = new RegisterPersonService(_unitOfWork);
                PersonContact         personContact         = await registerPersonService.GetPersonContactByPersonId(request.PersonId);

                if (personContact != null)
                {
                    await registerPersonService.UpdatePersonContact(request.PersonId, request.PhysicalAddress,
                                                                    request.MobileNumber, request.EmailAddress, request.AlternativeNumber);
                }
                else
                {
                    personContact = await registerPersonService.addPersonContact(request.PersonId,
                                                                                 request.PhysicalAddress, request.MobileNumber, request.AlternativeNumber, request.EmailAddress,
                                                                                 request.UserId);
                }

                return(Result <AddUpdatePersonContactResponse> .Valid(new AddUpdatePersonContactResponse()
                {
                    PersonContactId = personContact.Id,
                    Message = "Person Contact Successful"
                }));
            }
            catch (Exception e)
            {
                return(Result <AddUpdatePersonContactResponse> .Invalid(e.Message));
            }
        }
コード例 #2
0
        public async Task <Result <PersonContact> > Handle(UpdatePersonContactCommand request, CancellationToken cancellationToken)
        {
            using (_unitOfWork)
            {
                try
                {
                    PersonContact personContact = new PersonContact();

                    RegisterPersonService registerPersonService = new RegisterPersonService(_unitOfWork);
                    var personContactList = await registerPersonService.GetPersonContact(request.PersonId);

                    if (personContactList.Count > 0)
                    {
                        personContact = await registerPersonService.UpdatePersonContact(request.PersonId,
                                                                                        request.PhysicalAddress, request.MobileNumber);
                    }
                    else
                    {
                        personContact = await registerPersonService.addPersonContact(request.PersonId,
                                                                                     request.PhysicalAddress, request.MobileNumber, request.AlternativeNumber,
                                                                                     request.EmailAddress, request.UserId);
                    }

                    return(Result <PersonContact> .Valid(personContact));
                }
                catch (Exception e)
                {
                    Log.Error(e.Message);
                    return(Result <PersonContact> .Invalid(e.Message));
                }
            }
        }
コード例 #3
0
        public async Task <Result <AddUpdatePersonContactResponse> > Handle(AddUpdatePersonContactCommand request, CancellationToken cancellationToken)
        {
            try
            {
                RegisterPersonService rs = new RegisterPersonService(_unitOfWork);
                if (request.PersonId > 0)
                {
                    PersonContact pc = new PersonContact();
                    pc = await rs.GetPersonContactByPersonId(request.PersonId);

                    if (pc != null)
                    {
                        pc.MobileNumber      = request.MobileNumber;
                        pc.AlternativeNumber = request.AlternativeNumber;
                        pc.EmailAddress      = request.EmailAddress;
                        pc.PersonId          = request.PersonId;

                        var personcontact = await rs.UpdatePersonContact(pc.PersonId, pc.MobileNumber, pc.AlternativeNumber, pc.Id);

                        if (personcontact != null)
                        {
                            res  = personcontact.Id;
                            msg += "Person Contact Updated Successfully";
                        }
                    }
                    else
                    {
                        var personcontact = await rs.addPersonContact(request.PersonId, request.PhysicalAddress, request.MobileNumber, request.AlternativeNumber, request.EmailAddress, request.UserId);

                        if (personcontact != null)
                        {
                            res  = personcontact.Id;
                            msg += "Person Contact Added Successfully";
                        }
                    }
                }
                else
                {
                    var personcontact = await rs.addPersonContact(request.PersonId, request.PhysicalAddress, request.MobileNumber, request.AlternativeNumber, request.EmailAddress, request.UserId);

                    if (personcontact != null)
                    {
                        res  = personcontact.Id;
                        msg += "Person Contact Added Successfully";
                    }
                }


                return(Result <AddUpdatePersonContactResponse> .Valid(new AddUpdatePersonContactResponse()
                {
                    PersonContactId = res,
                    Message = msg
                }));
            }
            catch (Exception e)
            {
                return(Result <AddUpdatePersonContactResponse> .Invalid(e.Message));
            }
        }
        public async Task <Result <string> > Handle(AfyaMobileFamilyDemographicsCommand request, CancellationToken cancellationToken)
        {
            string afyaMobileId            = string.Empty;
            string indexClientAfyaMobileId = string.Empty;

            using (var trans = _unitOfWork.Context.Database.BeginTransaction())
            {
                RegisterPersonService registerPersonService = new RegisterPersonService(_unitOfWork);
                var facilityId = request.MESSAGE_HEADER.SENDING_FACILITY;

                try
                {
                    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, afyaMobileId, JsonConvert.SerializeObject(request), false);

                        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.Now;
                        try
                        {
                            dateOfBirth = DateTime.ParseExact(request.FAMILY[i].PATIENT_IDENTIFICATION.DATE_OF_BIRTH, "yyyyMMdd", null);
                        }
                        catch (Exception e)
                        {
                            Log.Error($"Could not parse family demographics DATE_OF_BIRTH: {request.FAMILY[i].PATIENT_IDENTIFICATION.DATE_OF_BIRTH} as a valid date: Incorrect format, date should be in the following format yyyyMMdd");
                            throw new Exception($"Could not parse family demographics DATE_OF_BIRTH: {request.FAMILY[i].PATIENT_IDENTIFICATION.DATE_OF_BIRTH} as a valid date: Incorrect format, date should be in the following format yyyyMMdd");
                        }

                        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    countyId    = request.FAMILY[i].PATIENT_IDENTIFICATION.PATIENT_ADDRESS.PHYSICAL_ADDRESS.COUNTY;
                        int    subCountyId = request.FAMILY[i].PATIENT_IDENTIFICATION.PATIENT_ADDRESS.PHYSICAL_ADDRESS.SUB_COUNTY;
                        int    wardId      = request.FAMILY[i].PATIENT_IDENTIFICATION.PATIENT_ADDRESS.PHYSICAL_ADDRESS.WARD;


                        int relationshipType = request.FAMILY[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);
                                }
                            }
                            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) || (countyId > 0) || (subCountyId > 0) || (wardId > 0))
                                {
                                    landmark = string.IsNullOrWhiteSpace(landmark) ? "" : landmark;
                                    var partnerLocation = await registerPersonService.addPersonLocation(person.Id, countyId, subCountyId, wardId, " ", landmark, providerId);
                                }

                                //Add PersonRelationship
                                var personRelationship = await registerPersonService.addPersonRelationship(person.Id, indexClient.Id, relationshipType, providerId);
                            }
                        }
                        else
                        {
                            //update message has been processed
                            await registerPersonService.UpdateAfyaMobileInbox(afyaMobileMessage.Id, afyaMobileId, true, DateTime.Now, $"Index clientid: {indexClientAfyaMobileId} for familyid: {afyaMobileId} not found", false);

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

                        //update message has been processed
                        await registerPersonService.UpdateAfyaMobileInbox(afyaMobileMessage.Id, afyaMobileId, true, DateTime.Now, "success", true);
                    }

                    trans.Commit();
                    return(Result <string> .Valid($"Successfully synchronized family: {afyaMobileId}"));
                }
                catch (Exception ex)
                {
                    trans.Rollback();
                    Log.Error($"Failed to synchronize family: {afyaMobileId} for clientid: {indexClientAfyaMobileId} " + ex.Message + " " + ex.InnerException);
                    return(Result <string> .Invalid($"Failed to synchronize family: {afyaMobileId} for clientid: {indexClientAfyaMobileId} " + ex.Message + " " + ex.InnerException));
                }
            }
        }
コード例 #5
0
        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));
                }
        }
コード例 #6
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));
                }
        }
コード例 #7
0
        public async Task <Result <string> > Handle(AfyaMobileSynchronizeClientsCommand request, CancellationToken cancellationToken)
        {
            string afyaMobileId = String.Empty;

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

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

                try
                {
                    var facilityId = request.MESSAGE_HEADER.SENDING_FACILITY;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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


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

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

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

                    trans.Commit();
                    return(Result <string> .Valid($"Successfully synchronized demographics for afyamobileid: {afyaMobileId}"));
                }
                catch (Exception ex)
                {
                    trans.Rollback();
                    Log.Error($"Error syncronizing afyamobileid: {afyaMobileId}. Exception Message: {ex.Message},  Inner Exception {ex.InnerException}");
                    return(Result <string> .Invalid($"Failed to synchronize clientId: {afyaMobileId} " + ex.Message + " " + ex.InnerException));
                }
            }
        }
コード例 #8
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));
                    }
                }
        }
コード例 #9
0
        public async Task <Result <string> > Handle(SynchronizeClientsCommand request, CancellationToken cancellationToken)
        {
            string afyaMobileId = String.Empty;

            using (_htsUnitOfWork)
                using (_unitOfWork)
                {
                    try
                    {
                        var facilityId = request.MESSAGE_HEADER.SENDING_FACILITY;
                        RegisterPersonService   registerPersonService   = new RegisterPersonService(_unitOfWork);
                        EncounterTestingService encounterTestingService = new EncounterTestingService(_unitOfWork, _htsUnitOfWork);
                        for (int i = 0; i < request.CLIENTS.Count; i++)
                        {
                            string   firstName       = request.CLIENTS[i].PATIENT_IDENTIFICATION.PATIENT_NAME.FIRST_NAME;
                            string   middleName      = string.IsNullOrWhiteSpace(request.CLIENTS[i].PATIENT_IDENTIFICATION.PATIENT_NAME.MIDDLE_NAME)?"": request.CLIENTS[i].PATIENT_IDENTIFICATION.PATIENT_NAME.MIDDLE_NAME;
                            string   lastName        = request.CLIENTS[i].PATIENT_IDENTIFICATION.PATIENT_NAME.LAST_NAME;
                            int      sex             = request.CLIENTS[i].PATIENT_IDENTIFICATION.SEX;
                            DateTime dateOfBirth     = DateTime.ParseExact(request.CLIENTS[i].PATIENT_IDENTIFICATION.DATE_OF_BIRTH, "yyyyMMdd", null);
                            DateTime dateEnrollment  = DateTime.ParseExact(request.CLIENTS[i].PATIENT_IDENTIFICATION.REGISTRATION_DATE, "yyyyMMdd", null);
                            int      maritalStatusId = request.CLIENTS[i].PATIENT_IDENTIFICATION.MARITAL_STATUS;
                            string   landmark        = request.CLIENTS[i].PATIENT_IDENTIFICATION.PATIENT_ADDRESS.PHYSICAL_ADDRESS
                                                       .LANDMARK;
                            string physicalAddress = request.CLIENTS[i].PATIENT_IDENTIFICATION.PATIENT_ADDRESS.POSTAL_ADDRESS;
                            string mobileNumber    = request.CLIENTS[i].PATIENT_IDENTIFICATION.PHONE_NUMBER;
                            string enrollmentNo    = string.Empty;
                            int    userId          = request.CLIENTS[i].PATIENT_IDENTIFICATION.USER_ID;

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

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

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

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

                                var updatedPerson = await registerPersonService.UpdatePerson(identifiers[0].PersonId, firstName, middleName, lastName, sex, dateOfBirth);

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

                                var updatedPatient = await registerPersonService.UpdatePatient(patient.Id, dateOfBirth, facilityId);

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

                                if (!string.IsNullOrWhiteSpace(landmark))
                                {
                                    var updatedLocation = await registerPersonService.UpdatePersonLocation(identifiers[0].PersonId, landmark);
                                }

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

                                /**
                                 * Encounter
                                 *
                                 */

                                if (request.CLIENTS[i].ENCOUNTER != null)
                                {
                                    if (request.CLIENTS[i].ENCOUNTER.PRE_TEST != null)
                                    {
                                        DateTime encounterDate     = DateTime.ParseExact(request.CLIENTS[i].ENCOUNTER.PRE_TEST.ENCOUNTER_DATE, "yyyyMMdd", null);
                                        var      emrEncounterTypes = await _unitOfWork.Repository <LookupItemView>()
                                                                     .Get(x => x.MasterName == "EncounterType" && x.ItemName == "Hts-encounter")
                                                                     .FirstOrDefaultAsync();

                                        int encounterTypeId = emrEncounterTypes.ItemId;

                                        //Get consent to testing
                                        int consentValue = request.CLIENTS[i].ENCOUNTER.PRE_TEST.CONSENT;
                                        var consentType  = await _unitOfWork.Repository <LookupItemView>().Get(x => x.MasterName == "ConsentType" && x.ItemName == "ConsentToBeTested").FirstOrDefaultAsync();

                                        int consentTypeId = consentType != null ? consentType.ItemId : 0;

                                        //Get TBStatus masterId
                                        var screeningType = await _unitOfWork.Repository <LookupItemView>().Get(x => x.MasterName == "TbScreening").FirstOrDefaultAsync();

                                        int screeningTypeId = screeningType != null ? screeningType.MasterId : 0;
                                        int tbStatus        = request.CLIENTS[i].ENCOUNTER.PRE_TEST.TB_SCREENING;

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

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

                                        string     htsEncounterRemarks  = request.CLIENTS[i].ENCOUNTER.PRE_TEST.REMARKS;
                                        int        clientEverTested     = request.CLIENTS[i].ENCOUNTER.PRE_TEST.EVER_TESTED;
                                        int        clientEverSelfTested = request.CLIENTS[i].ENCOUNTER.PRE_TEST.SELF_TEST_12_MONTHS;
                                        int        testEntryPoint       = request.CLIENTS[i].ENCOUNTER.PRE_TEST.SERVICE_POINT;
                                        int        htsencounterType     = request.CLIENTS[i].ENCOUNTER.PRE_TEST.ENCOUNTER_TYPE;
                                        int        testingStrategy      = request.CLIENTS[i].ENCOUNTER.PRE_TEST.STRATEGY;
                                        int        clientTestedAs       = request.CLIENTS[i].ENCOUNTER.PRE_TEST.TESTED_AS;
                                        int        monthsSinceLastTest  = request.CLIENTS[i].ENCOUNTER.PRE_TEST.MONTHS_SINCE_LAST_TEST;
                                        List <int> clientDisabilities   = request.CLIENTS[i].ENCOUNTER.PRE_TEST.DISABILITIES;
                                        int        providerId           = request.CLIENTS[i].ENCOUNTER.PLACER_DETAIL.PROVIDER_ID;
                                        string     encounterNumber      = request.CLIENTS[i].ENCOUNTER.PLACER_DETAIL.ENCOUNTER_NUMBER;


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

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

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

                                            getHtsEncounter.EverTested          = clientEverTested;
                                            getHtsEncounter.MonthsSinceLastTest = monthsSinceLastTest;
                                            getHtsEncounter.MonthSinceSelfTest  = null;
                                            getHtsEncounter.TestedAs            = clientTestedAs;
                                            getHtsEncounter.TestingStrategy     = testingStrategy;
                                            getHtsEncounter.EncounterRemarks    = htsEncounterRemarks;
                                            //getHtsEncounter.FinalResultGiven = ;
                                            //getHtsEncounter.CoupleDiscordant = 1;
                                            getHtsEncounter.TestEntryPoint = testEntryPoint;
                                            getHtsEncounter.EverSelfTested = clientEverSelfTested;
                                            getHtsEncounter.EncounterType  = htsencounterType;

                                            await encounterTestingService.UpdateHtsEncounter(getHtsEncounter);

                                            var getPatientScreenings = await encounterTestingService.GetPatientScreening(patient.Id, getPatientEncounter.PatientMasterVisitId, screeningTypeId, null);

                                            if (getPatientScreenings.Count > 0)
                                            {
                                                getPatientScreenings[0].ScreeningValueId = tbStatus;
                                                await encounterTestingService.UpdatePatientScreening(getPatientScreenings[0]);
                                            }
                                            else
                                            {
                                                //add patient screening
                                                var patientScreening = await encounterTestingService.addPatientScreening(patient.Id,
                                                                                                                         getPatientEncounter.PatientMasterVisitId, screeningTypeId, encounterDate, tbStatus, providerId);
                                            }

                                            await encounterTestingService.UpdateClientDisabilities(identifiers[0].PersonId, clientDisabilities, getPatientEncounter.Id, providerId);

                                            //check for hiv tests
                                            if (request.CLIENTS[i].ENCOUNTER.HIV_TESTS != null)
                                            {
                                                int             pnsAccepted        = request.CLIENTS[i].ENCOUNTER.HIV_TESTS.SUMMARY.PNS_ACCEPTED;
                                                int             pnsDeclineReason   = request.CLIENTS[i].ENCOUNTER.HIV_TESTS.SUMMARY.PNS_DECLINE_REASON;
                                                List <NewTests> screeningTests     = request.CLIENTS[i].ENCOUNTER.HIV_TESTS.SCREENING;
                                                List <NewTests> confirmatoryTests  = request.CLIENTS[i].ENCOUNTER.HIV_TESTS.CONFIRMATORY;
                                                int             coupleDiscordant   = request.CLIENTS[i].ENCOUNTER.HIV_TESTS.SUMMARY.COUPLE_DISCORDANT;
                                                int             finalResultGiven   = request.CLIENTS[i].ENCOUNTER.HIV_TESTS.SUMMARY.FINAL_RESULT_GIVEN;
                                                int             roundOneTestResult = request.CLIENTS[i].ENCOUNTER.HIV_TESTS.SUMMARY.SCREENING_RESULT;
                                                int?            roundTwoTestResult = request.CLIENTS[i].ENCOUNTER.HIV_TESTS.SUMMARY.CONFIRMATORY_RESULT;
                                                int?            finalResult        = request.CLIENTS[i].ENCOUNTER.HIV_TESTS.SUMMARY.FINAL_RESULT;

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

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

                                                    await encounterTestingService.UpdatePatientConsent(getPatientConsents[0]);
                                                }
                                                else
                                                {
                                                    //add consent to list partners
                                                    var partnersConsent = await encounterTestingService.addPatientConsent(patient.Id,
                                                                                                                          getPatientEncounter.PatientMasterVisitId, 2, pnsAccepted, consentListPartnersTypeId, encounterDate, providerId,
                                                                                                                          pnsDeclineReason);
                                                }

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

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

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

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

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

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

                                                    var updatedHtsEncounterResult = await encounterTestingService.UpdateHtsEncounterResult(getHtsEncounterResults[0]);
                                                }
                                                else
                                                {
                                                    var htsEncounterResult = await encounterTestingService.addHtsEncounterResult(getHtsEncounter.Id, roundOneTestResult, roundTwoTestResult, finalResult);
                                                }

                                                //Tracing
                                                var enrollmentTracing = await _unitOfWork.Repository <LookupItemView>()
                                                                        .Get(x => x.MasterName == "TracingType" && x.ItemName == "Enrolment").FirstOrDefaultAsync();

                                                int    tracingType    = enrollmentTracing.ItemId;
                                                string tracingRemarks = String.Empty;

                                                for (int j = 0; request.CLIENTS[i].ENCOUNTER.TRACING != null && j < request.CLIENTS[i].ENCOUNTER.TRACING.Count; j++)
                                                {
                                                    DateTime tracingDate = DateTime.ParseExact(request.CLIENTS[i].ENCOUNTER.TRACING[j].TRACING_DATE, "yyyyMMdd", null);
                                                    int      mode        = request.CLIENTS[i].ENCOUNTER.TRACING[j].TRACING_MODE;
                                                    int      outcome     = request.CLIENTS[i].ENCOUNTER.TRACING[j].TRACING_OUTCOME;

                                                    //add Client Tracing
                                                    var clientTracing = await encounterTestingService.addTracing(identifiers[0].PersonId, tracingType, tracingDate, mode, outcome,
                                                                                                                 providerId, tracingRemarks, null, null, null);
                                                }

                                                //check for linkage
                                                if (request.CLIENTS[i].ENCOUNTER.LINKAGE != null)
                                                {
                                                    DateTime dateLinkageEnrolled = DateTime.ParseExact(request.CLIENTS[i].ENCOUNTER.LINKAGE.DATE_ENROLLED, "yyyyMMdd", null);
                                                    string   linkageCCCNumber    = request.CLIENTS[i].ENCOUNTER.LINKAGE.CCC_NUMBER;
                                                    string   linkageFacility     = request.CLIENTS[i].ENCOUNTER.LINKAGE.FACILITY;
                                                    string   healthWorker        = request.CLIENTS[i].ENCOUNTER.LINKAGE.HEALTH_WORKER;
                                                    string   carde = request.CLIENTS[i].ENCOUNTER.LINKAGE.CARDE;

                                                    //add Client Linkage
                                                    var clientLinkage = await encounterTestingService.addLinkage(identifiers[0].PersonId, dateLinkageEnrolled,
                                                                                                                 linkageCCCNumber, linkageFacility, providerId, healthWorker, carde);
                                                }
                                            }
                                        }
                                        else
                                        {
                                            //add patient master visit
                                            var patientMasterVisit = await encounterTestingService.AddPatientMasterVisit(patient.Id, 2, encounterDate, providerId);

                                            //add patient encounter
                                            var patientEncounter = await encounterTestingService.AddPatientEncounter(patient.Id,
                                                                                                                     encounterTypeId, patientMasterVisit.Id, encounterDate, 2, providerId);

                                            //add patient consent
                                            var consent = await encounterTestingService.addPatientConsent(patient.Id, patientMasterVisit.Id,
                                                                                                          2, consentValue, consentTypeId, encounterDate, providerId, null);

                                            //add patient screening
                                            var patientScreening = await encounterTestingService.addPatientScreening(patient.Id,
                                                                                                                     patientMasterVisit.Id, screeningTypeId, encounterDate, tbStatus, providerId);

                                            //add patient encounter
                                            var htsEncounter = await encounterTestingService.addHtsEncounter(htsEncounterRemarks,
                                                                                                             clientEverSelfTested, clientEverTested, null,
                                                                                                             patientEncounter.Id, identifiers[0].PersonId, providerId, testEntryPoint, htsencounterType,
                                                                                                             testingStrategy, clientTestedAs, monthsSinceLastTest, null);

                                            //add disabilities
                                            var disabilities = await encounterTestingService.addDisabilities(clientDisabilities,
                                                                                                             patientEncounter.Id, identifiers[0].PersonId, providerId);

                                            //add afya mobile placer value
                                            var addplacerHtsPlacer = await registerPersonService.AddInteropPlacerValue(htsEncounter.Id, 4, 7, encounterNumber);

                                            //check for hiv tests
                                            if (request.CLIENTS[i].ENCOUNTER.HIV_TESTS != null)
                                            {
                                                int             pnsAccepted        = request.CLIENTS[i].ENCOUNTER.HIV_TESTS.SUMMARY.PNS_ACCEPTED;
                                                int             pnsDeclineReason   = request.CLIENTS[i].ENCOUNTER.HIV_TESTS.SUMMARY.PNS_DECLINE_REASON;
                                                List <NewTests> screeningTests     = request.CLIENTS[i].ENCOUNTER.HIV_TESTS.SCREENING;
                                                List <NewTests> confirmatoryTests  = request.CLIENTS[i].ENCOUNTER.HIV_TESTS.CONFIRMATORY;
                                                int             coupleDiscordant   = request.CLIENTS[i].ENCOUNTER.HIV_TESTS.SUMMARY.COUPLE_DISCORDANT;
                                                int             finalResultGiven   = request.CLIENTS[i].ENCOUNTER.HIV_TESTS.SUMMARY.FINAL_RESULT_GIVEN;
                                                int             roundOneTestResult = request.CLIENTS[i].ENCOUNTER.HIV_TESTS.SUMMARY.SCREENING_RESULT;
                                                int?            roundTwoTestResult = request.CLIENTS[i].ENCOUNTER.HIV_TESTS.SUMMARY.CONFIRMATORY_RESULT;
                                                int?            finalResult        = request.CLIENTS[i].ENCOUNTER.HIV_TESTS.SUMMARY.FINAL_RESULT;


                                                //add consent to list partners
                                                var partnersConsent = await encounterTestingService.addPatientConsent(patient.Id,
                                                                                                                      patientMasterVisit.Id, 2, pnsAccepted, consentListPartnersTypeId, encounterDate, providerId,
                                                                                                                      pnsDeclineReason);

                                                //add screening tests for client
                                                var clientScreeningTesting =
                                                    await encounterTestingService.addTesting(screeningTests, htsEncounter.Id, providerId);

                                                //add confirmatory tests for client
                                                var clientConfirmatoryTesting = await encounterTestingService.addTesting(confirmatoryTests, htsEncounter.Id, providerId);

                                                //update testing for client
                                                htsEncounter.CoupleDiscordant = coupleDiscordant;
                                                htsEncounter.FinalResultGiven = finalResultGiven;

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

                                                var htsEncounterResult = await encounterTestingService.addHtsEncounterResult(htsEncounter.Id, roundOneTestResult, roundTwoTestResult, finalResult);
                                            }


                                            //Tracing
                                            var enrollmentTracing = await _unitOfWork.Repository <LookupItemView>()
                                                                    .Get(x => x.MasterName == "TracingType" && x.ItemName == "Enrolment").FirstOrDefaultAsync();

                                            int    tracingType    = enrollmentTracing.ItemId;
                                            string tracingRemarks = String.Empty;

                                            for (int j = 0; request.CLIENTS[i].ENCOUNTER.TRACING != null && j < request.CLIENTS[i].ENCOUNTER.TRACING.Count; j++)
                                            {
                                                DateTime tracingDate = DateTime.ParseExact(request.CLIENTS[i].ENCOUNTER.TRACING[j].TRACING_DATE, "yyyyMMdd", null);
                                                int      mode        = request.CLIENTS[i].ENCOUNTER.TRACING[j].TRACING_MODE;
                                                int      outcome     = request.CLIENTS[i].ENCOUNTER.TRACING[j].TRACING_OUTCOME;

                                                //add Client Tracing
                                                var clientTracing = await encounterTestingService.addTracing(identifiers[0].PersonId, tracingType, tracingDate, mode, outcome,
                                                                                                             providerId, tracingRemarks, null, null, null);
                                            }

                                            //check for linkage
                                            if (request.CLIENTS[i].ENCOUNTER.LINKAGE != null)
                                            {
                                                DateTime dateLinkageEnrolled = DateTime.ParseExact(request.CLIENTS[i].ENCOUNTER.LINKAGE.DATE_ENROLLED, "yyyyMMdd", null);
                                                string   linkageCCCNumber    = request.CLIENTS[i].ENCOUNTER.LINKAGE.CCC_NUMBER;
                                                string   linkageFacility     = request.CLIENTS[i].ENCOUNTER.LINKAGE.FACILITY;
                                                string   healthWorker        = request.CLIENTS[i].ENCOUNTER.LINKAGE.HEALTH_WORKER;
                                                string   carde = request.CLIENTS[i].ENCOUNTER.LINKAGE.CARDE;

                                                //add Client Linkage
                                                var clientLinkage = await encounterTestingService.addLinkage(identifiers[0].PersonId, dateLinkageEnrolled,
                                                                                                             linkageCCCNumber, linkageFacility, providerId, healthWorker, carde);
                                            }

                                            //add referral

                                            /*await encounterTestingService.addReferral(person.Id, fromFacilityId: 1, serviceAreaId: 1,
                                             *  referralReason: 1, referredTo: 1, userId: 1, dateToBeEnrolled: DateTime.Now);*/
                                        }
                                    }
                                }
                            }
                            else
                            {
                                // Add Person
                                var person = await registerPersonService.RegisterPerson(firstName, middleName, lastName, sex,
                                                                                        dateOfBirth, userId);

                                // Add Patient
                                var patient = await registerPersonService.AddPatient(person.Id, userId, facilityId);

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

                                //Add PersonIdentifiers
                                var personIdentifier = await registerPersonService.addPersonIdentifiers(person.Id, 10, afyaMobileId, userId);

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

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

                                // Add Person Location
                                if (!string.IsNullOrWhiteSpace(landmark))
                                {
                                    var personLocation = await registerPersonService.addPersonLocation(person.Id, 0, 0, 0, "", landmark, userId);
                                }

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

                                /***
                                 * Encounter
                                 */

                                if (request.CLIENTS[i].ENCOUNTER != null)
                                {
                                    if (request.CLIENTS[i].ENCOUNTER.PRE_TEST != null)
                                    {
                                        DateTime encounterDate     = DateTime.ParseExact(request.CLIENTS[i].ENCOUNTER.PRE_TEST.ENCOUNTER_DATE, "yyyyMMdd", null);
                                        var      emrEncounterTypes = await _unitOfWork.Repository <LookupItemView>()
                                                                     .Get(x => x.MasterName == "EncounterType" && x.ItemName == "Hts-encounter")
                                                                     .FirstOrDefaultAsync();

                                        int encounterTypeId = emrEncounterTypes.ItemId;

                                        //Get consent to testing
                                        int consentValue = request.CLIENTS[i].ENCOUNTER.PRE_TEST.CONSENT;
                                        var consentType  = await _unitOfWork.Repository <LookupItemView>().Get(x => x.MasterName == "ConsentType" && x.ItemName == "ConsentToBeTested").FirstOrDefaultAsync();

                                        int consentTypeId = consentType != null ? consentType.ItemId : 0;

                                        //Get TBStatus masterId
                                        var screeningType = await _unitOfWork.Repository <LookupItemView>().Get(x => x.MasterName == "TbScreening").FirstOrDefaultAsync();

                                        int screeningTypeId = screeningType != null ? screeningType.MasterId : 0;
                                        int tbStatus        = request.CLIENTS[i].ENCOUNTER.PRE_TEST.TB_SCREENING;

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

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

                                        string     htsEncounterRemarks  = request.CLIENTS[i].ENCOUNTER.PRE_TEST.REMARKS;
                                        int        clientEverTested     = request.CLIENTS[i].ENCOUNTER.PRE_TEST.EVER_TESTED;
                                        int        clientEverSelfTested = request.CLIENTS[i].ENCOUNTER.PRE_TEST.SELF_TEST_12_MONTHS;
                                        int        testEntryPoint       = request.CLIENTS[i].ENCOUNTER.PRE_TEST.SERVICE_POINT;
                                        int        htsencounterType     = request.CLIENTS[i].ENCOUNTER.PRE_TEST.ENCOUNTER_TYPE;
                                        int        testingStrategy      = request.CLIENTS[i].ENCOUNTER.PRE_TEST.STRATEGY;
                                        int        clientTestedAs       = request.CLIENTS[i].ENCOUNTER.PRE_TEST.TESTED_AS;
                                        int        monthsSinceLastTest  = request.CLIENTS[i].ENCOUNTER.PRE_TEST.MONTHS_SINCE_LAST_TEST;
                                        List <int> clientDisabilities   = request.CLIENTS[i].ENCOUNTER.PRE_TEST.DISABILITIES;
                                        int        providerId           = request.CLIENTS[i].ENCOUNTER.PLACER_DETAIL.PROVIDER_ID;
                                        string     encounterNumber      = request.CLIENTS[i].ENCOUNTER.PLACER_DETAIL.ENCOUNTER_NUMBER;

                                        //add patient master visit
                                        var patientMasterVisit = await encounterTestingService.AddPatientMasterVisit(patient.Id, 2, encounterDate, providerId);

                                        //add patient encounter
                                        var patientEncounter = await encounterTestingService.AddPatientEncounter(patient.Id,
                                                                                                                 encounterTypeId, patientMasterVisit.Id, encounterDate, 2, providerId);

                                        //add patient consent
                                        var consent = await encounterTestingService.addPatientConsent(patient.Id, patientMasterVisit.Id,
                                                                                                      2, consentValue, consentTypeId, encounterDate, providerId, null);

                                        //add patient screening
                                        var patientScreening = await encounterTestingService.addPatientScreening(patient.Id,
                                                                                                                 patientMasterVisit.Id, screeningTypeId, encounterDate, tbStatus, providerId);

                                        //add patient encounter
                                        var htsEncounter = await encounterTestingService.addHtsEncounter(htsEncounterRemarks,
                                                                                                         clientEverSelfTested, clientEverTested, null,
                                                                                                         patientEncounter.Id, person.Id, providerId, testEntryPoint, htsencounterType,
                                                                                                         testingStrategy, clientTestedAs, monthsSinceLastTest, null);

                                        //add disabilities
                                        var disabilities = await encounterTestingService.addDisabilities(clientDisabilities,
                                                                                                         patientEncounter.Id, person.Id, providerId);

                                        //add afya mobile placer value
                                        var addplacerHtsPlacer = await registerPersonService.AddInteropPlacerValue(htsEncounter.Id, 4, 7, encounterNumber);

                                        //check for hiv tests
                                        if (request.CLIENTS[i].ENCOUNTER.HIV_TESTS != null)
                                        {
                                            int             pnsAccepted        = request.CLIENTS[i].ENCOUNTER.HIV_TESTS.SUMMARY.PNS_ACCEPTED;
                                            int             pnsDeclineReason   = request.CLIENTS[i].ENCOUNTER.HIV_TESTS.SUMMARY.PNS_DECLINE_REASON;
                                            List <NewTests> screeningTests     = request.CLIENTS[i].ENCOUNTER.HIV_TESTS.SCREENING;
                                            List <NewTests> confirmatoryTests  = request.CLIENTS[i].ENCOUNTER.HIV_TESTS.CONFIRMATORY;
                                            int             coupleDiscordant   = request.CLIENTS[i].ENCOUNTER.HIV_TESTS.SUMMARY.COUPLE_DISCORDANT;
                                            int             finalResultGiven   = request.CLIENTS[i].ENCOUNTER.HIV_TESTS.SUMMARY.FINAL_RESULT_GIVEN;
                                            int             roundOneTestResult = request.CLIENTS[i].ENCOUNTER.HIV_TESTS.SUMMARY.SCREENING_RESULT;
                                            int?            roundTwoTestResult = request.CLIENTS[i].ENCOUNTER.HIV_TESTS.SUMMARY.CONFIRMATORY_RESULT;
                                            int?            finalResult        = request.CLIENTS[i].ENCOUNTER.HIV_TESTS.SUMMARY.FINAL_RESULT;


                                            //add consent to list partners
                                            var partnersConsent = await encounterTestingService.addPatientConsent(patient.Id,
                                                                                                                  patientMasterVisit.Id, 2, pnsAccepted, consentListPartnersTypeId, encounterDate, providerId,
                                                                                                                  pnsDeclineReason);

                                            //add screening tests for client
                                            var clientScreeningTesting =
                                                await encounterTestingService.addTesting(screeningTests, htsEncounter.Id, providerId);

                                            //add confirmatory tests for client
                                            var clientConfirmatoryTesting = await encounterTestingService.addTesting(confirmatoryTests, htsEncounter.Id, providerId);

                                            //update testing for client
                                            htsEncounter.CoupleDiscordant = coupleDiscordant;
                                            htsEncounter.FinalResultGiven = finalResultGiven;

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

                                            var htsEncounterResult = await encounterTestingService.addHtsEncounterResult(htsEncounter.Id, roundOneTestResult, roundTwoTestResult, finalResult);
                                        }

                                        //Tracing
                                        var enrollmentTracing = await _unitOfWork.Repository <LookupItemView>()
                                                                .Get(x => x.MasterName == "TracingType" && x.ItemName == "Enrolment").FirstOrDefaultAsync();

                                        int    tracingType    = enrollmentTracing.ItemId;
                                        string tracingRemarks = String.Empty;

                                        for (int j = 0; request.CLIENTS[i].ENCOUNTER.TRACING != null && j < request.CLIENTS[i].ENCOUNTER.TRACING.Count; j++)
                                        {
                                            DateTime tracingDate = DateTime.ParseExact(request.CLIENTS[i].ENCOUNTER.TRACING[j].TRACING_DATE, "yyyyMMdd", null);
                                            int      mode        = request.CLIENTS[i].ENCOUNTER.TRACING[j].TRACING_MODE;
                                            int      outcome     = request.CLIENTS[i].ENCOUNTER.TRACING[j].TRACING_OUTCOME;

                                            //add Client Tracing
                                            var clientTracing = await encounterTestingService.addTracing(person.Id, tracingType, tracingDate, mode, outcome,
                                                                                                         providerId, tracingRemarks, null, null, null);
                                        }

                                        //check for linkage
                                        if (request.CLIENTS[i].ENCOUNTER.LINKAGE != null)
                                        {
                                            DateTime dateLinkageEnrolled = DateTime.ParseExact(request.CLIENTS[i].ENCOUNTER.LINKAGE.DATE_ENROLLED, "yyyyMMdd", null);
                                            string   linkageCCCNumber    = request.CLIENTS[i].ENCOUNTER.LINKAGE.CCC_NUMBER;
                                            string   linkageFacility     = request.CLIENTS[i].ENCOUNTER.LINKAGE.FACILITY;
                                            string   healthWorker        = request.CLIENTS[i].ENCOUNTER.LINKAGE.HEALTH_WORKER;
                                            string   carde = request.CLIENTS[i].ENCOUNTER.LINKAGE.CARDE;

                                            //add Client Linkage
                                            var clientLinkage = await encounterTestingService.addLinkage(person.Id, dateLinkageEnrolled,
                                                                                                         linkageCCCNumber, linkageFacility, providerId, healthWorker, carde);
                                        }

                                        //add referral

                                        /*await encounterTestingService.addReferral(person.Id, fromFacilityId: 1, serviceAreaId: 1,
                                         *  referralReason: 1, referredTo: 1, userId: 1, dateToBeEnrolled: DateTime.Now);*/
                                    }
                                }
                            }
                        }

                        return(Result <string> .Valid(afyaMobileId));
                    }
                    catch (Exception e)
                    {
                        Log.Error(e.Message);
                        return(Result <string> .Invalid(e.Message));
                    }
                }
        }