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));
            }
        }
        public async Task <Result <AddPersonLocationResponse> > Handle(AddPersonLocationCommand request, CancellationToken cancellationToken)
        {
            try
            {
                using (_unitOfWork)
                {
                    //PersonLocation personLocation = new PersonLocation()
                    //{
                    //    PersonId = request.PersonId,
                    //    County = request.CountyId,
                    //    SubCounty = request.SubCountyId,
                    //    Ward = request.WardId,
                    //    Village = request.Village,
                    //    Location = "",
                    //    SubLocation = "",
                    //    LandMark = request.LandMark,
                    //    NearestHealthCentre = "",
                    //    Active = false,
                    //    DeleteFlag = false,
                    //    CreateDate = DateTime.Now,
                    //    CreatedBy = request.UserId
                    //};

                    //await _unitOfWork.Repository<PersonLocation>().AddAsync(personLocation);
                    //await _unitOfWork.SaveAsync();

                    RegisterPersonService personService = new RegisterPersonService(_unitOfWork);
                    var personLocation = await personService.addPersonLocation(request.PersonId, request.CountyId,
                                                                               request.SubCountyId, request.WardId, request.Village, request.LandMark, request.UserId);

                    _unitOfWork.Dispose();

                    return(Result <AddPersonLocationResponse> .Valid(new AddPersonLocationResponse()
                    {
                        PersonLocationId = personLocation.Id
                    }));
                }
            }
            catch (Exception e)
            {
                return(Result <AddPersonLocationResponse> .Invalid(e.Message));
            }
        }
        public async Task <Result <AddPersonEducationalLevelResponse> > Handle(PersonEducationLevelCommand request, CancellationToken cancellationToken)
        {
            try {
                RegisterPersonService rs = new RegisterPersonService(_unitOfWork);
                if (request.PersonId > 0)
                {
                    PersonEducation pme = new PersonEducation();
                    pme = await rs.GetCurrentPersonEducation(request.PersonId);

                    if (pme != null)
                    {
                        pme.EducationLevel = request.EducationalLevel;
                        pme.CreatedBy      = request.UserId;
                        await Task.Run(() => rs.UpdatePersonEducation(pme));

                        msg += "Person Educatin updated successfully";
                    }
                    else
                    {
                        PersonEducation ped = new PersonEducation();
                        ped.PersonId       = request.PersonId;
                        ped.CreatedBy      = request.UserId;
                        ped.EducationLevel = request.EducationalLevel;
                        var peducation = await Task.Run(() => rs.AddPersonEducation(ped));

                        if (peducation != null)
                        {
                            msg = "PersonEducationalLevel added successfully for personId" + request.PersonId;
                        }
                    }
                }


                return(Result <AddPersonEducationalLevelResponse> .Valid(new AddPersonEducationalLevelResponse()
                {
                    Message = msg
                }));
            }

            catch (Exception e) {
                return(Result <AddPersonEducationalLevelResponse> .Invalid(e.Message));
            }
        }
        public async Task <Result <GetPersonIdentificationResponse> > Handle(GetPersonIdentificationCommand request, CancellationToken cancellationToken)
        {
            try
            {
                RegisterPersonService rs     = new RegisterPersonService(_unitOfWork);
                List <Identifier>     result = new List <Identifier>();
                result = await Task.Run(() => rs.GetPersonIdentifierType(request.CodeName));


                return(Result <GetPersonIdentificationResponse> .Valid(new GetPersonIdentificationResponse()
                {
                    Identifers = result
                }));
            }
            catch (Exception ex)
            {
                return(Result <GetPersonIdentificationResponse> .Invalid(ex.Message));
            }
        }
Exemplo n.º 5
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));
            }
        }
Exemplo n.º 6
0
        public async Task <Result <AddPersonOccupationLevelResponse> > Handle(PersonOccupationLevelCommand request, CancellationToken cancellationToken)
        {
            try
            {
                RegisterPersonService sc = new RegisterPersonService(_unitOfWork);
                if (request.PersonId > 0)
                {
                    PersonOccupation pmo = new PersonOccupation();
                    pmo = await Task.Run(() => sc.GetCurrentOccupation(request.PersonId));

                    if (pmo != null)
                    {
                        pmo.DeleteFlag = true;
                        var pm = await Task.Run(() => sc.UpdateOccupation(pmo));

                        // var AddedPersonOcc = await Task.Run(() => sc.AddPersonOccupation(request.PersonId, request.UserId, request.Occupation));
                        if (pm != null)
                        {
                            msg = "PersonOccupation Updated successfully";
                        }
                    }
                    else
                    {
                        var AddedPersonOcc = await Task.Run(() => sc.AddPersonOccupation(request.PersonId, request.UserId, request.Occupation));

                        if (AddedPersonOcc != null)
                        {
                            msg = "PersonOccupation Added  successfully for personId" + request.PersonId;
                        }
                    }
                }
                return(Result <AddPersonOccupationLevelResponse> .Valid(new AddPersonOccupationLevelResponse()
                {
                    Message = msg
                }));
            }
            catch (Exception e)
            {
                return(Result <AddPersonOccupationLevelResponse> .Invalid(e.Message));
            }
        }
Exemplo n.º 7
0
        public async Task <Library.Result <EnrolledServicesResponse> > Handle(GetEnrolledServicesCommand request, CancellationToken cancellationToken)
        {
            using (_unitOfWork)
            {
                try
                {
                    RegisterPersonService    registerPersonService = new RegisterPersonService(_unitOfWork);
                    List <PatientEnrollment> result             = new List <PatientEnrollment>();
                    List <PatientIdentifier> patientIdentifiers = new List <PatientIdentifier>();
                    List <Identifier>        identifiers        = new List <Identifier>();

                    var patient = await registerPersonService.GetPatientByPersonId(request.PersonId);

                    if (patient != null)
                    {
                        result = await _unitOfWork.Repository <PatientEnrollment>().Get(x => x.PatientId == patient.Id).ToListAsync();

                        patientIdentifiers = await _unitOfWork.Repository <PatientIdentifier>().Get(x => x.PatientId == patient.Id).ToListAsync();
                    }

                    var allIdentifiers = await _unitOfWork.Repository <Identifier>().GetAllAsync();

                    identifiers = allIdentifiers.ToList();

                    return(Library.Result <EnrolledServicesResponse> .Valid(new EnrolledServicesResponse()
                    {
                        PersonEnrollmentList = result,
                        PatientIdentifiers = patientIdentifiers,
                        Identifiers = identifiers
                    }));
                }
                catch (Exception e)
                {
                    Log.Error(e.Message + " " + e.InnerException);
                    return(Library.Result <EnrolledServicesResponse> .Invalid(e.Message));
                }
            }
        }
        public async Task <Result <PersonRegistrationResponse> > Handle(PersonRegistrationCommand request, CancellationToken cancellationToken)
        {
            try
            {
                using (_unitOfWork)
                {
                    Person person = new Person();
                    RegisterPersonService registerPersonService = new RegisterPersonService(_unitOfWork);
                    Facility clientFacility = await _unitOfWork.Repository <Facility>().Get(x => x.PosID == request.Person.PosId.ToString()).FirstOrDefaultAsync();

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

                    if (!request.Person.Id.HasValue)
                    {
                        person = await registerPersonService.RegisterPerson(request.Person.FirstName, request.Person.MiddleName,
                                                                            request.Person.LastName, request.Person.Sex, request.Person.CreatedBy, clientFacility.FacilityID, request.Person.DateOfBirth,
                                                                            request.Person.RegistrationDate, request.Person.NickName, request.Person.DobPrecision);
                    }
                    else
                    {
                        person = await registerPersonService.UpdatePerson(request.Person.Id.Value,
                                                                          request.Person.FirstName, request.Person.MiddleName, request.Person.LastName,
                                                                          request.Person.Sex, request.Person.DateOfBirth, clientFacility.FacilityID, request.Person.RegistrationDate, request.Person.DobPrecision, request.Person.NickName);
                    }

                    _unitOfWork.Dispose();
                    return(Result <PersonRegistrationResponse> .Valid(new PersonRegistrationResponse { PersonId = person.Id, Message = "Success" }));
                }
            }
            catch (Exception e)
            {
                Log.Error(e.Message + " " + e.InnerException);
                return(Result <PersonRegistrationResponse> .Invalid(e.Message + " " + e.InnerException));
            }
        }
        public async Task <Result <PatientARVHistory> > Handle(GetPatientARVHistoryCommand request, CancellationToken cancellationToken)
        {
            using (_unitOfWork)
            {
                try
                {
                    RegisterPersonService rs = new RegisterPersonService(_unitOfWork);

                    var Patient = await rs.GetPatientByPersonId(request.PersonId);

                    if (Patient != null)
                    {
                        PatientId = Patient.Id;
                    }
                    var enrollmentVisitType = await _unitOfWork.Repository <LookupItemView>().Get(x => x.MasterName == "VisitType" && x.ItemName == "Enrollment").FirstOrDefaultAsync();

                    int?visitType = enrollmentVisitType != null ? enrollmentVisitType.ItemId : 0;

                    var enrollmentPatientMasterVisit =
                        await _unitOfWork.Repository <Core.Models.PatientMasterVisit>().Get(x =>
                                                                                            x.PatientId == PatientId && x.ServiceId == request.ServiceId && x.VisitType == visitType).ToListAsync();

                    if (enrollmentPatientMasterVisit.Count > 0)
                    {
                        PatientMasterVisitId = enrollmentPatientMasterVisit[0].Id;
                    }
                    var aRVHistory = await rs.GetPatientARVHistory(PatientId, PatientMasterVisitId);



                    return(Result <PatientARVHistory> .Valid(aRVHistory));
                }
                catch (Exception ex)
                {
                    return(Result <PatientARVHistory> .Invalid(ex.Message));
                }
            }
        }
        public async Task <Result <List <IQCare.Common.Core.Models.PatientMasterVisit> > > Handle(GetEnrollmentMasterVisitCommand request, CancellationToken cancellationToken)
        {
            try
            {
                using (_unitOfWork)
                {
                    int PatientMasterVisitId = 0;
                    RegisterPersonService registerPersonService = new RegisterPersonService(_unitOfWork);
                    var enrollmentVisitType = await _unitOfWork.Repository <LookupItemView>().Get(x => x.MasterName == "VisitType" && x.ItemName == "Enrollment").FirstOrDefaultAsync();

                    int?visitType = enrollmentVisitType != null ? enrollmentVisitType.ItemId : 0;

                    var enrollmentPatientMasterVisit =
                        await _unitOfWork.Repository <Core.Models.PatientMasterVisit>().Get(x =>
                                                                                            x.PatientId == request.PatientId && x.ServiceId == request.ServiceAreaId && x.VisitType == visitType && x.DeleteFlag == false).OrderByDescending(x => x.Id).ToListAsync();

                    return(Result <List <IQCare.Common.Core.Models.PatientMasterVisit> > .Valid(enrollmentPatientMasterVisit));
                }
            }
            catch (Exception ex)
            {
                return(Result <List <IQCare.Common.Core.Models.PatientMasterVisit> > .Invalid(ex.Message));
            }
        }
