public async Task <LinkedCollectionResourceWrapperDto <ReportInstanceDetailDto> > Handle(ReportInstancesDetailQuery message, CancellationToken cancellationToken)
        {
            var searchFrom = message.SearchFrom;
            var searchTo   = message.SearchTo;

            if (message.NewReportsOnly || message.FeedbackReportsOnly)
            {
                var config = await _configRepository.GetAsync(c => c.ConfigType == ConfigType.ReportInstanceNewAlertCount);

                if (config == null)
                {
                    return(null);
                }

                if (String.IsNullOrEmpty(config.ConfigValue))
                {
                    return(null);
                }

                var alertCount = Convert.ToInt32(config.ConfigValue);

                // How many instances within the last alertcount
                searchFrom = DateTime.Now.AddDays(alertCount * -1);
                searchTo   = DateTime.Now;
            }

            return(await GetReportInstancesAsync(message.WorkFlowGuid, message.PageNumber, message.PageSize, message.SearchFrom, message.SearchTo, message.QualifiedName, message.SearchTerm, message.FeedbackReportsOnly, message.ActiveReportsOnly));
        }
Beispiel #2
0
        private async Task CustomMapAsync(PatientList patientListFromRepo, PatientDetailDto mappedPatient)
        {
            if (patientListFromRepo == null)
            {
                throw new ArgumentNullException(nameof(patientListFromRepo));
            }

            if (mappedPatient == null)
            {
                throw new ArgumentNullException(nameof(mappedPatient));
            }

            var patientFromRepo = await _patientRepository.GetAsync(p => p.Id == mappedPatient.Id);

            if (patientFromRepo == null)
            {
                return;
            }

            IExtendable patientExtended = patientFromRepo;

            // Map all custom attributes
            mappedPatient.PatientAttributes = _modelExtensionBuilder.BuildModelExtension(patientExtended)
                                              .Select(h => new AttributeValueDto()
            {
                Key            = h.AttributeKey,
                Value          = h.Value.ToString(),
                Category       = h.Category,
                SelectionValue = GetSelectionValue(h.Type, h.AttributeKey, h.Value.ToString())
            }).Where(s => (s.Value != "0" && !String.IsNullOrWhiteSpace(s.Value)) || !String.IsNullOrWhiteSpace(s.SelectionValue)).ToList();

            var attribute = patientExtended.GetAttributeValue("Medical Record Number");

            mappedPatient.MedicalRecordNumber = attribute != null?attribute.ToString() : "";
        }
Beispiel #3
0
        public async Task <IActionResult> UpdateConfig(long id,
                                                       [FromBody] ConfigForUpdateDto configForUpdate)
        {
            if (configForUpdate == null)
            {
                ModelState.AddModelError("Message", "Unable to locate payload for new request");
                return(BadRequest(ModelState));
            }

            var configFromRepo = await _configRepository.GetAsync(f => f.Id == id);

            if (configFromRepo == null)
            {
                return(NotFound());
            }

            if (ModelState.IsValid)
            {
                configFromRepo.ConfigValue = String.IsNullOrWhiteSpace(configForUpdate.ConfigValue) ? "-- not specified --" : configForUpdate.ConfigValue;

                _configRepository.Update(configFromRepo);
                await _unitOfWork.CompleteAsync();
            }

            return(Ok());
        }
Beispiel #4
0
        public async Task <IActionResult> UpdateHoliday(long id,
                                                        [FromBody] HolidayForUpdateDto holidayForUpdate)
        {
            if (holidayForUpdate == null)
            {
                ModelState.AddModelError("Message", "Unable to locate payload for new request");
                return(BadRequest(ModelState));
            }

            if (_unitOfWork.Repository <Holiday>().Queryable().
                Where(l => l.HolidayDate == holidayForUpdate.HolidayDate && l.Id != id)
                .Count() > 0)
            {
                ModelState.AddModelError("Message", "A holiday has already been loaded for this date");
                return(BadRequest(ModelState));
            }

            var holidayFromRepo = await _holidayRepository.GetAsync(f => f.Id == id);

            if (holidayFromRepo == null)
            {
                return(NotFound());
            }

            if (ModelState.IsValid)
            {
                holidayFromRepo.HolidayDate = holidayForUpdate.HolidayDate;
                holidayFromRepo.Description = holidayForUpdate.Description;

                _holidayRepository.Update(holidayFromRepo);
                await _unitOfWork.CompleteAsync();
            }

            return(Ok());
        }
