< Summary

Class:WinSolutions.Sveta.Server.Services.Implements.NotificationService
Assembly:WinSolutions.Sveta.Server
File(s):/opt/dev/sveta_api_build/WinSolutions.Sveta.Server/Services/Implements/NotificationService.cs
Covered lines:42
Uncovered lines:66
Coverable lines:108
Total lines:214
Line coverage:38.8% (42 of 108)
Covered branches:5
Total branches:76
Branch coverage:6.5% (5 of 76)

Metrics

MethodLine coverage Branch coverage
.ctor(...)100%100%
Create()100%50%
Delete()0%0%
GetNotification()0%100%
NotificationExists()0%100%
Update()0%0%
SortNotification(...)0%0%
CreateNotification()100%100%
CreateNotificationForUser()86.66%50%
CreateNotificationForUsers()0%0%

File(s)

/opt/dev/sveta_api_build/WinSolutions.Sveta.Server/Services/Implements/NotificationService.cs

#LineLine coverage
 1using Microsoft.EntityFrameworkCore;
 2using Microsoft.Extensions.Logging;
 3using System;
 4using System.Collections.Generic;
 5using System.Linq;
 6using System.Threading.Tasks;
 7using Org.BouncyCastle.Math.EC.Rfc7748;
 8using WinSolutions.Sveta.Server.Data.DataModel.Contexts;
 9using WinSolutions.Sveta.Server.Data.DataModel.Entities;
 10using WinSolutions.Sveta.Server.Data.DataModel.Kinds;
 11using WinSolutions.Sveta.Server.Services.Interfaces;
 12using WinSolutions.Sveta.Common;
 13
 14namespace WinSolutions.Sveta.Server.Services.Implements
 15{
 16    public class NotificationService : SvetaServiceBase, INotificationService
 17    {
 18        private readonly SvetaDbContext _db;
 19        private readonly ILogger<NotificationService> _logger;
 20        private readonly IAuthenticationService _authService;
 21        private readonly IEmailService _emailService;
 22        private readonly INotificationUsersService _notifyUserService;
 23        private readonly IDirectoriesService _dirService;
 24        private readonly IUserService _userService;
 25
 26        public NotificationService(SvetaDbContext db, ILogger<NotificationService> logger, IAuthenticationService authen
 27            IDirectoriesService dirService, IUserService userService, IEmailService emailService)
 18628            : base(authenticationService)
 18629        {
 18630            _db = db;
 18631            _emailService = emailService;
 18632            _userService = userService;
 18633            _authService = authenticationService;
 18634            _dirService = dirService;
 18635            _notifyUserService = notifyUserService;
 18636            _logger = logger;
 18637        }
 38
 39        /// <summary>
 40        /// создает запись
 41        /// </summary>
 42        /// <param name="data">объект Notification</param>
 43        /// <returns></returns>
 44        public async Task Create(Notification data)
 74545        {
 74546            _db.Entry(data.User).State = EntityState.Unchanged;
 74547            _db.Entry(data.RecState).State = EntityState.Unchanged;
 74548            _db.Entry(data.NotificationsType).State = EntityState.Unchanged;
 74549            await _db.Notifications.AddAsync(data);
 74550            await _db.SaveChangesAsync(CurrentUserId);
 74551        }
 52
 53        /// <summary>
 54        /// удаляет запись
 55        /// </summary>
 56        /// <param name="id">id записи</param>
 57        /// <param name="userId">id юзера (необязательный параметр)</param>
 58        /// <returns></returns>
 59        public async Task Delete(long id, long? userId = null)
 060        {
 061            var data = await _db.Notifications
 062                .Include(user => user.User)
 063                .Where(x => x.Id == id)
 064                .Where(u => userId == null || u.User.Id == userId)
 065                .FirstOrDefaultAsync();
 066            if (data == null)
 067            {
 068                throw new KeyNotFoundException($"Уведомление с id={id} не найдено");
 69            }
 070            data.IsDeleted = true;
 071            await _db.SaveChangesAsync(CurrentUserId);
 072        }
 73
 74        /// <summary>
 75        /// получить запись
 76        /// </summary>
 77        /// <param name="id">id записи</param>
 78        /// <returns></returns>
 079        public async Task<Notification> GetNotification(long id) => await _db.Notifications
 080            .Include(u => u.User)
 081            .Include(d => d.RecState)
 082            .Include(u => u.NotificationsType)
 083            .Where(e => !e.IsDeleted)
 084            .FirstOrDefaultAsync(n => n.Id == id);
 85
 86        /// <summary>
 87        /// проверяет существует ли запись
 88        /// </summary>
 89        /// <param name="id">id записи</param>
 90        /// <returns></returns>
 091        public async Task<bool> NotificationExists(long id) => await _db.Notifications
 092            .Where(e => e.Id == id)
 093            .Where(d => !d.IsDeleted)
 094            .AnyAsync();
 95
 96        /// <summary>
 97        /// обновляет запись
 98        /// </summary>
 99        /// <param name="data">объект Notification</param>
 100        /// <returns></returns>
 101        public async Task Update(Notification data)
 0102        {
 0103            if (!(await NotificationExists(data.Id)))
 0104            {
 0105                throw new ArgumentException($"Уведомление с id={data.Id} не найдено");
 106            }
 0107            _db.Notifications.Update(data);
 0108            await _db.SaveChangesAsync(CurrentUserId);
 0109        }
 110
 111        /// <summary>
 112        /// Сортирует коммуникации по полям
 113        /// </summary>
 114        /// <param name="movements"></param>
 115        /// <param name="sort">сортировка created_on,created_on|desc,state,state|desc,status,status|desc,subject,subject
 116        /// <returns></returns>
 0117        private IQueryable<Notification> SortNotification(IQueryable<Notification> movements, string sort = default) => 
 0118        {
 0119            "created_on" => movements.OrderBy(d => d.CreationDateTime),
 0120            "created_on|desc" => movements.OrderByDescending(d => d.CreationDateTime),
 0121            "state" => movements.OrderBy(d => d.RecState.Id),
 0122            "state|desc" => movements.OrderByDescending(d => d.RecState.Id),
 0123            "subject" => movements.OrderBy(d => d.Subject),
 0124            "subject|desc" => movements.OrderByDescending(d => d.Subject),
 0125            "body" => movements.OrderBy(d => d.Body),
 0126            "body|desc" => movements.OrderByDescending(d => d.Body),
 0127            "id|desc" => movements.OrderByDescending(d => d.Id),
 0128            _ => movements.OrderBy(d => d.Id),
 0129        };
 130
 131        /// <summary>
 132        /// созхдает запись для текущего пользователя
 133        /// </summary>
 134        /// <param name="subject">тема нотификации</param>
 135        /// <param name="body">тело нотификации</param>
 136        /// <param name="notificationType">тип нотификации</param>
 137        /// <returns></returns>
 138        private async Task<Notification> CreateNotification(string subject, string body, NotificationType notificationTy
 745139        {
 745140            var notification = new Notification()
 745141            {
 745142                User = await _userService.GetUser(_authService.UserId),
 745143                Subject = subject,
 745144                Body = body,
 745145                RecState = await _dirService.GetRecordState((long)RecordState.Active),
 745146                NotificationsType = await _dirService.GetNotificationType((long)notificationType)
 745147            };
 745148            await Create(notification);
 745149            return notification;
 745150        }
 151
 152        /// <summary>
 153        /// Создает нотификацию для одного пользователя с опцией отправки почты
 154        /// </summary>
 155        /// <param name="subject">Тема</param>
 156        /// <param name="body">Тело</param>
 157        /// <param name="receiver">Получатель</param>
 158        /// <param name="sendEmail">Отправить дополнительно письмо получателю на почту</param>
 159        /// <param name="notificationType">Тип нотификации. По умолчанию системный</param>
 160        /// <returns></returns>
 161        public async Task<NotificationUsers> CreateNotificationForUser(string subject, string body, User receiver, bool 
 162            NotificationType notificationType = NotificationType.System)
 745163        {
 0164            if (receiver == null) throw new ArgumentException("Не указан пользователь");
 745165            var notification = await CreateNotification(subject, body, notificationType);
 166
 745167            var notificationUsers = new NotificationUsers()
 745168            {
 745169                Notification = notification,
 745170                User = receiver,
 745171                NotificationsStatus = notificationType == NotificationType.System ? await _dirService.GetNotificationSta
 745172                    : await _dirService.GetNotificationStatus((long)NotificationStatus.Created),
 745173                RecState = await _dirService.GetRecordState((long)RecordState.Active)
 745174            };
 745175            await _notifyUserService.Create(notificationUsers);
 0176            if (sendEmail) await _emailService.Create(subject, body, receiver);
 745177            return notificationUsers;
 745178        }
 179
 180        /// <summary>
 181        /// Создает нотификацию для многих пользователей с опцией отправки почты
 182        /// </summary>
 183        /// <param name="subject">Тема</param>
 184        /// <param name="body">Тело</param>
 185        /// <param name="receivers">Получатель</param>
 186        /// <param name="sendEmail">Отправить дополнительно письмо получателю на почту</param>
 187        /// <param name="notificationType">Тип нотификации. По умолчанию системный</param>
 188        /// <returns></returns>
 189        public async Task<List<NotificationUsers>> CreateNotificationForUsers(string subject, string body, List<User> re
 190            NotificationType notificationType = NotificationType.System)
 0191        {
 0192            if (receivers  == null || receivers?.Count() == 0) throw new ArgumentException("Не указаны пользователи");
 0193            var notification = await CreateNotification(subject, body, notificationType);
 0194            var notificationsStatus = notificationType == NotificationType.System ? await _dirService.GetNotificationSta
 0195                    : await _dirService.GetNotificationStatus((long)NotificationStatus.Created);
 0196            var recState = await _dirService.GetRecordState((long)RecordState.Active);
 0197            List<NotificationUsers> notifyList = new List<NotificationUsers> ();
 0198            foreach (var user in receivers)
 0199            {
 0200                var notificationUsers = new NotificationUsers()
 0201                {
 0202                    Notification = notification,
 0203                    User = user,
 0204                    NotificationsStatus = notificationsStatus,
 0205                    RecState = recState
 0206                };
 0207                notifyList.Add(notificationUsers);
 0208            }
 0209            if (sendEmail) await _emailService.Create(subject, body, receivers);
 0210            await _notifyUserService.Create(notifyList.ToArray());
 0211            return await Task.FromResult(notifyList);
 0212        }
 213    }
 214}