Exemplo n.º 11
0
        public async Task <Result <string> > Handle(AfyaMobileSynchronizeHtsTestsCommand request, CancellationToken cancellationToken)
        {
            string afyaMobileId = String.Empty;

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

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

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

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

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

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

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

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

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

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

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

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

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

                                await encounterTestingService.UpdatePatientConsent(getPatientConsents[0]);


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

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

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

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

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

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

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

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

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

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

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

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

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


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

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

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

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

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

                    trans.Commit();
                    return(Result <string> .Valid($"Successfully synchronized HTS tests for afyamobileid: {afyaMobileId}"));
                }
                catch (Exception ex)
                {
                    trans.Rollback();
                    Log.Error($"Failed to synchronize Hts tests for clientid: {afyaMobileId} " + ex.Message + " " + ex.InnerException);
                    return(Result <string> .Invalid($"Failed to synchronize Hts tests for clientid: {afyaMobileId} " + ex.Message + " " + ex.InnerException));
                }
            }
        }
        public async Task <Result <SynchronizePartnersResponse> > Handle(SynchronizePartnersCommand request, CancellationToken cancellationToken)
        {
            using (_htsUnitOfWork)
                using (_unitOfWork)
                {
                    try
                    {
                        RegisterPersonService registerPersonService = new RegisterPersonService(_unitOfWork);

                        var facilityId = request.MESSAGE_HEADER.SENDING_FACILITY;
                        for (int i = 0; i < request.PARTNERS.Count; i++)
                        {
                            string afyaMobileId            = string.Empty;
                            string indexClientAfyaMobileId = string.Empty;

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

                            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;

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

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

                                //Register Partner
                                var person = await registerPersonService.RegisterPerson(firstName, middleName, lastName, sex, dateOfBirth, providerId);

                                //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
                                var partnerContacts = await registerPersonService.addPersonContact(person.Id, null,
                                                                                                   mobileNumber, null, null, providerId);

                                //add partner location
                                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
                                 */
                            }
                        }

                        return(Result <SynchronizePartnersResponse> .Valid(new SynchronizePartnersResponse()
                        {
                        }));
                    }
                    catch (Exception e)
                    {
                        return(Result <SynchronizePartnersResponse> .Invalid(e.Message));
                    }
                }
        }
        public async Task <Result <string> > Handle(SynchronizePartnersCommand request, CancellationToken cancellationToken)
        {
            using (_htsUnitOfWork)
                using (_unitOfWork)
                {
                    string afyaMobileId            = string.Empty;
                    string indexClientAfyaMobileId = string.Empty;

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

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

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

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

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

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

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

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

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

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

                                if (partnetPersonIdentifiers.Count > 0)
                                {
                                    await registerPersonService.UpdatePerson(partnetPersonIdentifiers[0].PersonId, firstName, middleName, lastName, sex, dateOfBirth, clientFacility.FacilityID);

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

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

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

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

                                    /***
                                     * Encounter
                                     */

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

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

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

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

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

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

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

                                        int tracingType = tracingLookup.FirstOrDefault().ItemId;

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

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

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

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

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

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

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


                                    /***
                                     * Encounter
                                     */

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

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

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

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

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

                                            var partnHtsScreenings = await encounterTestingService.AddPartnerScreening(person.Id, indexClient.Id, patientMasterVisitId, partnerOccupation,
                                                                                                                       screeningDate, bookingDate, newScreenings, providerId);
                                        }

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

                                        int tracingType = tracingLookup.FirstOrDefault().ItemId;

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

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

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

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

                    return(Result <string> .Valid(afyaMobileId));
                }
        }
Exemplo n.º 14
0
        public async Task <Result <PersonRegistrationResponse> > Handle(PersonRegistrationCommand request, CancellationToken cancellationToken)
        {
            try
            {
                Client c = new Client();
                c.FirstName     = request.Person.FirstName;
                c.LastName      = request.Person.LastName;
                c.MiddleName    = request.Person.MiddleName;
                c.LastName      = request.Person.LastName;
                c.MaritalStatus = request.Person.MaritalStatus;
                c.Sex           = request.Person.Sex;
                c.PersonId      = request.Person.PersonId;
                c.CreatedBy     = request.Person.CreatedBy;
                c.DateOfBirth   = request.Person.DateOfBirth;
                c.DobPrecision  = request.Person.DobPrecision;
                RegisterPersonService rs = new RegisterPersonService(_unitOfWork);
                int PerId;


                if (!String.IsNullOrEmpty(c.PersonId.ToString()))
                {
                    PerId = Convert.ToInt32(c.PersonId.ToString());

                    if (PerId > 0)
                    {
                        var result = await Task.Run(() => rs.UpdatePerson(PerId, c.FirstName, c.MiddleName, c.LastName, c.Sex, c.CreatedBy, c.DateOfBirth, c.DobPrecision));

                        PId = result.Id;
                        msg = String.Format("Person with the PersonId: {0} updated successfully", PId);
                        var _marStatus = await Task.Run(() => rs.GetFirstPatientMaritalStatus(PerId));

                        if (_marStatus != null && c.MaritalStatus > 0)
                        {
                            //_marStatus.DeleteFlag = true;
                            var maritalStatus = await Task.Run(() => rs.UpdateMaritalStatus(_marStatus));

                            // var finalupdatestatus = await Task.Run(() => rs.AddMaritalStatus(PerId, c.MaritalStatus, c.CreatedBy));
                            if (maritalStatus != null)
                            {
                                msg += "PersonMaritalStatus Updated Successfully";
                            }
                        }
                        else if (_marStatus != null && c.MaritalStatus == 0)
                        {
                            _marStatus.DeleteFlag = true;
                            var maritalStatus = await Task.Run(() => rs.UpdateMaritalStatus(_marStatus));

                            if (maritalStatus.DeleteFlag == true)
                            {
                                msg += "Person MaritalStatus Updated Successfully";
                            }
                        }
                        else
                        {
                            if (c.MaritalStatus > 0)
                            {
                                var finalupdatestatus = await Task.Run(() => rs.AddMaritalStatus(PerId, c.MaritalStatus, c.CreatedBy));

                                if (finalupdatestatus != null)
                                {
                                    msg += "PersonMaritalStatus Added Successfully!";
                                }
                            }
                        }
                    }
                }
                else
                {
                    var reg = rs.RegisterPerson(c.FirstName, c.MiddleName, c.LastName, c.Sex, c.DateOfBirth, c.CreatedBy, c.DobPrecision);
                    if (reg != null && reg.Id > 0)
                    {
                        int perId = reg.Id;
                        PId  = reg.Id;
                        msg += String.Format("New Person Added Successsfully:PersonId=>,{0}", reg.Id);
                        if (c.MaritalStatus > 0)
                        {
                            var mar = rs.AddMaritalStatus(perId, c.MaritalStatus, c.CreatedBy);
                            if (mar != null)
                            {
                                msg += "Person Marital Status added successfully";
                            }
                        }
                    }
                }



                _unitOfWork.Dispose();

                return(Result <PersonRegistrationResponse> .Valid(new PersonRegistrationResponse { PersonId = PId, Message = msg }));
            }
            catch (Exception e)
            {
                // msg = e.Message;
                return(Result <PersonRegistrationResponse> .Invalid(e.Message));
            }
        }
