< Summary

Class:SVETA.Api.Services.Implements.NotificationWorker
Assembly:SVETA.Api
File(s):/opt/dev/sveta_api_build/SVETA.Api/Services/Implements/NotificationWorker.cs
Covered lines:0
Uncovered lines:144
Coverable lines:144
Total lines:229
Line coverage:0% (0 of 144)
Covered branches:0
Total branches:57
Branch coverage:0% (0 of 57)

Metrics

MethodLine coverage Branch coverage
.ctor(...)0%100%
CreateNotification()0%0%
<CreateNotification()0%0%
SendNotification()0%0%
FormatComment()0%0%
SendBySocket(...)0%0%

File(s)

/opt/dev/sveta_api_build/SVETA.Api/Services/Implements/NotificationWorker.cs

#LineLine coverage
 1using System;
 2using System.Collections.Generic;
 3using System.Diagnostics;
 4using System.Linq;
 5using System.Net.Http;
 6using System.Threading;
 7using System.Threading.Tasks;
 8using Microsoft.AspNetCore.SignalR;
 9using Microsoft.Extensions.Logging;
 10using Microsoft.Extensions.Options;
 11using Newtonsoft.Json;
 12using Newtonsoft.Json.Serialization;
 13using Serilog;
 14using SVETA.Api.Data.Domain;
 15using SVETA.Api.Data.DTO.Notification;
 16using SVETA.Api.Helpers;
 17using SVETA.Api.Hubs;
 18using SVETA.API.IntegrationTest.Common;
 19using SVETA.Api.Services.Interfaces;
 20using WinSolutions.Sveta.Server.Data.DataModel.Entities;
 21using WinSolutions.Sveta.Server.Data.DataModel.Kinds;
 22using WinSolutions.Sveta.Server.Services.Interfaces;
 23using WinSolutions.Sveta.Server.Services.Implements;
 24
 25namespace SVETA.Api.Services.Implements
 26{
 27    public class NotificationWorker: INotificationWorker
 28    {
 29        private readonly ILogger<INotificationWorker> _logger;
 30        private readonly INotificationService _notificationService;
 31        private readonly IDepartmentService _departmentService;
 32        private readonly IUserService _userService;
 33        private readonly IContragentService _contragentService;
 34        private readonly IEmailService _emailService;
 35        private readonly CommonSettings _commonSettings;
 36        private readonly IHubContext<NotificationHub> _notificationHub;
 37        private readonly TelegramSettings _telegramSettings;
 38        private readonly ITelegramNotificationService _telegramService;
 39        private readonly IAddressService _addressService;
 40
 041        public NotificationWorker(ILogger<INotificationWorker> logger,
 042            INotificationService notificationService,
 043            IHubContext<NotificationHub> notificationHub,
 044            IDepartmentService departmentService,
 045            IContragentService contragentService,
 046            IEmailService emailService,
 047            IUserService userService,
 048            IOptions<CommonSettings> commonSettingsOption,
 049            ITelegramNotificationService telegramService,
 050            IAddressService addressService,
 051            IOptions<TelegramSettings> telegramOptions)
 052        {
 053            _telegramService = telegramService;
 054            _logger = logger;
 055            _notificationService = notificationService;
 056            _notificationHub = notificationHub;
 057            _telegramSettings = telegramOptions.Value;
 058            _departmentService = departmentService;
 059            _userService = userService;
 060            _contragentService = contragentService;
 061            _emailService = emailService;
 062            _commonSettings = commonSettingsOption.Value;
 063            _addressService = addressService;
 064        }
 65
 66
 67        /// <summary>
 68        /// Создает уведомление
 69        /// </summary>
 70        /// <param name="movement">Документ</param>
 71        /// <param name="subject">Тема уведомления</param>
 72        /// <param name="body">Тело уведомления</param>
 73        /// <param name="sendEmailToDepartment">Отправлять письмо на рассылку департамента-владельца статуса</param>
 74        /// <returns></returns>
 75        public async Task CreateNotification(Movement movement, string subject, string body = default, bool sendEmailToD
 076        {
 077            IEnumerable<User> userList = null;
 078            List<string> departmentsEmail = new List<string>() { };
 79
 080            switch (movement.MovementStatus.Id)
 81            {
 82                case (long)MovementsStatus.OrderDraft:
 83                case (long)MovementsStatus.Reject:
 84                case (long)MovementsStatus.InProgress:
 85                case (long)MovementsStatus.Finished:
 86                case (long)MovementsStatus.PaymentAwaiting:
 87                case (long)MovementsStatus.ReadyForShipment:
 88                case (long)MovementsStatus.Correction:
 89                case (long)MovementsStatus.SupplierReject:
 90                case (long)MovementsStatus.Shipped:
 091                    userList = await _userService.GetDepartmentUsers(movement.Receiver.Id);
 092                    departmentsEmail.Add(movement.Receiver.Email);
 093                    break;
 94                case (long)MovementsStatus.ShipmentDraft:
 95                case (long)MovementsStatus.Received:
 96                case (long)MovementsStatus.CustomerReject:
 097                    userList = await _userService.GetDepartmentUsers(movement.Sender.Id);
 098                    departmentsEmail.Add(movement.Sender.Email);
 099                    break;
 100                case (long)MovementsStatus.InQueue:
 0101                    userList = await _contragentService.GetContragentUsers(ContragentKind.Platform);
 0102                    departmentsEmail.Add((await _departmentService.GetPlatformDepartment())?.Email);
 0103                    break;
 104                case (long)MovementsStatus.Picking:
 105                case (long)MovementsStatus.ClaimInProgress:
 0106                    userList = (await _contragentService.GetContragentUsers(ContragentKind.Platform)).Union(await _userS
 0107                     await _userService.GetDepartmentUsers(movement.Sender.Id));
 0108                    departmentsEmail.Add((await _departmentService.GetPlatformDepartment()).Email);
 0109                    departmentsEmail.Add(movement.Receiver.Email);
 0110                    departmentsEmail.Add(movement.Sender.Email);
 0111                    break;
 112                case (long)MovementsStatus.ClaimAccepted:
 113                case (long)MovementsStatus.ClaimDeclined:
 0114                    userList = (await _userService.GetDepartmentUsers(movement.Receiver.Id)).Union(
 0115                    await _userService.GetDepartmentUsers(movement.Sender.Id));
 0116                    departmentsEmail.Add(movement.Receiver.Email);
 0117                    departmentsEmail.Add(movement.Sender.Email);
 0118                    break;
 0119            };
 0120            var tasks = new List<Task>();
 0121            if (userList != null && userList.Count() > 0)
 0122            {
 0123                var list = await _notificationService.CreateNotificationForUsers(subject, body, userList.ToList(), false
 0124                tasks.Add(Task.Factory.StartNew(async (list) =>
 0125                {
 0126                    await SendNotification((List<NotificationUsers>)list);
 0127                }, list));
 0128            }
 129
 130
 0131            if (sendEmailToDepartment && departmentsEmail.Count > 0)
 0132            {
 0133                if (movement.Notes?.Count > 0)
 0134                {
 0135                    var listComments = await FormatComment(movement.Notes);
 0136                    body += $"\n Комментарии к документу" +
 0137                            $": \n{string.Join("\n", listComments)}";
 0138                }
 139
 0140                await _emailService.Create(subject, body, departmentsEmail);
 0141            }
 142
 0143            if (movement.MovementStatus.Id != (long) MovementsStatus.OrderDraft)
 0144            {
 0145                if ((await _telegramService.CanSendToTelegram("#order")))
 0146                {
 0147                    string textTelegram =
 0148                        $"#order " +
 0149                        $"\nЗаявка № {movement.DocumentNumber} {_commonSettings.BaseFrontUrl}/{MovementHelpers.CreatePos
 0150                        $"переведена в статус \"{movement.MovementStatus.Name}\". " +
 0151                        $"\n Заказчик: {movement.Customer.ShortName} " +
 0152                        $"\n Фактический адрес: {(await _addressService.GetPhysicAddressByContragent(movement.Customer.I
 0153                        $"\n e-mail: {movement.Customer.Email} " +
 0154                        $"\n Номер телефона: {movement.Customer.PhoneNumber} " +
 0155                        $"\n Сумма заказа: {movement.PrepaimentSum} " +
 0156                        $"\n Время заказа: {movement.CreationDateTime} " +
 0157                        $"\n Статус заказа: {movement.MovementStatus.Name}";
 0158                    if (movement.Notes?.Count > 0)
 0159                    {
 0160                        var listComments = await FormatComment(movement.Notes);
 161
 0162                        textTelegram += $"\n Комментарии к документу" +
 0163                                        $": \n{string.Join("\n", listComments)}";
 0164                    }
 165
 0166                    tasks.Add(Task.Factory.StartNew(async () =>
 0167                    {
 0168                        await Telegram.SendNotification(textTelegram);
 0169                    }));
 0170                }
 0171            }
 0172            Task.WhenAll(tasks.ToArray());
 0173        }
 174
 175        public async Task SendNotification(List<NotificationUsers> list)
 0176        {
 0177            if (list != null && list.Count > 0)
 0178            {
 0179                Parallel.ForEach(list,notification =>
 0180                {
 0181                    SendBySocket(notification);
 0182                });
 0183            }
 0184        }
 185
 186        private async Task<List<string>> FormatComment(List<MovementNote> notes)
 0187        {
 0188            var listComments = new List<string>();
 0189            for (int i = 0; i < notes.Count; i++)
 0190            {
 0191                string res = notes[i].CreationDateTime.ToString("dd.MM.yyyy hh:mm") + " ";
 0192                if (notes[i].CreatedByUserId.HasValue)
 0193                {
 0194                    res += (await _userService.GetUser(notes[i].CreatedByUserId.Value)).GetName();
 0195                }
 0196                res += " --- " + notes[i].Body;
 0197                listComments.Add(res);
 0198            }
 199
 0200            return listComments;
 0201        }
 202
 203        void SendBySocket(NotificationUsers notification)
 0204        {
 0205            string connectionId = default;
 0206            UserHandler.ConnectedIds.TryGetValue(notification.User.ExternalKey.ToString(), out connectionId);
 0207            if (connectionId != default)
 0208            {
 0209                _notificationHub
 0210                    .Clients
 0211                    .Client(connectionId)
 0212                    .SendAsync("notificationReceived", JsonConvert.SerializeObject(new NotificationResponseDTO
 0213                    {
 0214                        NotificationId = notification.Notification.Id,
 0215                        Subject = notification.Notification.Subject,
 0216                        Body = notification.Notification.Body,
 0217                        SenderId = notification.Notification.User.Id,
 0218                        NotificationsType = notification.Notification.NotificationsType.Id,
 0219                        NotificationsStatus = notification.NotificationsStatus.Id,
 0220                        TimeToTurnOff = notification.Notification.TimeToTurnOff,
 0221                        CreationDateTime = notification.CreationDateTime
 0222                    }, new JsonSerializerSettings
 0223                    {
 0224                        ContractResolver = new CamelCasePropertyNamesContractResolver()
 0225                    }) ).Wait();
 0226            }
 0227        }
 228    }
 229}