< Summary

Class:SVETA.Api.Controllers.NotificationsController
Assembly:SVETA.Api
File(s):/opt/dev/sveta_api_build/SVETA.Api/Controllers/NotificationsController.cs
Covered lines:0
Uncovered lines:94
Coverable lines:94
Total lines:281
Line coverage:0% (0 of 94)
Covered branches:0
Total branches:44
Branch coverage:0% (0 of 44)

Metrics

MethodLine coverage Branch coverage
.ctor(...)0%100%
GetAllNotificationsUser()0%0%
GetNotificationsUserCount()0%0%
MarkAllNotificationsUserAsRead()0%100%
GetNotification()0%0%
PatchUserNotification()0%0%

File(s)

/opt/dev/sveta_api_build/SVETA.Api/Controllers/NotificationsController.cs

#LineLine coverage
 1using Microsoft.AspNetCore.Authorization;
 2using WinSolutions.Sveta.Common.Extensions;
 3using Microsoft.AspNetCore.Mvc;
 4using Microsoft.Extensions.Logging;
 5using Newtonsoft.Json;
 6using SVETA.Api.Data.DTO;
 7using SVETA.Api.Data.DTO.Notification;
 8using SVETA.Api.Helpers.Authorize;
 9using Swashbuckle.AspNetCore.Annotations;
 10using System;
 11using System.Collections.Generic;
 12using System.Linq;
 13using System.Threading.Tasks;
 14using WinSolutions.Sveta.Server.Data.DataModel.Entities;
 15using WinSolutions.Sveta.Server.Data.DataModel.Kinds;
 16using WinSolutions.Sveta.Server.Services.Interfaces;
 17using WinSolutions.Sveta.Common;
 18using SVETA.Api.Helpers;
 19
 20namespace SVETA.Api.Controllers
 21{
 22    [Route("api/v1/Notifications")]
 23    [ApiController]
 24    public class NotificationsController : SvetaController
 25    {
 26        const string _routeUrl = "api/v1/Notifications";
 27        readonly INotificationService _serviceNotification;
 28        readonly INotificationUsersService _serviceNotificationUsers;
 29        readonly IUserService _userService;
 30        readonly IDirectoriesService _dirService;
 31        readonly IClusterService _clusterService;
 32        readonly IAuthenticationService _authenticationService;
 33        readonly ILogger<NotificationsController> _logger;
 34
 35        public NotificationsController(
 36            INotificationService serviceNotification,
 37            INotificationUsersService serviceNotificationUsers,
 38            IUserService userService,
 39            IDirectoriesService dirService,
 40            IClusterService clusterService,
 41            IAuthenticationService authenticationService,
 042            ILogger<NotificationsController> logger) : base(logger)
 043        {
 044            _serviceNotification = serviceNotification;
 045            _serviceNotificationUsers = serviceNotificationUsers;
 046            _userService = userService;
 047            _dirService = dirService;
 048            _clusterService = clusterService;
 049            _authenticationService = authenticationService;
 050            _logger = logger;
 051        }
 52
 53        #region api/v1/Notifications
 54        /// <summary>
 55        /// Создать коммуникацию для одного пользователя, нескольких пользователей, кластера
 56        /// Коммуникация создается со статусом id# 2 - Создано
 57        /// </summary>
 58        /// <remarks>author IPod</remarks>
 59        /// <param name="data">Принимает DTO с обязательными для заполнения полями {
 60        /// Sender - отправитель (Если пользователь не Админ, то должен быть текущим);
 61        /// (Users[ids] и\или ClusterId) - получатели;
 62        /// Subject - Тема коммуникации;
 63        /// Body - тело коммуникации;
 64        /// TypeStatus - тип коммуникации (1- системная, 2 - новость);
 65        /// TimeToTurnOff - время жизни комуникации, после которого она будет отключена
 66        /// StateId - состояние записи(активна)}
 67        /// </param>
 68        /// <returns>В случае успеха возвращает id коммуникации</returns>
 69        [HttpPost("")]
 70        [SwaggerResponse(200, "Успешно", typeof(NotificationPostRequestDTO))]
 71        [SwaggerResponse(403, "Отказ в доступе", typeof(string))]
 72        [SwaggerResponse(404, "Нет записей", typeof(EmptyResult))]
 73        [SwaggerResponse(500, "Ошибка на стороне сервера", typeof(string))]
 74        [Authorize(Roles = Role.SystemAdmin)]
 75        public async Task<IActionResult> PostNotification([FromBody] NotificationRequestDTO data)
 76        {
 77            if (!ModelState.IsValid)
 78            {
 79                return BadRequestResult("Некорректные входные данные");
 80            }
 81            _logger.LogDebug($"Create Notification {JsonConvert.SerializeObject(data)}");
 82
 83            if (data.UserIds.Count == 0 && data.ClusterId == 0)
 84                return NotFoundResult("Не указаны получатели");
 85            Notification notify = null;
 86            if (data.UserIds?.Count > 0 )
 87            {
 088                var receivers = (await _userService.GetAllUsers()).Where(x => data.UserIds.Contains(x.Id)).ToList();
 089                notify = (await _serviceNotification.CreateNotificationForUsers(data.Subject, data.Body, receivers, fals
 90            }
 91
 92            if (data.ClusterId != 0)
 93            {
 94                var cluster = await _clusterService.GetClusterUsers(data.ClusterId);
 95                if (cluster == null)
 96                    throw new ArgumentException($"Кластер с id={data.ClusterId} не найден");
 097                var userDeparts = cluster.Departments.Select(x => x.UsersDepartments).ToList();
 98                List<User> receivers = new List<User> { };
 99                foreach (var item in userDeparts)
 0100                    receivers.AddRange(item.Select(x => x.User));
 101                receivers = receivers.Distinct().ToList();
 0102                notify = (await _serviceNotification.CreateNotificationForUsers(data.Subject, data.Body, receivers, fals
 103            }
 104            _logger.LogDebug($"Notification created with Id {notify.Id}");
 105            return Ok(new NotificationPostRequestDTO {NotificationsId = notify.Id});
 106        }
 107
 108        #endregion
 109
 110        #region User
 111        /// <summary>
 112        /// Возвращает все Уведомления пользователя
 113        /// </summary>
 114        /// <remarks>author IPod</remarks>
 115        /// <param name="userId">Id Пользователя чьи коммуникации проверяем</param>
 116        /// <param name="page">Любое значение ниже нуля изменится на 1, Номер страницы для паганации</param>
 117        /// <param name="limit">Любое значение ниже нуля изменится на 10, Количество коммуникаций на страницу</param>
 118        /// <param name="filter">фильтр по теме или телу уведомления</param>
 119        /// <param name="dateFrom">Дата создания с</param>
 120        /// <param name="dateTo">Дата создания по</param>
 121        /// <param name="notificationType">Тип коммуникации (1- системная, 2- новость, null- вернет все)</param>
 122        /// <param name="notificationsStatus">"Неизвестно" - 1, "Создано"- 2, "Отправлено"- 3,"Прочитано"- 4 "Отключено"
 123        /// <param name="sort">сортировка created_on,created_on|desc,state,state|desc,status,status|desc,subject,subject
 124        /// <returns></returns>
 125        [HttpGet("User/{userId}")]
 126        [SwaggerResponse(200, "Успешно", typeof(BaseResponseDTO<NotificationResponseDTO>))]
 127        [SwaggerResponse(403, "Отказ в доступе", typeof(string))]
 128        [SwaggerResponse(500, "Ошибка на стороне сервера", typeof(string))]
 129        [Authorize]
 130        public async Task<IActionResult> GetAllNotificationsUser(long userId, int page = 1, int limit = 10, string filte
 131            long? notificationType = null, long? notificationsStatus = null,string sort = default, DateTimeOffset dateFr
 0132        {
 0133            filter = filter.NormalizeName();
 0134            page = page < 1 ? 1 : page;
 0135            limit = limit < 1 ? 10 : limit;
 136
 0137            _logger.LogDebug($"Get list notification: page {page}, limit {limit}, filter {filter}, sort {sort}");
 138
 0139            if (!User.IsInRole( Role.SystemAdmin) || !User.IsInRole(Role.SystemOperator))
 0140                if (userId != _authenticationService.UserId)
 0141                    return ForbidResult();
 0142            var result = await _serviceNotificationUsers.GetAllNotificationsUser(userId, page - 1, limit, filter, notifi
 0143            var param = notificationType != null ? $"type={notificationType}" : "";
 0144            var items = result.Result.Select(x =>
 0145            {
 0146                if (x.Notification != null)
 0147                    return new NotificationResponseDTO
 0148                    {
 0149                        NotificationId = x.Notification.Id,
 0150                        Subject = x.Notification.Subject,
 0151                        Body = x.Notification.Body,
 0152                        SenderId = x.Notification.User.Id,
 0153                        NotificationsType = x.Notification.NotificationsType.Id,
 0154                        NotificationsStatus = x.NotificationsStatus.Id,
 0155                        TimeToTurnOff = x.Notification.TimeToTurnOff,
 0156                        CreationDateTime = x.CreationDateTime
 0157                    };
 0158                return null;
 0159            }).ToList();
 160
 0161            var response = new BaseResponseDTO<NotificationResponseDTO>(_routeUrl + "/User", page, limit, result.TotalFi
 0162            {
 0163                Data = items
 0164            };
 0165            return Ok(response);
 0166        }
 167        /// <summary>
 168        /// Получить общее количество коммуникаций пользователя
 169        /// </summary>
 170        /// <remarks>author IPod</remarks>
 171        /// <param name="userId">Id полльзователя по которому будет запрос коммуникаций</param>
 172        /// <param name="notificationsStatus">Статус нотификации "Неизвестно" - 1, "Создано"- 2, "Отправлено"- 3,"Прочит
 173        /// <param name="notificationType">Тип нотификации (1- системная, 2- новость, null- вернет все)</param>
 174        /// <param name="dateFrom">Дата создания с</param>
 175        /// <param name="dateTo">Дата создания по</param>
 176        /// <returns>Count notifications</returns>
 177        [HttpGet("User/{userId}/Count")]
 178        [SwaggerResponse(200, "Успешно", typeof(CountDTO))]
 179        [SwaggerResponse(403, "Отказ в доступе", typeof(ErrorDTO))]
 180        [SwaggerResponse(500, "Ошибка на стороне сервера", typeof(ErrorDTO))]
 181        [Authorize]
 182        public async Task<IActionResult> GetNotificationsUserCount(long userId, long? notificationsStatus, long? notific
 0183        {
 0184            if (!User.IsInRole(Role.SystemAdmin) || !User.IsInRole(Role.SystemOperator))
 0185                if (userId != _authenticationService.UserId)
 0186                    return ForbidResult();
 187
 0188            _logger.LogDebug($"Get notifications count by user #{userId}");
 0189            return Ok(new CountDTO(await _serviceNotificationUsers.GetNotificationsUserCount(userId, notificationsStatus
 0190        }
 191
 192        /// <summary>
 193        /// Выставить статус прочитано всем сообщениям(со статусом отправлено) выбранного пользователя
 194        /// </summary>
 195        /// <param name="userId">Текущий пользователь</param>
 196        /// <returns></returns>
 197        [HttpPost("User/{userid}/ReadAll")]
 198        [SwaggerResponse(200, "Успешно", typeof(EmptyResult))]
 199        [SwaggerResponse(400, "Не валидная модель", typeof(ErrorDTO))]
 200        [SwaggerResponse(403, "Отказ в доступе", typeof(ErrorDTO))]
 201        [SwaggerResponse(500, "Ошибка на стороне сервера", typeof(ErrorDTO))]
 202        [Authorize]
 203        public async Task<IActionResult> MarkAllNotificationsUserAsRead(long userId)
 0204        {
 0205            _logger.LogDebug($"Mark all notifications as read: userId# {_authenticationService.UserId}");
 0206            userId = _authenticationService.UserId;
 0207            await _serviceNotificationUsers.MarkAllNotificationsUser(userId);
 208
 0209            return Ok();
 0210        }
 211        #endregion
 212
 213        #region {notificationId}
 214        /// <summary>
 215        /// Получить одну коммуникацию
 216        /// </summary>
 217        /// <remarks>author IPod</remarks>
 218        /// <param name="notificationId">id коммуникации</param>
 219        /// <returns>Single NotificationResponseDTO</returns>
 220        [HttpGet("{notificationId}")]
 221        [SwaggerResponse(200, "Успешно", typeof(NotificationResponseWithoutStatusDTO))]
 222        [SwaggerResponse(403, "Отказ в доступе", typeof(ErrorDTO))]
 223        [SwaggerResponse(404, "Нет записей", typeof(ErrorDTO))]
 224        [SwaggerResponse(500, "Ошибка на стороне сервера", typeof(ErrorDTO))]
 225        [Authorize(Roles = Role.SystemAdmin + "," + Role.SystemOperator)]
 226        public async Task<IActionResult> GetNotification(long notificationId)
 0227        {
 0228            var data = await _serviceNotification.GetNotification(notificationId);
 0229            if (data == null)
 0230                return NotFoundResult($"Уведомление с id={notificationId} не найдено");
 0231            var result = new NotificationResponseWithoutStatusDTO
 0232            {
 0233                NotificationId = data.Id,
 0234                Subject = data.Subject,
 0235                Body = data.Body,
 0236                SenderId = data.User.Id,
 0237                NotificationsType = data.NotificationsType.Id,
 0238                TimeToTurnOff = data.TimeToTurnOff,
 0239                CreationDateTime = data.CreationDateTime
 0240
 0241            };
 0242            _logger.LogDebug($"Get notification by id {notificationId}");
 0243            return Ok(result);
 0244        }
 245
 246        /// <summary>
 247        /// Обновление статуса коммуникации у одного пользователя
 248        /// </summary>
 249        /// <remarks>author IPod</remarks>
 250        /// <param name="notificationId">id нотификации</param>
 251        /// <param name="userId">id юзера</param>
 252        /// <param name="data">Принимает Статус коммуникации {notificationsStatus}  (Неизвестно- 1,Создано- 2,Отправлено
 253        /// </param>
 254        /// <returns>В случае успеха возвращает код 200</returns>
 255        [HttpPatch("{notificationId}/User/{userId}")]
 256        [SwaggerResponse(200, "Успешно", typeof(EmptyResult))]
 257        [SwaggerResponse(403, "Отказано в доступе", typeof(ErrorDTO))]
 258        [SwaggerResponse(500, "Ошибка на стороне сервера", typeof(ErrorDTO))]
 259        [Authorize]
 260        public async Task<IActionResult> PatchUserNotification(long notificationId, long userId, NotificationPatchReques
 0261        {
 0262            userId = _authenticationService.UserId;
 0263            if (!ModelState.IsValid)
 0264            {
 0265                return BadRequestResult("Некорректные входные данные");
 266            }
 0267            var notifications = await _serviceNotificationUsers.GetNotifications(notificationId, userId);
 0268            if (notifications.Count == 0)
 0269                _logger.LogDebug($"Notification with #{notificationId} and user #{userId} not found");
 270
 0271            foreach (var not in notifications)
 0272            {
 0273                not.NotificationsStatus = await _dirService.GetNotificationStatus(data.NotificationsStatus);
 0274                _logger.LogDebug($"Patch notification #{notificationId} status #{data.NotificationsStatus}");
 0275                await _serviceNotificationUsers.Update(not);
 0276            }
 0277            return Ok();
 0278        }
 279        #endregion
 280    }
 281}