Exemplo n.º 15
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));
                }
        }
Exemplo n.º 16
0
        public async Task <Result <string> > Handle(SynchronizeFamilyCommand request, CancellationToken cancellationToken)
        {
            using (_htsUnitOfWork)
                using (_unitOfWork)
                {
                    try
                    {
                        string afyaMobileId            = string.Empty;
                        string indexClientAfyaMobileId = string.Empty;

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

                        var facilityId = request.MESSAGE_HEADER.SENDING_FACILITY;

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

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

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

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

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

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

                                if (partnetPersonIdentifiers.Count > 0)
                                {
                                    await registerPersonService.UpdatePerson(partnetPersonIdentifiers[0].PersonId, firstName, middleName, lastName, sex, dateOfBirth);

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

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

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

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

                                    /***
                                     * Encounter
                                     */
                                    if (request.FAMILY[i].ENCOUNTER != null)
                                    {
                                        if (request.FAMILY[i].ENCOUNTER.FAMILY_SCREENING != null)
                                        {
                                            DateTime screeningDate = DateTime.ParseExact(request.FAMILY[i].ENCOUNTER.FAMILY_SCREENING.SCREENING_DATE, "yyyyMMdd", null);
                                            int      hivStatus     = request.FAMILY[i].ENCOUNTER.FAMILY_SCREENING.HIV_STATUS;
                                            int      eligible      = request.FAMILY[i].ENCOUNTER.FAMILY_SCREENING.ELIGIBLE_FOR_HTS;
                                            DateTime bookingDate   = DateTime.ParseExact(request.FAMILY[i].ENCOUNTER.FAMILY_SCREENING.BOOKING_DATE, "yyyyMMdd", null);
                                            string   remarks       = request.FAMILY[i].ENCOUNTER.FAMILY_SCREENING.REMARKS;

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

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

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

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

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

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

                                            int tracingType = lookupitem[0].ItemId;

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

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

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

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

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

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


                                    /***
                                     * Encounter
                                     */
                                    if (request.FAMILY[i].ENCOUNTER != null)
                                    {
                                        if (request.FAMILY[i].ENCOUNTER.FAMILY_SCREENING != null)
                                        {
                                            DateTime screeningDate = DateTime.ParseExact(request.FAMILY[i].ENCOUNTER.FAMILY_SCREENING.SCREENING_DATE, "yyyyMMdd", null);
                                            int      hivStatus     = request.FAMILY[i].ENCOUNTER.FAMILY_SCREENING.HIV_STATUS;
                                            int      eligible      = request.FAMILY[i].ENCOUNTER.FAMILY_SCREENING.ELIGIBLE_FOR_HTS;
                                            DateTime bookingDate   = DateTime.ParseExact(request.FAMILY[i].ENCOUNTER.FAMILY_SCREENING.BOOKING_DATE, "yyyyMMdd", null);
                                            string   remarks       = request.FAMILY[i].ENCOUNTER.FAMILY_SCREENING.REMARKS;

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

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

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

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

                                            var familyScreeningReturnValue =
                                                await encounterTestingService.AddPartnerScreening(person.Id, indexClient.Id, patientMasterVisitId, null,
                                                                                                  screeningDate, bookingDate, familyScreeningList, providerId);
                                        }

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

                                            int tracingType = lookupitem[0].ItemId;

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

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

                                            var trace = await encounterTestingService.addTracing(person.Id, tracingType, tracingDate, mode, outcome,
                                                                                                 providerId, null, consent, tracingBookingDate, reminderDate);
                                        }
                                    }
                                }
                            }
                        }
                        return(Result <string> .Valid(afyaMobileId));
                    }
                    catch (Exception e)
                    {
                        return(Result <string> .Invalid(e.Message));
                    }
                }
        }
Exemplo n.º 17
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));
                    }
                }
        }
Exemplo n.º 18
0
        public async Task <Result <AddPersonEmergencyContactResponse> > Handle(PersonEmergencyContactCommand request, CancellationToken cancellationToken)
        {
            try
            {
                RegisterPersonService rs = new RegisterPersonService(_unitOfWork);

                if (request.PersonId > 0)
                {
                    if (request.EmergencyContactPersonId > 0)
                    {
                        PersonEmergencyContact pme = new PersonEmergencyContact();
                        pme = await Task.Run(() => rs.GetSpecificEmergencyContacts(Convert.ToInt32(request.EmergencyContactPersonId), request.PersonId));

                        if (pme != null)
                        {
                            pme.PersonId = request.PersonId;
                            pme.EmergencyContactPersonId = request.EmergencyContactPersonId;
                            pme.MobileContact            = request.MobileContact;
                            pme.CreatedBy  = request.CreatedBy;
                            pme.DeleteFlag = request.DeleteFlag;


                            int res = await Task.Run(() => rs.UpdatePersonEmergencyContact(pme));

                            if (res > 0)
                            {
                                msg += "Person Emergency Mobile Contact Updated Successfully";
                                personEmergencyContactId = request.EmergencyContactPersonId;
                            }
                            var personconsent = await Task.Run(() => rs.GetCurrentPersonConsent(pme.Id, Convert.ToInt32(request.PersonId)));

                            if (personconsent != null)
                            {
                                personconsent.ConsentType   = request.ConsentType;
                                personconsent.ConsentValue  = request.ConsentValue;
                                personconsent.ConsentDate   = DateTime.Now;
                                personconsent.ConsentReason = request.ConsentReason;

                                int consent = await Task.Run(() => rs.UpdatePersonConsent(personconsent));

                                if (consent > 0)
                                {
                                    msg += "Person Consent has been updated successfully";
                                }
                            }
                            else
                            {
                                PersonConsent pcs = new PersonConsent();
                                pcs.PersonId           = request.PersonId;
                                pcs.EmergencyContactId = pme.Id;
                                pcs.ConsentType        = request.ConsentType;
                                pcs.ConsentValue       = request.ConsentValue;
                                pcs.ConsentDate        = DateTime.Now;
                                pcs.ConsentReason      = request.ConsentReason;

                                var perc = await Task.Run(() => rs.AddPersonConsent(pcs));

                                if (perc != null)
                                {
                                    msg += "Person Consent Has been added successfully";
                                }
                            }



                            Person per = new Person();

                            per.FirstName = request.firstname;
                            per.MidName   = request.middlename;
                            per.LastName  = request.lastname;
                            per.Sex       = request.gender;
                            per.Id        = request.EmergencyContactPersonId;


                            int resupda = await Task.Run(() => rs.UpdatePerson(per, request.EmergencyContactPersonId));

                            if (resupda > 0)
                            {
                                msg += "PersonEmergencyContact updated successfully";
                            }
                        }
                    }
                }


                else
                {
                    var personEmerg = await Task.Run(() => rs.InsertPerson(request.firstname, request.middlename, request.lastname, request.gender, request.CreatedBy));

                    if (personEmerg != null)
                    {
                        personEmergencyContactId = personEmerg.Id;
                        PersonEmergencyContact pmm = new PersonEmergencyContact()
                        {
                            PersonId = request.PersonId,
                            EmergencyContactPersonId = personEmerg.Id,
                            MobileContact            = request.MobileContact,
                            CreatedBy  = request.CreatedBy,
                            DeleteFlag = request.DeleteFlag
                        };

                        int pmeid = await Task.Run(() => rs.AddPersonEmergencyContact(pmm));

                        if (pmeid > 0)
                        {
                            msg += "New Person Emergencycontact Added successfully";
                        }

                        PersonConsent pcs = new PersonConsent();
                        pcs.PersonId           = request.PersonId;
                        pcs.EmergencyContactId = pmeid;
                        pcs.ConsentType        = request.ConsentType;
                        pcs.ConsentValue       = request.ConsentValue;
                        pcs.ConsentDate        = DateTime.Now;
                        pcs.ConsentReason      = request.ConsentReason;

                        var perc = await Task.Run(() => rs.AddPersonConsent(pcs));

                        if (perc != null)
                        {
                            msg += "Person Consent Has been added successfully";
                        }


                        PersonRelation pl        = new PersonRelation();
                        var            personrel = await Task.Run(() => rs.AddPersonRelationship(request.PersonId, personEmerg.Id, request.RelationshipType, request.CreatedBy));

                        if (personrel != null)
                        {
                            msg += "Person EmergencyContact relationship added successfully";
                        }
                    }
                }



                return(Result <AddPersonEmergencyContactResponse> .Valid(new AddPersonEmergencyContactResponse()
                {
                    Message = msg,
                    PersonEmergencyContactId = personEmergencyContactId
                }));
            }

            catch (Exception e)
            {
                return(Result <AddPersonEmergencyContactResponse> .Invalid(e.Message));
            }
        }
