public async Task Recipient_Delete_DoesDelete() { //Arrange Random rnd = new Random(); NotificationRule rule = new NotificationRule(); rule.Data = Guid.NewGuid().ToString(); rule.Subject = Guid.NewGuid().ToString(); rule.Text = Guid.NewGuid().ToString(); rule.CheckListId = rnd.Next(1, 255); rule.DataItemId = rnd.Next(1, 255); rule.AttachReport = rnd.NextDouble() >= 0.5; rule.RuleType = RuleType.Number; await rule.Create(DbContext).ConfigureAwait(false); NotificationRule ruleForRecipient = DbContext.Rules.AsNoTracking().First(); Recipient recipient = new Recipient(); recipient.Email = Guid.NewGuid().ToString(); recipient.NotificationRuleId = ruleForRecipient.Id; await recipient.Create(DbContext).ConfigureAwait(false); //Act await recipient.Delete(DbContext).ConfigureAwait(false); Recipient dbRecipient = DbContext.Recipients.AsNoTracking().First(); List <Recipient> recipientList = DbContext.Recipients.AsNoTracking().ToList(); //Assert Assert.NotNull(dbRecipient); Assert.AreEqual(1, recipientList.Count); Assert.AreEqual(recipient.Email, dbRecipient.Email); Assert.AreEqual(recipient.NotificationRuleId, dbRecipient.NotificationRuleId); Assert.AreEqual(Constants.WorkflowStates.Removed, dbRecipient.WorkflowState); }
public async Task NotificationRule_Delete_DoesDelete_WRuleTypeNumber() { //Arrange Random rnd = new Random(); NotificationRule rule = new NotificationRule(); rule.Data = Guid.NewGuid().ToString(); rule.Subject = Guid.NewGuid().ToString(); rule.Text = Guid.NewGuid().ToString(); rule.CheckListId = rnd.Next(1, 255); rule.DataItemId = rnd.Next(1, 255); rule.AttachReport = rnd.NextDouble() >= 0.5; rule.RuleType = RuleType.Number; await rule.Create(DbContext).ConfigureAwait(false); // Act await rule.Delete(DbContext).ConfigureAwait(false); NotificationRule dbNotificationRule = DbContext.Rules.AsNoTracking().First(); List <NotificationRule> notificationRuleList = DbContext.Rules.AsNoTracking().ToList(); List <NotificationRuleVersion> notificationRuleVersionList = DbContext.RuleVersions.AsNoTracking().ToList(); //Assert Assert.NotNull(dbNotificationRule); Assert.AreEqual(1, notificationRuleList.Count); Assert.AreEqual(2, notificationRuleVersionList.Count); Assert.AreEqual(rule.Data, dbNotificationRule.Data); Assert.AreEqual(rule.Subject, dbNotificationRule.Subject); Assert.AreEqual(rule.Text, dbNotificationRule.Text); Assert.AreEqual(rule.CheckListId, dbNotificationRule.CheckListId); Assert.AreEqual(rule.DataItemId, dbNotificationRule.DataItemId); Assert.AreEqual(rule.AttachReport, dbNotificationRule.AttachReport); Assert.AreEqual(rule.RuleType, dbNotificationRule.RuleType); Assert.AreEqual(Constants.WorkflowStates.Removed, dbNotificationRule.WorkflowState); }
/// <summary> /// Sets the active state of a rule /// </summary> /// <param name="id">ID of the rule to deactivate</param> /// <param name="owner">Current user</param> /// <param name="isActive">New active state</param> private async Task SetRuleActivAsync(string id, ClaimsPrincipal owner, bool isActive) { // Find the rule NotificationRule rule = GetRuleById(id); if (rule == null) { throw new KeyNotFoundException("Rule not found"); } // Check authorization if (!(await owner.IsCoordinatorAsync(_authorizationService)) && rule.Owner != await _userManager.GetUserAsync(owner)) { // Not coordinator nor owner throw new InvalidOperationException("User is not owner of this rule"); } // Deactivate rule rule.IsActive = isActive; // Save await _dbContext.SaveChangesAsync(); }
public IActionResult Save(NotificationRule notificationRule) { try { CheckAuthorization(Role.Worker); if (notificationRule != null) { if (notificationRule.Id == 0) { FactoryConcentrator.NotificationRuleFactory.Add(notificationRule); } else { FactoryConcentrator.NotificationRuleFactory.Update(notificationRule); } } return(Ok()); } catch (Exception exception) { return(BadRequest(exception)); } }
/// <summary> /// Delete a notification rule. /// </summary> /// <param name="rule">The notification rule</param> /// <returns></returns> public async Task DeleteNotificationRuleAsync(NotificationRule rule) { Arguments.CheckNotNull(rule, nameof(rule)); await DeleteNotificationRuleAsync(rule.Id); }
/// <summary> /// Add a notification rule. /// </summary> /// <param name="rule">Notification rule to create</param> /// <returns>Notification rule created</returns> public async Task <NotificationRule> CreateRuleAsync(NotificationRule rule) { Arguments.CheckNotNull(rule, nameof(rule)); return(await _service.CreateNotificationRuleAsync(rule)); }
public void Update(NotificationRule notificationRule) { Database.NotificationRuleService.Update(notificationRule); }
public void Add(NotificationRule notificationRule) { Database.NotificationRuleService.Add(notificationRule); }
/// <summary> /// Returns a list of unassigned notifiers for a rule /// </summary> /// <param name="rule">Rule notifier are searched for</param> public IEnumerable <BaseNotifierData> GetUnassignedNotifiers(NotificationRule rule) => _dbContext.Notifiers.ToList().Except(rule.Notifiers.Select(notifier => notifier.Notifier));
public async Task <OperationResult> Create(NotificationRuleModel ruleModel) { using (var transaction = await _dbContext.Database.BeginTransactionAsync()) { try { var notificationRule = new NotificationRule() { Subject = ruleModel.Subject, Text = ruleModel.Text, AttachReport = ruleModel.AttachReport, AttachLink = ruleModel.AttachLink, IncludeValue = ruleModel.IncludeValue, DataItemId = ruleModel.DataItemId, CheckListId = ruleModel.CheckListId, RuleType = ruleModel.RuleType, CreatedByUserId = UserId, UpdatedByUserId = UserId, }; if (ruleModel.Data != null) { notificationRule.Data = ruleModel.Data?.ToString(); } await notificationRule.Create(_dbContext); foreach (var recipientModel in ruleModel.Recipients) { var recipient = new Recipient() { CreatedByUserId = UserId, UpdatedByUserId = UserId, Email = recipientModel.Email, NotificationRuleId = notificationRule.Id, }; await recipient.Create(_dbContext); } var deviceUsersGroupedIds = ruleModel.DeviceUsers .Where(x => x.Id != null) .GroupBy(x => x.Id) .Select(x => x.Key) .ToList(); foreach (var deviceUserId in deviceUsersGroupedIds) { if (deviceUserId != null) { var deviceUser = new DeviceUser() { CreatedByUserId = UserId, UpdatedByUserId = UserId, NotificationRuleId = notificationRule.Id, DeviceUserId = (int)deviceUserId, }; await deviceUser.Create(_dbContext); } } transaction.Commit(); return(new OperationResult( true, _localizationService.GetString("NotificationRuleCreatedSuccessfully"))); } catch (Exception e) { transaction.Rollback(); _logger.LogError(e.Message); return(new OperationResult( false, _localizationService.GetString("ErrorWhileCreatingNotificationRule"))); } } }
/// <summary> /// Trys to update a rule. Creates a new rule if not ID is supplied /// </summary> /// <param name="rule">ID of rule to change</param> /// <param name="owner">Current user (owner of new rule)</param> /// <param name="name">Name of rule</param> /// <param name="trigger">Trigger type</param> /// <param name="filter">Advanced filter</param> /// <param name="title">Message title</param> /// <param name="message">Message body</param> /// <param name="bodyType">Type of message body</param> /// <param name="useTemplate">Whether the global template should be applied</param> /// <param name="tags">Message tags</param> /// <param name="notifiers">List of assigned notifiers</param> /// <param name="recipients">List of assigned recipients</param> /// <exception cref="System.Collections.Generic.KeyNotFoundException">Thrown when rule is not found</exception> /// <exception cref="System.InvalidOperationException">Thrown when rule can't be edited by user</exception> public async Task SaveOrCreateRuleAsync( string id, ClaimsPrincipal owner, string name, string trigger, string filter, string title, string message, MessageBodyType bodyType, bool useTemplate, string tags, string[] notifiers, string[] recipients) { User currentUser = await _userManager.GetUserAsync(owner); if (owner == null || currentUser == null) { throw new InvalidOperationException("Current user unknown"); } NotificationRule rule = await GetOrCreateRuleAsync(id, currentUser); if (rule == null) { throw new KeyNotFoundException("Rule not found"); } // Check authorization if (!(await owner.IsCoordinatorAsync(_authorizationService)) && rule.Owner != currentUser) { // Not coordinator nor owner throw new InvalidOperationException("User is not owner of this rule"); } // Apply changes rule.UpdateProperties(name, trigger, filter, title, message, bodyType, useTemplate, tags); // Change notifiers _dbContext.RuleNotifiers.RemoveRange(rule.Notifiers); rule.Notifiers.Clear(); foreach (var notifier in _dbContext.Notifiers.Where(n => notifiers.Contains(n.Id))) { rule.Notifiers.Add(new RuleNotifier(notifier)); } // Change recipients List <string> addRecipients = new List <string>(recipients); // Remove recipients foreach (var curRecipient in rule.Recipients.ToList()) { if (curRecipient.User != null) { if (!recipients.Contains("U_" + curRecipient.User.Id)) { _dbContext.NotificationRecipients.Remove(curRecipient); rule.Recipients.Remove(curRecipient); } else { addRecipients.Remove("U_" + curRecipient.User.Id); } } else { if (!recipients.Contains("G_" + curRecipient.Role.Id)) { _dbContext.NotificationRecipients.Remove(curRecipient); rule.Recipients.Remove(curRecipient); } else { addRecipients.Remove("G_" + curRecipient.Role.Id); } } } // Add recipients foreach (var addRecipient in addRecipients) { if (addRecipient.StartsWith("U")) { var user = await _userManager.FindByIdAsync(addRecipient.Substring(2)); if (user != null) { rule.Recipients.Add(new NotificationRecipient(user)); } } else { var role = await _roleManager.FindByIdAsync(addRecipient.Substring(2)); if (role != null) { rule.Recipients.Add(new NotificationRecipient(role)); } } } // Save await _dbContext.SaveChangesAsync(); }
/// <summary> /// Returns a list of unassigned roles for a rule /// </summary> /// <param name="rule">Rule roles are searched for</param> public IEnumerable <Role> GetUnassignedRoles(NotificationRule rule) => _roleManager.Roles.ToList().Except(rule.Recipients.Select(r => r.Role).ToArray());
/// <summary> /// Returns a list of unassigned users for a rule /// </summary> /// <param name="rule">Rule users are searched for</param> public IEnumerable <User> GetUnassignedUsers(NotificationRule rule) => _userManager.Users.ToList().Except(rule.Recipients.Select(r => r.User).ToArray());
/// <summary> /// List all labels for a notification rule. /// </summary> /// <param name="rule">The notification rule.</param> /// <returns>A list of all labels for a notification rule</returns> public async Task <List <Label> > GetLabelsAsync(NotificationRule rule) { Arguments.CheckNotNull(rule, nameof(rule)); return(await GetLabelsAsync(rule.Id)); }
/// <summary> /// Delete a notification rule. /// </summary> /// <param name="rule">The notification rule</param> /// <returns></returns> public Task DeleteNotificationRuleAsync(NotificationRule rule) { Arguments.CheckNotNull(rule, nameof(rule)); return(DeleteNotificationRuleAsync(rule.Id)); }
private async Task <NotificationRule> CreateRuleAsync(string name, string every, RuleStatusLevel status, List <TagRule> tagRules, NotificationEndpoint notificationEndpoint, string orgId, NotificationRule rule) { Arguments.CheckNotNull(rule, "rule"); rule.Name = name; rule.Every = every; rule.OrgID = orgId; rule.TagRules = tagRules; rule.StatusRules = new List <StatusRule> { new StatusRule(status) }; rule.EndpointID = notificationEndpoint.Id; rule.Status = TaskStatusType.Active; return(await CreateRuleAsync(rule)); }
private async Task HandleInstrument(Context context, MarketInstrument instrument, NotificationRule notificationRule) { // try get candles var timePeriodInHours = notificationRule.TimePeriodInHours; var interval = CandleInterval.FiveMinutes; if (timePeriodInHours >= 12) { interval = CandleInterval.Hour; } var start = DateTime.UtcNow.AddHours(-2.5 * timePeriodInHours); var end = DateTime.UtcNow; var candles = await context.MarketCandlesAsync(instrument.Figi, start, end, interval); if (candles.Candles.Count == 0) { Log.Debug($"No candles for {instrument.Ticker}\t{start:dd.MM.yy HH:mm} - {end:dd.MM.yy HH:mm}"); await Task.Delay(_sleepTime); return; } // handle a candle with maximum timestamp var lastCandle = candles.Candles.OrderByDescending(i => i.Time).First(); // try to find a previuos candle var previousCandleTimestamp = lastCandle.Time.AddHours(-1 * timePeriodInHours); var previousCandles = candles.Candles.Where(i => i.Time <= previousCandleTimestamp).ToList(); var attempNumber = 1; //in case it is the start of the day then try to get the last price from the first previous working day while (previousCandles.Count == 0) { start = previousCandleTimestamp.AddHours(-12 * attempNumber); end = previousCandleTimestamp.AddHours(-12 * (attempNumber - 1)); Log.Debug($"Can not find a previous candle for {instrument.Ticker} for {end:dd.MM.yy HH:mm}"); Log.Debug($"Try to fetch candles for {instrument.Ticker} for {previousCandleTimestamp.AddHours(-12 * attempNumber):dd.MM.yy HH:mm} - {previousCandleTimestamp:dd.MM.yy HH:mm}"); previousCandles = (await context.MarketCandlesAsync(instrument.Figi, start, end, interval)).Candles; attempNumber++; continue; } var firstCandle = previousCandles.OrderByDescending(i => i.Time).First(); if (notificationRule.IsActual(firstCandle.Close, lastCandle.Close)) { await _sendNotification(notificationRule, instrument, firstCandle, lastCandle); } LogTicker(instrument, notificationRule, lastCandle, firstCandle); }