public void AddCustomAttribute(CustomAttributeConfigDetail customAttribute) { var newCustomAttribute = new CustomAttributeConfiguration() { ExtendableTypeName = customAttribute.EntityName, Category = customAttribute.Category, AttributeKey = customAttribute.AttributeName, AttributeDetail = customAttribute.AttributeDetail, CustomAttributeType = customAttribute.CustomAttributeType, IsRequired = customAttribute.Required, IsSearchable = customAttribute.Searchable }; switch (newCustomAttribute.CustomAttributeType) { case CustomAttributeType.Numeric: if (customAttribute.NumericMinValue.HasValue) { newCustomAttribute.NumericMinValue = customAttribute.NumericMinValue.Value; } if (customAttribute.NumericMaxValue.HasValue) { newCustomAttribute.NumericMaxValue = customAttribute.NumericMaxValue.Value; } break; case CustomAttributeType.String: if (customAttribute.StringMaxLength.HasValue) { newCustomAttribute.StringMaxLength = customAttribute.StringMaxLength.Value; } break; case CustomAttributeType.DateTime: newCustomAttribute.FutureDateOnly = customAttribute.FutureDateOnly; newCustomAttribute.PastDateOnly = customAttribute.PastDateOnly; break; default: break; } customAttributeConfigRepository.Save(newCustomAttribute); if (newCustomAttribute.CustomAttributeType == CustomAttributeType.Selection) { var newSelectionDataItem = new SelectionDataItem() { AttributeKey = customAttribute.AttributeName, Value = "", SelectionKey = "0" }; selectionDataRepository.Save(newSelectionDataItem); } }
/// <summary> /// Handle the updating of terminology for an existing condition /// </summary> /// <param name="conditionForUpdate">The payload containing the list of lab tests</param> /// <param name="conditionFromRepo">The condition entity that is being updated</param> /// <returns></returns> private void AddOrUpdateConditionMeddras(ConditionForUpdateDto conditionForUpdate, Condition conditionFromRepo) { // Determine what has been removed ArrayList deleteCollection = new ArrayList(); foreach (var conditionMeddra in conditionFromRepo.ConditionMedDras) { if (!conditionForUpdate.ConditionMedDras.Contains(conditionMeddra.TerminologyMedDra.Id)) { deleteCollection.Add(conditionMeddra); } } // Process deletes foreach (var conditionMeddra in deleteCollection) { _conditionMeddraRepository.Delete(conditionMeddra); } // Determine what needs to be added foreach (var meddraId in conditionForUpdate.ConditionMedDras) { if (!conditionFromRepo.ConditionMedDras.Any(c => c.TerminologyMedDra.Id == meddraId)) { var newConditionMedra = new ConditionMedDra() { Condition = conditionFromRepo, TerminologyMedDra = _terminologyMeddraRepository.Get(f => f.Id == meddraId) }; _conditionMeddraRepository.Save(newConditionMedra); } } }
/// <summary> /// Handle the updating of medications for an existing condition /// </summary> /// <param name="conditionForUpdate">The payload containing the list of lab tests</param> /// <param name="conditionFromRepo">The condition entity that is being updated</param> /// <returns></returns> private void AddOrUpdateConditionMedications(ConditionForUpdateDto conditionForUpdate, Condition conditionFromRepo) { // Determine what has been removed ArrayList deleteCollection = new ArrayList(); foreach (var conditionMedication in conditionFromRepo.ConditionMedications) { if (!conditionForUpdate.ConditionMedications.Contains(conditionMedication.Product.Id)) { deleteCollection.Add(conditionMedication); } } // Process deletes foreach (var conditionMedication in deleteCollection) { _conditionMedicationRepository.Delete(conditionMedication); } // Determine what needs to be added foreach (var productId in conditionForUpdate.ConditionMedications) { if (!conditionFromRepo.ConditionMedications.Any(c => c.Product.Id == productId)) { var product = _productRepository.Get(f => f.Id == productId); var newConditionMedication = new ConditionMedication() { Condition = conditionFromRepo, Product = product, Concept = product.Concept }; _conditionMedicationRepository.Save(newConditionMedication); } } }
/// <summary> /// Handle the updating of lab tests for an existing condition /// </summary> /// <param name="conditionForUpdate">The payload containing the list of lab tests</param> /// <param name="conditionFromRepo">The condition entity that is being updated</param> /// <returns></returns> private void AddOrUpdateConditionLabTests(ConditionForUpdateDto conditionForUpdate, Condition conditionFromRepo) { // Determine what has been removed ArrayList deleteCollection = new ArrayList(); foreach (var conditionLabTest in conditionFromRepo.ConditionLabTests) { if (!conditionForUpdate.ConditionLabTests.Contains(conditionLabTest.LabTest.Id)) { deleteCollection.Add(conditionLabTest); } } // Process deletes foreach (var conditionLabTest in deleteCollection) { _conditionLabTestRepository.Delete(conditionLabTest); } // Determine what needs to be added foreach (var labTestId in conditionForUpdate.ConditionLabTests) { if (!conditionFromRepo.ConditionLabTests.Any(c => c.LabTest.Id == labTestId)) { var newConditionLabTest = new ConditionLabTest() { Condition = conditionFromRepo, LabTest = _labTestRepository.Get(f => f.Id == labTestId) }; _conditionLabTestRepository.Save(newConditionLabTest); } } }
private async Task UpdateUserFacilitiesAsync(List <string> facilityNames, User userFromRepo) { var userFacilities = await _userFacilityRepository.ListAsync(uf => uf.User.Id == userFromRepo.Id, null, new string[] { "Facility" }); var facilitiesToBeRemoved = PrepareFacilitiesToBeRemoved(facilityNames, userFacilities); var facilitiesToBeAdded = await PrepareFacilitiesToBeAddedAsync(facilityNames, userFromRepo, userFacilities); facilitiesToBeRemoved.ForEach(userFacility => _userFacilityRepository.Delete(userFacility)); facilitiesToBeAdded.ForEach(userFacility => _userFacilityRepository.Save(userFacility)); }
public async Task <IActionResult> CreateLabTest( [FromBody] LabTestForUpdateDto labTestForUpdate) { if (labTestForUpdate == null) { ModelState.AddModelError("Message", "Unable to locate payload for new request"); } if (Regex.Matches(labTestForUpdate.LabTestName, @"[a-zA-Z0-9 ]").Count < labTestForUpdate.LabTestName.Length) { ModelState.AddModelError("Message", "Value contains invalid characters (Enter A-Z, a-z, 0-9, space)"); return(BadRequest(ModelState)); } if (_unitOfWork.Repository <LabTest>().Queryable(). Where(l => l.Description == labTestForUpdate.LabTestName) .Count() > 0) { ModelState.AddModelError("Message", "Item with same name already exists"); } long id = 0; if (ModelState.IsValid) { var newLabTest = new LabTest() { Description = labTestForUpdate.LabTestName, Active = true }; _labTestRepository.Save(newLabTest); id = newLabTest.Id; var mappedLabTest = await GetLabTestAsync <LabTestIdentifierDto>(id); if (mappedLabTest == null) { return(StatusCode(500, "Unable to locate newly added item")); } return(CreatedAtAction("GetLabTestByIdentifier", new { id = mappedLabTest.Id }, CreateLinksForLabTest <LabTestIdentifierDto>(mappedLabTest))); } return(BadRequest(ModelState)); }
public async Task <IActionResult> CreateCareEvent( [FromBody] CareEventForUpdateDto careEventForUpdate) { if (careEventForUpdate == null) { ModelState.AddModelError("Message", "Unable to locate payload for new request"); return(BadRequest(ModelState)); } if (Regex.Matches(careEventForUpdate.CareEventName, @"[a-zA-Z ']").Count < careEventForUpdate.CareEventName.Length) { ModelState.AddModelError("Message", "Description contains invalid characters (Enter A-Z, a-z)"); return(BadRequest(ModelState)); } if (_unitOfWork.Repository <CareEvent>().Queryable(). Where(l => l.Description == careEventForUpdate.CareEventName) .Count() > 0) { ModelState.AddModelError("Message", "Item with same name already exists"); return(BadRequest(ModelState)); } long id = 0; if (ModelState.IsValid) { var newCareEvent = new CareEvent() { Description = careEventForUpdate.CareEventName }; _careEventRepository.Save(newCareEvent); id = newCareEvent.Id; } var mappedCareEvent = await GetCareEventAsync <CareEventIdentifierDto>(id); if (mappedCareEvent == null) { return(StatusCode(500, "Unable to locate newly added item")); } return(CreatedAtAction("GetCareEventByIdentifier", new { id = mappedCareEvent.Id }, CreateLinksForCareEvent <CareEventIdentifierDto>(mappedCareEvent))); }
public async Task CreateAsync(UserInfo userInfo) { var user = new User { FirstName = userInfo.FirstName, LastName = userInfo.LastName, UserName = userInfo.UserName, PasswordHash = userInfo.PasswordHash, Email = userInfo.Email }; await Task.Run(() => { userRepository.Save(user); userInfo.Id = user.Id; }); }
public async Task <IActionResult> CreateLabResult( [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) .Count() > 0) { ModelState.AddModelError("Message", "Item with same name already exists"); return(BadRequest(ModelState)); } long id = 0; if (ModelState.IsValid) { var newLabResult = new LabResult() { Description = labResultForUpdate.LabResultName, Active = true }; _labResultRepository.Save(newLabResult); id = newLabResult.Id; } var mappedLabResult = await GetLabResultAsync <LabResultIdentifierDto>(id); if (mappedLabResult == null) { return(StatusCode(500, "Unable to locate newly added item")); } return(CreatedAtAction("GetLabResultByIdentifier", new { id = mappedLabResult.Id }, CreateLinksForLabResult <LabResultIdentifierDto>(mappedLabResult))); }
public async Task <IActionResult> CreateHoliday( [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) .Count() > 0) { ModelState.AddModelError("Message", "A holiday has already been loaded for this date"); return(BadRequest(ModelState)); } long id = 0; if (ModelState.IsValid) { var newHoliday = new Holiday() { HolidayDate = holidayForUpdate.HolidayDate, Description = holidayForUpdate.Description }; _holidayRepository.Save(newHoliday); id = newHoliday.Id; } var mappedHoliday = await GetHolidayAsync <HolidayIdentifierDto>(id); if (mappedHoliday == null) { return(StatusCode(500, "Unable to locate newly added item")); } return(CreatedAtAction("GetHolidayByIdentifier", new { id = mappedHoliday.Id }, CreateLinksForHoliday <HolidayIdentifierDto>(mappedHoliday))); }
public async Task AddToRoleAsync(UserInfo userInfo, string roleName) { var user = userRepository.Get(userInfo.Id); var role = roleRepository.Queryable().SingleOrDefault(r => r.Key == roleName); if (user == null) { throw new InvalidOperationException("User not found."); } if (role == null) { throw new InvalidOperationException("Role not recognised."); } await Task.Run(() => { userRoleRepository.Save(new UserRole { User = user, Role = role }); }); }
public async Task <ActionResult <LoginResponseDto> > Login( [FromBody] LoginRequestDto request) { if (request == null) { ModelState.AddModelError("Message", "Unable to locate payload for login request"); return(BadRequest(ModelState)); } var userFromManager = await _userManager.FindByNameAsync(request.UserName); var userFromRepo = await _userRepository.GetAsync(u => u.UserName == request.UserName, new string[] { "Facilities.Facility" }); if (userFromManager != null && userFromRepo != null) { if (await _userManager.CheckPasswordAsync(userFromManager, request.Password)) { if (userFromRepo.Active) { var audit = new AuditLog() { AuditType = AuditType.UserLogin, User = userFromRepo, ActionDate = DateTime.Now, Details = "User logged in to PViMS" }; _auditLogRepository.Save(audit); //var isAdmin = IsAdmin(user); //if (!isAdmin) return RedirectToLocal(returnUrl); //var pendingScriptsExist = AnyPendingScripts(); //// Send user to deployment page //if (pendingScriptsExist) //{ // return RedirectToAction("Index", "Deployment"); //} var refreshToken = _tokenFactory.GenerateToken(); userFromRepo.AddRefreshToken(refreshToken, HttpContext?.Connection?.RemoteIpAddress?.ToString()); _userRepository.Update(userFromRepo); await _unitOfWork.CompleteAsync(); return(Ok(new LoginResponseDto(await _jwtFactory.GenerateEncodedToken(userFromRepo, await _userManager.GetRolesAsync(userFromManager)), refreshToken, userFromRepo.EulaAcceptanceDate == null, userFromRepo.AllowDatasetDownload))); } else { ModelState.AddModelError("Message", "User is not active."); } } else { ModelState.AddModelError("Message", "Invalid password specified."); } } else { ModelState.AddModelError("Message", "Invalid username specified."); } return(BadRequest(ModelState)); }
public async Task <IActionResult> CreatePatientCondition(int patientId, [FromBody] PatientConditionForUpdateDto conditionForUpdate) { if (conditionForUpdate == null) { ModelState.AddModelError("Message", "Unable to locate payload for new condition"); return(BadRequest(ModelState)); } var patientFromRepo = await _patientRepository.GetAsync(f => f.Id == patientId); if (patientFromRepo == null) { return(NotFound()); } var sourceTermFromRepo = _terminologyMeddraRepository.Get(conditionForUpdate.SourceTerminologyMedDraId); if (sourceTermFromRepo == null) { ModelState.AddModelError("Message", "Unable to locate source term"); } Outcome outcomeFromRepo = null; if (!String.IsNullOrWhiteSpace(conditionForUpdate.Outcome)) { outcomeFromRepo = _outcomeRepository.Get(o => o.Description == conditionForUpdate.Outcome); if (outcomeFromRepo == null) { ModelState.AddModelError("Message", "Unable to locate outcome"); } } TreatmentOutcome treatmentOutcomeFromRepo = null; if (!String.IsNullOrWhiteSpace(conditionForUpdate.TreatmentOutcome)) { treatmentOutcomeFromRepo = _treatmentOutcomeRepository.Get(to => to.Description == conditionForUpdate.TreatmentOutcome); if (treatmentOutcomeFromRepo == null) { ModelState.AddModelError("Message", "Unable to locate treatment outcome"); } } ValidateConditionForUpdateModel(patientFromRepo, conditionForUpdate, 0); // Custom validation if (outcomeFromRepo != null && treatmentOutcomeFromRepo != null) { if (outcomeFromRepo.Description == "Fatal" && treatmentOutcomeFromRepo.Description != "Died") { ModelState.AddModelError("Message", "Treatment Outcome not consistent with Condition Outcome"); } if (outcomeFromRepo.Description != "Fatal" && treatmentOutcomeFromRepo.Description == "Died") { ModelState.AddModelError("Message", "Condition Outcome not consistent with Treatment Outcome"); } } if (ModelState.IsValid) { var conditionDetail = PrepareConditionDetail(conditionForUpdate); if (!conditionDetail.IsValid()) { conditionDetail.InvalidAttributes.ForEach(element => ModelState.AddModelError("Message", element)); } if (ModelState.IsValid) { var patientCondition = patientFromRepo.AddOrUpdatePatientCondition(0, sourceTermFromRepo, conditionForUpdate.StartDate, conditionForUpdate.OutcomeDate, outcomeFromRepo, treatmentOutcomeFromRepo, conditionForUpdate.CaseNumber, conditionForUpdate.Comments, conditionForUpdate.SourceDescription, _patientStatusRepository.Get(ps => ps.Description == "Died")); //throw new Exception(JsonConvert.SerializeObject(patientCondition)); _modelExtensionBuilder.UpdateExtendable(patientCondition, conditionDetail.CustomAttributes, "Admin"); _patientConditionRepository.Save(patientCondition); await _unitOfWork.CompleteAsync(); var mappedPatientCondition = _mapper.Map <PatientConditionIdentifierDto>(patientCondition); if (mappedPatientCondition == null) { return(StatusCode(500, "Unable to locate newly added condition")); } return(CreatedAtAction("GetPatientConditionByIdentifier", new { id = mappedPatientCondition.Id }, CreateLinksForPatientCondition <PatientConditionIdentifierDto>(mappedPatientCondition))); } } return(BadRequest(ModelState)); }
public async Task <IActionResult> CreatePatientEnrolment(long patientId, [FromBody] EnrolmentForCreationDto enrolmentForCreationDto) { if (enrolmentForCreationDto == null) { ModelState.AddModelError("Message", "Enrolment payload not populated"); return(BadRequest(ModelState)); } var patientFromRepo = await _patientRepository.GetAsync(f => f.Id == patientId); if (patientFromRepo == null) { ModelState.AddModelError("Message", "Unable to locate patient record"); return(BadRequest(ModelState)); } var cohortGroupFromRepo = await _cohortGroupRepository.GetAsync(f => f.Id == enrolmentForCreationDto.CohortGroupId); if (cohortGroupFromRepo == null) { ModelState.AddModelError("Message", "Unable to locate the cohort group"); return(BadRequest(ModelState)); } var enrolmentFromRepo = await _cohortGroupEnrolmentRepository.GetAsync(f => f.Patient.Id == patientId && f.CohortGroup.Id == enrolmentForCreationDto.CohortGroupId); if (enrolmentFromRepo != null) { ModelState.AddModelError("Message", "Patient has already been enrolled into this cohort"); return(BadRequest(ModelState)); } var enroledDate = enrolmentForCreationDto.EnrolmentDate.AddDays(1).Date; if (enroledDate > DateTime.Today) { ModelState.AddModelError("Message", "Enrolment Date should be less than or the same date as today"); return(BadRequest(ModelState)); } var conditionStartDate = patientFromRepo.GetConditionForGroupAndDate(cohortGroupFromRepo.Condition.Description, DateTime.Today).OnsetDate; if (enroledDate < conditionStartDate.Date) { ModelState.AddModelError("Message", "Enrolment Date should be after or the same date as the condition start date"); return(BadRequest(ModelState)); } long id = 0; if (ModelState.IsValid) { var newEnrolment = new CohortGroupEnrolment() { CohortGroup = cohortGroupFromRepo, EnroledDate = enroledDate, Patient = patientFromRepo }; _cohortGroupEnrolmentRepository.Save(newEnrolment); id = newEnrolment.Id; } var mappedEnrolment = await GetEnrolmentAsync(id); if (mappedEnrolment == null) { return(StatusCode(500, "Unable to locate newly added enrolment")); } return(CreatedAtAction("GetPatientEnrolmentByIdentifier", new { patientId, id = mappedEnrolment.Id }, CreateLinksForEnrolment <EnrolmentIdentifierDto>(patientId, mappedEnrolment))); }
public async Task <IActionResult> CreateDatasetElement( [FromBody] DatasetElementForUpdateDto datasetElementForUpdate) { if (datasetElementForUpdate == null) { ModelState.AddModelError("Message", "Unable to load payload for new request"); } if (Regex.Matches(datasetElementForUpdate.ElementName, @"[a-zA-Z() ']").Count < datasetElementForUpdate.ElementName.Length) { ModelState.AddModelError("Message", "Element contains invalid characters (Enter A-Z, a-z, open and Close brackets)"); } if (Regex.Matches(datasetElementForUpdate.OID, @"[-a-zA-Z0-9 ']").Count < datasetElementForUpdate.OID.Length) { ModelState.AddModelError("Message", "OID contains invalid characters (Enter A-Z, a-z, 0-9, hyphen)"); } if (Regex.Matches(datasetElementForUpdate.DefaultValue, @"[-a-zA-Z0-9 ']").Count < datasetElementForUpdate.DefaultValue.Length) { ModelState.AddModelError("Message", "Default value contains invalid characters (Enter A-Z, a-z, 0-9, hyphen)"); } if (_unitOfWork.Repository <DatasetElement>().Queryable(). Where(l => l.ElementName == datasetElementForUpdate.ElementName) .Count() > 0) { ModelState.AddModelError("Message", "Item with same name already exists"); } var fieldType = await _fieldTypeRepository.GetAsync(ft => ft.Description == datasetElementForUpdate.FieldTypeName.ToString()); if (fieldType == null) { ModelState.AddModelError("Message", "Unable to locate field type"); } var elementType = await _datasetElementTypeRepository.GetAsync(ft => ft.Description == "Generic"); if (elementType == null) { ModelState.AddModelError("Message", "Unable to locate element type"); } long id = 0; if (ModelState.IsValid) { var newDatasetElement = new DatasetElement() { DatasetElementType = elementType, ElementName = datasetElementForUpdate.ElementName, Oid = datasetElementForUpdate.OID, DefaultValue = datasetElementForUpdate.DefaultValue, Field = new Field() { Anonymise = (datasetElementForUpdate.Anonymise == Models.ValueTypes.YesNoValueType.Yes), Mandatory = (datasetElementForUpdate.Mandatory == Models.ValueTypes.YesNoValueType.Yes), FieldType = fieldType, MaxLength = datasetElementForUpdate.FieldTypeName == FieldTypes.AlphaNumericTextbox ? datasetElementForUpdate.MaxLength : (short?)null, Decimals = datasetElementForUpdate.FieldTypeName == FieldTypes.NumericTextbox ? datasetElementForUpdate.Decimals : (short?)null, MinSize = datasetElementForUpdate.FieldTypeName == FieldTypes.NumericTextbox ? datasetElementForUpdate.MinSize : (decimal?)null, MaxSize = datasetElementForUpdate.FieldTypeName == FieldTypes.NumericTextbox ? datasetElementForUpdate.MaxSize : (decimal?)null }, System = (datasetElementForUpdate.System == Models.ValueTypes.YesNoValueType.Yes) }; var rule = newDatasetElement.GetRule(DatasetRuleType.ElementCanoOnlyLinkToSingleDataset); rule.RuleActive = (datasetElementForUpdate.SingleDatasetRule == Models.ValueTypes.YesNoValueType.Yes); _datasetElementRepository.Save(newDatasetElement); id = newDatasetElement.Id; var mappedDatasetElement = await GetDatasetElementAsync <DatasetElementIdentifierDto>(id); if (mappedDatasetElement == null) { return(StatusCode(500, "Unable to locate newly added item")); } return(CreatedAtAction("GetDatasetElementByIdentifier", new { id = mappedDatasetElement.Id }, CreateLinksForDatasetElement <DatasetElementIdentifierDto>(mappedDatasetElement))); } return(BadRequest(ModelState)); }
public async Task <IActionResult> CreateEncounterType( [FromBody] EncounterTypeForUpdateDto encounterTypeForUpdate) { if (encounterTypeForUpdate == null) { ModelState.AddModelError("Message", "Unable to locate payload for new request"); } if (Regex.Matches(encounterTypeForUpdate.EncounterTypeName, @"[a-zA-Z ']").Count < encounterTypeForUpdate.EncounterTypeName.Length) { ModelState.AddModelError("Message", "Description contains invalid characters (Enter A-Z, a-z)"); } if (!String.IsNullOrWhiteSpace(encounterTypeForUpdate.Help)) { if (Regex.Matches(encounterTypeForUpdate.Help, @"[a-zA-Z0-9. ']").Count < encounterTypeForUpdate.Help.Length) { ModelState.AddModelError("Message", "Help contains invalid characters (Enter A-Z, a-z, 0-9, period)"); } } if (_unitOfWork.Repository <EncounterType>().Queryable(). Where(l => l.Description == encounterTypeForUpdate.EncounterTypeName) .Count() > 0) { ModelState.AddModelError("Message", "Item with same name already exists"); } var workPlan = _workPlanRepository.Get(wp => wp.Description == encounterTypeForUpdate.WorkPlanName); if (workPlan == null) { ModelState.AddModelError("Message", "Unable to locate work plan"); } long id = 0; if (ModelState.IsValid) { var newEncounterType = new EncounterType() { Description = encounterTypeForUpdate.EncounterTypeName, Help = encounterTypeForUpdate.Help }; var newEncounterTypeWorkPlan = new EncounterTypeWorkPlan() { CohortGroup = null, EncounterType = newEncounterType, WorkPlan = workPlan }; _encounterTypeRepository.Save(newEncounterType); _encounterTypeWorkPlanRepository.Save(newEncounterTypeWorkPlan); id = newEncounterType.Id; var mappedEncounterType = await GetEncounterTypeAsync <EncounterTypeIdentifierDto>(id); if (mappedEncounterType == null) { return(StatusCode(500, "Unable to locate newly added item")); } return(CreatedAtAction("GetEncounterTypeByIdentifier", new { id = mappedEncounterType.Id }, CreateLinksForEncounterType <EncounterTypeIdentifierDto>(mappedEncounterType))); } return(BadRequest(ModelState)); }
public async Task <IActionResult> CreateCondition( [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) .Count() > 0) { ModelState.AddModelError("Message", "Item with same name already exists"); } if (ModelState.IsValid) { var newCondition = new Condition() { Description = conditionForUpdate.ConditionName, Chronic = (conditionForUpdate.Chronic == Models.ValueTypes.YesNoValueType.Yes), Active = (conditionForUpdate.Active == Models.ValueTypes.YesNoValueType.Yes) }; // ensure lab tests are linked to condition foreach (var labTestId in conditionForUpdate.ConditionLabTests) { newCondition.ConditionLabTests.Add(new ConditionLabTest() { LabTest = _labTestRepository.Get(f => f.Id == labTestId) }); } // ensure products are linked to condition foreach (var productId in conditionForUpdate.ConditionMedications) { var concept = _conceptRepository.Get(c => c.Id == productId, new string[] { "" }); newCondition.ConditionMedications.Add(new ConditionMedication() { Product = null, Concept = concept }); } // ensure meddra terms are linked to condition foreach (var terminologyMeddraId in conditionForUpdate.ConditionMedDras) { newCondition.ConditionMedDras.Add(new ConditionMedDra() { TerminologyMedDra = _terminologyMeddraRepository.Get(f => f.Id == terminologyMeddraId) }); } _conditionRepository.Save(newCondition); await _unitOfWork.CompleteAsync(); var mappedCondition = await GetConditionAsync <ConditionIdentifierDto>(newCondition.Id); if (mappedCondition == null) { return(StatusCode(500, "Unable to locate newly added item")); } return(CreatedAtAction("GetConditionByIdentifier", new { id = mappedCondition.Id }, CreateLinksForCondition <ConditionIdentifierDto>(mappedCondition))); } return(BadRequest(ModelState)); }
public async Task <IActionResult> CreateMetaReport( [FromBody] MetaReportForUpdateDto metaReportForUpdate) { if (metaReportForUpdate == null) { ModelState.AddModelError("Message", "Unable to locate payload for new request"); } if (Regex.Matches(metaReportForUpdate.ReportName, @"[a-zA-Z0-9 ]").Count < metaReportForUpdate.ReportName.Length) { ModelState.AddModelError("Message", "Report name contains invalid characters (Enter A-Z, a-z, 0-9, space)"); } var coreEntityFromRepo = await _metaTableRepository.GetAsync(f => f.TableName == metaReportForUpdate.CoreEntity); if (coreEntityFromRepo == null) { ModelState.AddModelError("Message", "Unable to locate core entity"); } if (!string.IsNullOrWhiteSpace(metaReportForUpdate.ReportDefinition)) { if (Regex.Matches(metaReportForUpdate.ReportDefinition, @"[-a-zA-Z0-9 .,]").Count < metaReportForUpdate.ReportDefinition.Length) { ModelState.AddModelError("Message", "Report definition contains invalid characters (Enter A-Z, a-z, 0-9, space, hyphen, period, comma)"); } } if (!string.IsNullOrWhiteSpace(metaReportForUpdate.Breadcrumb)) { if (Regex.Matches(metaReportForUpdate.Breadcrumb, @"[-a-zA-Z0-9 .,]").Count < metaReportForUpdate.Breadcrumb.Length) { ModelState.AddModelError("Message", "Bread crumb contains invalid characters (Enter A-Z, a-z, 0-9, space, hyphen, period, comma)"); } } if (_unitOfWork.Repository <MetaReport>().Queryable(). Where(l => l.ReportName == metaReportForUpdate.ReportName) .Count() > 0) { ModelState.AddModelError("Message", "Item with same name already exists"); } if (ModelState.IsValid) { var newMetaReport = new MetaReport() { ReportName = metaReportForUpdate.ReportName, ReportDefinition = metaReportForUpdate.ReportDefinition, Breadcrumb = metaReportForUpdate.Breadcrumb, IsSystem = false, MetaReportGuid = Guid.NewGuid(), ReportStatus = metaReportForUpdate.ReportStatus, MetaDefinition = PrepareMetaDefinition(metaReportForUpdate) }; _metaReportRepository.Save(newMetaReport); var mappedMetaReport = await GetMetaReportAsync <MetaReportIdentifierDto>(newMetaReport.Id); if (mappedMetaReport == null) { return(StatusCode(500, "Unable to locate newly added item")); } return(CreatedAtAction("GetMetaReportByIdentifier", new { id = mappedMetaReport.Id }, CreateLinksForMetaReport <MetaReportIdentifierDto>(mappedMetaReport))); } return(BadRequest(ModelState)); }
public async Task <IActionResult> CreateForm([FromBody] FormForCreationDto formForCreation) { if (formForCreation == null) { ModelState.AddModelError("Message", "Unable to locate payload for new form"); return(BadRequest(ModelState)); } if (formForCreation.HasAttachment == false) { ModelState.AddModelError("Message", "Unable to process form as no attachment has been submitted"); return(BadRequest(ModelState)); } // Meta form for template extraction var metaFormFromRepo = await _metaFormRepository.GetAsync(f => f.ActionName.ToLower().Replace(" ", "") == formForCreation.FormType.ToLower().Replace(" ", "")); if (metaFormFromRepo == null) { ModelState.AddModelError("Message", "Unable to locate meta form for template extraction"); return(BadRequest(ModelState)); } // Store user for audit log generation purposes var userName = _httpContextAccessor.HttpContext.User.FindFirst(ClaimTypes.NameIdentifier).Value; var userFromRepo = _userRepository.Get(u => u.UserName == userName); AuditLog auditLog = null; // TODO Use meta form to identify context handler (add/update encounter/patient) //var handler = new FormValueHandler(formForCreation.FormValues.Where(fv => fv.FormControlKey == "Object").Select(fv => fv.FormControlValue).ToList()); _formHandler.SetForm(formForCreation); // Validation of the source entity _formHandler.ValidateSourceIdentifier(); if (_formHandler.GetValidationErrors().Count > 0) { foreach (string message in _formHandler.GetValidationErrors()) { ModelState.AddModelError("Message", message); } } if (ModelState.IsValid) { _formHandler.PreparePatientAndClinicalDetail(); if (_formHandler.GetValidationErrors().Count > 0) { foreach (string message in _formHandler.GetValidationErrors()) { ModelState.AddModelError("Message", message); } } } if (ModelState.IsValid) { try { auditLog = new AuditLog() { AuditType = AuditType.SynchronisationForm, User = userFromRepo, ActionDate = DateTime.Now, Details = $"Form submission successful {formForCreation.FormIdentifier}", Log = JsonConvert.SerializeObject(formForCreation, Formatting.Indented) }; await _auditLogRepository.SaveAsync(auditLog); await _formHandler.ProcessFormForCreationOrUpdateAsync(); await _unitOfWork.CompleteAsync(); return(Ok()); } catch (Exception ex) { var error = new Dictionary <string, string> { { "Type", ex.GetType().ToString() }, { "Message", ex.Message }, { "StackTrace", ex.StackTrace } }; auditLog = new AuditLog() { AuditType = AuditType.SynchronisationError, User = userFromRepo, ActionDate = DateTime.Now, Details = $"Error on form {formForCreation.FormIdentifier}", Log = JsonConvert.SerializeObject(error, Formatting.Indented) }; _auditLogRepository.Save(auditLog); return(StatusCode(500, ex.Message + " " + ex.InnerException?.Message)); } } var audit = new AuditLog() { AuditType = AuditType.SynchronisationError, User = userFromRepo, ActionDate = DateTime.Now, Details = $"Form submission with model error {formForCreation.FormIdentifier}", Log = JsonConvert.SerializeObject(formForCreation, Formatting.Indented) }; await _auditLogRepository.SaveAsync(audit); return(BadRequest(ModelState)); }
public void AddSelectionDataItem(SelectionDataItem newItem) { _selectionDataItemRepository.Save(newItem); }
public async Task <IActionResult> CreateMetaWidget(long metaPageId, [FromBody] MetaWidgetForCreationDto metaWidgetForCreation) { if (metaWidgetForCreation == null) { ModelState.AddModelError("Message", "Unable to locate payload for new request"); } var metaPageFromRepo = await _metaPageRepository.GetAsync(f => f.Id == metaPageId); if (metaPageFromRepo == null) { return(NotFound()); } if (Regex.Matches(metaWidgetForCreation.WidgetName, @"[a-zA-Z0-9 ]").Count < metaWidgetForCreation.WidgetName.Length) { ModelState.AddModelError("Message", "Widget name contains invalid characters (Enter A-Z, a-z, 0-9, space)"); } if (Regex.Matches(metaWidgetForCreation.WidgetType, @"[a-zA-Z]").Count < metaWidgetForCreation.WidgetType.Length) { ModelState.AddModelError("Message", "Widget type contains invalid characters (Enter A-Z, a-z)"); } if (!string.IsNullOrWhiteSpace(metaWidgetForCreation.WidgetDefinition)) { if (Regex.Matches(metaWidgetForCreation.WidgetDefinition, @"[-a-zA-Z0-9 .,]").Count < metaWidgetForCreation.WidgetDefinition.Length) { ModelState.AddModelError("Message", "Widget definition contains invalid characters (Enter A-Z, a-z, 0-9, space, hyphen, period, comma)"); } } if (Regex.Matches(metaWidgetForCreation.Icon, @"[a-zA-Z_]").Count < metaWidgetForCreation.Icon.Length) { ModelState.AddModelError("Message", "Icon contains invalid characters (Enter A-Z, a-z, underscore)"); } var metaWidgetTypeFromRepo = await _metaWidgetTypeRepository.GetAsync(f => f.Description == metaWidgetForCreation.WidgetType); if (metaWidgetTypeFromRepo == null) { ModelState.AddModelError("Message", "Unable to locate widget type"); } if (_unitOfWork.Repository <MetaWidget>().Queryable(). Where(l => l.MetaPage.Id == metaPageId && l.WidgetName == metaWidgetForCreation.WidgetName) .Count() > 0) { ModelState.AddModelError("Message", "Item with same name already exists"); } if (ModelState.IsValid) { var widgetTypeE = (MetaWidgetTypes)metaWidgetTypeFromRepo.Id; var content = string.Empty; switch (widgetTypeE) { case MetaWidgetTypes.General: content = "** PLEASE ENTER YOUR CONTENT HERE **"; break; case MetaWidgetTypes.SubItem: case MetaWidgetTypes.ItemList: content = GetBaseTemplate(widgetTypeE, metaPageId); break; default: break; } var newMetaWidget = new MetaWidget() { Content = content, MetaPage = metaPageFromRepo, WidgetDefinition = metaWidgetForCreation.WidgetDefinition, WidgetType = metaWidgetTypeFromRepo, WidgetLocation = MetaWidgetLocation.Unassigned, WidgetName = metaWidgetForCreation.WidgetName, WidgetStatus = MetaWidgetStatus.Unpublished, Icon = metaWidgetForCreation.Icon }; _metaWidgetRepository.Save(newMetaWidget); var mappedMetaWidget = await GetMetaWidgetAsync <MetaWidgetIdentifierDto>(metaPageId, newMetaWidget.Id); if (mappedMetaWidget == null) { return(StatusCode(500, "Unable to locate newly added item")); } return(CreatedAtAction("GetMetaWidgetByIdentifier", new { metaPageId, id = mappedMetaWidget.Id }, CreateLinksForMetaWidget <MetaWidgetIdentifierDto>(metaPageId, mappedMetaWidget))); } return(BadRequest(ModelState)); }
public async Task <IActionResult> CreateMetaPage( [FromBody] MetaPageForUpdateDto metaPageForUpdate) { if (metaPageForUpdate == null) { ModelState.AddModelError("Message", "Unable to locate payload for new request"); } if (Regex.Matches(metaPageForUpdate.PageName, @"[a-zA-Z0-9 ]").Count < metaPageForUpdate.PageName.Length) { ModelState.AddModelError("Message", "Page name contains invalid characters (Enter A-Z, a-z, 0-9, space)"); return(BadRequest(ModelState)); } if (!string.IsNullOrWhiteSpace(metaPageForUpdate.PageDefinition)) { if (Regex.Matches(metaPageForUpdate.PageDefinition, @"[-a-zA-Z0-9 .,]").Count < metaPageForUpdate.PageDefinition.Length) { ModelState.AddModelError("Message", "Page definition contains invalid characters (Enter A-Z, a-z, 0-9, space, hyphen, period, comma)"); return(BadRequest(ModelState)); } } if (!string.IsNullOrWhiteSpace(metaPageForUpdate.Breadcrumb)) { if (Regex.Matches(metaPageForUpdate.Breadcrumb, @"[-a-zA-Z0-9 .,]").Count < metaPageForUpdate.Breadcrumb.Length) { ModelState.AddModelError("Message", "Bread crumb contains invalid characters (Enter A-Z, a-z, 0-9, space, hyphen, period, comma)"); return(BadRequest(ModelState)); } } if (_unitOfWork.Repository <MetaPage>().Queryable(). Where(l => l.PageName == metaPageForUpdate.PageName) .Count() > 0) { ModelState.AddModelError("Message", "Item with same name already exists"); } if (ModelState.IsValid) { var newMetaPage = new MetaPage() { PageName = metaPageForUpdate.PageName, PageDefinition = metaPageForUpdate.PageDefinition, Breadcrumb = metaPageForUpdate.Breadcrumb, IsSystem = false, MetaDefinition = string.Empty, MetaPageGuid = Guid.NewGuid(), IsVisible = (metaPageForUpdate.Visible == Models.ValueTypes.YesNoValueType.Yes) }; _metaPageRepository.Save(newMetaPage); var mappedMetaPage = await GetMetaPageAsync <MetaPageIdentifierDto>(newMetaPage.Id); if (mappedMetaPage == null) { return(StatusCode(500, "Unable to locate newly added item")); } return(CreatedAtAction("GetMetaPageByIdentifier", new { id = mappedMetaPage.Id }, CreateLinksForMetaPage <MetaPageIdentifierDto>(mappedMetaPage))); } return(BadRequest(ModelState)); }