< Summary

Class:SVETA.Api.Controllers.IncidentsController
Assembly:SVETA.Api
File(s):/opt/dev/sveta_api_build/SVETA.Api/Controllers/IncidentsController.cs
Covered lines:0
Uncovered lines:61
Coverable lines:61
Total lines:167
Line coverage:0% (0 of 61)
Covered branches:0
Total branches:24
Branch coverage:0% (0 of 24)

Metrics

MethodLine coverage Branch coverage
.ctor(...)0%100%
CreateIncident()0%0%
UploadImage()0%0%

File(s)

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

#LineLine coverage
 1using System;
 2using System.Text;
 3using System.IO;
 4using Microsoft.AspNetCore.Http;
 5using System.Collections.Generic;
 6using System.Linq;
 7using System.Threading.Tasks;
 8using Microsoft.AspNetCore.Authorization;
 9using Microsoft.AspNetCore.Mvc;
 10using SVETA.Api.Data.Domain;
 11using Microsoft.Extensions.Logging;
 12using Microsoft.Extensions.Options;
 13using WinSolutions.Sveta.Server.Data.DataModel.Entities;
 14using WinSolutions.Sveta.Server.Data.DataModel.Kinds;
 15using SVETA.Api.Data.DTO;
 16using WinSolutions.Sveta.Common;
 17using SVETA.Api.Helpers.Authorize;
 18using WinSolutions.Sveta.Server.Services.Interfaces;
 19using Swashbuckle.AspNetCore.Annotations;
 20using System.Runtime.InteropServices.ComTypes;
 21
 22namespace SVETA.Api.Controllers
 23{
 24    [Authorize]
 25    [Route("api/v1/Incidents")]
 26    [ApiController]
 27    public class IncidentsController : SvetaController
 28    {
 29        const string _routeUrl = "api/v1/Incidents";
 30        private readonly IIncidentService _service;
 31        private readonly IUserService _userService;
 32        private readonly IAuthenticationService _authService;
 33        private readonly INotificationService _notifyService;
 34        private readonly INotificationUsersService _notifyUserService;
 35        private readonly IDirectoriesService _dirService;
 36        private readonly IEmailService _emailService;
 37        private readonly UploadDownloadSettings _uploadSettings;
 38        private readonly EmailSettings _emailSettings;
 39        private readonly ILogger<IncidentsController> _logger;
 40
 41        public IncidentsController(IIncidentService service, INotificationService notifyService, INotificationUsersServi
 42            IUserService userService, IDirectoriesService dirService, IEmailService emailService, IOptions<UploadDownloa
 043            IOptions<EmailSettings> emailSettings) : base(logger)
 044        {
 045            _dirService = dirService;
 046            _emailSettings = emailSettings.Value;
 047            _authService = authService;
 048            _uploadSettings = uploadSettings.Value;
 049            _notifyService = notifyService;
 050            _notifyUserService = notifyUserService;
 051            _emailService = emailService;
 052            _userService = userService;
 053            _service = service;
 054            _logger = logger;
 055        }
 56
 57
 58
 59        /// <summary>
 60        /// Получить список видов инцидентов
 61        /// </summary>
 62        /// <remarks>author i.rebenok</remarks>
 63        [HttpGet("Kind")]
 64        [SwaggerResponse(200, "Успешно", typeof(IEnumerable<IdNameDTO>))]
 65        [SwaggerResponse(404, "Нет записей", typeof(ErrorDTO))]
 66        [SwaggerResponse(500, "Ошибка на стороне сервера", typeof(ErrorDTO))]
 67        [SwaggerResponse(403, "Не разрешено для этого пользователя", typeof(ErrorDTO))]
 68        [Authorize (Roles = Role.SystemAdmin+","+Role.SystemOperator + "," +Role.ShopOwner + "," +Role.ShopMerchandiser
 69            + "," +Role.ShopSeller + "," +Role.SupplierOwner + "," +Role.SupplierOperator + "," +Role.SupplierSpec)]
 70        public async Task<IActionResult> GetKindType()
 71        {
 72            var result = await _service.GetKindType();
 073            return Ok(result.Select(x => new IdNameDTO { Id = x.Id, Name = x.Name }));
 74        }
 75
 76        /// <summary>
 77        /// Получить список статусов инцидентов
 78        /// </summary>
 79        /// <remarks>author i.rebenok</remarks>
 80        [HttpGet("Status")]
 81        [SwaggerResponse(200, "Успешно", typeof(IEnumerable<IdNameDTO>))]
 82        [SwaggerResponse(500, "Ошибка на стороне сервера", typeof(ErrorDTO))]
 83        [SwaggerResponse(403, "Не разрешено для этого пользователя", typeof(ErrorDTO))]
 84        private async Task<IActionResult> GetStatusType()
 85        {
 86            var result = await _service.GetStatusType();
 087            return Ok(result.Select(x => new IdNameDTO { Id = x.Id, Name = x.Name }));
 88        }
 89
 90        /// <summary>
 91        /// Создает инцидент  и возвращает созданный объект. Типы 1-неизвестно, 2-ошибка, 3-вопрос, 4- предложение
 92        /// </summary>
 93        /// <remarks>author i.rebenok</remarks>
 94        /// <param name="incidentDto">IncidentRequestDTO</param>
 95        [HttpPost("")]
 96        [SwaggerResponse(201, "Успешно создано", typeof(IncidentDTO_GET))]
 97        [SwaggerResponse(404, "Нет записей", typeof(ErrorDTO))]
 98        [SwaggerResponse(500, "Ошибка на стороне сервера", typeof(ErrorDTO))]
 99        [SwaggerResponse(403, "Не разрешено для этого пользователя", typeof(ErrorDTO))]
 100        [SwaggerResponse(400, "Некорректные входные данные", typeof(ErrorDTO))]
 101        [Authorize(Roles = Role.SystemAdmin + "," + Role.SystemOperator + "," + Role.ShopOwner + "," + Role.ShopMerchand
 102            + "," + Role.ShopSeller + "," + Role.SupplierOwner + "," + Role.SupplierOperator + "," + Role.SupplierSpec)]
 103        public async Task<IActionResult> CreateIncident([FromBody] [SwaggerParameter(Required = true)] IncidentRequestDT
 0104        {
 0105            if (!ModelState.IsValid)
 0106                return BadRequestResult("");
 0107            var incident = new Incident()
 0108            {
 0109              //  RecState = await _dirService.GetRecordState((int)RecordState.Empty),
 0110                User = await _userService.GetUser(_authService.UserId),
 0111                Kind = (await _service.GetKindType()).FirstOrDefault(x => x.Id == incidentDto.KindId),
 0112                Status = (await _service.GetStatusType()).FirstOrDefault(x => x.Id == (int)IncidentStatus.Open),
 0113                Body = incidentDto.Body,
 0114                Subject = incidentDto.Subject,
 0115            };//TODO: i.rebenok надо эти поля поставить required с errorMessage в модели как у договоров. И можно попроб
 0116            if (incident.User == null)
 0117                return NotFoundResult($"Пользователь с id={_authService.UserId} не найден");
 0118            if (incident.Kind == null)
 0119                return NotFoundResult($"Тип инцидента с id={incidentDto.KindId} не найден");
 0120            if (incident.Status == null)
 0121                return NotFoundResult($"Статус инцидента с id={(int)IncidentStatus.Open} не найден");
 122            /*if (incident.RecState == null)
 123                return NotFoundResult("Служебный тип записи не найден");*/
 0124            await _service.CreateIncident(incident);
 0125            StringBuilder sb = new StringBuilder();
 0126            sb.Append("<b>В системе создан новый инцидент:</b><br>");
 0127            sb.Append("Дата создания: " + incident.DtCreated + "<br>");
 0128            sb.Append("Тема инцидента: " + incident.Subject + "<br>");
 0129            sb.Append("Тип инцидента: " + incident.Kind.Name + "<br>");
 0130            sb.Append("Статус инцидента: " + incident.Status.Name + "<br>");
 0131            sb.Append("Пользователь: " + incident.User.FirstName + " " + incident.User.LastName + "<br>");
 0132            sb.Append("Почта: " + incident.User.Email + "<br>");
 0133            sb.Append("Телефон: " + incident.User.Phone + "<br>");
 0134            sb.Append("Содержание: " + incident.Body + "<br>");
 0135            await _emailService.Create("Создан новый инцидент", sb.ToString(), _emailSettings.ServiceDeskMail, !string.I
 0136            await _notifyService.CreateNotificationForUser("Создание инцидента", "Ваше сообщение успешно отправлено в те
 0137            return StatusCode(201, new IncidentDTO_GET(incident));
 0138        }
 139
 140        /// <summary>
 141        /// Загружает файл  для инцидента
 142        /// </summary>
 143        /// <remarks>author i.rebenok</remarks>
 144        /// <param name="file">файл</param>
 145        /// <returns>статус загрузки и имя файла</returns>
 146        [HttpPost("UploadImage")]
 147        [SwaggerResponse(200, "Успешно", typeof(EmptyResult))]
 148        [SwaggerResponse(500, "Ошибка на стороне сервера", typeof(ErrorDTO))]
 149        [SwaggerResponse(403, "Не разрешено для этого пользователя", typeof(ErrorDTO))]
 150        [Authorize(Roles = Role.SystemAdmin + "," + Role.SystemOperator + "," + Role.ShopOwner + "," + Role.ShopMerchand
 151            + "," + Role.ShopSeller + "," + Role.SupplierOwner + "," + Role.SupplierOperator + "," + Role.SupplierSpec)]
 152        public async Task<IActionResult> UploadImage([SwaggerParameter(Required = true)] IFormFile file)
 0153        {
 0154            if (file == null || file?.Length == 0)
 0155                return BadRequestResult("Необходимо указать файл");
 0156            var fname = "inc_" + Guid.NewGuid() + Path.GetExtension(file.FileName);
 0157            string filepath = Path.Combine(_uploadSettings.UploadsSavePath, fname);
 0158            var success = false;
 0159            using (var stream = new FileStream(filepath, FileMode.Create))
 0160            {
 0161                await file.CopyToAsync(stream);
 0162                success = true;
 0163            }
 0164            return Ok(new { succeed = success, filename = fname });
 0165        }
 166    }
 167}