コード例 #1
0
        public async Task <Result <AddPatientResponse> > Handle(AddPatientCommand request, CancellationToken cancellationToken)
        {
            try
            {
                using (_unitOfWork)
                {
                    //var sqlPatient = "exec pr_OpenDecryptedSession;" +
                    //                 "Insert Into  Patient(ptn_pk,PersonId,PatientIndex,PatientType,FacilityId,Active,DateOfBirth,NationalId,DeleteFlag,CreatedBy,CreateDate,AuditData,DobPrecision)" +
                    //                 $"Values(0, {request.PersonId}, {DateTime.Now.Year + '-' + request.PersonId}, 258, 13028, 1," +
                    //                 $"'{request.DateOfBirth.ToString("yyyy-MM-dd")}', ENCRYPTBYKEY(KEY_GUID('Key_CTC'), '99999999'), 0, 1, GETDATE()," +
                    //                 $"NULL, 1);" +
                    //                 $"SELECT [Id],[ptn_pk],[PersonId],[PatientIndex],[PatientType],[FacilityId],[Active],[DateOfBirth]," +
                    //                 $"[DobPrecision],CAST(DECRYPTBYKEY(NationalId) AS VARCHAR(50)) [NationalId],[DeleteFlag],[CreatedBy]," +
                    //                 $"[CreateDate],[AuditData],[RegistrationDate] FROM [dbo].[Patient] WHERE Id = SCOPE_IDENTITY();" +
                    //                 $"exec [dbo].[pr_CloseDecryptedSession];";

                    //var patientInsert = await _unitOfWork.Repository<Patient>().FromSql(sqlPatient);

                    RegisterPersonService registerPersonService = new RegisterPersonService(_unitOfWork);
                    var patient = await registerPersonService.AddPatient(request.PersonId, request.DateOfBirth, request.UserId);

                    _unitOfWork.Dispose();

                    return(Result <AddPatientResponse> .Valid(new AddPatientResponse()
                    {
                        PatientId = patient.Id
                    }));
                }
            }
            catch (Exception e)
            {
                return(Result <AddPatientResponse> .Invalid(e.Message));
            }
        }
コード例 #2
0
        public async Task <Result <AddPatientResponse> > Handle(AddPatientCommand request, CancellationToken cancellationToken)
        {
            try
            {
                using (_unitOfWork)
                {
                    RegisterPersonService registerPersonService = new RegisterPersonService(_unitOfWork);

                    var registeredPerson = await registerPersonService.GetPerson(request.PersonId);

                    var gender = await _unitOfWork.Repository <LookupItemView>().Get(x => x.ItemId == registeredPerson.Sex && x.MasterName == "Gender")
                                 .ToListAsync();

                    var maritalStatus = await registerPersonService.GetPersonMaritalStatus(request.PersonId);

                    var maritalStatusName = "Single";
                    if (maritalStatus.Count > 0)
                    {
                        var matList = await _unitOfWork.Repository <LookupItemView>()
                                      .Get(x => x.ItemId == maritalStatus[0].MaritalStatusId && x.MasterName == "MaritalStatus").ToListAsync();

                        if (matList.Count > 0)
                        {
                            maritalStatusName = matList[0].ItemName;
                        }
                    }

                    var mstResult = await registerPersonService.InsertIntoBlueCard(registeredPerson.FirstName, registeredPerson.LastName,
                                                                                   registeredPerson.LastName, request.EnrollmentDate, maritalStatusName, "", "", gender[0].ItemName, "EXACT", registeredPerson.DateOfBirth, request.UserId, request.PosId);

                    var patient = await registerPersonService.AddPatient(request.PersonId, request.UserId, mstResult[0].Ptn_Pk);


                    return(Result <AddPatientResponse> .Valid(new AddPatientResponse()
                    {
                        PatientId = patient.Id
                    }));
                }
            }
            catch (Exception e)
            {
                return(Result <AddPatientResponse> .Invalid(e.Message));
            }
        }
コード例 #3
0
        public async Task <Result <AddPatientResponse> > Handle(AddPatientCommand request, CancellationToken cancellationToken)
        {
            try
            {
                using (_unitOfWork)
                {
                    RegisterPersonService registerPersonService = new RegisterPersonService(_unitOfWork);
                    var patient = await registerPersonService.AddPatient(request.PersonId, request.UserId);

                    return(Result <AddPatientResponse> .Valid(new AddPatientResponse()
                    {
                        PatientId = patient.Id
                    }));
                }
            }
            catch (Exception e)
            {
                return(Result <AddPatientResponse> .Invalid(e.Message));
            }
        }
コード例 #4
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));
                }
            }
        }
コード例 #5
0
        public async Task <Result <SynchronizeClientsResponse> > 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      = 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    providerId      = request.CLIENTS[i].ENCOUNTER.PLACER_DETAIL.PROVIDER_ID;

                            for (int j = 0; j < request.CLIENTS[j].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)
                            {
                            }
                            else
                            {
                                // Add Person
                                var person = await registerPersonService.RegisterPerson(firstName, middleName, lastName, sex,
                                                                                        dateOfBirth, providerId);

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

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

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

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

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

                                // Add Person Location
                                var personLocation =
                                    await registerPersonService.addPersonLocation(person.Id, 0, 0, 0, "", landmark, providerId);

                                //add Person Contact
                                var personContact = await registerPersonService.addPersonContact(person.Id, physicalAddress,
                                                                                                 mobileNumber, string.Empty, string.Empty, providerId);


                                /***
                                 * Encounter
                                 */

                                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 == "ConsentToListPartners").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             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;
                                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;

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

                                int      tracingType    = enrollmentTracing.ItemId;
                                DateTime tracingDate    = DateTime.ParseExact(request.CLIENTS[i].ENCOUNTER.TRACING.TRACING_DATE, "yyyyMMdd", null);
                                int      mode           = request.CLIENTS[i].ENCOUNTER.TRACING.TRACING_MODE;
                                int      outcome        = request.CLIENTS[i].ENCOUNTER.TRACING.TRACING_OUTCOME;
                                string   tracingRemarks = String.Empty;

                                //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 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);

                                //add referral

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

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

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

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