Beispiel #5
0
        public async Task <IActionResult> UpdateLabResult(long id,
                                                          [FromBody] LabResultForUpdateDto labResultForUpdate)
        {
            if (labResultForUpdate == null)
            {
                ModelState.AddModelError("Message", "Unable to locate payload for new request");
                return(BadRequest(ModelState));
            }

            if (_unitOfWork.Repository <LabResult>().Queryable().
                Where(l => l.Description == labResultForUpdate.LabResultName && l.Id != id)
                .Count() > 0)
            {
                ModelState.AddModelError("Message", "Item with same name already exists");
                return(BadRequest(ModelState));
            }

            var labResultFromRepo = await _labResultRepository.GetAsync(f => f.Id == id);

            if (labResultFromRepo == null)
            {
                return(NotFound());
            }

            if (ModelState.IsValid)
            {
                labResultFromRepo.Description = labResultForUpdate.LabResultName;
                labResultFromRepo.Active      = (labResultForUpdate.Active == Models.ValueTypes.YesNoValueType.Yes);

                _labResultRepository.Update(labResultFromRepo);
                await _unitOfWork.CompleteAsync();
            }

            return(Ok());
        }
Beispiel #6
0
        private async Task ValidateCommandModelAsync(int meddraTermId, int?cohortGroupId, int encounterTypeId)
        {
            var sourceTermFromRepo = await _terminologyMeddraRepository.GetAsync(tm => tm.Id == meddraTermId);

            if (sourceTermFromRepo == null)
            {
                throw new KeyNotFoundException("Unable to locate terminology for MedDRA");
            }

            if (cohortGroupId.HasValue)
            {
                if (cohortGroupId > 0)
                {
                    var cohortGroupFromRepo = await _cohortGroupRepository.GetAsync(cg => cg.Id == cohortGroupId.Value);

                    if (cohortGroupFromRepo == null)
                    {
                        throw new KeyNotFoundException("Unable to locate cohort group");
                    }
                }
            }

            var encounterTypeFromRepo = await _encounterTypeRepository.GetAsync(et => et.Id == encounterTypeId);

            if (encounterTypeFromRepo == null)
            {
                throw new KeyNotFoundException("Unable to locate encounter type");
            }
        }
Beispiel #7
0
        public async Task <IActionResult> UpdateCondition(int id,
                                                          [FromBody] ConditionForUpdateDto conditionForUpdate)
        {
            if (conditionForUpdate == null)
            {
                ModelState.AddModelError("Message", "Unable to locate payload for new request");
            }

            if (Regex.Matches(conditionForUpdate.ConditionName, @"[a-zA-Z0-9 ]").Count < conditionForUpdate.ConditionName.Length)
            {
                ModelState.AddModelError("Message", "Condition contains invalid characters (Enter A-Z, a-z, 0-9, space)");
                return(BadRequest(ModelState));
            }

            if (conditionForUpdate.ConditionMedDras.Count == 0)
            {
                ModelState.AddModelError("Message", "Condition must contain at least one MedDra term");
                return(BadRequest(ModelState));
            }

            if (_unitOfWork.Repository <Condition>().Queryable().
                Where(l => l.Description == conditionForUpdate.ConditionName && l.Id != id)
                .Count() > 0)
            {
                ModelState.AddModelError("Message", "Item with same name already exists");
            }

            var conditionFromRepo = await _conditionRepository.GetAsync(f => f.Id == id);

            if (conditionFromRepo == null)
            {
                return(NotFound());
            }

            if (ModelState.IsValid)
            {
                conditionFromRepo.Description = conditionForUpdate.ConditionName;
                conditionFromRepo.Chronic     = (conditionForUpdate.Chronic == Models.ValueTypes.YesNoValueType.Yes);
                conditionFromRepo.Active      = (conditionForUpdate.Active == Models.ValueTypes.YesNoValueType.Yes);

                _conditionRepository.Update(conditionFromRepo);

                AddOrUpdateConditionLabTests(conditionForUpdate, conditionFromRepo);
                AddOrUpdateConditionMeddras(conditionForUpdate, conditionFromRepo);
                AddOrUpdateConditionMedications(conditionForUpdate, conditionFromRepo);

                await _unitOfWork.CompleteAsync();

                return(Ok());
            }

            return(BadRequest(ModelState));
        }
Beispiel #8
0
        private async Task <ReportInstance> GetReportInstanceForPatientClinicalEventAsync(Guid contextGuid)
        {
            var reportInstance = await _reportInstanceRepository.GetAsync(ri => ri.ContextGuid == contextGuid, new string[] { "Medications",
                                                                                                                              "TerminologyMedDra" });

            if (reportInstance == null)
            {
                throw new KeyNotFoundException(nameof(reportInstance));
            }

            return(reportInstance);
        }