Exemplo n.º 19
0
        public async Task <Result <string> > Handle(AfyaMobileFamilyTracingEncounterCommand request, CancellationToken cancellationToken)
        {
            string afyaMobileId            = string.Empty;
            string indexClientAfyaMobileId = string.Empty;

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

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

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

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

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

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

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

                        if (partnetPersonIdentifiers.Count > 0)
                        {
                            for (int j = 0; j < request.TRACING_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.Now;
                                try
                                {
                                    tracingDate = DateTime.ParseExact(request.TRACING_ENCOUNTER.TRACING[j].TRACING_DATE, "yyyyMMdd", null);
                                }
                                catch (Exception e)
                                {
                                    Log.Error($"Could not parse family tracing TRACING_DATE: {request.TRACING_ENCOUNTER.TRACING[j].TRACING_DATE} as a valid date: Incorrect format, date should be in the following format yyyyMMdd");
                                    throw new Exception($"Could not parse family tracing TRACING_DATE: {request.TRACING_ENCOUNTER.TRACING[j].TRACING_DATE} as a valid date: Incorrect format, date should be in the following format yyyyMMdd");
                                }
                                int mode    = request.TRACING_ENCOUNTER.TRACING[j].TRACING_MODE;
                                int outcome = request.TRACING_ENCOUNTER.TRACING[j].TRACING_OUTCOME;

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

                                int?   reasonnotcontacted      = request.TRACING_ENCOUNTER.TRACING[j].REASONNOTCONTACTED;
                                string reasonnotcontactedother = request.TRACING_ENCOUNTER.TRACING[j].REASONNOTCONTACTEDOTHER;
                                var    trace = await encounterTestingService.addTracing(partnetPersonIdentifiers[0].PersonId, tracingType, tracingDate, mode, outcome,
                                                                                        1, null, consent, tracingBookingDate, reminderDate, reasonnotcontacted, reasonnotcontactedother);
                            }
                        }
                        else
                        {
                            //update message has been processed
                            await registerPersonService.UpdateAfyaMobileInbox(afyaMobileMessage.Id, afyaMobileId, true, DateTime.Now, $"Family member with afyamobileid: {afyaMobileId} could not be found", false);

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

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

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

                    trans.Commit();
                    return(Result <string> .Valid($"Successfully synchronized family tracing for afyamobileid: {afyaMobileId}"));
                }
                catch (Exception ex)
                {
                    trans.Rollback();
                    Log.Error($"Failed to synchronize family tracing for clientId: {afyaMobileId} " + ex.Message + " " + ex.InnerException);
                    return(Result <string> .Invalid($"Failed to synchronize family tracing for clientId: {afyaMobileId} " + ex.Message + " " + ex.InnerException));
                }
            }
        }
Exemplo n.º 20
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));
                }
            }
        }
