< Summary

Class:WinSolutions.Sveta.Server.Services.Implements.NotificationUsersService
Assembly:WinSolutions.Sveta.Server
File(s):/opt/dev/sveta_api_build/WinSolutions.Sveta.Server/Services/Implements/NotificationUsersService.cs
Covered lines:13
Uncovered lines:133
Coverable lines:146
Total lines:276
Line coverage:8.9% (13 of 146)
Covered branches:2
Total branches:90
Branch coverage:2.2% (2 of 90)

Metrics

MethodLine coverage Branch coverage
.ctor(...)100%100%
Create()100%50%
Create()0%0%
Delete()0%0%
GetAllNotificationsUser()0%0%
GetNotifications()0%100%
GetNotificationsCount()0%0%
GetNotificationsUserCount()0%0%
NotificationUsersExists()0%100%
MarkAllNotificationsUser()0%0%
Update()0%0%
SortNotification(...)0%0%

File(s)

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

#LineLine coverage
 1using System;
 2using Microsoft.EntityFrameworkCore;
 3using Microsoft.Extensions.Logging;
 4using System.Collections.Generic;
 5using System.Linq;
 6using System.Threading.Tasks;
 7using WinSolutions.Sveta.Server.Data.DataModel.Contexts;
 8using WinSolutions.Sveta.Server.Data.DataModel.Entities;
 9using WinSolutions.Sveta.Server.Domain;
 10using WinSolutions.Sveta.Server.Services.Interfaces;
 11using WinSolutions.Sveta.Server.Data.DataModel.Kinds;
 12using WinSolutions.Sveta.Common;
 13using SVETA.Api.Helpers;
 14
 15namespace WinSolutions.Sveta.Server.Services.Implements
 16{
 17    public class NotificationUsersService : SvetaServiceBase, INotificationUsersService
 18    {
 19        private readonly SvetaDbContext _db;
 20        private readonly ILogger<NotificationUsersService> _logger;
 21
 22        public NotificationUsersService(SvetaDbContext db, ILogger<NotificationUsersService> logger, IAuthenticationServ
 18623            : base(authenticationService)
 18624        {
 18625            _db = db;
 18626            _logger = logger;
 18627        }
 28
 29        /// <summary>
 30        /// создает запись
 31        /// </summary>
 32        /// <param name="data">объект NotificationUsers</param>
 33        /// <returns></returns>
 34        public async Task Create(NotificationUsers data)
 74535        {
 74536            _db.Entry(data.NotificationsStatus).State = EntityState.Unchanged;
 74537            _db.Entry(data.RecState).State = EntityState.Unchanged;
 74538            _db.Entry(data.User).State = EntityState.Unchanged;
 74539            _db.Entry(data.Notification).State = EntityState.Unchanged;
 74540            await _db.NotificationUsers.AddAsync(data);
 74541            await _db.SaveChangesAsync(CurrentUserId);
 74542        }
 43
 44        /// <summary>
 45        /// создает массив записей
 46        /// </summary>
 47        /// <param name="data">массив объектов NotificationUsers</param>
 48        /// <returns></returns>
 49        public async Task Create(NotificationUsers[] data)
 050        {
 051            foreach (NotificationUsers nuser in data)
 052            {
 053                _db.Entry(nuser.NotificationsStatus).State = EntityState.Unchanged;
 054                _db.Entry(nuser.RecState).State = EntityState.Unchanged;
 055                _db.Entry(nuser.User).State = EntityState.Unchanged;
 056                _db.Entry(nuser.Notification).State = EntityState.Unchanged;
 057            }
 058            await _db.NotificationUsers.AddRangeAsync(data);
 059            await _db.SaveChangesAsync(CurrentUserId);
 060        }
 61
 62        /// <summary>
 63        /// Удаляет запись
 64        /// </summary>
 65        /// <param name="id">id записи</param>
 66        /// <returns></returns>
 67        public async Task Delete(long id)
 068        {
 069            var data = await _db.NotificationUsers.Where(d => !d.IsDeleted).FirstAsync(n => n.Id == id);
 070            if (data == null)
 071            {
 072                throw new KeyNotFoundException($"Уведомление с id={id} не найдено");
 73            }
 074            data.IsDeleted = true;
 075            await _db.SaveChangesAsync(CurrentUserId);
 076        }
 77
 78        /// <summary>
 79        /// Получает список записей с пагинацией, сортировкой и фльтрацией
 80        /// </summary>
 81        /// <param name="id">id юзера</param>
 82        /// <param name="page">номер страницы</param>
 83        /// <param name="limit">размер страницы</param>
 84        /// <param name="filter">фильтр по теме или телу</param>
 85        /// <param name="notificationsType">тип нотификации</param>
 86        /// <param name="notificationsStatus">статус нотификации</param>
 87        /// <param name="dateFrom">дата с</param>
 88        /// <param name="dateTo">дата по</param>
 89        /// <param name="sort">тип сортировки</param>
 90        /// <returns></returns>
 91        public async Task<PaginatedData<List<NotificationUsers>>> GetAllNotificationsUser(long id, int page, int? limit,
 092        {
 093            var data = _db.NotificationUsers
 094              .Include(u => u.User)
 095              .Include(d => d.RecState)
 096              .Include(n => n.Notification)
 097              .ThenInclude(notifications => notifications.NotificationsType)
 098              .Include(n => n.Notification)
 099              .ThenInclude(notifications => notifications.User)
 0100              .Include(s => s.NotificationsStatus)
 0101              .Where(x => x.User.Id == id)
 0102              .Where(d => !d.IsDeleted)
 0103              .Where(t => notificationsType == null || notificationsType == t.Notification.NotificationsType.Id)
 0104              .Where(t => notificationsStatus == null || notificationsStatus == t.NotificationsStatus.Id)
 0105              .Where(f => string.IsNullOrWhiteSpace(filter) || f.Notification.Subject.ToUpper().Contains(filter.ToUpper(
 106
 0107            if (!dateFrom.IsNullOrMinValue())
 0108                data = data.Where(x => x.CreationDateTime >= dateFrom);
 109
 0110            if (!dateTo.IsNullOrMinValue())
 0111                data = data.Where(x => x.CreationDateTime < dateTo);
 0112            data = SortNotification(data, sort?.ToLower());
 0113            var filtered = data?.Count() ?? 0;
 0114            if (limit != null)
 0115                data = data.Skip(page * (int)limit).Take((int)limit);
 0116            var total = await GetNotificationsCount(id, 0, null, null, null, null);
 117
 118
 0119            return new PaginatedData<List<NotificationUsers>>
 0120            {
 0121                Result = await data.ToListAsync(),
 0122                TotalCount = total,
 0123                TotalFilteredCount = filtered
 0124            };
 0125        }
 126
 127        /// <summary>
 128        /// получает записи
 129        /// </summary>
 130        /// <param name="notificationId">id родительской записи</param>
 131        /// <param name="userId">id юзера</param>
 132        /// <returns></returns>
 133        public async Task<List<NotificationUsers>> GetNotifications(long notificationId, long? userId = null)
 0134        {
 0135            var items = _db.NotificationUsers
 0136              .Include(s => s.NotificationsStatus)
 0137              .Include(u => u.User)
 0138              .Include(n => n.Notification)
 0139              .Where(x => x.Notification.Id == notificationId)
 0140              .Where(u => userId == null || u.User.Id == userId)
 0141              .Where(d => !d.IsDeleted);
 142
 0143            return await items.ToListAsync();
 0144        }
 145
 146        /// <summary>
 147        /// Получить общее количество сообщений с фильтрами
 148        /// </summary>
 149        /// <param name="userId">id юзера</param>
 150        /// <param name="page">номер страницы</param>
 151        /// <param name="limit">размер страницы</param>
 152        /// <param name="filter">фильтр по теме и телу</param>
 153        /// <param name="notificationType">тип нотификации</param>
 154        /// <param name="notificationStatus">статус нотификации</param>
 155        /// <returns></returns>
 156        public async Task<int> GetNotificationsCount(long userId, int page, int? limit, string filter, long? notificatio
 0157        {
 0158            var data = _db.NotificationUsers
 0159              .Include(u => u.User)
 0160              .Include(d => d.RecState)
 0161              .Include(n => n.Notification)
 0162              .ThenInclude(u => u.User)
 0163              .Include(s => s.NotificationsStatus)
 0164              .Include(s => s.Notification.NotificationsType)
 0165              .Where(x => x.User.Id == userId)
 0166              .Where(d => !d.IsDeleted)
 0167              .Where(t => (notificationsType != null ? notificationsType == t.Notification.NotificationsType.Id : true))
 0168              .Where(t => (notificationsStatus != null ? notificationsStatus == t.NotificationsStatus.Id : true))
 0169              .Where(f => !string.IsNullOrWhiteSpace(filter) ? f.Notification.Subject.ToUpper().Contains(filter.ToUpper(
 0170            if (dateFrom.HasValue)
 0171                data = data.Where(x => x.CreationDateTime >= dateFrom.Value.Date);
 172
 0173            if (dateTo.HasValue)
 0174                data = data.Where(x => x.CreationDateTime <= dateTo.Value.Date.AddDays(1).AddMilliseconds(-1));
 175
 0176            return await data.CountAsync();
 0177        }
 178
 179        /// <summary>
 180        /// Получить общее количество сообщений для одного пользователя
 181        /// </summary>
 182        /// <param name="id">id пользователя</param>
 183        /// <param name="notificationStatus">статус нотификации</param>
 184        /// <param name="notificationType">Тип нотификации</param>
 185        /// <param name="dateFrom">дата с</param>
 186        /// <param name="dateTo">дата по</param>
 187        /// <returns></returns>
 188        public async Task<int> GetNotificationsUserCount(long id, long? notificationStatus, long? notificationType, Date
 0189        {
 0190            var data = _db.NotificationUsers
 0191                .Include(n => n.Notification)
 0192                .Include(s => s.NotificationsStatus)
 0193                .Include(t => t.Notification.NotificationsType)
 0194                .Where(x => x.User.Id == id)
 0195                .Where(d => !d.IsDeleted)
 0196                .Where(s => notificationStatus == null || s.NotificationsStatus.Id == notificationStatus)
 0197                .Where(s => notificationType == null || s.Notification.NotificationsType.Id == notificationType);
 0198            if (!dateFrom.IsNullOrMinValue())
 0199                data = data.Where(x => x.CreationDateTime >= dateFrom);
 200
 0201            if (!dateTo.IsNullOrMinValue())
 0202                data = data.Where(x => x.CreationDateTime < dateTo);
 0203            return await data.CountAsync();
 0204        }
 205
 206        /// <summary>
 207        /// проверяет существует ли запись
 208        /// </summary>
 209        /// <param name="id">id записи</param>
 210        /// <returns></returns>
 0211        public async Task<bool> NotificationUsersExists(long id) => await _db.NotificationUsers
 0212            .Where(e => e.Id == id)
 0213            .Where(d => !d.IsDeleted)
 0214            .AnyAsync();
 215
 216
 217        /// <summary>
 218        /// Помечает все отправленные сообщения прочитанными
 219        /// </summary>
 220        /// <param name="userId">id юзера</param>
 221        /// <returns></returns>
 222        public async Task MarkAllNotificationsUser(long userId)
 0223        {
 0224            var items = await _db.NotificationUsers
 0225                .Include(u => u.User)
 0226                .Include(s => s.NotificationsStatus)
 0227                .Where(x => x.User.Id == userId)
 0228                .Where(m => !m.IsDeleted)
 0229                .Where(n => n.NotificationsStatus.Id == (int)NotificationStatus.Sent)
 0230                .ToListAsync();
 0231            foreach (var item in items)
 0232            {
 0233                item.NotificationsStatus = await _db.refNotificationsStatus.Where(e => !e.IsDeleted).FirstOrDefaultAsync
 0234                _db.NotificationUsers.Update(item);
 0235            }
 236
 0237            await _db.SaveChangesAsync(CurrentUserId);
 0238        }
 239
 240        /// <summary>
 241        /// обновляет запись
 242        /// </summary>
 243        /// <param name="data">объект NotificationUsers</param>
 244        /// <returns></returns>
 245        public async Task Update(NotificationUsers data)
 0246        {
 0247            if (!(await NotificationUsersExists(data.Id)))
 0248            {
 0249                throw new ArgumentException($"Пользовательское уведомление с id={data.Id} не найдено");
 250            }
 0251            _db.NotificationUsers.Update(data);
 0252            await _db.SaveChangesAsync(CurrentUserId);
 0253        }
 254
 255        /// <summary>
 256        /// Сортирует коммуникации по полям
 257        /// </summary>
 258        /// <param name="movements"></param>
 259        /// <param name="sort">сортировка по умолчанию по id - id|desc,created_on,created_on|desc,state,state|desc,statu
 260        /// <returns></returns>
 0261        private IQueryable<NotificationUsers> SortNotification(IQueryable<NotificationUsers> notifies, string sort = def
 0262        {
 0263            "created_on" => notifies.OrderBy(d => d.CreationDateTime),
 0264            "created_on|desc" => notifies.OrderByDescending(d => d.CreationDateTime),
 0265            "state" => notifies.OrderBy(d => d.Notification.RecState.Id),
 0266            "state|desc" => notifies.OrderByDescending(d => d.Notification.RecState.Id),
 0267            "subject" => notifies.OrderBy(d => d.Notification.Subject),
 0268            "subject|desc" => notifies.OrderByDescending(d => d.Notification.Subject),
 0269            "body" => notifies.OrderBy(d => d.Notification.Body),
 0270            "body|desc" => notifies.OrderByDescending(d => d.Notification.Body),
 0271            "id|desc" => notifies.OrderByDescending(d => d.Notification.Id),
 0272            "id" => notifies.OrderBy(d => d.Notification.Id),
 0273            _ => notifies.OrderBy(d => d.NotificationsStatus.Id).ThenByDescending(x=>x.CreationDateTime),
 0274        };
 275    }
 276}