| | | 1 | | using System; |
| | | 2 | | using System.Text; |
| | | 3 | | using System.IO; |
| | | 4 | | using Microsoft.AspNetCore.Http; |
| | | 5 | | using System.Collections.Generic; |
| | | 6 | | using System.Linq; |
| | | 7 | | using System.Threading.Tasks; |
| | | 8 | | using Microsoft.AspNetCore.Authorization; |
| | | 9 | | using Microsoft.AspNetCore.Mvc; |
| | | 10 | | using SVETA.Api.Data.Domain; |
| | | 11 | | using Microsoft.Extensions.Logging; |
| | | 12 | | using Microsoft.Extensions.Options; |
| | | 13 | | using WinSolutions.Sveta.Server.Data.DataModel.Entities; |
| | | 14 | | using WinSolutions.Sveta.Server.Data.DataModel.Kinds; |
| | | 15 | | using SVETA.Api.Data.DTO; |
| | | 16 | | using WinSolutions.Sveta.Common; |
| | | 17 | | using SVETA.Api.Helpers.Authorize; |
| | | 18 | | using WinSolutions.Sveta.Server.Services.Interfaces; |
| | | 19 | | using Swashbuckle.AspNetCore.Annotations; |
| | | 20 | | using System.Runtime.InteropServices.ComTypes; |
| | | 21 | | |
| | | 22 | | namespace 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 |
| | 0 | 43 | | IOptions<EmailSettings> emailSettings) : base(logger) |
| | 0 | 44 | | { |
| | 0 | 45 | | _dirService = dirService; |
| | 0 | 46 | | _emailSettings = emailSettings.Value; |
| | 0 | 47 | | _authService = authService; |
| | 0 | 48 | | _uploadSettings = uploadSettings.Value; |
| | 0 | 49 | | _notifyService = notifyService; |
| | 0 | 50 | | _notifyUserService = notifyUserService; |
| | 0 | 51 | | _emailService = emailService; |
| | 0 | 52 | | _userService = userService; |
| | 0 | 53 | | _service = service; |
| | 0 | 54 | | _logger = logger; |
| | 0 | 55 | | } |
| | | 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(); |
| | 0 | 73 | | 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(); |
| | 0 | 87 | | 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 |
| | 0 | 104 | | { |
| | 0 | 105 | | if (!ModelState.IsValid) |
| | 0 | 106 | | return BadRequestResult(""); |
| | 0 | 107 | | var incident = new Incident() |
| | 0 | 108 | | { |
| | 0 | 109 | | // RecState = await _dirService.GetRecordState((int)RecordState.Empty), |
| | 0 | 110 | | User = await _userService.GetUser(_authService.UserId), |
| | 0 | 111 | | Kind = (await _service.GetKindType()).FirstOrDefault(x => x.Id == incidentDto.KindId), |
| | 0 | 112 | | Status = (await _service.GetStatusType()).FirstOrDefault(x => x.Id == (int)IncidentStatus.Open), |
| | 0 | 113 | | Body = incidentDto.Body, |
| | 0 | 114 | | Subject = incidentDto.Subject, |
| | 0 | 115 | | };//TODO: i.rebenok надо эти поля поставить required с errorMessage в модели как у договоров. И можно попроб |
| | 0 | 116 | | if (incident.User == null) |
| | 0 | 117 | | return NotFoundResult($"Пользователь с id={_authService.UserId} не найден"); |
| | 0 | 118 | | if (incident.Kind == null) |
| | 0 | 119 | | return NotFoundResult($"Тип инцидента с id={incidentDto.KindId} не найден"); |
| | 0 | 120 | | if (incident.Status == null) |
| | 0 | 121 | | return NotFoundResult($"Статус инцидента с id={(int)IncidentStatus.Open} не найден"); |
| | | 122 | | /*if (incident.RecState == null) |
| | | 123 | | return NotFoundResult("Служебный тип записи не найден");*/ |
| | 0 | 124 | | await _service.CreateIncident(incident); |
| | 0 | 125 | | StringBuilder sb = new StringBuilder(); |
| | 0 | 126 | | sb.Append("<b>В системе создан новый инцидент:</b><br>"); |
| | 0 | 127 | | sb.Append("Дата создания: " + incident.DtCreated + "<br>"); |
| | 0 | 128 | | sb.Append("Тема инцидента: " + incident.Subject + "<br>"); |
| | 0 | 129 | | sb.Append("Тип инцидента: " + incident.Kind.Name + "<br>"); |
| | 0 | 130 | | sb.Append("Статус инцидента: " + incident.Status.Name + "<br>"); |
| | 0 | 131 | | sb.Append("Пользователь: " + incident.User.FirstName + " " + incident.User.LastName + "<br>"); |
| | 0 | 132 | | sb.Append("Почта: " + incident.User.Email + "<br>"); |
| | 0 | 133 | | sb.Append("Телефон: " + incident.User.Phone + "<br>"); |
| | 0 | 134 | | sb.Append("Содержание: " + incident.Body + "<br>"); |
| | 0 | 135 | | await _emailService.Create("Создан новый инцидент", sb.ToString(), _emailSettings.ServiceDeskMail, !string.I |
| | 0 | 136 | | await _notifyService.CreateNotificationForUser("Создание инцидента", "Ваше сообщение успешно отправлено в те |
| | 0 | 137 | | return StatusCode(201, new IncidentDTO_GET(incident)); |
| | 0 | 138 | | } |
| | | 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) |
| | 0 | 153 | | { |
| | 0 | 154 | | if (file == null || file?.Length == 0) |
| | 0 | 155 | | return BadRequestResult("Необходимо указать файл"); |
| | 0 | 156 | | var fname = "inc_" + Guid.NewGuid() + Path.GetExtension(file.FileName); |
| | 0 | 157 | | string filepath = Path.Combine(_uploadSettings.UploadsSavePath, fname); |
| | 0 | 158 | | var success = false; |
| | 0 | 159 | | using (var stream = new FileStream(filepath, FileMode.Create)) |
| | 0 | 160 | | { |
| | 0 | 161 | | await file.CopyToAsync(stream); |
| | 0 | 162 | | success = true; |
| | 0 | 163 | | } |
| | 0 | 164 | | return Ok(new { succeed = success, filename = fname }); |
| | 0 | 165 | | } |
| | | 166 | | } |
| | | 167 | | } |