Exemplo n.º 21
0
        public async Task <Result <EnrollClientResponse> > Handle(EnrollClientCommand request, CancellationToken cancellationToken)
        {
            try
            {
                RegisterPersonService registerPersonService = new RegisterPersonService(_unitOfWork);
                var patientIdentifier = await registerPersonService.EnrollPatient(request.ClientEnrollment.EnrollmentNo,
                                                                                  request.ClientEnrollment.PatientId, request.ClientEnrollment.ServiceAreaId,
                                                                                  request.ClientEnrollment.CreatedBy, request.ClientEnrollment.DateOfEnrollment);

                return(Result <EnrollClientResponse> .Valid(new EnrollClientResponse()
                {
                    IdentifierId = patientIdentifier.Id,
                    IdentifierValue = request.ClientEnrollment.EnrollmentNo
                }));
            }
            catch (Exception e)
            {
                Log.Error(e.Message);
                return(Result <EnrollClientResponse> .Invalid(e.Message));
            }
            //using (var trans = _unitOfWork.Context.Database.BeginTransaction())
            //{
            //    try
            //    {
            //        var previouslyIdentifiers = await _unitOfWork.Repository<PatientIdentifier>().Get(y =>
            //                y.IdentifierValue == request.ClientEnrollment.EnrollmentNo && y.IdentifierTypeId == 8)
            //            .ToListAsync();

            //        if (previouslyIdentifiers.Count > 0)
            //        {
            //            var exception = new Exception("No: " + request.ClientEnrollment.EnrollmentNo + " already exists");
            //            throw exception;
            //        }

            //        var enrollmentVisitType = await _unitOfWork.Repository<LookupItemView>().Get(x => x.MasterName == "VisitType" && x.ItemName == "Enrollment").FirstOrDefaultAsync();
            //        int? visitType = enrollmentVisitType != null ? enrollmentVisitType.ItemId : 0;
            //        var patientMasterVisit = new PatientMasterVisit()
            //        {
            //            PatientId = request.ClientEnrollment.PatientId,
            //            ServiceId = request.ClientEnrollment.ServiceAreaId,
            //            Start = DateTime.Now,
            //            End = null,
            //            Active = false,
            //            VisitDate = DateTime.Now,
            //            VisitType = visitType,
            //            Status = 1,
            //            CreateDate = DateTime.Now,
            //            DeleteFlag = false,
            //            CreatedBy = request.ClientEnrollment.CreatedBy
            //        };

            //        await _unitOfWork.Repository<PatientMasterVisit>().AddAsync(patientMasterVisit);
            //        await _unitOfWork.SaveAsync();

            //        var patientEnrollment = new PatientEnrollment()
            //        {
            //            PatientId = request.ClientEnrollment.PatientId,
            //            ServiceAreaId = request.ClientEnrollment.ServiceAreaId,
            //            EnrollmentDate = request.ClientEnrollment.DateOfEnrollment,
            //            EnrollmentStatusId = 0,
            //            TransferIn = false,
            //            CareEnded = false,
            //            DeleteFlag = false,
            //            CreatedBy = request.ClientEnrollment.CreatedBy,
            //            CreateDate = DateTime.Now

            //        };

            //        await _unitOfWork.Repository<PatientEnrollment>().AddAsync(patientEnrollment);
            //        await _unitOfWork.SaveAsync();

            //        var patientIdentifier = new PatientIdentifier()
            //        {
            //            PatientId = request.ClientEnrollment.PatientId,
            //            PatientEnrollmentId = patientEnrollment.Id,
            //            IdentifierTypeId = 8,
            //            IdentifierValue = request.ClientEnrollment.EnrollmentNo,
            //            DeleteFlag = false,
            //            CreatedBy = request.ClientEnrollment.CreatedBy,
            //            CreateDate = DateTime.Now,
            //            Active = true

            //        };

            //        await _unitOfWork.Repository<PatientIdentifier>().AddAsync(patientIdentifier);
            //        await _unitOfWork.SaveAsync();

            //        GetPatientDetails patientDetails = new GetPatientDetails(_unitOfWork);
            //        LookupLogic lookupLogic = new LookupLogic(_unitOfWork);

            //        var patientLookup = await patientDetails.GetPatientByPatientId(request.ClientEnrollment.PatientId);

            //        if (patientLookup.Count > 0)
            //        {
            //            Facility facility = await _unitOfWork.Repository<Facility>().Get(x => x.DeleteFlag == 0).FirstOrDefaultAsync();
            //            var referralId = await lookupLogic.GetDecodeIdByName("VCT", 17);
            //            var maritalStatusId = await lookupLogic.GetDecodeIdByName(patientLookup[0].MaritalStatusName, 17);
            //            var address = patientLookup[0].PhysicalAddress == null ? " " : patientLookup[0].PhysicalAddress;
            //            var phone = patientLookup[0].MobileNumber == null ? " " : patientLookup[0].MobileNumber;
            //            var dobPrecision = patientLookup[0].DobPrecision ? 1 : 0;

            //            var gender = 0;
            //            if (patientLookup[0].Gender == "Male")
            //            {
            //                gender = 16;
            //            }
            //            else if (patientLookup[0].Gender == "Female")
            //            {
            //                gender = 17;
            //            }

            //            StringBuilder sql = new StringBuilder();
            //            sql.Append("exec pr_OpenDecryptedSession;");
            //            sql.Append("Insert Into mst_Patient(FirstName, LastName, MiddleName, LocationID, PatientEnrollmentID, ReferredFrom, RegistrationDate, Sex, DOB, DobPrecision, MaritalStatus, Address, Phone, UserID, PosId, Status, DeleteFlag, CreateDate,MovedToPatientTable)");
            //            sql.Append("Values(");
            //            sql.Append($"ENCRYPTBYKEY(KEY_GUID('Key_CTC'),'{patientLookup[0].FirstName}'),");
            //            sql.Append($"ENCRYPTBYKEY(KEY_GUID('Key_CTC'),'{patientLookup[0].LastName}'),");
            //            sql.Append($"ENCRYPTBYKEY(KEY_GUID('Key_CTC'),'{patientLookup[0].MidName}'),");
            //            sql.Append($"'{facility.FacilityID}',");
            //            sql.Append("' ',");
            //            sql.Append($"'{referralId}',");
            //            sql.Append($"'{request.ClientEnrollment.DateOfEnrollment.ToString("yyyy-MM-dd")}',");
            //            sql.Append($"'{gender}',");
            //            sql.Append($"'{patientLookup[0].DateOfBirth.ToString("yyyy-MM-dd")}',");
            //            sql.Append($"'{dobPrecision}',");
            //            sql.Append($"'{maritalStatusId}',");
            //            sql.Append($"ENCRYPTBYKEY(KEY_GUID('Key_CTC'),'{address}'),");
            //            sql.Append($"ENCRYPTBYKEY(KEY_GUID('Key_CTC'),'{phone}'),");
            //            sql.Append($"'{request.ClientEnrollment.CreatedBy}',");
            //            sql.Append($"'{facility.PosID}',");
            //            sql.Append("0,");
            //            sql.Append("0,");
            //            sql.Append($"'{request.ClientEnrollment.DateOfEnrollment.ToString("yyyy-MM-dd")}',");
            //            sql.Append("1");
            //            sql.Append(");");

            //            sql.Append("SELECT Ptn_Pk, CAST(DECRYPTBYKEY([FirstName]) AS VARCHAR(50)) AS FirstName, CAST(DECRYPTBYKEY([LastName]) AS VARCHAR(50)) AS LastName, LocationID FROM [dbo].[mst_Patient] WHERE [Ptn_Pk] = SCOPE_IDENTITY();");
            //            sql.Append("exec [dbo].[pr_CloseDecryptedSession];");

            //            var result = await _unitOfWork.Repository<MstPatient>().FromSql(sql.ToString());

            //            StringBuilder sqlBuilder = new StringBuilder();
            //            sqlBuilder.Append("Insert Into Lnk_PatientProgramStart(Ptn_pk, ModuleId, StartDate, UserID, CreateDate)");
            //            sqlBuilder.Append("Values(");
            //            sqlBuilder.Append($"'{result[0].Ptn_Pk}',");
            //            sqlBuilder.Append("283,");
            //            sqlBuilder.Append($"'{request.ClientEnrollment.DateOfEnrollment.ToString("yyyy-MM-dd")}',");
            //            sqlBuilder.Append($"'{request.ClientEnrollment.CreatedBy}',");
            //            sqlBuilder.Append($"'{request.ClientEnrollment.DateOfEnrollment.ToString("yyyy-MM-dd")}'");
            //            sqlBuilder.Append(");");

            //            var insertResult = await _unitOfWork.Context.Database.ExecuteSqlCommandAsync(sqlBuilder.ToString());

            //            StringBuilder sqlPatient = new StringBuilder();
            //            sqlPatient.Append($"UPDATE Patient SET ptn_pk = '{result[0].Ptn_Pk}' WHERE Id = '{request.ClientEnrollment.PatientId}';");
            //            var updateResult = await _unitOfWork.Context.Database.ExecuteSqlCommandAsync(sqlPatient.ToString());
            //        }

            //        trans.Commit();

            //        _unitOfWork.Dispose();

            //        return Result<EnrollClientResponse>.Valid(new EnrollClientResponse
            //        {
            //            IdentifierValue = request.ClientEnrollment.EnrollmentNo,
            //            IdentifierId = patientIdentifier.Id
            //        });
            //    }
            //    catch (Exception ex)
            //    {
            //        trans.Rollback();
            //        return Result<EnrollClientResponse>.Invalid(ex.Message);
            //    }
            //}
        }
