| | | 1 | | using Microsoft.EntityFrameworkCore; |
| | | 2 | | using Microsoft.Extensions.Logging; |
| | | 3 | | using System; |
| | | 4 | | using System.Collections.Generic; |
| | | 5 | | using System.Linq; |
| | | 6 | | using System.Threading.Tasks; |
| | | 7 | | using Org.BouncyCastle.Math.EC.Rfc7748; |
| | | 8 | | using WinSolutions.Sveta.Server.Data.DataModel.Contexts; |
| | | 9 | | using WinSolutions.Sveta.Server.Data.DataModel.Entities; |
| | | 10 | | using WinSolutions.Sveta.Server.Data.DataModel.Kinds; |
| | | 11 | | using WinSolutions.Sveta.Server.Services.Interfaces; |
| | | 12 | | using WinSolutions.Sveta.Common; |
| | | 13 | | |
| | | 14 | | namespace 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) |
| | 186 | 28 | | : base(authenticationService) |
| | 186 | 29 | | { |
| | 186 | 30 | | _db = db; |
| | 186 | 31 | | _emailService = emailService; |
| | 186 | 32 | | _userService = userService; |
| | 186 | 33 | | _authService = authenticationService; |
| | 186 | 34 | | _dirService = dirService; |
| | 186 | 35 | | _notifyUserService = notifyUserService; |
| | 186 | 36 | | _logger = logger; |
| | 186 | 37 | | } |
| | | 38 | | |
| | | 39 | | /// <summary> |
| | | 40 | | /// создает запись |
| | | 41 | | /// </summary> |
| | | 42 | | /// <param name="data">объект Notification</param> |
| | | 43 | | /// <returns></returns> |
| | | 44 | | public async Task Create(Notification data) |
| | 745 | 45 | | { |
| | 745 | 46 | | _db.Entry(data.User).State = EntityState.Unchanged; |
| | 745 | 47 | | _db.Entry(data.RecState).State = EntityState.Unchanged; |
| | 745 | 48 | | _db.Entry(data.NotificationsType).State = EntityState.Unchanged; |
| | 745 | 49 | | await _db.Notifications.AddAsync(data); |
| | 745 | 50 | | await _db.SaveChangesAsync(CurrentUserId); |
| | 745 | 51 | | } |
| | | 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) |
| | 0 | 60 | | { |
| | 0 | 61 | | var data = await _db.Notifications |
| | 0 | 62 | | .Include(user => user.User) |
| | 0 | 63 | | .Where(x => x.Id == id) |
| | 0 | 64 | | .Where(u => userId == null || u.User.Id == userId) |
| | 0 | 65 | | .FirstOrDefaultAsync(); |
| | 0 | 66 | | if (data == null) |
| | 0 | 67 | | { |
| | 0 | 68 | | throw new KeyNotFoundException($"Уведомление с id={id} не найдено"); |
| | | 69 | | } |
| | 0 | 70 | | data.IsDeleted = true; |
| | 0 | 71 | | await _db.SaveChangesAsync(CurrentUserId); |
| | 0 | 72 | | } |
| | | 73 | | |
| | | 74 | | /// <summary> |
| | | 75 | | /// получить запись |
| | | 76 | | /// </summary> |
| | | 77 | | /// <param name="id">id записи</param> |
| | | 78 | | /// <returns></returns> |
| | 0 | 79 | | public async Task<Notification> GetNotification(long id) => await _db.Notifications |
| | 0 | 80 | | .Include(u => u.User) |
| | 0 | 81 | | .Include(d => d.RecState) |
| | 0 | 82 | | .Include(u => u.NotificationsType) |
| | 0 | 83 | | .Where(e => !e.IsDeleted) |
| | 0 | 84 | | .FirstOrDefaultAsync(n => n.Id == id); |
| | | 85 | | |
| | | 86 | | /// <summary> |
| | | 87 | | /// проверяет существует ли запись |
| | | 88 | | /// </summary> |
| | | 89 | | /// <param name="id">id записи</param> |
| | | 90 | | /// <returns></returns> |
| | 0 | 91 | | public async Task<bool> NotificationExists(long id) => await _db.Notifications |
| | 0 | 92 | | .Where(e => e.Id == id) |
| | 0 | 93 | | .Where(d => !d.IsDeleted) |
| | 0 | 94 | | .AnyAsync(); |
| | | 95 | | |
| | | 96 | | /// <summary> |
| | | 97 | | /// обновляет запись |
| | | 98 | | /// </summary> |
| | | 99 | | /// <param name="data">объект Notification</param> |
| | | 100 | | /// <returns></returns> |
| | | 101 | | public async Task Update(Notification data) |
| | 0 | 102 | | { |
| | 0 | 103 | | if (!(await NotificationExists(data.Id))) |
| | 0 | 104 | | { |
| | 0 | 105 | | throw new ArgumentException($"Уведомление с id={data.Id} не найдено"); |
| | | 106 | | } |
| | 0 | 107 | | _db.Notifications.Update(data); |
| | 0 | 108 | | await _db.SaveChangesAsync(CurrentUserId); |
| | 0 | 109 | | } |
| | | 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> |
| | 0 | 117 | | private IQueryable<Notification> SortNotification(IQueryable<Notification> movements, string sort = default) => |
| | 0 | 118 | | { |
| | 0 | 119 | | "created_on" => movements.OrderBy(d => d.CreationDateTime), |
| | 0 | 120 | | "created_on|desc" => movements.OrderByDescending(d => d.CreationDateTime), |
| | 0 | 121 | | "state" => movements.OrderBy(d => d.RecState.Id), |
| | 0 | 122 | | "state|desc" => movements.OrderByDescending(d => d.RecState.Id), |
| | 0 | 123 | | "subject" => movements.OrderBy(d => d.Subject), |
| | 0 | 124 | | "subject|desc" => movements.OrderByDescending(d => d.Subject), |
| | 0 | 125 | | "body" => movements.OrderBy(d => d.Body), |
| | 0 | 126 | | "body|desc" => movements.OrderByDescending(d => d.Body), |
| | 0 | 127 | | "id|desc" => movements.OrderByDescending(d => d.Id), |
| | 0 | 128 | | _ => movements.OrderBy(d => d.Id), |
| | 0 | 129 | | }; |
| | | 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 |
| | 745 | 139 | | { |
| | 745 | 140 | | var notification = new Notification() |
| | 745 | 141 | | { |
| | 745 | 142 | | User = await _userService.GetUser(_authService.UserId), |
| | 745 | 143 | | Subject = subject, |
| | 745 | 144 | | Body = body, |
| | 745 | 145 | | RecState = await _dirService.GetRecordState((long)RecordState.Active), |
| | 745 | 146 | | NotificationsType = await _dirService.GetNotificationType((long)notificationType) |
| | 745 | 147 | | }; |
| | 745 | 148 | | await Create(notification); |
| | 745 | 149 | | return notification; |
| | 745 | 150 | | } |
| | | 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) |
| | 745 | 163 | | { |
| | 0 | 164 | | if (receiver == null) throw new ArgumentException("Не указан пользователь"); |
| | 745 | 165 | | var notification = await CreateNotification(subject, body, notificationType); |
| | | 166 | | |
| | 745 | 167 | | var notificationUsers = new NotificationUsers() |
| | 745 | 168 | | { |
| | 745 | 169 | | Notification = notification, |
| | 745 | 170 | | User = receiver, |
| | 745 | 171 | | NotificationsStatus = notificationType == NotificationType.System ? await _dirService.GetNotificationSta |
| | 745 | 172 | | : await _dirService.GetNotificationStatus((long)NotificationStatus.Created), |
| | 745 | 173 | | RecState = await _dirService.GetRecordState((long)RecordState.Active) |
| | 745 | 174 | | }; |
| | 745 | 175 | | await _notifyUserService.Create(notificationUsers); |
| | 0 | 176 | | if (sendEmail) await _emailService.Create(subject, body, receiver); |
| | 745 | 177 | | return notificationUsers; |
| | 745 | 178 | | } |
| | | 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) |
| | 0 | 191 | | { |
| | 0 | 192 | | if (receivers == null || receivers?.Count() == 0) throw new ArgumentException("Не указаны пользователи"); |
| | 0 | 193 | | var notification = await CreateNotification(subject, body, notificationType); |
| | 0 | 194 | | var notificationsStatus = notificationType == NotificationType.System ? await _dirService.GetNotificationSta |
| | 0 | 195 | | : await _dirService.GetNotificationStatus((long)NotificationStatus.Created); |
| | 0 | 196 | | var recState = await _dirService.GetRecordState((long)RecordState.Active); |
| | 0 | 197 | | List<NotificationUsers> notifyList = new List<NotificationUsers> (); |
| | 0 | 198 | | foreach (var user in receivers) |
| | 0 | 199 | | { |
| | 0 | 200 | | var notificationUsers = new NotificationUsers() |
| | 0 | 201 | | { |
| | 0 | 202 | | Notification = notification, |
| | 0 | 203 | | User = user, |
| | 0 | 204 | | NotificationsStatus = notificationsStatus, |
| | 0 | 205 | | RecState = recState |
| | 0 | 206 | | }; |
| | 0 | 207 | | notifyList.Add(notificationUsers); |
| | 0 | 208 | | } |
| | 0 | 209 | | if (sendEmail) await _emailService.Create(subject, body, receivers); |
| | 0 | 210 | | await _notifyUserService.Create(notifyList.ToArray()); |
| | 0 | 211 | | return await Task.FromResult(notifyList); |
| | 0 | 212 | | } |
| | | 213 | | } |
| | | 214 | | } |