| | | 1 | | using AutoMapper; |
| | | 2 | | using SkiaSharp; |
| | | 3 | | using Microsoft.AspNetCore.Http; |
| | | 4 | | using Microsoft.AspNetCore.Mvc; |
| | | 5 | | using Microsoft.EntityFrameworkCore; |
| | | 6 | | using Microsoft.Extensions.Logging; |
| | | 7 | | using Microsoft.Extensions.Options; |
| | | 8 | | using SVETA.Api.Data.Domain; |
| | | 9 | | using SVETA.Api.Data.DTO; |
| | | 10 | | using SVETA.Api.Data.DTO.Goods; |
| | | 11 | | using SVETA.Api.Helpers; |
| | | 12 | | using Swashbuckle.AspNetCore.Annotations; |
| | | 13 | | using System; |
| | | 14 | | using System.Collections.Generic; |
| | | 15 | | using System.IO; |
| | | 16 | | using System.Linq; |
| | | 17 | | using System.Text; |
| | | 18 | | using System.Threading.Tasks; |
| | | 19 | | using WinSolutions.Sveta.Server.Data.DataModel.Entities; |
| | | 20 | | using WinSolutions.Sveta.Server.Data.DataModel.Kinds; |
| | | 21 | | using WinSolutions.Sveta.Server.Services.Interfaces; |
| | | 22 | | using Microsoft.AspNetCore.Authorization; |
| | | 23 | | using Microsoft.EntityFrameworkCore.Internal; |
| | | 24 | | using WinSolutions.Sveta.Common.Extensions; |
| | | 25 | | using WinSolutions.Sveta.Common; |
| | | 26 | | using SVETA.Api.Services.Interfaces; |
| | | 27 | | using WinSolutions.Sveta.Server.Data.DataModel.Extensions; |
| | | 28 | | using Department = DocumentFormat.OpenXml.Bibliography.Department; |
| | | 29 | | |
| | | 30 | | namespace SVETA.Api.Controllers |
| | | 31 | | { |
| | | 32 | | /// <summary> |
| | | 33 | | /// Controller goods |
| | | 34 | | /// </summary> |
| | | 35 | | /// [SwaggerOperation(Tags = new[] { "Management Reports" })] |
| | | 36 | | [Route("api/v1/Goods")] |
| | | 37 | | [ApiController] |
| | | 38 | | [Authorize] |
| | | 39 | | public partial class GoodsController : SvetaController |
| | | 40 | | { |
| | | 41 | | const string _routeUrl = "api/v1/Goods"; |
| | | 42 | | readonly IGoodService _service; |
| | | 43 | | readonly IContragentService _contragentService; |
| | | 44 | | readonly ICategoryService _categoryService; |
| | | 45 | | readonly IBrandService _brandService; |
| | | 46 | | readonly IDirectoriesService _dirService; |
| | | 47 | | readonly ICountryService _countryService; |
| | | 48 | | readonly ILogger<GoodsController> _logger; |
| | | 49 | | readonly ImagesSettings _imagesSettings; |
| | | 50 | | readonly ConfigurationsSettings _confSettings; |
| | | 51 | | readonly IBarcodeService _barcodeService; |
| | | 52 | | readonly IDownloadGoodsImagesWorker _downloadGoodsImagesWorker; |
| | | 53 | | IDiskStorageService _diskStorage; |
| | | 54 | | const int searchLimit = 12; |
| | | 55 | | |
| | | 56 | | public GoodsController(IGoodService service, |
| | | 57 | | IContragentService contragentService, |
| | | 58 | | ICategoryService categoryService, |
| | | 59 | | IBrandService brandService, |
| | | 60 | | IDirectoriesService dirService, |
| | | 61 | | ICountryService countryService, |
| | | 62 | | IBarcodeService barcodeService, |
| | | 63 | | IDiskStorageService diskStorage, |
| | | 64 | | IOptions<ImagesSettings> imagesSettings, |
| | | 65 | | IOptions<ConfigurationsSettings> confSettings, |
| | | 66 | | IDownloadGoodsImagesWorker downloadGoodsImagesWorker, |
| | 0 | 67 | | ILogger<GoodsController> logger) : base(logger) |
| | 0 | 68 | | { |
| | 0 | 69 | | _service = service; |
| | 0 | 70 | | _logger = logger; |
| | 0 | 71 | | _dirService = dirService; |
| | 0 | 72 | | _confSettings = confSettings.Value; |
| | 0 | 73 | | _contragentService = contragentService; |
| | 0 | 74 | | _categoryService = categoryService; |
| | 0 | 75 | | _brandService = brandService; |
| | 0 | 76 | | _countryService = countryService; |
| | 0 | 77 | | _barcodeService = barcodeService; |
| | 0 | 78 | | _imagesSettings = imagesSettings.Value; |
| | 0 | 79 | | _diskStorage = diskStorage; |
| | 0 | 80 | | _downloadGoodsImagesWorker = downloadGoodsImagesWorker; |
| | 0 | 81 | | } |
| | | 82 | | |
| | | 83 | | |
| | | 84 | | /// <summary> |
| | | 85 | | /// Возвращает только активные товары из категории |
| | | 86 | | /// </summary> |
| | | 87 | | /// <param name="id">код категории, 0 если возвращать товары из всех категорий</param> |
| | | 88 | | /// <param name="page">Любое значение ниже нуля изменится на 1, пейджинг: номер страницы</param> |
| | | 89 | | /// <param name="limit">Любое значение ниже нуля изменится на 10, пейджинг: размер страницы</param> |
| | | 90 | | /// <param name="filter">фильтр по значимым полям (Name, Barcode)</param> |
| | | 91 | | /// <param name="sort">сортировка по полям name,name|desc, brandName,brandName|desc, По умолчанию по id</param> |
| | | 92 | | /// <remarks>author: oboligatov\aabelentsov</remarks> |
| | | 93 | | [HttpGet("Active/FromCategory/{id}")] |
| | | 94 | | [SwaggerResponse(200, "Успешно", typeof(BaseResponseDTO<GoodCatalogDTO>))] |
| | | 95 | | [SwaggerResponse(500, "Ошибка на стороне сервера", typeof(ErrorDTO))] |
| | | 96 | | [Authorize(Roles = Role.SystemAdmin+"," + Role.SystemOperator)] |
| | | 97 | | public async Task<IActionResult> GetActiveGoodsFromCategory(long id, int page = 1, int limit = 10, string filter |
| | 0 | 98 | | { |
| | 0 | 99 | | filter = filter.NormalizeName(); |
| | 0 | 100 | | page = page < 1 ? 1 : page; |
| | 0 | 101 | | limit = limit < 1 ? 10 : limit; |
| | 0 | 102 | | var goods = await _service.GetGoods(page - 1, limit, filter, sort, id != 0 ? id : (long?)null, true); |
| | 0 | 103 | | goods.ForEach(g => g.Photos.SetPhotoUrl(_imagesSettings)); |
| | | 104 | | |
| | | 105 | | |
| | 0 | 106 | | var totalCount = await _service.GetGoodsCount(null, (long?)null, true); |
| | 0 | 107 | | var totalFiltredCount = await _service.GetGoodsCount(filter, id != 0 ? id : (long?)null, true); |
| | | 108 | | |
| | 0 | 109 | | var response = new BaseResponseDTO<GoodCatalogDTO>(_routeUrl, page, limit, totalFiltredCount, totalCount, so |
| | 0 | 110 | | { |
| | 0 | 111 | | Data = ToCatalogGoodDtoMapper().Map<List<GoodCatalogDTO>>(goods) |
| | 0 | 112 | | }; |
| | 0 | 113 | | return Ok(response); |
| | 0 | 114 | | } |
| | | 115 | | |
| | | 116 | | /// <summary> |
| | | 117 | | /// Возвращает количество только активных товаров из категории |
| | | 118 | | /// </summary> |
| | | 119 | | /// <param name="id">код категории, 0 если возвращать товары из всех категорий</param> |
| | | 120 | | /// <param name="filter">фильтр по значимым полям (Name, Barcode)</param> |
| | | 121 | | /// <remarks>author: oboligatov</remarks> |
| | | 122 | | [HttpGet("Active/FromCategory/{id}/Count")] |
| | | 123 | | [SwaggerResponse(200, "Успешно", typeof(CountDTO))] |
| | | 124 | | [SwaggerResponse(500, "Ошибка на стороне сервера", typeof(ErrorDTO))] |
| | | 125 | | [Authorize(Roles = Role.SystemAdmin+"," + Role.SystemOperator)] |
| | | 126 | | public async Task<IActionResult> GetActiveGoodsFromCategoryCount(long id, string filter = null) |
| | 0 | 127 | | { |
| | 0 | 128 | | filter = filter.NormalizeName(); |
| | 0 | 129 | | return Ok(new CountDTO(await _service.GetGoodsCount(filter, id != 0 ? id : (long?)null, true))); |
| | 0 | 130 | | } |
| | | 131 | | |
| | | 132 | | /// <summary> |
| | | 133 | | /// Возвращает все (активные + неактивные) товары из категории |
| | | 134 | | /// </summary> |
| | | 135 | | /// <param name="id">код категории, 0 если возвращать товары из всех категорий</param> |
| | | 136 | | /// <param name="page">Любое значение ниже нуля изменится на 1, пейджинг: номер страницы</param> |
| | | 137 | | /// <param name="limit">Любое значение ниже нуля изменится на 10, пейджинг: размер страницы</param> |
| | | 138 | | /// <param name="filter">фильтр по значимым полям (Name, Barcode)</param> |
| | | 139 | | /// <param name="sort">сортировка по полям name,name|desc, brandName,brandName|desc, По умолчанию по id</param> |
| | | 140 | | /// <remarks>author: oboligatov</remarks> |
| | | 141 | | [HttpGet("FromCategory/{id}")] |
| | | 142 | | [SwaggerResponse(200, "Успешно", typeof(BaseResponseDTO<GoodCatalogDTO>))] |
| | | 143 | | [SwaggerResponse(500, "Ошибка на стороне сервера", typeof(ErrorDTO))] |
| | | 144 | | [Authorize(Roles = Role.SystemAdmin+"," + Role.SystemOperator)] |
| | | 145 | | public async Task<IActionResult> GetAllGoodsFromCategory(long id, int page = 1, int limit = 10, string filter = |
| | 0 | 146 | | { |
| | 0 | 147 | | filter = filter.NormalizeName(); |
| | 0 | 148 | | page = page < 1 ? 1 : page; |
| | 0 | 149 | | limit = limit < 1 ? 10 : limit; |
| | 0 | 150 | | var goods = await _service.GetGoods(page - 1, limit, filter, sort, id != 0 ? id : (long?)null, false); |
| | 0 | 151 | | goods.ForEach(g => g.Photos.SetPhotoUrl(_imagesSettings)); |
| | | 152 | | |
| | 0 | 153 | | var totalCount = await _service.GetGoodsCount(null, null, false); |
| | 0 | 154 | | var totalFiltredCount = await _service.GetGoodsCount(filter, id != 0 ? id : (long?)null, false); |
| | | 155 | | |
| | 0 | 156 | | var response = new BaseResponseDTO<GoodCatalogDTO>(_routeUrl, page, limit, totalFiltredCount, totalCount, so |
| | 0 | 157 | | { |
| | 0 | 158 | | Data = ToCatalogGoodDtoMapper().Map<List<GoodCatalogDTO>>(goods) |
| | 0 | 159 | | }; |
| | 0 | 160 | | return Ok(response); |
| | 0 | 161 | | } |
| | | 162 | | |
| | | 163 | | /// <summary> |
| | | 164 | | /// Возвращает количество всех (активные + неактивные) товаров из категории |
| | | 165 | | /// </summary> |
| | | 166 | | /// <param name="id">код категории, 0 если возвращать товары из всех категорий</param> |
| | | 167 | | /// <param name="filter">фильтр по значимым полям (Name, Barcode)</param> |
| | | 168 | | /// <remarks>author: oboligatov</remarks> |
| | | 169 | | [HttpGet("FromCategory/{id}/Count")] |
| | | 170 | | [SwaggerResponse(200, "Успешно", typeof(CountDTO))] |
| | | 171 | | [SwaggerResponse(500, "Ошибка на стороне сервера", typeof(ErrorDTO))] |
| | | 172 | | [Authorize(Roles = Role.SystemAdmin+"," + Role.SystemOperator)] |
| | | 173 | | public async Task<IActionResult> GetAllGoodsFromCategoryCount(long id, string filter = null) |
| | 0 | 174 | | { |
| | 0 | 175 | | filter = filter.NormalizeName(); |
| | 0 | 176 | | return Ok(new CountDTO(await _service.GetGoodsCount(filter, id != 0 ? id : (long?)null, false))); |
| | 0 | 177 | | } |
| | | 178 | | |
| | | 179 | | /// <summary> |
| | | 180 | | /// Возвращает группы, расположенные над товаром |
| | | 181 | | /// </summary> |
| | | 182 | | /// <remarks>author: oboligatov</remarks> |
| | | 183 | | /// <param name="id">Id товара</param> |
| | | 184 | | [HttpGet("{id}/ParentCategories")] |
| | | 185 | | [SwaggerResponse(200, "Успешно", typeof(IEnumerable<CategoryResponseDTO>))] |
| | | 186 | | [SwaggerResponse(404, "Нет записей", typeof(ErrorDTO))] |
| | | 187 | | [SwaggerResponse(500, "Ошибка на стороне сервера", typeof(ErrorDTO))] |
| | | 188 | | [Authorize(Roles = Role.SystemAdmin+"," + Role.SystemOperator)] |
| | | 189 | | public async Task<IActionResult> GetCategoriesParent(long id) |
| | 0 | 190 | | { |
| | 0 | 191 | | var good = await _service.GetGood(id); |
| | 0 | 192 | | if (good == null) |
| | 0 | 193 | | { |
| | 0 | 194 | | return NotFoundResult(); |
| | | 195 | | } |
| | | 196 | | |
| | 0 | 197 | | List<CategoryResponseDTO> categories = new List<CategoryResponseDTO>(); |
| | 0 | 198 | | var category = await _categoryService.GetNoTrackCategory(good.Category.Id); |
| | | 199 | | |
| | 0 | 200 | | var config = new MapperConfiguration(cfg => |
| | | 201 | | { |
| | | 202 | | cfg.CreateMap<Category, CategoryResponseDTO>() |
| | | 203 | | .ForMember(d => d.ParentId, e => e.MapFrom(s => s.Parent != null ? s.Parent.Id : 0)); |
| | | 204 | | }); |
| | 0 | 205 | | IMapper mapper = config.CreateMapper(); |
| | | 206 | | |
| | 0 | 207 | | while (category != null) |
| | 0 | 208 | | { |
| | 0 | 209 | | CategoryResponseDTO categoryDto = mapper.Map<Category, CategoryResponseDTO>(category); |
| | 0 | 210 | | categories.Add(categoryDto); |
| | 0 | 211 | | category = category.Parent != null ? await _categoryService.GetCategory(category.Parent.Id) : null; |
| | 0 | 212 | | } |
| | | 213 | | |
| | 0 | 214 | | return Ok(categories); |
| | 0 | 215 | | } |
| | | 216 | | |
| | | 217 | | /// <summary> |
| | | 218 | | /// Возвращает товар |
| | | 219 | | /// </summary> |
| | | 220 | | /// <remarks>author: oboligatov</remarks> |
| | | 221 | | /// <param name="id">код товара</param> |
| | | 222 | | [HttpGet("{id}")] |
| | | 223 | | [SwaggerResponse(200, "Успешно", typeof(GoodDTO))] |
| | | 224 | | [SwaggerResponse(404, "Нет записей", typeof(ErrorDTO))] |
| | | 225 | | [SwaggerResponse(500, "Ошибка на стороне сервера", typeof(ErrorDTO))] |
| | | 226 | | [Authorize(Roles = Role.SystemAdmin +"," + Role.SystemOperator)] |
| | | 227 | | public async Task<IActionResult> GetGood(long id) |
| | 0 | 228 | | { |
| | 0 | 229 | | var good = await _service.GetGood(id); |
| | 0 | 230 | | if (good == null) |
| | 0 | 231 | | { |
| | 0 | 232 | | return NotFoundResult(); |
| | | 233 | | } |
| | | 234 | | |
| | 0 | 235 | | good.Photos.SetPhotoUrl(_imagesSettings); |
| | | 236 | | |
| | 0 | 237 | | return Ok(ToGoodDtoMapper().Map<Good, GoodDTO>(good)); |
| | 0 | 238 | | } |
| | | 239 | | |
| | | 240 | | /// <summary> |
| | | 241 | | /// Загружает картинку для товара |
| | | 242 | | /// </summary> |
| | | 243 | | /// <remarks>author: oboligatov</remarks> |
| | | 244 | | /// <param name="id">Id товара</param> |
| | | 245 | | /// <param name="file">картинка</param> |
| | | 246 | | /// <returns></returns> |
| | | 247 | | [HttpPost("{id}/Image")] |
| | | 248 | | [SwaggerResponse(200, "Успешно", typeof(EmptyResult))] |
| | | 249 | | [SwaggerResponse(404, "Нет записей", typeof(ErrorDTO))] |
| | | 250 | | [SwaggerResponse(500, "Ошибка на стороне сервера", typeof(ErrorDTO))] |
| | | 251 | | [Authorize(Roles = Role.SystemAdmin)] |
| | | 252 | | public async Task<IActionResult> UploadGoodImage(long id, IFormFile file) |
| | 0 | 253 | | { |
| | 0 | 254 | | int prevWidth = _imagesSettings.ImagePreveiwWidth, prevHeight = _imagesSettings.ImagePreveiwHeight; |
| | | 255 | | int fullWidth, fullHeight, newPrevWidth, newPrevHeight; |
| | 0 | 256 | | Good good = await _service.GetGood(id); |
| | | 257 | | |
| | 0 | 258 | | if (good == null) |
| | 0 | 259 | | throw new ArgumentException($"Товар #{id} не найден"); |
| | | 260 | | |
| | 0 | 261 | | if (file == null || file?.Length == 0) |
| | 0 | 262 | | throw new ArgumentException("Изображение не выбрано"); |
| | | 263 | | |
| | 0 | 264 | | string[] extensions = _confSettings.GetConfValue("ImageSettings", "AllowedExtensions").Split(","); |
| | 0 | 265 | | string fileExtension = Path.GetExtension(file.FileName.ToLower()); |
| | 0 | 266 | | if (!extensions.Contains(fileExtension)) |
| | 0 | 267 | | throw new ArgumentException($"Расширение файла {fileExtension} не поддерживается"); |
| | | 268 | | |
| | 0 | 269 | | string fileNameFull = Transliteration.Translit(good.Name.ToLowerInvariant()) + "_" + DateTime.Now.Ticks.ToSt |
| | 0 | 270 | | string fileNamePrev = Transliteration.Translit(good.Name.ToLowerInvariant()) + "_" + DateTime.Now.Ticks.ToSt |
| | 0 | 271 | | string filePathFull = Path.Combine(_imagesSettings.ImageSavePath, fileNameFull); |
| | 0 | 272 | | string filePathPrev = Path.Combine(_imagesSettings.ImageSavePath, fileNamePrev); |
| | 0 | 273 | | System.Drawing.Image fullImage = System.Drawing.Image.FromStream(file.OpenReadStream()); |
| | 0 | 274 | | fullWidth = fullImage.Width; |
| | 0 | 275 | | fullHeight = fullImage.Height; |
| | 0 | 276 | | using (var stream = new FileStream(filePathFull, FileMode.Create)) |
| | 0 | 277 | | { |
| | 0 | 278 | | await file.CopyToAsync(stream); |
| | 0 | 279 | | } |
| | 0 | 280 | | if (fullWidth > fullHeight) //сохраняем пропорции |
| | 0 | 281 | | { |
| | 0 | 282 | | newPrevWidth = prevWidth; |
| | 0 | 283 | | newPrevHeight = fullHeight * prevWidth / fullWidth; |
| | 0 | 284 | | } |
| | | 285 | | else |
| | 0 | 286 | | { |
| | 0 | 287 | | newPrevWidth = fullWidth * prevHeight / fullHeight; |
| | 0 | 288 | | newPrevHeight = prevHeight; |
| | 0 | 289 | | } |
| | 0 | 290 | | using (var stream = System.IO.File.OpenRead(filePathFull)) |
| | 0 | 291 | | using (var inputStream = new SKManagedStream(stream)) |
| | 0 | 292 | | using (var original = SKBitmap.Decode(inputStream)) |
| | 0 | 293 | | { |
| | 0 | 294 | | using (var resized = original.Resize(new SKImageInfo(newPrevWidth, newPrevHeight), SKFilterQuality.Mediu |
| | 0 | 295 | | using (var image = SKImage.FromBitmap(resized)) |
| | 0 | 296 | | using (var output = System.IO.File.OpenWrite(filePathPrev)) |
| | 0 | 297 | | image.Encode(SKEncodedImageFormat.Jpeg, 75).SaveTo(output); |
| | 0 | 298 | | } |
| | 0 | 299 | | var photo = new Photo |
| | 0 | 300 | | { |
| | 0 | 301 | | FullSizeUrl = fileNameFull, |
| | 0 | 302 | | PreviewUrl = fileNamePrev, |
| | 0 | 303 | | PreviewHeight = newPrevHeight, |
| | 0 | 304 | | PreviewWidth = newPrevWidth, |
| | 0 | 305 | | FullSizeHeight = fullHeight, |
| | 0 | 306 | | FullSizeWidth = fullWidth |
| | 0 | 307 | | }; |
| | 0 | 308 | | if (good.Photos.Count == 0) |
| | 0 | 309 | | good.Photos.Add(photo); |
| | | 310 | | else |
| | 0 | 311 | | good.Photos[0] = photo; |
| | 0 | 312 | | await _service.SetPhoto(good, good.Photos); |
| | | 313 | | |
| | 0 | 314 | | return Ok(); |
| | 0 | 315 | | } |
| | | 316 | | |
| | | 317 | | /// <summary> |
| | | 318 | | /// Обновляет поля товара |
| | | 319 | | /// </summary> |
| | | 320 | | /// <remarks>author: oboligatov</remarks> |
| | | 321 | | /// <param name="id">Id товара</param> |
| | | 322 | | /// <param name="goodDto"></param> |
| | | 323 | | [HttpPut("{id}")] |
| | | 324 | | [SwaggerResponse(200, "Успешно", typeof(GoodDTO))] |
| | | 325 | | [SwaggerResponse(400, "Неверные входные параметры", typeof(ErrorDTO))] |
| | | 326 | | [SwaggerResponse(404, "Нет записей", typeof(ErrorDTO))] |
| | | 327 | | [SwaggerResponse(500, "Ошибка на стороне сервера", typeof(ErrorDTO))] |
| | | 328 | | [Authorize(Roles = Role.SystemAdmin)] |
| | | 329 | | public async Task<IActionResult> UpdateGood(long id, [FromBody] [SwaggerParameter(Required = true)] GoodInputDTO |
| | 0 | 330 | | { |
| | 0 | 331 | | var good = await _service.GetGood(id); |
| | 0 | 332 | | if (good == null) |
| | 0 | 333 | | { |
| | 0 | 334 | | return NotFoundResult($"Good #{id} not found"); |
| | | 335 | | } |
| | | 336 | | |
| | 0 | 337 | | await PrepareGood(goodDto, good); |
| | 0 | 338 | | await _service.UpdateGood(good); |
| | | 339 | | |
| | 0 | 340 | | return Ok(ToGoodDtoMapper().Map<GoodDTO>(good)); |
| | 0 | 341 | | } |
| | | 342 | | |
| | | 343 | | /// <summary> |
| | | 344 | | /// Создает товар |
| | | 345 | | /// </summary> |
| | | 346 | | /// <remarks>author: oboligatov</remarks> |
| | | 347 | | [HttpPost()] |
| | | 348 | | [SwaggerResponse(200, "Успешно", typeof(GoodDTO))] |
| | | 349 | | [SwaggerResponse(400, "Неверные входные параметры", typeof(ErrorDTO))] |
| | | 350 | | [SwaggerResponse(404, "Нет записей", typeof(ErrorDTO))] |
| | | 351 | | [SwaggerResponse(500, "Ошибка на стороне сервера", typeof(ErrorDTO))] |
| | | 352 | | [Authorize(Roles = Role.SystemAdmin)] |
| | | 353 | | public async Task<IActionResult> CreateGood([FromBody] [SwaggerParameter(Required = true)] GoodInputDTO goodDto) |
| | 0 | 354 | | { |
| | 0 | 355 | | var good = new Good(); |
| | 0 | 356 | | await PrepareGood(goodDto, good); |
| | 0 | 357 | | await _service.CreateGood(good); |
| | | 358 | | |
| | 0 | 359 | | return Ok(ToGoodDtoMapper().Map<GoodDTO>(good)); |
| | 0 | 360 | | } |
| | | 361 | | |
| | | 362 | | /// <summary> |
| | | 363 | | /// Удалить товар |
| | | 364 | | /// </summary> |
| | | 365 | | /// <remarks>author: oboligatov</remarks> |
| | | 366 | | /// <param name="id">Id товара</param> |
| | | 367 | | [HttpDelete("{id}")] |
| | | 368 | | [SwaggerResponse(200, "Успешно", typeof(EmptyResult))] |
| | | 369 | | [SwaggerResponse(404, "Нет записей", typeof(ErrorDTO))] |
| | | 370 | | [SwaggerResponse(500, "Ошибка на стороне сервера", typeof(ErrorDTO))] |
| | | 371 | | [Authorize(Roles = Role.SystemAdmin)] |
| | | 372 | | public async Task<IActionResult> DeleteGood(long id) |
| | 0 | 373 | | { |
| | 0 | 374 | | await _service.DeleteGood(id); |
| | 0 | 375 | | return Ok(); |
| | 0 | 376 | | } |
| | | 377 | | |
| | | 378 | | /// <summary> |
| | | 379 | | /// Удалить все фотографии у товара |
| | | 380 | | /// </summary> |
| | | 381 | | /// <param name="goodId">идентификатор товара</param> |
| | | 382 | | /// <returns></returns> |
| | | 383 | | [HttpPost("{goodId}/DeleteImages")] |
| | | 384 | | [SwaggerResponse(200, "Успешно", typeof(EmptyResult))] |
| | | 385 | | [SwaggerResponse(400, "Ошибка входных данных", typeof(ErrorDTO))] |
| | | 386 | | [SwaggerResponse(500, "Ошибка на стороне сервера", typeof(ErrorDTO))] |
| | | 387 | | [Authorize(Roles = Role.SystemAdmin)] |
| | | 388 | | public async Task<IActionResult> DeleteImages(long goodId) |
| | 0 | 389 | | { |
| | 0 | 390 | | var good = await _service.GetGood(goodId) ?? |
| | 0 | 391 | | throw new ArgumentException($"Товар #{goodId} не найден"); |
| | 0 | 392 | | good.Photos.RemoveRange(0, good.Photos.Count); |
| | 0 | 393 | | await _service.UpdateGood(good); |
| | 0 | 394 | | return Ok(); |
| | 0 | 395 | | } |
| | | 396 | | |
| | | 397 | | /// <summary> |
| | | 398 | | /// Создает задачу на выгрузку картинок для товаров |
| | | 399 | | /// </summary> |
| | | 400 | | /// <param name="activeOnly">возвращать картинки только для активных товаров</param> |
| | | 401 | | /// <remarks> значения возвращаемого статуса: 0 - Нет активных скачиваний, 1 - В очереди, 2 - Выгружается, 3 - З |
| | | 402 | | [HttpPost("DownloadGoodsImages")] |
| | | 403 | | [SwaggerResponse(200, "Успешно", typeof(DownloadGoodsImagesStatusDTO))] |
| | | 404 | | [SwaggerResponse(500, "Ошибка на стороне сервера", typeof(ErrorDTO))] |
| | | 405 | | public async Task<IActionResult> StartDownloadingGoodsImages(bool activeOnly = true) |
| | 0 | 406 | | { |
| | 0 | 407 | | return Ok(await _downloadGoodsImagesWorker.StartDownload(activeOnly)); |
| | 0 | 408 | | } |
| | | 409 | | |
| | | 410 | | /// <summary> |
| | | 411 | | /// Возвращает статус активного скачивания |
| | | 412 | | /// </summary> |
| | | 413 | | /// <remarks> значения возвращаемого статуса: 0 - Нет активных скачиваний, 1 - В очереди, 2 - Выгружается, 3 - З |
| | | 414 | | [HttpGet("DownloadGoodsImages/Status")] |
| | | 415 | | [SwaggerResponse(200, "Успешно", typeof(DownloadGoodsImagesStatusDTO))] |
| | | 416 | | [SwaggerResponse(500, "Ошибка на стороне сервера", typeof(ErrorDTO))] |
| | | 417 | | public async Task<IActionResult> GetDownloadingGoodsImagesStatus() |
| | 0 | 418 | | { |
| | 0 | 419 | | return Ok(await _downloadGoodsImagesWorker.GetDownloadStatus()); |
| | 0 | 420 | | } |
| | | 421 | | |
| | | 422 | | /// <summary> |
| | | 423 | | /// Выгрузка номенклатуры в excel |
| | | 424 | | /// </summary> |
| | | 425 | | /// <param name="activeOnly">выгружать только активные товары (иначе все)</param> |
| | | 426 | | /// <returns></returns> |
| | | 427 | | [HttpGet("DownloadGoods")] |
| | | 428 | | [SwaggerResponse(200, "Успешно", typeof(File))] |
| | | 429 | | [SwaggerResponse(500, "Ошибка на стороне сервера", typeof(ErrorDTO))] |
| | | 430 | | [Authorize(Roles = Role.SystemAdmin + "," + Role.SystemOperator)] |
| | | 431 | | public async Task<IActionResult> DownloadGoods(bool activeOnly = true) |
| | 0 | 432 | | { |
| | 0 | 433 | | var goods = await _service.GetGoods(0, int.MaxValue, null, null, (long?)null, activeOnly); |
| | | 434 | | |
| | 0 | 435 | | var rows = new List<string[]>(); |
| | 0 | 436 | | rows.Add(new string[] |
| | 0 | 437 | | { |
| | 0 | 438 | | "BarCode", "Name", "ManufacturerName", "ExpirationDays", "Weight", |
| | 0 | 439 | | "Width", "Height", "Thickness", "ParentCategoryName", "CategoryCode", "CategoryName", |
| | 0 | 440 | | "VatName", "CustomDeclarationNumber", "UnitName", "CountryName", "ConformityCertNumber", |
| | 0 | 441 | | "GroupPackNesting", "GroupPackWidth", "GroupPackHeight", "GroupPackThickness", "PalletNesting", |
| | 0 | 442 | | "BrandName", "SubbrandName", "LargeImageFileName", "SmallImageFileName", "LargeImageFileExists", "SmallI |
| | 0 | 443 | | "UniqueCode", "IsActive" |
| | 0 | 444 | | }); |
| | | 445 | | |
| | 0 | 446 | | goods.ForEach(x => |
| | 0 | 447 | | { |
| | 0 | 448 | | rows.Add(new string[] |
| | 0 | 449 | | { |
| | | 450 | | x.GoodBarcodes.FirstOrDefault(d => d.IsPrimary) != null |
| | | 451 | | ? x.GoodBarcodes.FirstOrDefault(d => d.IsPrimary).BarCode.Code |
| | 0 | 452 | | : x.DefaultBarCode?.Code, |
| | 0 | 453 | | x.Name, |
| | 0 | 454 | | "Производитель не указан", |
| | 0 | 455 | | x.ExpirationDays.ToString(), |
| | 0 | 456 | | x.Weight.ToString(), |
| | 0 | 457 | | x.Width.ToString(), |
| | 0 | 458 | | x.Height.ToString(), |
| | 0 | 459 | | x.Thickness.ToString(), |
| | 0 | 460 | | x.Category.Parent?.Name, |
| | 0 | 461 | | x.Category.Code, |
| | 0 | 462 | | x.Category.Name, |
| | 0 | 463 | | x.VatsKind.Code, |
| | 0 | 464 | | x.CustomDeclarationNumber, |
| | 0 | 465 | | x.UnitsKind.Name, |
| | 0 | 466 | | x.Country.Name, |
| | 0 | 467 | | x.ConformityCertNumber, |
| | 0 | 468 | | x.GroupPackNesting.ToString(), |
| | 0 | 469 | | x.GroupPackWidth.ToString(), |
| | 0 | 470 | | x.GroupPackHeight.ToString(), |
| | 0 | 471 | | x.GroupPackThickness.ToString(), |
| | 0 | 472 | | x.PalletNesting.ToString(), |
| | 0 | 473 | | x.Brand.Name, |
| | 0 | 474 | | x.SubBrand?.Name, |
| | 0 | 475 | | x.Photos.FirstOrDefault()?.FullSizeUrl, |
| | 0 | 476 | | x.Photos.FirstOrDefault()?.PreviewUrl, |
| | 0 | 477 | | _diskStorage.PictureExists(x.Photos.FirstOrDefault()?.FullSizeUrl) ? "1" : "0", |
| | 0 | 478 | | _diskStorage.PictureExists(x.Photos.FirstOrDefault()?.PreviewUrl) ? "1" : "0", |
| | 0 | 479 | | x.UniqueCode, |
| | 0 | 480 | | (x.RecState.Id == (long)RecordState.Active) ? "1" : "0" |
| | 0 | 481 | | }); |
| | 0 | 482 | | }); |
| | | 483 | | |
| | 0 | 484 | | var stream = CsvUtil.ToExcelStream(rows); |
| | 0 | 485 | | _diskStorage.SaveDownload("goods.xlsx", stream, out string fileName); |
| | 0 | 486 | | return File(stream, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", Path.GetFileName(fi |
| | 0 | 487 | | } |
| | | 488 | | |
| | 0 | 489 | | static char[] trimChars = new char[] { '/', '\\' }; |
| | | 490 | | |
| | 0 | 491 | | private static IMapper ToCatalogGoodDtoMapper() => new MapperConfiguration(cfg => |
| | 0 | 492 | | { |
| | 0 | 493 | | cfg.CreateMap<Good, GoodCatalogDTO>() |
| | 0 | 494 | | .ForMember(d => d.Barcode, |
| | 0 | 495 | | e => e.MapFrom( |
| | 0 | 496 | | s => s.GoodBarcodes.FirstOrDefault(barcode => barcode.IsPrimary) != null ? |
| | 0 | 497 | | s.GoodBarcodes.FirstOrDefault(barcode => barcode.IsPrimary).BarCode.Code |
| | 0 | 498 | | : s.DefaultBarCode.Code)) |
| | 0 | 499 | | .ForMember(d => d.BrandId, e => e.MapFrom(s => s.Brand.Id)); |
| | 0 | 500 | | cfg.CreateMap<Photo, PhotoDTO>(); |
| | 0 | 501 | | cfg.CreateMap<Brand, IdNameDTO>(); |
| | 0 | 502 | | }).CreateMapper(); |
| | | 503 | | |
| | | 504 | | private static IMapper ToGoodDtoMapper() |
| | 0 | 505 | | { |
| | 0 | 506 | | var config = new MapperConfiguration(cfg => |
| | 0 | 507 | | { |
| | 0 | 508 | | cfg.CreateMap<Good, GoodDTO>() |
| | 0 | 509 | | .ForMember(d => d.CategoryId, e => e.MapFrom(s => s.Category.Id)) |
| | 0 | 510 | | .ForMember(d => d.BrandId, e => e.MapFrom(s => s.Brand.Id)) |
| | 0 | 511 | | .ForMember(d => d.SubBrandId, e => e.MapFrom(s => s.SubBrand.Id)) |
| | 0 | 512 | | .ForMember(d => d.UnitKindId, e => e.MapFrom(s => int.Parse(s.UnitsKind.Code))) |
| | 0 | 513 | | .ForMember(d => d.VatId, e => e.MapFrom(s => int.Parse(s.VatsKind.Code))) |
| | 0 | 514 | | .ForMember(d => d.VatKind, e => e.MapFrom(s => new EnumDB_DTO { Id = s.VatsKind.Id, Code = s.VatsKin |
| | 0 | 515 | | .ForMember(d => d.UnitKind, e => e.MapFrom(s => new EnumDB_DTO { Id = s.UnitsKind.Id, Code = s.Units |
| | 0 | 516 | | .ForMember(d => d.CountryId, e => e.MapFrom(s => s.Country.Id)) |
| | 0 | 517 | | .ForMember(d => d.MainBarcode, e => e.MapFrom( |
| | 0 | 518 | | s => new BarCodeDTO |
| | 0 | 519 | | { |
| | 0 | 520 | | Id = s.GoodBarcodes.FirstOrDefault(b => b.IsPrimary) != null ? |
| | 0 | 521 | | s.GoodBarcodes.FirstOrDefault(b => b.IsPrimary).BarCode.Id |
| | 0 | 522 | | : s.DefaultBarCode.Id, |
| | 0 | 523 | | Code = s.GoodBarcodes.FirstOrDefault(b => b.IsPrimary) != null ? |
| | 0 | 524 | | s.GoodBarcodes.FirstOrDefault(b => b.IsPrimary).BarCode.Code |
| | 0 | 525 | | : s.DefaultBarCode.Code |
| | 0 | 526 | | })) |
| | 0 | 527 | | .ForMember(d => d.Barcodes, e => |
| | 0 | 528 | | e.MapFrom(s => s.GoodBarcodes.Where(b => !b.IsPrimary).Select(b => new BarCodeDTO{Code = b.BarCo |
| | 0 | 529 | | .ForMember(d => d.IsActive, e => e.MapFrom(s => s.RecState.Code == RecordState.Active.ToString())); |
| | 0 | 530 | | cfg.CreateMap<Photo, PhotoDTO>(); |
| | 0 | 531 | | cfg.CreateMap<Category, IdNameDTO>() |
| | 0 | 532 | | .ForMember(d => d.Id, e => e.MapFrom(s => s.Id)) |
| | 0 | 533 | | .ForMember(d => d.Name, e => e.MapFrom(s => s.Name)); |
| | 0 | 534 | | cfg.CreateMap<Contragent, IdNameDTO>() |
| | 0 | 535 | | .ForMember(d => d.Id, e => e.MapFrom(s => s.Id)) |
| | 0 | 536 | | .ForMember(d => d.Name, e => e.MapFrom(s => s.ShortName)); |
| | 0 | 537 | | cfg.CreateMap<Brand, IdNameDTO>() |
| | 0 | 538 | | .ForMember(d => d.Id, e => e.MapFrom(s => s.Id)) |
| | 0 | 539 | | .ForMember(d => d.Name, e => e.MapFrom(s => s.Name)); |
| | 0 | 540 | | cfg.CreateMap<BarCode, BarCodeDTO>(); |
| | 0 | 541 | | cfg.CreateMap<Country, IdNameDTO>(); |
| | 0 | 542 | | }); |
| | 0 | 543 | | var mapper = config.CreateMapper(); |
| | 0 | 544 | | return mapper; |
| | 0 | 545 | | } |
| | | 546 | | |
| | | 547 | | async Task<Good> PrepareGood(GoodInputDTO dto, Good good) |
| | | 548 | | { |
| | | 549 | | dto.Name = dto.Name.NormalizeName().Required(nameof(dto.Name)); |
| | | 550 | | dto.Barcode = dto.Barcode.NormalizeName().Required(nameof(dto.Barcode)); |
| | | 551 | | if (_service.GetGoodsByName(dto.Name).Any(d => d.Id != good.Id)) |
| | | 552 | | { |
| | | 553 | | throw new ArgumentException($"Товар с именем'{dto.Name}' уже существует"); |
| | | 554 | | } |
| | | 555 | | |
| | | 556 | | good.Country = await _countryService.GetCountry(dto.CountryId); |
| | | 557 | | if (good.Country == null) |
| | | 558 | | { |
| | | 559 | | throw new ArgumentException($"Страна #{dto.CountryId} не найдена"); |
| | | 560 | | } |
| | | 561 | | good.GoodBarcodes ??= new List<GoodBarcode>(); |
| | | 562 | | |
| | | 563 | | good.Category = await _categoryService.FindCategory(dto.CategoryId); |
| | | 564 | | if (good.Category == null) |
| | | 565 | | { |
| | | 566 | | throw new ArgumentException($"Категория #{dto.CategoryId} не найдена"); |
| | | 567 | | } |
| | | 568 | | |
| | | 569 | | if (dto.BrandId == dto.SubBrandId) |
| | | 570 | | { |
| | | 571 | | throw new ArgumentException($"Бранд #{dto.BrandId} равен субренду #{dto.SubBrandId}"); |
| | | 572 | | } |
| | | 573 | | |
| | | 574 | | if (dto.ExpirationDays < 0) |
| | | 575 | | { |
| | | 576 | | throw new ArgumentException("Срок годности не может быть отрицательным"); |
| | | 577 | | } |
| | | 578 | | |
| | | 579 | | good.Brand = dto.BrandId != 0 ? await _brandService.GetBrand(dto.BrandId) : null; |
| | | 580 | | |
| | | 581 | | good.SubBrand = dto.SubBrandId.HasValue ? await _brandService.GetBrand(dto.SubBrandId.Value) : null; |
| | | 582 | | |
| | | 583 | | good.UnitsKind = await _dirService.GetUnitKindByCode(dto.UnitKindId); |
| | | 584 | | good.RecState = dto.IsActive ? await _dirService.GetRecordState((long)RecordState.Active) : await _dirServic |
| | | 585 | | good.ConformityCertNumber = dto.ConformityCertNumber; |
| | | 586 | | good.CustomDeclarationNumber = dto.CustomDeclarationNumber; |
| | | 587 | | //good.VendorCode = dto.VendorCode; |
| | | 588 | | good.VatsKind = await _dirService.GetVatKindByCode(dto.Vat); |
| | | 589 | | good.Weight = dto.Weight; |
| | | 590 | | good.Width = dto.Width; |
| | | 591 | | good.Height = dto.Height; |
| | | 592 | | good.Thickness = dto.Thickness; |
| | | 593 | | good.GroupPackNesting = dto.GroupPackNesting; |
| | | 594 | | good.GroupPackWidth = dto.GroupPackWidth; |
| | | 595 | | good.GroupPackHeight = dto.GroupPackHeight; |
| | | 596 | | good.GroupPackThickness = dto.GroupPackThickness; |
| | | 597 | | good.MinDeliveryLot = dto.MinDeliveryLot; |
| | | 598 | | good.ExpirationDays = dto.ExpirationDays ?? 0; |
| | | 599 | | good.Name = dto.Name; |
| | | 600 | | |
| | | 601 | | var defaultBarcode = await _barcodeService.GetOrCreateBarcode(dto.Barcode); |
| | 0 | 602 | | if (!good.GoodBarcodes.Any(d => d.BarCodeId == defaultBarcode.Id && d.IsPrimary)) |
| | | 603 | | { |
| | | 604 | | var bar = good.GoodBarcodes.FirstOrDefault(d => d.IsPrimary); |
| | | 605 | | if (bar != null) |
| | | 606 | | { |
| | | 607 | | bar.IsPrimary = false; |
| | | 608 | | await _barcodeService.UpdateGoodBarcode(bar); |
| | | 609 | | } |
| | | 610 | | |
| | | 611 | | if (good.GoodBarcodes.Select(d => d.BarCode).Contains(default)) |
| | | 612 | | { |
| | | 613 | | for (int i = 0; i < good.GoodBarcodes.Count; i++) |
| | | 614 | | { |
| | | 615 | | if (good.GoodBarcodes[i].BarCodeId == defaultBarcode.Id) |
| | | 616 | | { |
| | | 617 | | good.GoodBarcodes[i].IsPrimary = true; |
| | | 618 | | } |
| | | 619 | | } |
| | | 620 | | } |
| | | 621 | | else |
| | | 622 | | { |
| | | 623 | | good.GoodBarcodes.Add(new GoodBarcode { BarCode = defaultBarcode, IsPrimary = true}); |
| | | 624 | | } |
| | | 625 | | } |
| | | 626 | | |
| | | 627 | | if (!string.IsNullOrWhiteSpace(dto.AdditionalBarcode)) |
| | | 628 | | { |
| | | 629 | | var addBarcode = await _barcodeService.GetOrCreateBarcode(dto.AdditionalBarcode); |
| | | 630 | | |
| | 0 | 631 | | if (!good.GoodBarcodes.Any(d => d.BarCodeId == addBarcode.Id)) |
| | | 632 | | { |
| | | 633 | | good.GoodBarcodes.Add(new GoodBarcode { BarCode = addBarcode, IsPrimary = false}); |
| | | 634 | | } |
| | | 635 | | } |
| | | 636 | | |
| | | 637 | | return good; |
| | | 638 | | } |
| | | 639 | | } |
| | | 640 | | } |