Exemplo n.º 22
0
        public async Task <Result <string> > Handle(AfyaMobileSynchronizeLinkageCommand request, CancellationToken cancellationToken)
        {
            string afyaMobileId = String.Empty;

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

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

                    int providerId = request.PLACER_DETAIL.PROVIDER_ID;
                    //check if person already exists
                    var identifiers = await registerPersonService.getPersonIdentifiers(afyaMobileId, 10);

                    if (identifiers.Count > 0)
                    {
                        DateTime dateLinkageEnrolled = DateTime.Now;
                        try
                        {
                            dateLinkageEnrolled = DateTime.ParseExact(request.LINKAGE.DATE_ENROLLED, "yyyyMMdd", null);
                        }
                        catch (Exception e)
                        {
                            Log.Error($"Could not parse linkage DATE_ENROLLED: {request.LINKAGE.DATE_ENROLLED} as a valid date: Incorrect format, date should be in the following format yyyyMMdd");
                            throw new Exception($"Could not parse linkage DATE_ENROLLED: {request.LINKAGE.DATE_ENROLLED} as a valid date: Incorrect format, date should be in the following format yyyyMMdd");
                        }
                        string linkageCCCNumber = request.LINKAGE.CCC_NUMBER;
                        string linkageFacility  = request.LINKAGE.FACILITY;
                        string healthWorker     = request.LINKAGE.HEALTH_WORKER;
                        string carde            = request.LINKAGE.CARDE;
                        string ARTStartDate     = request.LINKAGE.ARTStartDate;
                        string remarks          = request.LINKAGE.REMARKS;

                        DateTime?artstartDate = null;
                        if (!string.IsNullOrWhiteSpace(ARTStartDate))
                        {
                            try
                            {
                                artstartDate = DateTime.ParseExact(ARTStartDate, "yyyyMMdd", null);
                            }
                            catch (Exception e)
                            {
                                Log.Error($"Could not parse linkage ARTStartDate: {request.LINKAGE.ARTStartDate} as a valid date: Incorrect format, date should be in the following format yyyyMMdd");
                                throw new Exception($"Could not parse linkage ARTStartDate: {request.LINKAGE.ARTStartDate} as a valid date: Incorrect format, date should be in the following format yyyyMMdd");
                            }
                        }

                        var previousLinkage = await encounterTestingService.GetPersonLinkage(identifiers[0].PersonId);

                        if (previousLinkage.Count > 0)
                        {
                            previousLinkage[0].ArtStartDate = artstartDate;
                            previousLinkage[0].LinkageDate  = dateLinkageEnrolled;
                            previousLinkage[0].CCCNumber    = linkageCCCNumber;
                            previousLinkage[0].Facility     = linkageFacility;
                            previousLinkage[0].HealthWorker = healthWorker;
                            previousLinkage[0].Cadre        = carde;
                            previousLinkage[0].Comments     = remarks;

                            await encounterTestingService.UpdatePersonLinkage(previousLinkage[0]);
                        }
                        else
                        {
                            //add Client Linkage
                            var clientLinkage = await encounterTestingService.AddLinkage(identifiers[0].PersonId, dateLinkageEnrolled,
                                                                                         linkageCCCNumber, linkageFacility, providerId, healthWorker, carde, remarks, artstartDate);
                        }
                    }
                    else
                    {
                        //update message has been processed
                        await registerPersonService.UpdateAfyaMobileInbox(afyaMobileMessage.Id, afyaMobileId, true, DateTime.Now, $"Person with afyaMobileId: {afyaMobileId} could not be found", false);

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

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

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

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

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

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

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

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

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

                        var searchFacility = await encounterTestingService.SearchFacility(facilityReferred);

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

                        var facility = await encounterTestingService.GetCurrentFacility();

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

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

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

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

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

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

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

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

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

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

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

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

                    int    tracingType    = enrollmentTracing.ItemId;
                    int    providerId     = request.PLACER_DETAIL.PROVIDER_ID;
                    string tracingRemarks = String.Empty;

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

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

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

                        //check for client tracing
                        for (int j = 0; (request.TRACING != null && j < request.TRACING.Count); j++)
                        {
                            DateTime tracingDate = DateTime.Now;
                            try
                            {
                                tracingDate = DateTime.ParseExact(request.TRACING[j].TRACING_DATE, "yyyyMMdd", null);
                            }
                            catch (Exception e)
                            {
                                Log.Error($"Could not parse tracing TRACING_DATE: {request.TRACING[j].TRACING_DATE} as a valid date: Incorrect format, date should be in the following format yyyyMMdd");
                                throw new Exception($"Could not parse tracing TRACING_DATE: {request.TRACING[j].TRACING_DATE} as a valid date: Incorrect format, date should be in the following format yyyyMMdd");
                            }
                            int    mode                    = request.TRACING[j].TRACING_MODE;
                            int    outcome                 = request.TRACING[j].TRACING_OUTCOME;
                            int?   reasonnotcontacted      = request.TRACING[j].REASONNOTCONTACTED;
                            string reasonnotcontactedother = request.TRACING[j].REASONNOTCONTACTEDOTHER;

                            //add Client Tracing
                            var clientTracing = await encounterTestingService.addTracing(person.Id, tracingType,
                                                                                         tracingDate, mode, outcome,
                                                                                         providerId, tracingRemarks, null, null, null, reasonnotcontacted, reasonnotcontactedother);
                        }
                    }
                    else
                    {
                        //update message has been processed
                        await registerPersonService.UpdateAfyaMobileInbox(afyaMobileMessage.Id, afyaMobileId, true, DateTime.Now, $"Person with afyaMobileId: {afyaMobileId} could not be found", false);

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

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

                    trans.Commit();
                    return(Result <string> .Valid($"Successfully synchronized HTS Tracing for afyamobileid: {afyaMobileId}"));
                }
                catch (Exception ex)
                {
                    trans.Rollback();
                    Log.Error($"Failed to synchronize Hts Tracing for clientid: {afyaMobileId} " + ex.Message + " " + ex.InnerException);
                    return(Result <string> .Invalid($"Failed to synchronize Hts Tracing for clientid: {afyaMobileId} " + ex.Message + " " + ex.InnerException));
                }
            }
        }
        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));
                }
            }
        }
        public async Task <Result <AddPatientARVHistoryResponse> > Handle(AddPatientARVHistoryCommand request, CancellationToken cancellationToken)
        {
            try
            {
                using (_unitOfWork)
                {
                    int Id = 0;
                    int PatientMasterVisitId = 0;

                    RegisterPersonService rs = new RegisterPersonService(_unitOfWork);

                    var enrollmentVisitType = await _unitOfWork.Repository <LookupItemView>().Get(x => x.MasterName == "VisitType" && x.ItemName == "Enrollment").FirstOrDefaultAsync();

                    int?visitType = enrollmentVisitType != null ? enrollmentVisitType.ItemId : 0;

                    var enrollmentPatientMasterVisit =
                        await _unitOfWork.Repository <Core.Models.PatientMasterVisit>().Get(x =>
                                                                                            x.PatientId == request.PatientId && x.ServiceId == request.ServiceId && x.VisitType == visitType).ToListAsync();

                    if (enrollmentPatientMasterVisit.Count > 0)
                    {
                        PatientMasterVisitId = enrollmentPatientMasterVisit[0].Id;
                        var previousPatientEnrollment = await _unitOfWork.Repository <PatientEnrollment>().Get(x =>
                                                                                                               x.PatientId == request.PatientId && x.ServiceAreaId == request.ServiceId && x.DeleteFlag == false)
                                                        .ToListAsync();

                        if (previousPatientEnrollment.Count > 0)
                        {
                            var PatientARVHistory = await rs.GetPatientARVHistory(request.PatientId, PatientMasterVisitId);

                            if (PatientARVHistory != null)
                            {
                                PatientARVHistory.Purpose = request.Purpose;
                                PatientARVHistory.Regimen = request.Regimen;
                                // PatientARVHistory.Months = request.Months;
                                PatientARVHistory.InitiationDate = request.InitiationDate;
                                PatientARVHistory.TreatmentType  = request.TreatmentType;
                                PatientARVHistory.DateLastUsed   = request.DateLastUsed;
                                //PatientARVHistory.Weeks = request.Weeks;
                                PatientARVHistory.Months = request.Months;


                                var results = await rs.UpdatePatientARVHistory(PatientARVHistory);

                                Id = results.Id;
                            }
                            else
                            {
                                PatientARVHistory part = new PatientARVHistory();
                                part.Purpose        = request.Purpose;
                                part.CreateDate     = DateTime.Now;
                                part.CreatedBy      = request.CreatedBy;
                                part.DeleteFlag     = request.DeleteFlag;
                                part.Months         = request.Months;
                                part.InitiationDate = request.InitiationDate;
                                // part.Weeks = request.Weeks;
                                part.Purpose       = request.Purpose;
                                part.Regimen       = request.Regimen;
                                part.TreatmentType = request.TreatmentType;
                                part.DateLastUsed  = request.DateLastUsed;

                                part.PatientId            = request.PatientId;
                                part.PatientMasterVisitId = PatientMasterVisitId;

                                var results = await rs.AddPatientARVHistory(part);

                                Id = results.Id;
                            }
                        }
                    }
                    return(Result <AddPatientARVHistoryResponse> .Valid(new AddPatientARVHistoryResponse()
                    {
                        ARVHistoryId = Id
                    }));
                }
            }
            catch (Exception ex)
            {
                return(Result <AddPatientARVHistoryResponse> .Invalid(ex.Message));
            }
        }
