| | | 1 | | using System; |
| | | 2 | | using WinSolutions.Sveta.Common.Extensions; |
| | | 3 | | using System.Collections.Generic; |
| | | 4 | | using System.Linq; |
| | | 5 | | using System.Threading.Tasks; |
| | | 6 | | using Microsoft.AspNetCore.Mvc; |
| | | 7 | | using Microsoft.Extensions.Logging; |
| | | 8 | | using WinSolutions.Sveta.Server.Data.DataModel.Entities; |
| | | 9 | | using WinSolutions.Sveta.Server.Services.Interfaces; |
| | | 10 | | using Swashbuckle.AspNetCore.Annotations; |
| | | 11 | | using SVETA.Api.Data.DTO; |
| | | 12 | | using Microsoft.AspNetCore.Authorization; |
| | | 13 | | |
| | | 14 | | namespace SVETA.Api.Controllers |
| | | 15 | | { |
| | | 16 | | [Route("api/v1/Brands")] |
| | | 17 | | [ApiController] |
| | | 18 | | [Authorize] |
| | | 19 | | public class BrandsController : SvetaController |
| | | 20 | | { |
| | | 21 | | private readonly IBrandService _brandService; |
| | | 22 | | private readonly ILogger<BrandsController> _logger; |
| | | 23 | | |
| | 0 | 24 | | public BrandsController(IBrandService brandService, ILogger<BrandsController> logger): base(logger) |
| | 0 | 25 | | { |
| | 0 | 26 | | _brandService = brandService; |
| | 0 | 27 | | _logger = logger; |
| | 0 | 28 | | } |
| | | 29 | | |
| | | 30 | | /// <summary> |
| | | 31 | | /// Возвращает количество брендов с учётом фильтрации |
| | | 32 | | /// </summary> |
| | | 33 | | /// <remarks>author: nko/obo</remarks> |
| | | 34 | | /// <param name="filter">Фильтр по значимым полям (Name)</param> |
| | | 35 | | /// <param name="parentId">код родительского бренда, -1 если считать по всем брендам базы</param> |
| | | 36 | | /// <returns>Количество брендов </returns> |
| | | 37 | | [HttpGet("Count")] |
| | | 38 | | [SwaggerResponse(200, "Успешно", typeof(CountDTO))] |
| | | 39 | | [SwaggerResponse(400, "Переданы некорректные параметры", typeof(ErrorDTO))] |
| | | 40 | | [SwaggerResponse(500, "Ошибка на стороне сервера", typeof(ErrorDTO))] |
| | | 41 | | [Authorize(Roles = Role.SystemAdmin +"," + Role.SystemOperator)] |
| | | 42 | | public async Task<IActionResult> GetBrandsCount(string filter = "", long parentId = -1) |
| | 0 | 43 | | { |
| | 0 | 44 | | filter = filter.NormalizeName(); |
| | 0 | 45 | | return Ok(new CountDTO ((int)await _brandService.GetBrandsCount(filter, parentId != -1 ? parentId : (long?)n |
| | 0 | 46 | | } |
| | | 47 | | |
| | | 48 | | /// <summary> |
| | | 49 | | /// Возвращает список брендов с учётом фильтрации, сортировки и пагинации |
| | | 50 | | /// </summary> |
| | | 51 | | /// <remarks>author: nko</remarks> |
| | | 52 | | /// <param name="sort">Сортировка в виде field_name|order. order может принимать значения asc либо desc, field_n |
| | | 53 | | /// <param name="filter">Фильтр по значимым полям (name)</param> |
| | | 54 | | /// <param name="page">Любое значение ниже нуля изменится на 1, Номер страницы</param> |
| | | 55 | | /// <param name="limit">Любое значение ниже нуля изменится на 10, Записей на странице</param> |
| | | 56 | | /// <param name="parentId">Идентифиатор родительской категории: null - все категории, 0 - корневые категории, 1. |
| | | 57 | | /// <returns>Список брендов</returns> |
| | | 58 | | [HttpGet("")] |
| | | 59 | | [SwaggerResponse(200, "Успешно", typeof(List<BrandOutputDTO>))] |
| | | 60 | | [SwaggerResponse(400, "Переданы некорректные параметры", typeof(ErrorDTO))] |
| | | 61 | | [SwaggerResponse(500, "Ошибка на стороне сервера", typeof(ErrorDTO))] |
| | | 62 | | [Authorize(Roles = Role.SystemAdmin+"," + Role.SystemOperator)] |
| | | 63 | | public async Task<IActionResult> GetBrands(string sort = "", string filter = "", int page = 1, int limit = 10, l |
| | | 64 | | { |
| | | 65 | | filter = filter.NormalizeName(); |
| | | 66 | | page = page < 1 ? 1 : page; |
| | | 67 | | limit = limit < 1 ? 10 : limit; |
| | | 68 | | var items = await _brandService.GetBrands(sort, filter, page, limit, parentId != -1 ? parentId : (long?)null |
| | | 69 | | |
| | 0 | 70 | | var itemIds = items.Select(x => x.Id).ToArray(); |
| | | 71 | | |
| | | 72 | | var parentsId = await _brandService.CheckParentIds(itemIds); |
| | 0 | 73 | | var result = items.Select(x => new BrandOutputDTO(x) |
| | 0 | 74 | | { |
| | 0 | 75 | | Expandable = parentsId.Count != 0 && parentsId.Contains(x.Id) |
| | 0 | 76 | | }); |
| | | 77 | | return Ok(result); |
| | | 78 | | } |
| | | 79 | | |
| | | 80 | | /// <summary> |
| | | 81 | | /// Возвращает бренд по его ID |
| | | 82 | | /// </summary> |
| | | 83 | | /// <remarks>author: nko</remarks> |
| | | 84 | | /// <param name="id">ID записи</param> |
| | | 85 | | /// <returns></returns> |
| | | 86 | | [HttpGet("{id}")] |
| | | 87 | | [SwaggerResponse(200, "Успешно", typeof(BrandOutputDTO))] |
| | | 88 | | [SwaggerResponse(400, "Переданы некорректные параметры", typeof(ErrorDTO))] |
| | | 89 | | [SwaggerResponse(404, "Нет записей", typeof(ErrorDTO))] |
| | | 90 | | [SwaggerResponse(500, "Ошибка на стороне сервера", typeof(ErrorDTO))] |
| | | 91 | | [Authorize(Roles = Role.SystemAdmin+"," + Role.SystemOperator)] |
| | | 92 | | public async Task<IActionResult> GetBrand([SwaggerParameter(Required = true)]long id) |
| | 0 | 93 | | { |
| | 0 | 94 | | var brand = await _brandService.GetBrand(id); |
| | 0 | 95 | | if(brand == null) |
| | 0 | 96 | | { |
| | 0 | 97 | | return NotFoundResult("Бренд не найден"); |
| | | 98 | | } |
| | | 99 | | else |
| | 0 | 100 | | { |
| | 0 | 101 | | long[] itemIds = { brand.Id}; |
| | | 102 | | |
| | 0 | 103 | | var parentsId = await _brandService.CheckParentIds(itemIds); |
| | 0 | 104 | | var result = new BrandOutputDTO(brand) |
| | 0 | 105 | | { |
| | 0 | 106 | | Expandable = parentsId.Count != 0 && parentsId.Contains(brand.Id) |
| | 0 | 107 | | }; |
| | 0 | 108 | | return Ok(result); |
| | | 109 | | } |
| | 0 | 110 | | } |
| | | 111 | | |
| | | 112 | | /// <summary> |
| | | 113 | | /// Создает новый бренд |
| | | 114 | | /// </summary> |
| | | 115 | | /// <remarks>author: nko</remarks> |
| | | 116 | | /// <param name="brand">Объект с полями брэнда</param> |
| | | 117 | | /// <returns></returns> |
| | | 118 | | [HttpPost("")] |
| | | 119 | | [SwaggerResponse(200, "Успешно", typeof(BrandOutputDTO))] |
| | | 120 | | [SwaggerResponse(400, "Переданы некорректные параметры", typeof(ErrorDTO))] |
| | | 121 | | [SwaggerResponse(404, "Нет записей", typeof(ErrorDTO))] |
| | | 122 | | [SwaggerResponse(500, "Ошибка на стороне сервера", typeof(ErrorDTO))] |
| | | 123 | | [Authorize(Roles = Role.SystemAdmin)] |
| | | 124 | | public async Task<IActionResult> CreateBrand([FromBody] [SwaggerParameter(Required = true)]BrandInputDTO brand) |
| | 0 | 125 | | { |
| | 0 | 126 | | Brand newBrand = new Brand(); |
| | 0 | 127 | | newBrand.GUID = newBrand.GUID == Guid.Empty ? Guid.NewGuid() : newBrand.GUID; |
| | 0 | 128 | | newBrand.Name = brand.Name; |
| | 0 | 129 | | if (brand.ParentId > 0) |
| | 0 | 130 | | { |
| | 0 | 131 | | newBrand.Parent = await _brandService.GetBrand(brand.ParentId); |
| | 0 | 132 | | if(newBrand.Parent == null) |
| | 0 | 133 | | { |
| | 0 | 134 | | return NotFoundResult($"Родительский брэнд #{brand.ParentId} не найден"); |
| | | 135 | | } |
| | 0 | 136 | | } |
| | 0 | 137 | | await _brandService.CreateBrand(newBrand); |
| | | 138 | | |
| | 0 | 139 | | return CreatedAtAction("GetBrand", new { id = newBrand.Id }, newBrand); |
| | 0 | 140 | | } |
| | | 141 | | |
| | | 142 | | /// <summary> |
| | | 143 | | /// Обновляет существующий бренд |
| | | 144 | | /// </summary> |
| | | 145 | | /// <remarks>author: nko</remarks> |
| | | 146 | | /// <param name="brand">Объект с полями брэнда</param> |
| | | 147 | | /// <param name="id">Id объекта для обновления</param> |
| | | 148 | | /// <returns></returns> |
| | | 149 | | [HttpPut("{id}")] |
| | | 150 | | [SwaggerResponse(200, "Успешно", typeof(BrandOutputDTO))] |
| | | 151 | | [SwaggerResponse(400, "Переданы некорректные параметры", typeof(ErrorDTO))] |
| | | 152 | | [SwaggerResponse(404, "Нет записей", typeof(ErrorDTO))] |
| | | 153 | | [SwaggerResponse(500, "Ошибка на стороне сервера", typeof(ErrorDTO))] |
| | | 154 | | [Authorize(Roles = Role.SystemAdmin)] |
| | | 155 | | public async Task<IActionResult> UpdateBrand([SwaggerParameter(Required = true)] long id, [FromBody] [SwaggerPar |
| | 0 | 156 | | { |
| | 0 | 157 | | Brand editedBrand = await _brandService.GetBrand(id); |
| | 0 | 158 | | if(editedBrand == null) |
| | 0 | 159 | | { |
| | 0 | 160 | | return NotFoundResult("Бренд не найден"); |
| | | 161 | | } |
| | 0 | 162 | | editedBrand.Name = brand.Name; |
| | 0 | 163 | | if (brand.ParentId > 0) |
| | 0 | 164 | | { |
| | 0 | 165 | | var isCollisium = await _brandService.CheckCollision(editedBrand.Id, brand.ParentId); |
| | 0 | 166 | | if (editedBrand.Id == brand.ParentId || isCollisium) //TODO переделать проверку |
| | 0 | 167 | | return BadRequestResult("Дочерний и родительский брэнд не могут ссылаться друг на друга"); |
| | | 168 | | |
| | 0 | 169 | | editedBrand.Parent = await _brandService.GetBrand(brand.ParentId); |
| | 0 | 170 | | if (editedBrand.Parent == null) |
| | 0 | 171 | | { |
| | 0 | 172 | | return NotFoundResult($"Родительский брэнд не найден"); |
| | | 173 | | } |
| | 0 | 174 | | } |
| | 0 | 175 | | await _brandService.UpdateBrand(editedBrand); |
| | | 176 | | |
| | 0 | 177 | | return CreatedAtAction("GetBrand", new { id = editedBrand.Id }, new BrandOutputDTO(editedBrand)); |
| | 0 | 178 | | } |
| | | 179 | | |
| | | 180 | | /// <summary> |
| | | 181 | | /// Удаляет запись Бренд |
| | | 182 | | /// </summary> |
| | | 183 | | /// <remarks>author: nko</remarks> |
| | | 184 | | /// <param name="id">ID записи</param> |
| | | 185 | | /// <returns></returns> |
| | | 186 | | [HttpDelete("{id}")] |
| | | 187 | | [SwaggerResponse(200, "Успешно", typeof(OkResult))] |
| | | 188 | | [SwaggerResponse(400, "Переданы некорректные параметры", typeof(ErrorDTO))] |
| | | 189 | | [SwaggerResponse(404, "Нет записей", typeof(ErrorDTO))] |
| | | 190 | | [SwaggerResponse(500, "Ошибка на стороне сервера", typeof(ErrorDTO))] |
| | | 191 | | [Authorize(Roles = Role.SystemAdmin)] |
| | | 192 | | public async Task<IActionResult> DeleteBrand([SwaggerParameter(Required = true)]long id) |
| | 0 | 193 | | { |
| | 0 | 194 | | if (await _brandService.BrandExists(id) == false) |
| | 0 | 195 | | { |
| | 0 | 196 | | return NotFoundResult("Бренд не найден"); |
| | | 197 | | } |
| | | 198 | | |
| | 0 | 199 | | if(await _brandService.GetBrandsCount(null, id) > 0) |
| | 0 | 200 | | { |
| | 0 | 201 | | return BadRequestResult($"Брэнд #{id} имеет дочерние брэнды и не может быть удалён"); |
| | | 202 | | } |
| | | 203 | | |
| | 0 | 204 | | await _brandService.DeleteBrand(id); |
| | 0 | 205 | | return Ok(); |
| | 0 | 206 | | } |
| | | 207 | | } |
| | | 208 | | } |