public async Task Recipient_Save_DoesSave()
        {
            //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;

            //Act
            await recipient.Create(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);
        }
        public Recipient CreateNewRecipient(string name, string phoneNo, string email)
        {
            var recipient = Recipient.Create(name, phoneNo, email);

            recipient = recipientRepository.Add(recipient);
            PersistenceContext.SaveChanges();
            return(recipient);
        }
        public async Task <OperationResult> Update(NotificationRuleModel ruleModel)
        {
            using (var transaction = await _dbContext.Database.BeginTransactionAsync())
            {
                try
                {
                    var rule = await _dbContext.Rules
                               .Include(x => x.Recipients)
                               .FirstOrDefaultAsync(x => x.WorkflowState != Constants.WorkflowStates.Removed &&
                                                    x.Id == ruleModel.Id);

                    if (rule == null)
                    {
                        return(new OperationResult(false,
                                                   _localizationService.GetString("NotificationRuleNotFound")));
                    }

                    rule.AttachReport = ruleModel.AttachReport;
                    rule.AttachLink   = ruleModel.AttachLink;
                    rule.IncludeValue = ruleModel.IncludeValue;
                    rule.RuleType     = ruleModel.RuleType;
                    rule.Subject      = ruleModel.Subject;
                    rule.CheckListId  = ruleModel.CheckListId;
                    rule.Text         = ruleModel.Text;
                    rule.DataItemId   = ruleModel.DataItemId;

                    if (ruleModel.Data != null)
                    {
                        rule.Data = ruleModel.Data.ToString();
                    }

                    await rule.Update(_dbContext);

                    // work with recipients
                    var currentRecipients = ruleModel.Recipients.Select(x => x.Id).ToList();
                    var recipientsDelete  = await _dbContext.Recipients
                                            .Where(r => r.NotificationRuleId == rule.Id && !currentRecipients.Contains(r.Id))
                                            .ToListAsync();

                    foreach (var rd in recipientsDelete)
                    {
                        await rd.Delete(_dbContext);
                    }

                    foreach (var recipientModel in ruleModel.Recipients.Where(r => r.Id == null))
                    {
                        var recipient = new Recipient
                        {
                            Email = recipientModel.Email,
                            NotificationRuleId = rule.Id,
                            CreatedByUserId    = UserId,
                            UpdatedByUserId    = UserId
                        };

                        await recipient.Create(_dbContext);
                    }

                    // work with device users
                    var currentDeviseUserId = ruleModel.DeviceUsers.Select(x => x.Id).ToList();
                    var deviceUsersDelete   = await _dbContext.DeviceUsers
                                              .Where(r => r.NotificationRuleId == rule.Id && !currentDeviseUserId.Contains(r.DeviceUserId))
                                              .ToListAsync();

                    foreach (var dud in deviceUsersDelete)
                    {
                        await dud.Delete(_dbContext);
                    }

                    foreach (var deviceUserModel in ruleModel.DeviceUsers)
                    {
                        if (!await _dbContext.DeviceUsers.AnyAsync(
                                x => x.DeviceUserId == deviceUserModel.Id &&
                                x.NotificationRuleId == rule.Id &&
                                x.WorkflowState != Constants.WorkflowStates.Removed))
                        {
                            if (deviceUserModel.Id != null)
                            {
                                var deviceUser = new DeviceUser()
                                {
                                    NotificationRuleId = rule.Id,
                                    CreatedByUserId    = UserId,
                                    UpdatedByUserId    = UserId,
                                    DeviceUserId       = (int)deviceUserModel.Id,
                                };

                                await deviceUser.Create(_dbContext);
                            }
                        }
                    }

                    transaction.Commit();
                    return(new OperationResult(
                               true,
                               _localizationService.GetString("NotificationRuleHasBeenUpdated")));
                }
                catch (Exception e)
                {
                    transaction.Rollback();
                    _logger.LogError(e.Message);
                    return(new OperationResult(
                               false,
                               _localizationService.GetString("ErrorWhileUpdatingNotificationRule")));
                }
            }
        }
        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")));
                }
            }
        }