Exemplo n.º 27
0
        public async Task <Result <AddPersonEmergencyContactResponse> > Handle(PersonEmergencyContactCommand request, CancellationToken cancellationToken)
        {
            try
            {
                RegisterPersonService rs = new RegisterPersonService(_unitOfWork);
                if (request.emergencycontacts != null || request.emergencycontacts.Count > 0)
                {
                    foreach (EmergencyContact em in request.emergencycontacts)
                    {
                        if (em.PersonId > 0)
                        {
                            if (em.EmergencyContactPersonId > 0)
                            {
                                PersonEmergencyContact pme = new PersonEmergencyContact();
                                PersonEmergencyContact pmt = new PersonEmergencyContact();
                                if (em.emgEmergencyContactType > 0)
                                {
                                    pme = await rs.GetSpecificEmergencyContacts(Convert.ToInt32(em.EmergencyContactPersonId), em.PersonId);

                                    //pmt = await rs.GetNextofkinEmergencyContacts(Convert.ToInt32(em.EmergencyContactPersonId), em.PersonId);
                                    if (pme != null)
                                    {
                                        pme.PersonId = em.PersonId;
                                        pme.EmergencyContactPersonId = em.EmergencyContactPersonId;
                                        pme.MobileContact            = em.MobileContact;
                                        pme.CreatedBy   = em.CreatedBy;
                                        pme.DeleteFlag  = em.DeleteFlag;
                                        pme.ContactType = em.emgEmergencyContactType;

                                        pme.RegisteredToClinic = em.RegisteredToClinic;

                                        int res = await rs.UpdatePersonEmergencyContact(pme);

                                        if (res > 0)
                                        {
                                            msg += "Person Emergency Mobile Contact Updated Successfully";
                                            personEmergencyContactId = em.EmergencyContactPersonId;
                                        }
                                    }
                                    else
                                    {
                                        PersonEmergencyContact pmm = new PersonEmergencyContact()
                                        {
                                            PersonId = em.PersonId,
                                            EmergencyContactPersonId = em.EmergencyContactPersonId,
                                            MobileContact            = em.MobileContact,
                                            CreatedBy          = em.CreatedBy,
                                            DeleteFlag         = em.DeleteFlag,
                                            ContactType        = em.emgEmergencyContactType,
                                            RegisteredToClinic = em.RegisteredToClinic
                                        };

                                        PersonEmergencyContact pmeid = new PersonEmergencyContact();
                                        pmeid = await rs.AddPersonEmergencyContact(pmm);

                                        if (pmeid != null)
                                        {
                                            msg += "New Person Emergencycontact Added successfully";
                                        }
                                    }
                                    var personconsent = await rs.GetCurrentPersonConsent(em.EmergencyContactPersonId, Convert.ToInt32(em.PersonId));

                                    if (personconsent != null)
                                    {
                                        personconsent.ConsentType   = em.ConsentType;
                                        personconsent.ConsentValue  = em.ConsentValue;
                                        personconsent.ConsentDate   = DateTime.Now;
                                        personconsent.ConsentReason = em.ConsentReason;

                                        int consent = await rs.UpdatePersonConsent(personconsent);

                                        if (consent > 0)
                                        {
                                            msg += "Person Consent has been updated successfully";
                                        }
                                    }
                                    else
                                    {
                                        PersonConsent pcs = new PersonConsent();
                                        pcs.PersonId           = em.PersonId;
                                        pcs.EmergencyContactId = em.EmergencyContactPersonId;
                                        pcs.ConsentType        = em.ConsentType;
                                        pcs.ConsentValue       = em.ConsentValue;
                                        pcs.ConsentDate        = DateTime.Now;
                                        pcs.ConsentReason      = em.ConsentReason;

                                        var perc = await rs.AddPersonConsent(pcs);

                                        if (perc != null)
                                        {
                                            msg += "Person Consent Has been added successfully";
                                        }
                                    }



                                    Person per = new Person();

                                    per.FirstName = em.firstname;
                                    per.MidName   = em.middlename;
                                    per.LastName  = em.lastname;
                                    per.Sex       = em.gender;
                                    per.Id        = em.EmergencyContactPersonId;


                                    var resupd = await rs.UpdateEmergencyPerson(per);

                                    if (resupd != null)
                                    {
                                        msg += "PersonEmergencyContact updated successfully";
                                    }
                                }
                                if (em.emgNextofKinContactType > 0)
                                {
                                    pmt = await rs.GetNextofkinEmergencyContacts(Convert.ToInt32(em.EmergencyContactPersonId), em.PersonId);

                                    if (pmt != null)
                                    {
                                        pmt.PersonId = em.PersonId;
                                        pmt.EmergencyContactPersonId = em.EmergencyContactPersonId;
                                        pmt.MobileContact            = em.MobileContact;
                                        pmt.CreatedBy   = em.CreatedBy;
                                        pmt.DeleteFlag  = em.DeleteFlag;
                                        pmt.ContactType = em.emgNextofKinContactType;

                                        pmt.RegisteredToClinic = em.RegisteredToClinic;

                                        int res = await rs.UpdatePersonEmergencyContact(pmt);

                                        if (res > 0)
                                        {
                                            msg += "Person Emergency Mobile Contact Updated Successfully";
                                            personEmergencyContactId = em.EmergencyContactPersonId;
                                        }
                                    }
                                    else
                                    {
                                        PersonEmergencyContact pmm = new PersonEmergencyContact()
                                        {
                                            PersonId = em.PersonId,
                                            EmergencyContactPersonId = em.EmergencyContactPersonId,
                                            MobileContact            = em.MobileContact,
                                            CreatedBy          = em.CreatedBy,
                                            DeleteFlag         = em.DeleteFlag,
                                            ContactType        = em.emgEmergencyContactType,
                                            RegisteredToClinic = em.RegisteredToClinic
                                        };

                                        PersonEmergencyContact pmeid = new PersonEmergencyContact();
                                        pmeid = await rs.AddPersonEmergencyContact(pmm);

                                        if (pmeid != null)
                                        {
                                            msg += "New Person Emergencycontact Added successfully";
                                        }
                                    }
                                    var personconsent = await rs.GetCurrentPersonConsent(em.EmergencyContactPersonId, Convert.ToInt32(em.PersonId));

                                    if (personconsent != null)
                                    {
                                        personconsent.ConsentType   = em.ConsentType;
                                        personconsent.ConsentValue  = em.ConsentValue;
                                        personconsent.ConsentDate   = DateTime.Now;
                                        personconsent.ConsentReason = em.ConsentReason;

                                        int consent = await rs.UpdatePersonConsent(personconsent);

                                        if (consent > 0)
                                        {
                                            msg += "Person Consent has been updated successfully";
                                        }
                                    }
                                    else
                                    {
                                        if (em.ConsentValue > 0)
                                        {
                                            PersonConsent pcs = new PersonConsent();
                                            pcs.PersonId           = em.PersonId;
                                            pcs.EmergencyContactId = pme.Id;
                                            pcs.ConsentType        = em.ConsentType;
                                            pcs.ConsentValue       = em.ConsentValue;
                                            pcs.ConsentDate        = DateTime.Now;
                                            pcs.ConsentReason      = em.ConsentReason;

                                            var perc = await rs.AddPersonConsent(pcs);

                                            if (perc != null)
                                            {
                                                msg += "Person Consent Has been added successfully";
                                            }
                                        }
                                    }



                                    Person per = new Person();

                                    per.FirstName = em.firstname;
                                    per.MidName   = em.middlename;
                                    per.LastName  = em.lastname;
                                    per.Sex       = em.gender;
                                    per.Id        = em.EmergencyContactPersonId;


                                    var resupda = await rs.UpdateEmergencyPerson(per);

                                    if (resupda != null)
                                    {
                                        msg += "PersonEmergencyContact updated successfully";
                                    }
                                }
                            }
                            else
                            {
                                var personEmerg = await rs.InsertPerson(em.firstname, em.middlename, em.lastname, em.gender, em.CreatedBy);

                                if (personEmerg != null)
                                {
                                    personEmergencyContactId = personEmerg.Id;
                                    if (em.emgEmergencyContactType > 0)
                                    {
                                        PersonEmergencyContact pmm = new PersonEmergencyContact()
                                        {
                                            PersonId = em.PersonId,
                                            EmergencyContactPersonId = personEmerg.Id,
                                            MobileContact            = em.MobileContact,
                                            CreatedBy          = em.CreatedBy,
                                            DeleteFlag         = em.DeleteFlag,
                                            ContactType        = em.emgEmergencyContactType,
                                            RegisteredToClinic = em.RegisteredToClinic
                                        };

                                        PersonEmergencyContact pmeid = new PersonEmergencyContact();
                                        pmeid = await rs.AddPersonEmergencyContact(pmm);

                                        if (pmeid != null)
                                        {
                                            msg += "New Person Emergencycontact Added successfully";
                                        }
                                    }
                                    if (em.emgNextofKinContactType > 0)
                                    {
                                        PersonEmergencyContact pmm = new PersonEmergencyContact()
                                        {
                                            PersonId = em.PersonId,
                                            EmergencyContactPersonId = personEmerg.Id,
                                            MobileContact            = em.MobileContact,
                                            CreatedBy          = em.CreatedBy,
                                            DeleteFlag         = em.DeleteFlag,
                                            ContactType        = em.emgNextofKinContactType,
                                            RegisteredToClinic = em.RegisteredToClinic
                                        };

                                        PersonEmergencyContact pmeid = new PersonEmergencyContact();
                                        pmeid = await rs.AddPersonEmergencyContact(pmm);

                                        if (pmeid != null)
                                        {
                                            msg += "New Person Emergencycontact Added successfully";
                                        }
                                    }
                                    if (em.ConsentValue > 0)
                                    {
                                        PersonConsent pcs = new PersonConsent();
                                        pcs.PersonId           = em.PersonId;
                                        pcs.EmergencyContactId = personEmergencyContactId;
                                        pcs.ConsentType        = em.ConsentType;
                                        pcs.ConsentValue       = em.ConsentValue;
                                        pcs.ConsentDate        = DateTime.Now;
                                        pcs.ConsentReason      = em.ConsentReason;

                                        var perc = await rs.AddPersonConsent(pcs);

                                        if (perc != null)
                                        {
                                            msg += "Person Consent Has been added successfully";
                                        }
                                    }
                                    PersonRelationship pl = new PersonRelationship();
                                    var personrel         = await rs.AddPersonRelationship(em.PersonId, personEmerg.Id, em.RelationshipType, em.CreatedBy);

                                    if (personrel != null)
                                    {
                                        msg += "Person EmergencyContact relationship added successfully";
                                    }
                                }
                            }
                        }
                    }
                }



                return(Result <AddPersonEmergencyContactResponse> .Valid(new AddPersonEmergencyContactResponse()
                {
                    Message = msg,
                    PersonEmergencyContactId = personEmergencyContactId
                }));
            }
            catch (Exception e)
            {
                return(Result <AddPersonEmergencyContactResponse> .Invalid(e.Message));
            }
        }
        public async Task <Result <AddPersonEmergencyContactResponse> > Handle(PersonEmergencyContactCommand request, CancellationToken cancellationToken)
        {
            try
            {
                RegisterPersonService registerPersonService = new RegisterPersonService(_unitOfWork);
                PersonContactsService personContactsService = new PersonContactsService(_unitOfWork);

                for (int i = 0; i < request.Emergencycontact.Count; i++)
                {
                    Facility clientFacility = await _unitOfWork.Repository <Facility>().Get(x => x.PosID == request.Emergencycontact[i].PosId.ToString()).FirstOrDefaultAsync();

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

                    int emergencyPersonId = 0;
                    if (request.Emergencycontact[i].RegisteredPersonId > 0)
                    {
                        emergencyPersonId = request.Emergencycontact[i].RegisteredPersonId;
                    }
                    else
                    {
                        //add new person
                        var contactPerson = await registerPersonService.RegisterPerson(request.Emergencycontact[i].Firstname, request.Emergencycontact[i].Middlename,
                                                                                       request.Emergencycontact[i].Lastname, request.Emergencycontact[i].Gender, request.Emergencycontact[i].CreatedBy, clientFacility.FacilityID, null, DateTime.Now);

                        emergencyPersonId = contactPerson.Id;
                    }


                    //make the person an emergency contact
                    await personContactsService.Add(request.Emergencycontact[i].PersonId, emergencyPersonId,
                                                    request.Emergencycontact[i].CreatedBy, request.Emergencycontact[i].ContactCategory,
                                                    request.Emergencycontact[i].RelationshipType);

                    //add the person mobile contact
                    await registerPersonService.addPersonContact(emergencyPersonId, "", request.Emergencycontact[i].MobileContact,
                                                                 "", "", request.Emergencycontact[i].CreatedBy);

                    var consentTypeList = await _unitOfWork.Repository <LookupItemView>()
                                          .Get(x => x.MasterName == "ConsentType" && x.ItemName == "ConsentToSendSMS").ToListAsync();

                    int consentType = 0;
                    if (consentTypeList.Count > 0)
                    {
                        consentType = consentTypeList[0].ItemId;
                    }

                    //add person consent to sms
                    PatientConsent patientConsent = new PatientConsent()
                    {
                        PatientMasterVisitId = 0,
                        PatientId            = 0,
                        ServiceAreaId        = 0,
                        ConsentType          = consentType,
                        ConsentValue         = request.Emergencycontact[i].Consent,
                        ConsentDate          = DateTime.Now,
                        DeclineReason        = null,
                        DeleteFlag           = false,
                        CreatedBy            = request.Emergencycontact[i].CreatedBy,
                        CreateDate           = DateTime.Now,
                        PersonId             = emergencyPersonId,
                        Comments             = request.Emergencycontact[i].ConsentDecline
                    };

                    await registerPersonService.AddPatientConsent(patientConsent);
                }

                return(Result <AddPersonEmergencyContactResponse> .Valid(new AddPersonEmergencyContactResponse()
                {
                    Message = "Successfully registered emergency contact",
                    PersonEmergencyContactId = 1
                }));
            }
            catch (Exception e)
            {
                return(Result <AddPersonEmergencyContactResponse> .Invalid(e.Message));
            }
        }
        public async Task <Result <string> > Handle(AfyaMobileFamilyScreeningEncounterCommand request, CancellationToken cancellationToken)
        {
            string afyaMobileId            = string.Empty;
            string indexClientAfyaMobileId = string.Empty;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

                    trans.Commit();
                    return(Result <string> .Valid($"Successfully synchronized family screening for afyamobileId: {afyaMobileId}"));
                }
                catch (Exception ex)
                {
                    trans.Rollback();
                    Log.Error($"Failed to synchronize family screening for clientId: {afyaMobileId} " + ex.Message + " " + ex.InnerException);
                    return(Result <string> .Invalid($"Failed to synchronize family screening for clientId: {afyaMobileId} " + ex.Message + " " + ex.InnerException));
                }
            }
        }
