public async Task <Result <AcceptReportResponseDto> > AcceptReport(int alertId, int reportId) { var alertReport = await _nyssContext.AlertReports .Include(ar => ar.Alert) .Include(ar => ar.Report) .Where(ar => ar.AlertId == alertId && ar.ReportId == reportId) .SingleAsync(); if (!GetAlertHasStatusThatAllowsReportCrossChecks(alertReport)) { return(Error <AcceptReportResponseDto>(ResultKey.Alert.AcceptReport.WrongAlertStatus)); } if (alertReport.Report.Status != ReportStatus.Pending) { return(Error <AcceptReportResponseDto>(ResultKey.Alert.AcceptReport.WrongReportStatus)); } alertReport.Report.Status = ReportStatus.Accepted; alertReport.Report.AcceptedAt = _dateTimeProvider.UtcNow; alertReport.Report.AcceptedBy = _authorizationService.GetCurrentUser(); await _nyssContext.SaveChangesAsync(); var response = new AcceptReportResponseDto { AssessmentStatus = await _alertService.GetAssessmentStatus(alertId) }; return(Success(response)); }
public async Task <Alert> ReportAdded(Report report) { var dataCollectorIsNotHuman = report.DataCollector.DataCollectorType != DataCollectorType.Human; var reportTypeIsAggregateOrDcp = report.ReportType == ReportType.Aggregate || report.ReportType == ReportType.DataCollectionPoint; var healthRiskTypeIsActivity = report.ProjectHealthRisk.HealthRisk.HealthRiskType == HealthRiskType.Activity; if (report.IsTraining || dataCollectorIsNotHuman || reportTypeIsAggregateOrDcp || healthRiskTypeIsActivity) { return(null); } var projectHealthRisk = await _nyssContext.ProjectHealthRisks .Where(phr => phr == report.ProjectHealthRisk) .Include(phr => phr.AlertRule) .Include(phr => phr.HealthRisk) .SingleAsync(); if (projectHealthRisk.HealthRisk.HealthRiskType == HealthRiskType.Activity) { return(null); } await _reportLabelingService.ResolveLabelsOnReportAdded(report, projectHealthRisk); await _nyssContext.SaveChangesAsync(); var triggeredAlert = await HandleAlerts(report); await _nyssContext.SaveChangesAsync(); return(triggeredAlert); }
public async Task <Result> Escalate(int alertId) { var alertData = await _nyssContext.Alerts .Where(a => a.Id == alertId) .Select(alert => new { Alert = alert, LastReportVillage = alert.AlertReports.OrderByDescending(r => r.Report.Id).First().Report.RawReport.Village.Name, LastReportGateway = alert.AlertReports.OrderByDescending(r => r.Report.Id).First().Report.RawReport.ApiKey, HealthRisk = alert.ProjectHealthRisk.HealthRisk.LanguageContents .Where(lc => lc.ContentLanguage.Id == alert.ProjectHealthRisk.Project.NationalSociety.ContentLanguage.Id) .Select(lc => lc.Name) .Single(), Project = alert.ProjectHealthRisk.Project.Name, LanguageCode = alert.ProjectHealthRisk.Project.NationalSociety.ContentLanguage.LanguageCode, NotificationEmails = alert.ProjectHealthRisk.Project.EmailAlertRecipients.Select(ear => ear.EmailAddress).ToList(), NotificationPhoneNumbers = alert.ProjectHealthRisk.Project.SmsAlertRecipients.Select(sar => sar.PhoneNumber).ToList(), CountThreshold = alert.ProjectHealthRisk.AlertRule.CountThreshold, AcceptedReportCount = alert.AlertReports.Count(r => r.Report.Status == ReportStatus.Accepted), NationalSocietyId = alert.ProjectHealthRisk.Project.NationalSociety.Id }) .SingleAsync(); if (alertData.Alert.Status != AlertStatus.Pending) { return(Error(ResultKey.Alert.EscalateAlert.WrongStatus)); } if (alertData.AcceptedReportCount < alertData.CountThreshold) { return(Error(ResultKey.Alert.EscalateAlert.ThresholdNotReached)); } alertData.Alert.Status = AlertStatus.Escalated; alertData.Alert.EscalatedAt = _dateTimeProvider.UtcNow; alertData.Alert.EscalatedBy = _authorizationService.GetCurrentUser(); await _nyssContext.SaveChangesAsync(); try { await SendNotificationEmails(alertData.LanguageCode, alertData.NotificationEmails, alertData.Project, alertData.HealthRisk, alertData.LastReportVillage); await SendNotificationSmses(alertData.NationalSocietyId, alertData.LastReportGateway, alertData.LanguageCode, alertData.NotificationPhoneNumbers, alertData.Project, alertData.HealthRisk, alertData.LastReportVillage); } catch (ResultException exception) { return(Success(exception.Result.Message.Key)); } return(Success(ResultKey.Alert.EscalateAlert.Success)); }
public async Task <Result> Edit(int reportId, ReportRequestDto reportRequestDto) { var report = await _nyssContext.Reports .Include(r => r.RawReport) .Include(r => r.ProjectHealthRisk) .ThenInclude(phr => phr.Project) .SingleOrDefaultAsync(r => r.Id == reportId); if (report == null) { return(Error <ReportResponseDto>(ResultKey.Report.ReportNotFound)); } if (report.ReportType != ReportType.Aggregate && report.ReportType != ReportType.DataCollectionPoint) { return(Error <ReportResponseDto>(ResultKey.Report.Edit.HealthRiskCannotBeEdited)); } var projectHealthRisk = await _nyssContext.ProjectHealthRisks .Include(phr => phr.HealthRisk) .SingleOrDefaultAsync(phr => phr.HealthRiskId == reportRequestDto.HealthRiskId && phr.HealthRisk.HealthRiskType == HealthRiskType.Human && phr.Project.Id == report.ProjectHealthRisk.Project.Id); if (projectHealthRisk == null) { return(Error <ReportResponseDto>(ResultKey.Report.Edit.HealthRiskNotAssignedToProject)); } var updatedReceivedAt = new DateTime(reportRequestDto.Date.Year, reportRequestDto.Date.Month, reportRequestDto.Date.Day, report.ReceivedAt.Hour, report.ReceivedAt.Minute, report.ReceivedAt.Second); report.RawReport.ReceivedAt = updatedReceivedAt; report.ReceivedAt = updatedReceivedAt; report.ProjectHealthRisk = projectHealthRisk; report.ReportedCase.CountMalesBelowFive = reportRequestDto.CountMalesBelowFive; report.ReportedCase.CountMalesAtLeastFive = reportRequestDto.CountMalesAtLeastFive; report.ReportedCase.CountFemalesBelowFive = reportRequestDto.CountFemalesBelowFive; report.ReportedCase.CountFemalesAtLeastFive = reportRequestDto.CountFemalesAtLeastFive; report.ReportedCaseCount = reportRequestDto.CountMalesBelowFive + reportRequestDto.CountMalesAtLeastFive + reportRequestDto.CountFemalesBelowFive + reportRequestDto.CountFemalesAtLeastFive; if (report.ReportType == ReportType.DataCollectionPoint) { report.DataCollectionPointCase.ReferredCount = reportRequestDto.ReferredCount; report.DataCollectionPointCase.DeathCount = reportRequestDto.DeathCount; report.DataCollectionPointCase.FromOtherVillagesCount = reportRequestDto.FromOtherVillagesCount; } report.ModifiedAt = _dateTimeProvider.UtcNow; report.ModifiedBy = _authorizationService.GetCurrentUserName(); await _nyssContext.SaveChangesAsync(); return(SuccessMessage(ResultKey.Report.Edit.EditSuccess)); }
public async Task <Result> Create(CreateNationalSocietyRequestDto dto) { if (_nyssContext.NationalSocieties.Any(ns => ns.Name.ToLower() == dto.Name.ToLower())) { return(Error <int>(ResultKey.NationalSociety.Creation.NameAlreadyExists)); } var nationalSociety = new NationalSociety { Name = dto.Name, ContentLanguage = await GetLanguageById(dto.ContentLanguageId), Country = await GetCountryById(dto.CountryId), IsArchived = false, StartDate = DateTime.UtcNow }; if (nationalSociety.ContentLanguage == null) { return(Error <int>(ResultKey.NationalSociety.Creation.LanguageNotFound)); } if (nationalSociety.Country == null) { return(Error <int>(ResultKey.NationalSociety.Creation.CountryNotFound)); } await _nyssContext.AddAsync(nationalSociety); await _nyssContext.SaveChangesAsync(); _loggerAdapter.Info($"A national society {nationalSociety} was created"); return(Success(nationalSociety.Id)); }
public async Task <Result> Edit(int supervisorId, EditSupervisorRequestDto editSupervisorRequestDto) { try { var supervisorUserData = await _dataContext.Users.FilterAvailable() .OfType <SupervisorUser>() .Include(u => u.UserNationalSocieties) .Where(u => u.Id == supervisorId) .Select(u => new { User = u, CurrentProjectReference = u.SupervisorUserProjects .SingleOrDefault(sup => sup.Project.State == ProjectState.Open) }) .SingleOrDefaultAsync(); if (supervisorUserData == null) { _loggerAdapter.Debug($"A supervisor with id {supervisorId} was not found"); return(Error(ResultKey.User.Common.UserNotFound)); } var supervisorUser = supervisorUserData.User; supervisorUser.Name = editSupervisorRequestDto.Name; supervisorUser.Sex = editSupervisorRequestDto.Sex; supervisorUser.DecadeOfBirth = editSupervisorRequestDto.DecadeOfBirth; supervisorUser.PhoneNumber = editSupervisorRequestDto.PhoneNumber; supervisorUser.AdditionalPhoneNumber = editSupervisorRequestDto.AdditionalPhoneNumber; supervisorUser.Organization = editSupervisorRequestDto.Organization; await UpdateSupervisorProjectReferences(supervisorUser, supervisorUserData.CurrentProjectReference, editSupervisorRequestDto.ProjectId); await _dataContext.SaveChangesAsync(); return(Success()); } catch (ResultException e) { _loggerAdapter.Debug(e); return(e.Result); } }
public async Task <Result> Create(CreateGlobalCoordinatorRequestDto dto) { try { string securityStamp; GlobalCoordinatorUser user; using (var transactionScope = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled)) { var identityUser = await _identityUserRegistrationService.CreateIdentityUser(dto.Email, Role.GlobalCoordinator); securityStamp = await _identityUserRegistrationService.GenerateEmailVerification(identityUser.Email); var defaultUserApplicationLanguage = await _dataContext.ApplicationLanguages .SingleOrDefaultAsync(al => al.LanguageCode == EnglishLanguageCode); user = new GlobalCoordinatorUser { IdentityUserId = identityUser.Id, EmailAddress = identityUser.Email, Name = dto.Name, PhoneNumber = dto.PhoneNumber, AdditionalPhoneNumber = dto.AdditionalPhoneNumber, Organization = dto.Organization, Role = Role.GlobalCoordinator, ApplicationLanguage = defaultUserApplicationLanguage }; await _dataContext.AddAsync(user); await _dataContext.SaveChangesAsync(); transactionScope.Complete(); } await _verificationEmailService.SendVerificationEmail(user, securityStamp); return(Success(ResultKey.User.Registration.Success)); } catch (ResultException e) { _loggerAdapter.Debug(e); return(e.Result); } }
public async Task <Result <int> > Create(int nationalSocietyId, GatewaySettingRequestDto gatewaySettingRequestDto) { try { var nationalSocietyExists = await _nyssContext.NationalSocieties.AnyAsync(ns => ns.Id == nationalSocietyId); if (!nationalSocietyExists) { return(Error <int>(ResultKey.NationalSociety.SmsGateway.NationalSocietyDoesNotExist)); } var apiKeyExists = await _nyssContext.GatewaySettings.AnyAsync(gs => gs.ApiKey == gatewaySettingRequestDto.ApiKey); if (apiKeyExists) { return(Error <int>(ResultKey.NationalSociety.SmsGateway.ApiKeyAlreadyExists)); } var gatewaySettingToAdd = new GatewaySetting { Name = gatewaySettingRequestDto.Name, ApiKey = gatewaySettingRequestDto.ApiKey, GatewayType = gatewaySettingRequestDto.GatewayType, EmailAddress = gatewaySettingRequestDto.EmailAddress, NationalSocietyId = nationalSocietyId }; await _nyssContext.GatewaySettings.AddAsync(gatewaySettingToAdd); await _nyssContext.SaveChangesAsync(); await UpdateAuthorizedApiKeys(); return(Success(gatewaySettingToAdd.Id, ResultKey.NationalSociety.SmsGateway.SuccessfullyAdded)); } catch (ResultException exception) { _loggerAdapter.Debug(exception); return(exception.GetResult <int>()); } }
public async Task <Result> Edit(int technicalAdvisorId, EditTechnicalAdvisorRequestDto editTechnicalAdvisorRequestDto) { try { var user = await _nationalSocietyUserService.GetNationalSocietyUser <TechnicalAdvisorUser>(technicalAdvisorId); user.Name = editTechnicalAdvisorRequestDto.Name; user.PhoneNumber = editTechnicalAdvisorRequestDto.PhoneNumber; user.Organization = editTechnicalAdvisorRequestDto.Organization; user.AdditionalPhoneNumber = editTechnicalAdvisorRequestDto.AdditionalPhoneNumber; await _dataContext.SaveChangesAsync(); return(Success()); } catch (ResultException e) { _loggerAdapter.Debug(e); return(e.Result); } }
public async Task <Result> Create(HealthRiskRequestDto healthRiskRequestDto) { if (await _nyssContext.HealthRisks.AnyAsync(hr => hr.HealthRiskCode == healthRiskRequestDto.HealthRiskCode)) { return(Error(ResultKey.HealthRisk.HealthRiskNumberAlreadyExists)); } var languageContentIds = healthRiskRequestDto.LanguageContent.Select(lc => lc.LanguageId).ToArray(); var contentLanguages = await _nyssContext.ContentLanguages.Where(cl => languageContentIds.Contains(cl.Id)).ToDictionaryAsync(cl => cl.Id, cl => cl); var healthRisk = new HealthRisk { HealthRiskType = healthRiskRequestDto.HealthRiskType, HealthRiskCode = healthRiskRequestDto.HealthRiskCode, LanguageContents = healthRiskRequestDto.LanguageContent.Select(lc => new HealthRiskLanguageContent { Name = lc.Name, FeedbackMessage = lc.FeedbackMessage, CaseDefinition = lc.CaseDefinition, ContentLanguage = contentLanguages[lc.LanguageId] }).ToList(), AlertRule = healthRiskRequestDto.AlertRuleCountThreshold.HasValue ? new AlertRule { CountThreshold = healthRiskRequestDto.AlertRuleCountThreshold.Value, DaysThreshold = healthRiskRequestDto.AlertRuleDaysThreshold, KilometersThreshold = healthRiskRequestDto.AlertRuleKilometersThreshold } : null }; await _nyssContext.AddAsync(healthRisk); await _nyssContext.SaveChangesAsync(); return(SuccessMessage(ResultKey.HealthRisk.Create.CreationSuccess)); }
public async Task <Result> AddExisting(int nationalSocietyId, string userEmail) { var userData = await _dataContext.Users.FilterAvailable() .Where(u => u.EmailAddress == userEmail) .Select(u => new { u.Id, u.Role }) .SingleOrDefaultAsync(); if (userData == null) { return(Error(ResultKey.User.Registration.UserNotFound)); } if (userData.Role != Role.TechnicalAdvisor && userData.Role != Role.DataConsumer) { return(Error(ResultKey.User.Registration.NoAssignableUserWithThisEmailFound)); } var userAlreadyIsInThisNationalSociety = await _dataContext.UserNationalSocieties .FilterAvailableUsers() .AnyAsync(uns => uns.NationalSocietyId == nationalSocietyId && uns.UserId == userData.Id); if (userAlreadyIsInThisNationalSociety) { return(Error(ResultKey.User.Registration.UserIsAlreadyInThisNationalSociety)); } var nationalSocietyIsArchived = await _dataContext.NationalSocieties.AnyAsync(ns => ns.Id == nationalSocietyId && ns.IsArchived); if (nationalSocietyIsArchived) { return(Error(ResultKey.User.Registration.CannotAddExistingUsersToArchivedNationalSociety)); } var userNationalSociety = new UserNationalSociety { NationalSocietyId = nationalSocietyId, UserId = userData.Id }; await _dataContext.UserNationalSocieties.AddAsync(userNationalSociety); await _dataContext.SaveChangesAsync(); return(Success()); }
public async Task <Result <int> > Create(int nationalSocietyId, ProjectRequestDto projectRequestDto) { try { var nationalSocietyData = await _nyssContext.NationalSocieties .Where(ns => ns.Id == nationalSocietyId) .Select(ns => new { ns.IsArchived }) .SingleOrDefaultAsync(); if (nationalSocietyData == null) { return(Error <int>(ResultKey.Project.NationalSocietyDoesNotExist)); } if (nationalSocietyData.IsArchived) { return(Error <int>(ResultKey.Project.CannotAddProjectInArchivedNationalSociety)); } var healthRiskIdsInDatabase = await _nyssContext.HealthRisks.Select(hr => hr.Id).ToListAsync(); var healthRiskIdsToAttach = projectRequestDto.HealthRisks.Select(hr => hr.HealthRiskId).ToList(); if (!healthRiskIdsToAttach.All(healthRiskId => healthRiskIdsInDatabase.Contains(healthRiskId))) { return(Error <int>(ResultKey.Project.HealthRiskDoesNotExist)); } var projectToAdd = new Project { Name = projectRequestDto.Name, TimeZone = projectRequestDto.TimeZoneId, NationalSocietyId = nationalSocietyId, State = ProjectState.Open, StartDate = _dateTimeProvider.UtcNow, EndDate = null, ProjectHealthRisks = projectRequestDto.HealthRisks.Select(phr => new ProjectHealthRisk { FeedbackMessage = phr.FeedbackMessage, CaseDefinition = phr.CaseDefinition, HealthRiskId = phr.HealthRiskId, AlertRule = new AlertRule { //ToDo: make CountThreshold nullable or change validation CountThreshold = phr.AlertRuleCountThreshold ?? 0, DaysThreshold = phr.AlertRuleDaysThreshold, KilometersThreshold = phr.AlertRuleKilometersThreshold } }).ToList(), EmailAlertRecipients = projectRequestDto.EmailAlertRecipients.Select(ar => new EmailAlertRecipient { EmailAddress = ar.Email }).ToList(), SmsAlertRecipients = projectRequestDto.SmsAlertRecipients.Select(ar => new SmsAlertRecipient { PhoneNumber = ar.PhoneNumber }).ToList() }; await _nyssContext.Projects.AddAsync(projectToAdd); await _nyssContext.SaveChangesAsync(); return(Success(projectToAdd.Id, ResultKey.Project.SuccessfullyAdded)); } catch (ResultException exception) { _loggerAdapter.Debug(exception); return(exception.GetResult <int>()); } }
public async Task Handle(string queryString) { var parsedQueryString = HttpUtility.ParseQueryString(queryString); var sender = parsedQueryString[SenderParameterName]; var timestamp = parsedQueryString[TimestampParameterName]; var text = parsedQueryString[TextParameterName]; var incomingMessageId = parsedQueryString[IncomingMessageIdParameterName].ParseToNullableInt(); var outgoingMessageId = parsedQueryString[OutgoingMessageIdParameterName].ParseToNullableInt(); var modemNumber = parsedQueryString[ModemNumberParameterName].ParseToNullableInt(); var apiKey = parsedQueryString[ApiKeyParameterName]; ErrorReportData reportErrorData = null; try { Alert triggeredAlert = null; ProjectHealthRisk projectHealthRisk = null; GatewaySetting gatewaySetting = null; using (var transactionScope = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled)) { var rawReport = new RawReport { Sender = sender, Timestamp = timestamp, ReceivedAt = _dateTimeProvider.UtcNow, Text = text, IncomingMessageId = incomingMessageId, OutgoingMessageId = outgoingMessageId, ModemNumber = modemNumber, ApiKey = apiKey }; await _nyssContext.AddAsync(rawReport); var reportValidationResult = await ParseAndValidateReport(rawReport, parsedQueryString); if (reportValidationResult.IsSuccess) { gatewaySetting = reportValidationResult.GatewaySetting; projectHealthRisk = reportValidationResult.ReportData.ProjectHealthRisk; var epiDate = _dateTimeProvider.GetEpiDate(reportValidationResult.ReportData.ReceivedAt); var report = new Report { IsTraining = reportValidationResult.ReportData.DataCollector.IsInTrainingMode, ReportType = reportValidationResult.ReportData.ParsedReport.ReportType, Status = ReportStatus.New, ReceivedAt = reportValidationResult.ReportData.ReceivedAt, CreatedAt = _dateTimeProvider.UtcNow, DataCollector = reportValidationResult.ReportData.DataCollector, EpiWeek = epiDate.EpiWeek, EpiYear = epiDate.EpiYear, PhoneNumber = sender, Location = reportValidationResult.ReportData.DataCollector.Location, ReportedCase = reportValidationResult.ReportData.ParsedReport.ReportedCase, KeptCase = new ReportCase { CountMalesBelowFive = null, CountMalesAtLeastFive = null, CountFemalesBelowFive = null, CountFemalesAtLeastFive = null }, DataCollectionPointCase = reportValidationResult.ReportData.ParsedReport.DataCollectionPointCase, ProjectHealthRisk = projectHealthRisk, ReportedCaseCount = projectHealthRisk.HealthRisk.HealthRiskType == HealthRiskType.Human ? (reportValidationResult.ReportData.ParsedReport.ReportedCase.CountFemalesAtLeastFive ?? 0) + (reportValidationResult.ReportData.ParsedReport.ReportedCase.CountFemalesBelowFive ?? 0) + (reportValidationResult.ReportData.ParsedReport.ReportedCase.CountMalesAtLeastFive ?? 0) + (reportValidationResult.ReportData.ParsedReport.ReportedCase.CountMalesBelowFive ?? 0) : 1 }; rawReport.Report = report; await _nyssContext.Reports.AddAsync(report); triggeredAlert = await _alertService.ReportAdded(report); } else { reportErrorData = reportValidationResult.ErrorReportData; gatewaySetting = reportValidationResult.GatewaySetting; } await _nyssContext.SaveChangesAsync(); transactionScope.Complete(); } if (reportErrorData == null) { if (!string.IsNullOrEmpty(gatewaySetting?.EmailAddress) && projectHealthRisk != null) { var recipients = new List <string> { sender }; await _queuePublisherService.SendSMSesViaEagle(gatewaySetting.EmailAddress, gatewaySetting.Name, recipients, projectHealthRisk.FeedbackMessage); } if (triggeredAlert != null) { await _alertService.SendNotificationsForNewAlert(triggeredAlert, gatewaySetting); } } else { await SendFeedbackOnError(reportErrorData, gatewaySetting); } } catch (ReportValidationException e) { _loggerAdapter.Warn(e.Message); } }
public async Task <Result <StructureResponseDto.StructureRegionDto> > CreateRegion(int nationalSocietyId, string name) { if (await _nyssContext.NationalSocieties.AnyAsync(ns => ns.Id == nationalSocietyId && ns.IsArchived)) { return(Error <StructureResponseDto.StructureRegionDto>(ResultKey.NationalSociety.Structure.CannotCreateItemInArchivedNationalSociety)); } if (await _nyssContext.Regions.AnyAsync(ns => ns.Name == name && ns.NationalSociety.Id == nationalSocietyId)) { return(Error <StructureResponseDto.StructureRegionDto>(ResultKey.NationalSociety.Structure.ItemAlreadyExists)); } var entry = await _nyssContext.Regions.AddAsync(new Region { NationalSociety = _nyssContext.NationalSocieties .Attach(new NationalSociety { Id = nationalSocietyId }) .Entity, Name = name }); await _nyssContext.SaveChangesAsync(); return(Success(new StructureResponseDto.StructureRegionDto { Id = entry.Entity.Id, Name = name, Districts = new StructureResponseDto.StructureDistrictDto[0] })); }