< Summary

Class:SVETA.Api.Controllers.GoodLabelsController
Assembly:SVETA.Api
File(s):/opt/dev/sveta_api_build/SVETA.Api/Controllers/GoodLabelsController.cs
Covered lines:0
Uncovered lines:60
Coverable lines:60
Total lines:163
Line coverage:0% (0 of 60)
Covered branches:0
Total branches:20
Branch coverage:0% (0 of 20)

Metrics

MethodLine coverage Branch coverage
.ctor(...)0%100%
GetGoodLabels()0%0%
GetGoodLabel()0%100%
CreateGoodLabel()0%0%
UpdateGoodLabel()0%0%
DeleteGoodLabel()0%100%

File(s)

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

#LineLine coverage
 1using WinSolutions.Sveta.Common.Extensions;
 2using System;
 3using System.Collections.Generic;
 4using System.Linq;
 5using System.Threading.Tasks;
 6using Microsoft.AspNetCore.Mvc;
 7using Microsoft.Extensions.Logging;
 8using WinSolutions.Sveta.Server.Data.DataModel.Entities;
 9using Microsoft.AspNetCore.Authorization;
 10using SVETA.Api.Data.Domain;
 11using WinSolutions.Sveta.Server.Services.Interfaces;
 12using SVETA.Api.Data.DTO.DiscountColorDTO;
 13using SVETA.Api.Data.DTO;
 14using SVETA.Api.Helpers.Authorize;
 15using WinSolutions.Sveta.Server.Data.DataModel.Kinds;
 16using Swashbuckle.AspNetCore.Annotations;
 17using WinSolutions.Sveta.Server.Domain;
 18using WinSolutions.Sveta.Common;
 19using CrmVtbc;
 20
 21namespace SVETA.Api.Controllers
 22{
 23    [Authorize]
 24    [Route("api/v1/GoodLabels")]
 25    [ApiController]
 26    public class GoodLabelsController : SvetaController
 27    {
 28        const string _routeUrl = "api/v1/GoodLabels";
 29        readonly IGoodLabelService _service;
 30        readonly IAuthenticationService _authUserService;
 31        readonly ILogger<GoodLabelsController> _logger;
 032        public GoodLabelsController(IGoodLabelService service, IAuthenticationService authUserService, ILogger<GoodLabel
 033        {
 034            _service = service;
 035            _authUserService = authUserService;
 036            _logger = logger;
 037        }
 38
 39        /// <summary>
 40        /// Возвращает все ярлыки
 41        /// </summary>
 42        /// <remarks>author i.rebenok</remarks>
 43        /// <param name="page">Любое значение ниже нуля изменится на 1, пагинация: номер страницы</param>
 44        /// <param name="limit">Любое значение ниже нуля изменится на 10, пагинация: размер страницы</param>
 45        /// <param name="sort">Сортировка по имени и id: name, name|desc, id, id|desc. По умолчанию name</param>
 46        /// <param name="filter">Поиск по названию ярлыка</param>
 47        /// <param name="showcaseVisible">Вдимость на витрине. True - только видимые, false - только невидимые, null - в
 48        [HttpGet("")]
 49        [SwaggerResponse(200, "Успешно", typeof(BaseResponseDTO<GoodLabelResponseDTO>))]
 50        [SwaggerResponse(500, "Ошибка на стороне сервера", typeof(ErrorDTO))]
 51        [SwaggerResponse(403, "Не разрешено для этого пользователя", typeof(ErrorDTO))]
 52        [Authorize(Roles = Role.SystemAdmin + "," + Role.SystemOperator + "," + Role.SupplierOwner + "," + Role.Supplier
 53        public async Task<IActionResult> GetGoodLabels(int page = 1, int limit = 10, string sort = default, string filte
 054        {
 055            filter = filter.NormalizeName();
 056            page = page < 1 ? 1 : page;
 057            limit = limit < 1 ? 10 : limit;
 058            var result = await _service.GetGoodLabels(page - 1, limit, sort, filter, showcaseVisible);
 059            var param = $"";
 060            var response = new BaseResponseDTO<GoodLabelResponseDTO>(_routeUrl, page, limit, result.TotalFilteredCount, 
 061            {
 062                Data = result.Result.Select(x => new GoodLabelResponseDTO(x)).ToList(),
 063            };
 064            return Ok(response);
 065        }
 66
 67        /// <summary>
 68        /// Возвращает ярлык по id
 69        /// </summary>
 70        /// <remarks>author i.rebenok</remarks>
 71        /// <param name="id">id ярлыка</param>
 72        [HttpGet("{id}")]
 73        [SwaggerResponse(200, "Успешно", typeof(IEnumerable<GoodLabelResponseDTO>))]
 74        [SwaggerResponse(500, "Ошибка на стороне сервера", typeof(ErrorDTO))]
 75        [SwaggerResponse(403, "Не разрешено для этого пользователя", typeof(ErrorDTO))]
 76        [Authorize(Roles = Role.SystemAdmin + "," + Role.SystemOperator + "," + Role.SupplierOwner + "," + Role.Supplier
 77        public async Task<IActionResult> GetGoodLabel([SwaggerParameter(Required = true)] long id)
 078        {
 079            var result = await _service.GetGoodLabel(id);
 080            return Ok(new GoodLabelResponseDTO(result));
 081        }
 82
 83        /// <summary>
 84        /// Создает запись с ярлыком и цветом. Цвет состоит из 6 символов RGB модели
 85        /// </summary>
 86        /// <remarks>author i.rebenok</remarks>
 87        /// <param name="data">объект GoodLabelRequestDTO</param>
 88        [HttpPost("")]
 89        [SwaggerResponse(201, "Успешно создано", typeof(GoodLabelRequestDTO))]
 90        [SwaggerResponse(404, "Нет записей", typeof(ErrorDTO))]
 91        [SwaggerResponse(500, "Ошибка на стороне сервера", typeof(ErrorDTO))]
 92        [SwaggerResponse(400, "Некорректные входные данные", typeof(ErrorDTO))]
 93        [SwaggerResponse(403, "Не разрешено для этого пользователя", typeof(ErrorDTO))]
 94        [Authorize(Roles = Role.SystemAdmin + "," + Role.SystemOperator + "," + Role.SupplierOwner + "," + Role.Supplier
 95        public async Task<IActionResult> CreateGoodLabel([FromBody][SwaggerParameter(Required = true)] GoodLabelRequestD
 096        {
 097            if (!ModelState.IsValid)
 098                return BadRequestResult("Некорректные входные данные");
 099            var existLabel = await _service.GetGoodLabelByName(data.Name);
 0100            if (existLabel != null)
 0101                return BadRequestResult($"Ярлык с именем {data.Name} уже существует");
 0102            var label = new GoodLabel()
 0103            {
 0104                Name = data.Name,
 0105                Priority = data.Priority,
 0106                LabelColor = data.LabelColor,
 0107                TextColor = data.TextColor,
 0108                ShowcaseVisible = data.ShowcaseVisible
 0109            };
 0110            await _service.Create(label);
 0111            return CreatedAtAction("GetGoodLabel", new { id = label.Id }, new GoodLabelResponseDTO(label));
 0112        }
 113
 114        /// <summary>
 115        /// Обновляет ярлык по id. Цвет состоит из 6 символов RGB модели
 116        /// </summary>
 117        /// <remarks>author i.rebenok</remarks>
 118        /// <param name="id">id записи</param>
 119        /// <param name="data">обюект GoodLabelRequestDTO</param>
 120        [HttpPut("{id}")]
 121        [SwaggerResponse(200, "Успешно обновлено", typeof(GoodLabelRequestDTO))]
 122        [SwaggerResponse(404, "Нет записей", typeof(ErrorDTO))]
 123        [SwaggerResponse(500, "Ошибка на стороне сервера", typeof(ErrorDTO))]
 124        [SwaggerResponse(400, "Некорректные входные данные", typeof(ErrorDTO))]
 125        [SwaggerResponse(403, "Не разрешено для этого пользователя", typeof(ErrorDTO))]
 126        [Authorize(Roles = Role.SystemAdmin + "," + Role.SystemOperator + "," + Role.SupplierOwner + "," + Role.Supplier
 127        public async Task<IActionResult> UpdateGoodLabel([SwaggerParameter(Required = true)] long id, [FromBody][Swagger
 0128        {
 0129            if (!ModelState.IsValid)
 0130                return BadRequestResult("Некорректные входные данные");
 0131            var label = await _service.GetGoodLabel(id);
 0132            if (label == null)
 0133                return NotFoundResult($"Ярлык с id={id} не найден");
 0134            var existLabel = await _service.GetGoodLabelByName(data.Name);
 0135            if (existLabel?.Id != id)
 0136                return BadRequestResult($"Ярлык с именем {data.Name} уже существует");
 0137            label.Name = data.Name;
 0138            label.Priority = data.Priority;
 0139            label.LabelColor = data.LabelColor;
 0140            label.TextColor = data.TextColor;
 0141            label.ShowcaseVisible = data.ShowcaseVisible;
 0142            await _service.Update(label);
 0143            return Ok(new GoodLabelResponseDTO(label));
 0144        }
 145
 146        /// <summary>
 147        /// Удаляет ярлык по id
 148        /// </summary>
 149        /// <remarks>author i.rebenok</remarks>
 150        /// <param name="id">id записи</param>
 151        [HttpDelete("{id}")]
 152        [SwaggerResponse(200, "Успешно удалено", typeof(EmptyResult))]
 153        [SwaggerResponse(404, "Нет записей", typeof(ErrorDTO))]
 154        [SwaggerResponse(500, "Ошибка на стороне сервера", typeof(ErrorDTO))]
 155        [SwaggerResponse(403, "Не разрешено для этого пользователя", typeof(ErrorDTO))]
 156        [Authorize(Roles = Role.SystemAdmin + "," + Role.SystemOperator + "," + Role.SupplierOwner + "," + Role.Supplier
 157        public async Task<IActionResult> DeleteGoodLabel([SwaggerParameter(Required = true)] long id)
 0158        {
 0159            await _service.Delete(id);
 0160            return Ok();
 0161        }
 162    }
 163}