Exemplo n.º 30
0
        public async Task <Result <AddPatientTransferInResponse> > Handle(AddPatientTransferInCommand request, CancellationToken cancellationToken)
        {
            try
            {
                using (_unitOfWork)
                {
                    int Id = 0;
                    int PatientMasterVisitId = 0;
                    RegisterPersonService registerPersonService = new RegisterPersonService(_unitOfWork);
                    var enrollmentVisitType = await _unitOfWork.Repository <LookupItemView>().Get(x => x.MasterName == "VisitType" && x.ItemName == "Enrollment").FirstOrDefaultAsync();

                    int?     visitType = enrollmentVisitType != null ? enrollmentVisitType.ItemId : 0;
                    DateTime TreatmentStartDate;
                    if (request.TreatmentStartDate == null)
                    {
                        TreatmentStartDate = request.TransferInDate;
                    }
                    else
                    {
                        TreatmentStartDate = request.TreatmentStartDate;
                    }
                    var enrollmentPatientMasterVisit =
                        await _unitOfWork.Repository <Core.Models.PatientMasterVisit>().Get(x =>
                                                                                            x.PatientId == request.PatientId && x.ServiceId == request.ServiceId && x.VisitType == visitType).ToListAsync();

                    if (enrollmentPatientMasterVisit.Count > 0)
                    {
                        PatientMasterVisitId = enrollmentPatientMasterVisit[0].Id;
                        var previousPatientEnrollment = await _unitOfWork.Repository <PatientEnrollment>().Get(x =>
                                                                                                               x.PatientId == request.PatientId && x.ServiceAreaId == request.ServiceId && x.DeleteFlag == false)
                                                        .ToListAsync();

                        if (previousPatientEnrollment.Count > 0)
                        {
                            previousPatientEnrollment[0].TransferIn = true;

                            _unitOfWork.Repository <PatientEnrollment>().Update(previousPatientEnrollment[0]);
                        }

                        var transferin = await registerPersonService.GetPatientTransferIn(request.PatientId, PatientMasterVisitId);

                        if (transferin != null)
                        {
                            transferin.TransferInDate     = request.TransferInDate;
                            transferin.TransferInNotes    = request.TransferInNotes;
                            transferin.TreatmentStartDate = TreatmentStartDate;
                            transferin.CountyFrom         = request.CountyFrom;
                            transferin.CurrentTreatment   = request.CurrentTreatment;
                            transferin.ServiceAreaId      = request.ServiceId;
                            transferin.MflCode            = request.MflCode;
                            transferin.DeleteFlag         = request.DeleteFlag;
                            transferin.FacilityFrom       = request.FacilityFrom;

                            var results = await registerPersonService.UpdatePatientTransferIn(transferin);

                            Id = results.Id;
                        }
                        else
                        {
                            PatientTransferIn pt = new PatientTransferIn();

                            pt.TransferInDate       = request.TransferInDate;
                            pt.TransferInNotes      = request.TransferInNotes;
                            pt.TreatmentStartDate   = TreatmentStartDate;
                            pt.FacilityFrom         = request.FacilityFrom;
                            pt.CountyFrom           = request.CountyFrom;
                            pt.CurrentTreatment     = request.CurrentTreatment;
                            pt.ServiceAreaId        = request.ServiceId;
                            pt.MflCode              = request.MflCode;
                            pt.PatientId            = request.PatientId;
                            pt.PatientMasterVisitId = PatientMasterVisitId;
                            pt.CreateDate           = DateTime.Now;
                            pt.CreatedBy            = request.CreatedBy;
                            pt.DeleteFlag           = request.DeleteFlag;
                            var results = await registerPersonService.AddPatientTransferIn(pt);

                            Id = results.Id;
                        }
                    }
                    return(Result <AddPatientTransferInResponse> .Valid(new AddPatientTransferInResponse()
                    {
                        TransferInId = Id
                    }));
                }
            }

            catch (Exception ex)
            {
                return(Result <AddPatientTransferInResponse> .Invalid(ex.Message));
            }
        }