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));
            }
        }
Exemple #2
0
        public async Task <Result <string> > Handle(AfyaMobileSynchronizeClientsCommand request, CancellationToken cancellationToken)
        {
            string afyaMobileId = String.Empty;

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

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

                try
                {
                    var facilityId = request.MESSAGE_HEADER.SENDING_FACILITY;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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


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

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

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

                    trans.Commit();
                    return(Result <string> .Valid($"Successfully synchronized demographics for afyamobileid: {afyaMobileId}"));
                }
                catch (Exception ex)
                {
                    trans.Rollback();
                    Log.Error($"Error syncronizing afyamobileid: {afyaMobileId}. Exception Message: {ex.Message},  Inner Exception {ex.InnerException}");
                    return(Result <string> .Invalid($"Failed to synchronize clientId: {afyaMobileId} " + ex.Message + " " + ex.InnerException));
                }
            }
        }
        public async Task <Result <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);

                GetPatientDetails patientDetails = new GetPatientDetails(_unitOfWork);


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

                if (patientLookup.Count > 0 && patientLookup[0].ptn_pk == null)
                {
                    var dobPrecision = "EXACT";
                    var dob          = DateTime.Now;
                    if (patientLookup[0].DobPrecision.HasValue)
                    {
                        dobPrecision = patientLookup[0].DobPrecision.Value ? "ESTIMATED" : "EXACT";
                    }

                    if (patientLookup[0].DateOfBirth.HasValue)
                    {
                        dob = patientLookup[0].DateOfBirth.Value;
                    }


                    var response = await registerPersonService.InsertIntoBlueCard(
                        patientLookup[0].FirstName,
                        patientLookup[0].LastName,
                        patientLookup[0].MidName,
                        request.ClientEnrollment.DateOfEnrollment,
                        patientLookup[0].MaritalStatusName,
                        patientLookup[0].PhysicalAddress,
                        patientLookup[0].MobileNumber,
                        patientLookup[0].Gender,
                        dobPrecision,
                        dob,
                        request.ClientEnrollment.CreatedBy,
                        request.ClientEnrollment.PosId
                        );

                    if (response.Count > 0)
                    {
                        await registerPersonService.UpdatePatient(request.ClientEnrollment.PatientId,
                                                                  request.ClientEnrollment.DateOfEnrollment, request.ClientEnrollment.PosId);
                    }
                }


                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);
            //    }
            //}
        }
        public async Task <Result <EnrollClientResponse> > Handle(EnrollClientCommand request, CancellationToken cancellationToken)
        {
            try
            {
                var transferIn = false;
                if (request.ClientEnrollment.transferIn)
                {
                    transferIn = true;
                }

                RegisterPersonService registerPersonService = new RegisterPersonService(_unitOfWork);
                await registerPersonService.DynamicEnrollment(request.ClientEnrollment.PatientId,
                                                              request.ClientEnrollment.ServiceAreaId, request.ClientEnrollment.CreatedBy,
                                                              request.ClientEnrollment.DateOfEnrollment, request.ClientEnrollment.ServiceIdentifiersList, transferIn);

                /*var patientIdentifier = await registerPersonService.EnrollPatient(request.ClientEnrollment.EnrollmentNo,
                 *  request.ClientEnrollment.PatientId, request.ClientEnrollment.ServiceAreaId,
                 *  request.ClientEnrollment.CreatedBy, request.ClientEnrollment.DateOfEnrollment);*/

                string cccNumber = String.Empty;
                int    moduleId  = 283;
                foreach (var item in request.ClientEnrollment.ServiceIdentifiersList)
                {
                    if (item.IdentifierId == 1)
                    {
                        cccNumber = item.IdentifierValue;
                        moduleId  = 203;
                    }
                }

                GetPatientDetails patientDetails = new GetPatientDetails(_unitOfWork);


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

                if (patientLookup.Count > 0 && (patientLookup[0].ptn_pk == 0 || patientLookup[0].ptn_pk == null))
                {
                    var dobPrecision = "EXACT";
                    var dob          = DateTime.Now;
                    if (patientLookup[0].DobPrecision.HasValue)
                    {
                        dobPrecision = patientLookup[0].DobPrecision.Value ? "ESTIMATED" : "EXACT";
                    }

                    if (patientLookup[0].DateOfBirth.HasValue)
                    {
                        dob = patientLookup[0].DateOfBirth.Value;
                    }


                    var response = await registerPersonService.InsertIntoBlueCard(
                        patientLookup[0].FirstName,
                        patientLookup[0].LastName,
                        patientLookup[0].MidName,
                        request.ClientEnrollment.DateOfEnrollment,
                        cccNumber,
                        moduleId,
                        patientLookup[0].MaritalStatusName,
                        patientLookup[0].PhysicalAddress,
                        patientLookup[0].MobileNumber,
                        patientLookup[0].Gender,
                        dobPrecision,
                        dob,
                        request.ClientEnrollment.CreatedBy,
                        request.ClientEnrollment.PosId
                        );

                    if (response.Count > 0)
                    {
                        await registerPersonService.UpdatePatient(request.ClientEnrollment.PatientId,
                                                                  request.ClientEnrollment.DateOfEnrollment, request.ClientEnrollment.PosId);
                    }
                }
                else
                {
                    if (moduleId == 203)
                    {
                        await registerPersonService.UpdateBlueCard(patientLookup[0].ptn_pk, cccNumber, moduleId);
                    }
                }


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