Beispiel #9
0
        public async Task <ActionResult> DownloadDataset(Guid id,
                                                         [FromQuery] AnalyserDatasetResourceParameters analyserDatasetResourceParameters)
        {
            var workflowFromRepo = await _workFlowRepository.GetAsync(f => f.WorkFlowGuid == id);

            if (workflowFromRepo == null)
            {
                return(NotFound());
            }

            var userName     = _httpContextAccessor.HttpContext.User.FindFirst(ClaimTypes.NameIdentifier).Value;
            var userFromRepo = _userRepository.Get(u => u.UserName == userName);

            if (!userFromRepo.AllowDatasetDownload)
            {
                ModelState.AddModelError("Message", "You do not have permissions to download a dataset");
                return(BadRequest(ModelState));
            }

            var model = id == new Guid("4096D0A3-45F7-4702-BDA1-76AEDE41B986")
                ? _excelDocumentService.CreateSpontaneousDatasetForDownload()
                : _excelDocumentService.CreateActiveDatasetForDownload(new long[] { }, analyserDatasetResourceParameters?.CohortGroupId ?? 0);

            return(PhysicalFile(model.FullPath, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"));
        }
Beispiel #10
0
        public async Task <CohortGroupDetailDto> Handle(AddCohortGroupCommand message, CancellationToken cancellationToken)
        {
            var conditionFromRepo = await _conditionRepository.GetAsync(c => c.Description == message.ConditionName);

            if (conditionFromRepo == null)
            {
                throw new KeyNotFoundException("Unable to locate condition");
            }

            if (_cohortGroupRepository.Exists(cg => cg.CohortName == message.CohortName ||
                                              cg.CohortCode == message.CohortCode))
            {
                throw new DomainException("Cohort group with same name already exists");
            }

            var newCohortGroup = new CohortGroup(message.CohortName, message.CohortCode, conditionFromRepo, message.StartDate, message.FinishDate);

            await _cohortGroupRepository.SaveAsync(newCohortGroup);

            _logger.LogInformation($"----- Cohort group {message.CohortName} created");

            var mappedCohortGroup = _mapper.Map <CohortGroupDetailDto>(newCohortGroup);

            return(CreateLinks(mappedCohortGroup));
        }
        public async Task <bool> Handle(RemoveRoleFromUserCommand message, CancellationToken cancellationToken)
        {
            var userFromRepo = await _userRepository.GetAsync(u => u.Id == message.UserId,
                                                              new string[] { "" });

            if (userFromRepo == null)
            {
                throw new KeyNotFoundException("Unable to locate user");
            }

            var userFromManager = await _userManager.FindByNameAsync(userFromRepo.UserName);

            var result = await _userManager.RemoveFromRoleAsync(userFromManager, message.Role);

            if (!result.Succeeded)
            {
                foreach (var error in result.Errors)
                {
                    throw new DomainException($"{error.Description} ({error.Code})");
                }
                throw new DomainException($"Unknown error changing user roles");
            }

            _logger.LogInformation($"----- User {userFromRepo.Id} roles updated");

            return(true);
        }
Beispiel #12
0
        public async Task <PatientExpandedDto> Handle(PatientExpandedQuery message, CancellationToken cancellationToken)
        {
            var patientFromRepo = await _patientRepository.GetAsync(p => p.Archived == false &&
                                                                    p.Id == message.PatientId,
                                                                    new string[] {
                "PatientFacilities.Facility.OrgUnit",
                "PatientClinicalEvents.SourceTerminologyMedDra",
                "PatientConditions.TerminologyMedDra",
                "PatientConditions.Outcome",
                "PatientConditions.TreatmentOutcome",
                "PatientMedications.Concept.MedicationForm",
                "PatientMedications.Product",
                "Attachments.AttachmentType",
                "PatientLabTests.LabTest",
                "PatientLabTests.TestUnit",
                "Appointments",
                "Encounters.EncounterType",
                "PatientStatusHistories.PatientStatus"
            });

            if (patientFromRepo == null)
            {
                throw new KeyNotFoundException("Unable to locate patient");
            }

            var mappedPatient = _mapper.Map <PatientExpandedDto>(patientFromRepo);

            await CustomMapAsync(patientFromRepo, mappedPatient);

            CreateLinks(mappedPatient);

            return(mappedPatient);
        }
Beispiel #13
0
        public async Task <ConceptIdentifierDto> Handle(AddConceptCommand message, CancellationToken cancellationToken)
        {
            var medicationFormFromRepo = await _medicationFormRepository.GetAsync(mf => mf.Description == message.MedicationForm);

            if (medicationFormFromRepo == null)
            {
                throw new KeyNotFoundException("Unable to locate medication form");
            }

            if (_conceptRepository.Exists(c => c.ConceptName == message.ConceptName &&
                                          c.MedicationForm.Id == medicationFormFromRepo.Id &&
                                          c.Strength == message.Strength))
            {
                throw new DomainException("Concept with same name, strength and form already exists");
            }

            var newConcept = new Concept(message.ConceptName, message.Strength, medicationFormFromRepo);

            await _conceptRepository.SaveAsync(newConcept);

            _logger.LogInformation($"----- Concept {message.ConceptName} created");

            var mappedConcept = _mapper.Map <ConceptIdentifierDto>(newConcept);

            CreateLinks(mappedConcept);

            return(mappedConcept);
        }
        private async Task CustomMedicationMapAsync(PatientMedicationDetailDto dto)
        {
            var medication = await _patientMedicationRepository.GetAsync(p => p.Id == dto.Id);

            if (medication == null)
            {
                return;
            }

            IExtendable medicationExtended = medication;

            // Map all custom attributes
            dto.MedicationAttributes = _modelExtensionBuilder.BuildModelExtension(medicationExtended)
                                       .Select(h => new AttributeValueDto()
            {
                Id             = h.Id,
                Key            = h.AttributeKey,
                Value          = h.TransformValueToString(),
                Category       = h.Category,
                SelectionValue = GetSelectionValue(h.Type, h.AttributeKey, h.Value.ToString())
            }).Where(s => (s.Value != "0" && !String.IsNullOrWhiteSpace(s.Value)) || !String.IsNullOrWhiteSpace(s.SelectionValue)).ToList();


            dto.IndicationType = await _customAttributeService.GetCustomAttributeValueAsync("PatientMedication", "Type of Indication", medicationExtended);

            dto.ReasonForStopping = await _customAttributeService.GetCustomAttributeValueAsync("PatientMedication", "Reason For Stopping", medicationExtended);

            dto.ClinicianAction = await _customAttributeService.GetCustomAttributeValueAsync("PatientMedication", "Clinician action taken with regard to medicine if related to AE", medicationExtended);

            dto.ChallengeEffect = await _customAttributeService.GetCustomAttributeValueAsync("PatientMedication", "Effect OF Dechallenge (D) & Rechallenge (R)", medicationExtended);
        }
Beispiel #15
0
        private async Task CreateLinksForTerminologyStepAsync(ReportInstance reportInstanceFromRepo, ReportInstanceDetailDto mappedReportInstance)
        {
            var config = await _configRepository.GetAsync(c => c.ConfigType == ConfigType.AssessmentScale);

            if (config == null)
            {
                return;
            }
            ;

            mappedReportInstance.Links.Add(new LinkDto(_linkGeneratorService.CreateResourceUriForReportInstance("UpdateReportInstanceTerminology",
                                                                                                                reportInstanceFromRepo.WorkFlow.WorkFlowGuid, mappedReportInstance.Id), "setmeddra", "PUT"));

            if (reportInstanceFromRepo.CurrentActivity.CurrentStatus.Description != "NOTSET")
            {
                // ConfigType.AssessmentScale

                if (config.ConfigValue == "Both Scales" || config.ConfigValue == "WHO Scale")
                {
                    mappedReportInstance.Links.Add(new LinkDto(_linkGeneratorService.CreateResourceUriForReportInstance("UpdateReportInstanceStatus",
                                                                                                                        reportInstanceFromRepo.WorkFlow.WorkFlowGuid, reportInstanceFromRepo.Id), "whocausalityset", "PUT"));
                }

                if (config.ConfigValue == "Both Scales" || config.ConfigValue == "Naranjo Scale")
                {
                    mappedReportInstance.Links.Add(new LinkDto(_linkGeneratorService.CreateResourceUriForReportInstance("UpdateReportInstanceStatus",
                                                                                                                        reportInstanceFromRepo.WorkFlow.WorkFlowGuid, reportInstanceFromRepo.Id), "naranjocausalityset", "PUT"));
                }

                mappedReportInstance.Links.Add(new LinkDto(_linkGeneratorService.CreateResourceUriForReportInstance("UpdateReportInstanceStatus",
                                                                                                                    reportInstanceFromRepo.WorkFlow.WorkFlowGuid, reportInstanceFromRepo.Id), "causalityset", "PUT"));
            }
        }
        public async Task <EncounterExpandedDto> Handle(EncounterExpandedQuery message, CancellationToken cancellationToken)
        {
            var encounterFromRepo = await _encounterRepository.GetAsync(e => e.Patient.Id == message.PatientId &&
                                                                        e.Archived == false &&
                                                                        e.Id == message.EncounterId,
                                                                        new string[] {
                "Patient.PatientClinicalEvents",
                "Patient.PatientConditions.Outcome",
                "Patient.PatientLabTests.TestUnit",
                "Patient.PatientLabTests.LabTest",
                "Patient.PatientMedications",
                "EncounterType"
            });

            if (encounterFromRepo == null)
            {
                throw new KeyNotFoundException("Unable to locate encounter");
            }

            var mappedEncounter = _mapper.Map <EncounterExpandedDto>(encounterFromRepo);

            await CustomMapAsync(encounterFromRepo, mappedEncounter);

            CreateLinks(encounterFromRepo.Patient.Id, encounterFromRepo.Id, mappedEncounter);

            return(mappedEncounter);
        }
        public async Task <AppointmentIdentifierDto> Handle(AddAppointmentCommand message, CancellationToken cancellationToken)
        {
            var patientFromRepo = await _patientRepository.GetAsync(p => p.Id == message.PatientId);

            if (patientFromRepo == null)
            {
                throw new KeyNotFoundException("Unable to locate patient");
            }

            var appointmentFromRepo = await _appointmentRepository.GetAsync(a => a.PatientId == message.PatientId && a.AppointmentDate == message.AppointmentDate && !a.Archived);

            if (appointmentFromRepo != null)
            {
                throw new DomainException("Patient already has an appointment for this date");
            }

            var newAppointment = new Appointment(message.PatientId, message.AppointmentDate, message.Reason);

            await _appointmentRepository.SaveAsync(newAppointment);

            _logger.LogInformation($"----- Appointment {newAppointment.Id} created");

            var mappedAppointment = _mapper.Map <AppointmentIdentifierDto>(newAppointment);

            CreateLinks(mappedAppointment);

            return(mappedAppointment);
        }
Beispiel #18
0
        public async Task <bool> Handle(DeleteUserCommand message, CancellationToken cancellationToken)
        {
            var userFromRepo = await _userRepository.GetAsync(u => u.Id == message.UserId,
                                                              new string[] { "Facilities" });

            if (userFromRepo == null)
            {
                throw new KeyNotFoundException("Unable to locate user");
            }

            if (_auditLogRepository.Exists(a => a.User.Id == message.UserId))
            {
                throw new DomainException("Unable to delete as item is in use");
            }

            var userFacilities = await _userFacilityRepository.ListAsync(c => c.User.Id == message.UserId);

            userFacilities.ToList().ForEach(userFacility => _userFacilityRepository.Delete(userFacility));

            _userRepository.Delete(userFromRepo);
            await _unitOfWork.CompleteAsync();

            _logger.LogInformation($"----- User {userFromRepo.Id} deleted");

            return(true);
        }
        private async Task <ClinicalEventDetail> PrepareClinicalEventDetailAsync(IDictionary <int, string> attributes)
        {
            var clinicalEventDetail = new ClinicalEventDetail();

            clinicalEventDetail.CustomAttributes = _modelExtensionBuilder.BuildModelExtension <PatientClinicalEvent>();

            //clinicalEventDetail = _mapper.Map<ClinicalEventDetail>(clinicalEventForUpdate);
            foreach (var newAttribute in attributes)
            {
                var customAttribute = await _customAttributeRepository.GetAsync(ca => ca.Id == newAttribute.Key);

                if (customAttribute == null)
                {
                    throw new KeyNotFoundException($"Unable to locate custom attribute {newAttribute.Key}");
                }

                var attributeDetail = clinicalEventDetail.CustomAttributes.SingleOrDefault(ca => ca.AttributeKey == customAttribute.AttributeKey);

                if (attributeDetail == null)
                {
                    throw new KeyNotFoundException($"Unable to locate custom attribute on patient clinical event {newAttribute.Key}");
                }

                attributeDetail.Value = newAttribute.Value;
            }

            return(clinicalEventDetail);
        }
        public async Task <PatientExpandedDto> Handle(PatientExpandedByConditionTermQuery message, CancellationToken cancellationToken)
        {
            var caseNumberParm = new SqlParameter("@CaseNumber", !String.IsNullOrWhiteSpace(message.CaseNumber) ? (Object)message.CaseNumber : DBNull.Value);

            var patientsFromRepo = _context.PatientLists
                                   .FromSqlRaw <PatientList>($"EXECUTE spSearchPatientsByConditionCaseNumber @CaseNumber"
                                                             , caseNumberParm)
                                   .AsEnumerable();

            if (patientsFromRepo.Count() != 1)
            {
                return(null);
            }

            var patientFromRepo = await _patientRepository.GetAsync(p => p.Id == patientsFromRepo.First().PatientId, new string[] {
                "PatientFacilities.Facility.OrgUnit",
                "PatientClinicalEvents.SourceTerminologyMedDra",
                "PatientConditions.TerminologyMedDra",
                "PatientMedications.Concept.MedicationForm",
                "PatientMedications.Product"
            });

            if (patientFromRepo == null)
            {
                throw new KeyNotFoundException("Unable to locate patient");
            }

            var mappedPatient = _mapper.Map <PatientExpandedDto>(patientFromRepo);

            await CustomMapAsync(patientFromRepo, mappedPatient);

            CreateLinks(mappedPatient);

            return(mappedPatient);
        }
Beispiel #21
0
        private async Task CreatePatientSummaryAndLinkToExecutionEventAsync(ReportInstance reportInstance, ActivityExecutionStatusEvent executionEvent)
        {
            if (reportInstance is null)
            {
                throw new ArgumentNullException(nameof(reportInstance));
            }

            if (executionEvent is null)
            {
                throw new ArgumentNullException(nameof(executionEvent));
            }

            var artefactModel = reportInstance.WorkFlow.Description == "New Active Surveilliance Report" ?
                                await _artefactService.CreatePatientSummaryForActiveReportAsync(reportInstance.ContextGuid) :
                                await _artefactService.CreatePatientSummaryForSpontaneousReportAsync(reportInstance.ContextGuid);

            using (var tempFile = File.OpenRead(artefactModel.FullPath))
            {
                if (tempFile.Length > 0)
                {
                    BinaryReader rdr = new BinaryReader(tempFile);
                    executionEvent.AddAttachment(Path.GetFileName(artefactModel.FileName),
                                                 await _attachmentTypeRepository.GetAsync(at => at.Key == "docx"),
                                                 tempFile.Length,
                                                 rdr.ReadBytes((int)tempFile.Length),
                                                 "PatientSummary");
                }
            }
        }
Beispiel #22
0
        public async Task <bool> Handle(ChangeProductDetailsCommand message, CancellationToken cancellationToken)
        {
            var conceptFromRepo = await _conceptRepository.GetAsync(c => c.ConceptName + "; " + c.Strength + " (" + c.MedicationForm.Description + ")" == message.ConceptName, new string[] {
                "Products"
            });

            if (conceptFromRepo == null)
            {
                throw new KeyNotFoundException($"Unable to locate concept {message.ConceptName}");
            }

            if (_productRepository.Exists(p => p.ConceptId == conceptFromRepo.Id &&
                                          p.ProductName == message.ProductName &&
                                          p.Id != message.ProductId))
            {
                throw new DomainException("Product with same name annd concept already exists");
            }

            conceptFromRepo.ChangeProductDetails(message.ProductId, message.ProductName, message.Manufacturer, message.Description);
            if (message.Active)
            {
                conceptFromRepo.MarkProductAsActive(message.ProductId);
            }
            else
            {
                conceptFromRepo.MarkProductAsInActive(message.ProductId);
            }
            _conceptRepository.Update(conceptFromRepo);

            _logger.LogInformation($"----- Product {message.ProductId} details updated");

            return(await _unitOfWork.CompleteAsync());
        }
Beispiel #23
0
        private async Task CustomReportInstanceMedicationMapAsync(ReportInstance reportInstanceFromRepo, ReportInstanceMedicationDetailDto dto)
        {
            if (reportInstanceFromRepo.WorkFlow.Description == "New Spontaneous Surveilliance Report")
            {
                var datasetInstanceFromRepo = await _datasetInstanceRepository.GetAsync(di => di.DatasetInstanceGuid == reportInstanceFromRepo.ContextGuid);

                if (datasetInstanceFromRepo != null)
                {
                    var      drugItemValues = datasetInstanceFromRepo.GetInstanceSubValues("Product Information", dto.ReportInstanceMedicationGuid);
                    var      drugName       = drugItemValues.SingleOrDefault(div => div.DatasetElementSub.ElementName == "Product")?.InstanceValue;
                    DateTime tempdt;

                    var startElement = drugItemValues.SingleOrDefault(div => div.DatasetElementSub.ElementName == "Drug Start Date");
                    var stopElement  = drugItemValues.SingleOrDefault(div => div.DatasetElementSub.ElementName == "Drug End Date");

                    dto.StartDate = startElement != null?DateTime.TryParse(startElement.InstanceValue, out tempdt) ? Convert.ToDateTime(startElement.InstanceValue).ToString("yyyy-MM-dd") : "" : "";

                    dto.EndDate = stopElement != null?DateTime.TryParse(stopElement.InstanceValue, out tempdt) ? Convert.ToDateTime(stopElement.InstanceValue).ToString("yyyy-MM-dd") : "" : "";
                }
            }
            else
            {
                var medication = await _patientMedicationRepository.GetAsync(p => p.PatientMedicationGuid == dto.ReportInstanceMedicationGuid);

                if (medication == null)
                {
                    return;
                }

                dto.StartDate = medication.StartDate.ToString("yyyy-MM-dd");
                dto.EndDate   = medication.EndDate.HasValue ? medication.EndDate.Value.ToString("yyyy-MM-dd") : "";
            }
        }
Beispiel #24
0
        /// <summary>
        /// Prepare patient record with associated lab tests
        /// </summary>
        private async Task AddLabTestsAsync(Patient patient, List <LabTestDetail> labTests)
        {
            if (patient == null)
            {
                throw new ArgumentNullException(nameof(patient));
            }
            if (labTests == null)
            {
                throw new ArgumentNullException(nameof(labTests));
            }
            if (labTests.Count == 0)
            {
                return;
            }

            foreach (var labTest in labTests)
            {
                var labTestFromRepo = await _labTestRepository.GetAsync(lt => lt.Description == labTest.LabTestSource);

                var newLabTest = patient.AddLabTest(labTest.TestDate, labTest.TestResult, labTestFromRepo, null, string.Empty, string.Empty, string.Empty);

                // Custom Property handling
                _typeExtensionHandler.UpdateExtendable(newLabTest, labTest.CustomAttributes, "Admin");

                patient.PatientLabTests.Add(newLabTest);
            }
        }
Beispiel #25
0
        private async Task MapIdsForReportInstanceAsync(ReportInstance reportInstanceFromRepo, ReportInstanceDetailDto dto)
        {
            var patientClinicalEvent = await _patientClinicalEventRepository.GetAsync(p => p.PatientClinicalEventGuid == reportInstanceFromRepo.ContextGuid, new string[] { "Patient" });

            dto.PatientId = patientClinicalEvent != null ? patientClinicalEvent.Patient.Id : 0;
            dto.PatientClinicalEventId = patientClinicalEvent != null ? patientClinicalEvent.Id : 0;
        }
        public async Task <bool> Handle(ChangeReportTerminologyCommand message, CancellationToken cancellationToken)
        {
            var reportInstanceFromRepo = await _reportInstanceRepository.GetAsync(ri => ri.WorkFlow.WorkFlowGuid == message.WorkFlowGuid &&
                                                                                  ri.Id == message.ReportInstanceId,
                                                                                  new string[] { "" });

            if (reportInstanceFromRepo == null)
            {
                throw new KeyNotFoundException("Unable to locate report instance");
            }

            var terminologyFromRepo = _terminologyMeddraRepository.Get(message.TerminologyMedDraId);

            if (terminologyFromRepo == null)
            {
                throw new KeyNotFoundException("Unable to locate terminology");
            }

            if (await _workFlowService.ValidateExecutionStatusForCurrentActivityAsync(reportInstanceFromRepo.ContextGuid, "MEDDRASET") == false)
            {
                throw new DomainException($"Activity MEDDRASET not valid for workflow");
            }

            reportInstanceFromRepo.ChangeTerminology(terminologyFromRepo);

            _reportInstanceRepository.Update(reportInstanceFromRepo);
            await _unitOfWork.CompleteAsync();

            _logger.LogInformation($"----- Report {reportInstanceFromRepo.Id} terminology updated");

            await _workFlowService.ExecuteActivityAsync(reportInstanceFromRepo.ContextGuid, "MEDDRASET", $"AUTOMATION: MedDRA Term set to {terminologyFromRepo.DisplayName}", null, "");

            return(true);
        }
        private async Task CustomMapAsync(PatientClinicalEvent patientClinicalEventFromRepo, PatientClinicalEventExpandedDto dto)
        {
            IExtendable patientClinicalEventExtended = patientClinicalEventFromRepo;

            // Map all custom attributes
            dto.ClinicalEventAttributes = _modelExtensionBuilder.BuildModelExtension(patientClinicalEventExtended)
                                          .Select(h => new AttributeValueDto()
            {
                Id             = h.Id,
                Key            = h.AttributeKey,
                Value          = h.TransformValueToString(),
                Category       = h.Category,
                SelectionValue = GetSelectionValue(h.Type, h.AttributeKey, h.Value.ToString())
            }).Where(s => (s.Value != "0" && !String.IsNullOrWhiteSpace(s.Value)) || !String.IsNullOrWhiteSpace(s.SelectionValue)).ToList();

            dto.ReportDate = await _customAttributeService.GetCustomAttributeValueAsync("PatientClinicalEvent", "Date of Report", patientClinicalEventExtended);

            dto.IsSerious = await _customAttributeService.GetCustomAttributeValueAsync("PatientClinicalEvent", "Is the adverse event serious?", patientClinicalEventExtended);

            var activity = await _reportInstanceQueries.GetExecutionStatusEventsForEventViewAsync(patientClinicalEventFromRepo.Id);

            dto.Activity = activity.ToList();

            var reportInstanceFromRepo = await _reportInstanceRepository.GetAsync(ri => ri.ContextGuid == patientClinicalEventFromRepo.PatientClinicalEventGuid, new string[] { "TerminologyMedDra", "Medications", "Tasks.Comments" });

            if (reportInstanceFromRepo == null)
            {
                return;
            }

            dto.SetMedDraTerm     = reportInstanceFromRepo.TerminologyMedDra?.DisplayName;
            dto.SetClassification = ReportClassification.From(reportInstanceFromRepo.ReportClassificationId).Name;
            dto.Medications       = _mapper.Map <ICollection <ReportInstanceMedicationDetailDto> >(reportInstanceFromRepo.Medications.Where(m => !String.IsNullOrWhiteSpace(m.WhoCausality) || (!String.IsNullOrWhiteSpace(m.NaranjoCausality))));
            dto.Tasks             = _mapper.Map <ICollection <TaskDto> >(reportInstanceFromRepo.Tasks.Where(t => t.TaskStatusId != Core.Aggregates.ReportInstanceAggregate.TaskStatus.Cancelled.Id));
        }
        public async Task <DatasetInstanceDetailDto> Handle(DatasetInstanceDetailQuery message, CancellationToken cancellationToken)
        {
            var datasetFromRepo = await _datasetRepository.GetAsync(d => d.Id == message.DatasetId);

            if (datasetFromRepo == null)
            {
                throw new KeyNotFoundException("Unable to locate dataset");
            }

            var datasetInstanceFromRepo = await _datasetInstanceRepository.GetAsync(di => di.Dataset.Id == message.DatasetId &&
                                                                                    di.Id == message.DatasetInstanceId,
                                                                                    new string[] { "Dataset.DatasetCategories.DatasetCategoryElements"
                                                                                                   , "Dataset.DatasetCategories.DatasetCategoryElements.DatasetElement.Field.FieldValues"
                                                                                                   , "Dataset.DatasetCategories.DatasetCategoryElements.DatasetElement.Field.FieldType"
                                                                                                   , "Dataset.DatasetCategories.DatasetCategoryElements.DatasetElement.DatasetElementSubs.Field.FieldValues"
                                                                                                   , "Dataset.DatasetCategories.DatasetCategoryElements.DatasetElement.DatasetElementSubs.Field.FieldType"
                                                                                                   , "Dataset.DatasetCategories.DatasetCategoryElements.DatasetCategoryElementConditions"
                                                                                                   , "DatasetInstanceValues.DatasetInstanceSubValues" });

            if (datasetInstanceFromRepo == null)
            {
                throw new KeyNotFoundException("Unable to locate dataset instance");
            }

            var mappedDatasetInstance = _mapper.Map <DatasetInstanceDetailDto>(datasetInstanceFromRepo);

            CustomMap(datasetInstanceFromRepo, mappedDatasetInstance);
            CreateLinks(mappedDatasetInstance);

            return(mappedDatasetInstance);
        }
Beispiel #29
0
        public async Task <bool> Handle(ChangeMedicationDetailsCommand message, CancellationToken cancellationToken)
        {
            var patientFromRepo = await _patientRepository.GetAsync(f => f.Id == message.PatientId, new string[] { "PatientClinicalEvents", "PatientMedications.Concept.MedicationForm", "PatientMedications.Product" });

            if (patientFromRepo == null)
            {
                throw new KeyNotFoundException("Unable to locate patient");
            }

            var medicationToUpdate   = patientFromRepo.PatientMedications.Single(pm => pm.Id == message.PatientMedicationId);
            var medicationAttributes = await PrepareMedicationAttributesWithNewValuesAsync(medicationToUpdate, message.Attributes);

            var userName = _httpContextAccessor.HttpContext.User.FindFirst(ClaimTypes.NameIdentifier).Value;

            patientFromRepo.ChangeMedicationDetails(message.PatientMedicationId, message.StartDate, message.EndDate, message.Dose, message.DoseFrequency, message.DoseUnit);

            _modelExtensionBuilder.ValidateAndUpdateExtendable(medicationToUpdate, medicationAttributes, userName);

            _patientRepository.Update(patientFromRepo);

            await RefreshMedicationOnMatchingReportInstancesAsync(patientFromRepo, message.StartDate, message.EndDate, patientFromRepo.PatientMedications.Single(pm => pm.Id == message.PatientMedicationId).DisplayName, patientFromRepo.PatientMedications.Single(pm => pm.Id == message.PatientMedicationId).PatientMedicationGuid);

            _logger.LogInformation($"----- Medication {message.PatientMedicationId} details updated");

            return(await _unitOfWork.CompleteAsync());
        }
Beispiel #30
0
        public async Task <ReportInstanceExpandedDto> Handle(ReportInstanceExpandedQuery message, CancellationToken cancellationToken)
        {
            var reportInstanceFromRepo = await _reportInstanceRepository.GetAsync(f => f.WorkFlow.WorkFlowGuid == message.WorkFlowGuid &&
                                                                                  f.Id == message.ReportInstanceId,
                                                                                  new string[] { "WorkFlow", "Activities.CurrentStatus", "Activities.ExecutionEvents.ExecutionStatus.Activity", "Activities.ExecutionEvents.Attachments", "Tasks.Comments", "Medications" });

            if (reportInstanceFromRepo == null)
            {
                throw new KeyNotFoundException("Unable to locate report instance");
            }

            var mappedReport = _mapper.Map <ReportInstanceExpandedDto>(reportInstanceFromRepo);

            await CustomMapAsync(reportInstanceFromRepo, mappedReport);
            await CreateLinksAsync(reportInstanceFromRepo, mappedReport);

            foreach (var activity in reportInstanceFromRepo.Activities.OrderBy(a => a.Created))
            {
                foreach (var executionEvent in activity.ExecutionEvents)
                {
                    var mappedExecutionEvent = _mapper.Map <ActivityExecutionStatusEventDto>(executionEvent);
                    mappedReport.Events.Add(await CustomActivityExecutionStatusEventMap(mappedExecutionEvent));
                }
            }

            return(mappedReport);
        }