ProductAPI
305 строк · 15.0 Кб
1namespace ProductAPI.Service.Implementations2{
3public class ProductService : BaseService<ProductService, ProductDTO>,IProductService4{5private readonly IProductRepository _productRep;6private readonly ICloudinaryActions _cloudinary;7public ProductService(IProductRepository productRep, ICloudinaryActions cloudinary, IMapper mapper, ILogger<ProductService> logger)8:base(mapper, logger, new())9{10_productRep = productRep;11_cloudinary = cloudinary;12}13
14#region Create15/// <summary>16/// Создание продукта.17/// </summary>18/// <param name="createModel"></param>19/// <returns>Базовый ответ.</returns>20public async Task<IBaseResponse<ProductDTO>> CreateServiceAsync(CreateProductDTO createModel)21{22_logger.LogInformation($"Создание продукта. / method: CreateServiceAsync");23if (await _productRep.GetByAsync(x => x.ProductName == createModel.ProductName) != null)24{25_logger.LogWarning("Продукт с таким наименованием существует.");26_baseResponse.DisplayMessage = "Продукт с таким наименованием существует.";27_baseResponse.Status = Status.ExistsName;28return _baseResponse;29}30
31Product product = _mapper.Map<Product>(createModel);32if(createModel.FileMainImage != null && createModel.FileMainImage.Length > 0)33{34var image = await _cloudinary.AddImageAsync(createModel.FileMainImage, product.ProductId);35AssigningImageToProduct(image, product);36}37if (createModel.FileSecondaryImages != null)38{39var secondaryImages = await _cloudinary.AddImagesAsync(createModel.FileSecondaryImages, product.ProductId);40AssigningImagesToProduct(secondaryImages, product);41}42
43var productRep = await _productRep.CreateAsync(product);44if (productRep != null)45{46_logger.LogInformation("Продукт создан.");47}48else49{50_logger.LogWarning("Продукт не создан.");51_baseResponse.DisplayMessage += "\nПродукт не создан.";52_baseResponse.Status = Status.NotCreate;53}54_baseResponse.Result = _mapper.Map<ProductDTO>(productRep);55_logger.LogInformation($"Ответ отправлен контролеру/method: CreateServiceAsync");56return _baseResponse;57}58#endregion59
60#region Delete61/// <summary>62/// Удаление продукта63/// </summary>64/// <param name="id"></param>65/// <returns>Базовый ответ.</returns>66public async Task<IBaseResponse<bool>> DeleteServiceAsync(int id)67{68_logger.LogInformation($"Удаление продукта. / method: DeleteServiceAsync");69var baseResponse = new BaseResponse<bool>();70_logger.LogInformation($"Поиск продукта по id: {id}. / method: DeleteServiceAsync");71Product product = await _productRep.GetByAsync(x => x.ProductId == id, true);72if (product is null)73{74_logger.LogWarning($"Продукт c id: {id} не найден.");75baseResponse.DisplayMessage = $"Продукт c id: {id} не найден.";76baseResponse.Result = false;77_logger.LogInformation($"Ответ отправлен контролеру (false)/ method: DeleteServiceAsync");78return baseResponse;79}80if (product.ImageId != null)81{82await _cloudinary.DeleteImageAsync(product.ImageId);83}84if (product.SecondaryImages != null)85{86foreach (var image in product.SecondaryImages)87{88if (image != null)89{90await _cloudinary.DeleteImageAsync(image.ImageId);91}92}93}94await _productRep.DeleteAsync(product);95baseResponse.DisplayMessage = "Продукт удален.";96baseResponse.Result = true;97_logger.LogInformation($"Ответ отправлен контролеру (true)/ method: DeleteServiceAsync");98return baseResponse;99}100#endregion101
102#region GetById103/// <summary>104/// Вывод продукта105/// </summary>106/// <param name="id"></param>107/// <returns>Базовый ответ.</returns>108public async Task<IBaseResponse<ProductDTO>> GetByIdServiceAsync(int id)109{110_logger.LogInformation($"Поиск продукта по id: {id}. / method: GetByIdServiceAsync");111Product product = await _productRep.GetByAsync(x => x.ProductId == id);112if (product is null)113{114_logger.LogWarning($"Продукт по id [{id}] не найден.");115_baseResponse.DisplayMessage = $"Продукт по id [{id}] не найден.";116_baseResponse.Status = Status.NotFound;117}118else119{120_logger.LogInformation($"Вывод продукта по id [{id}]");121}122_baseResponse.Result = _mapper.Map<ProductDTO>(product);123_logger.LogInformation($"Ответ отправлен контролеру/ method: GetByIdServiceAsync");124return _baseResponse;125}126#endregion127
128#region Get129/// <summary>130/// Список продуктов (возможно приминение фильра и поиска)131/// </summary>132/// <param name="paging"></param>133/// <param name="filter"></param>134/// <param name="search"></param>135/// <returns>Базовый ответ.</returns>136public async Task<IBaseResponse<PagedList<ProductDTO>>> GetServiceAsync(PagingQueryParameters paging, string? filter = null, string? search = null)137{138_logger.LogInformation($"Список продуктов. /method: GetServiceAsync");139var baseResponse = new BaseResponse<PagedList<ProductDTO>>();140string[] includeProperties = { nameof(ProductDTO.Category), nameof(ProductDTO.SecondaryImages) };141IEnumerable<Product>? products = null;142if (!string.IsNullOrEmpty(filter) && !string.IsNullOrEmpty(search))143{144var result = await FilterAndSearchAsync(products, includeProperties, filter, search);145products = result.Item1;146baseResponse.DisplayMessage = result.Item2;147}148if (!string.IsNullOrEmpty(filter) && string.IsNullOrEmpty(search))149{150var result = await FilterAndSearchAsync(products, includeProperties, filter);151products = result.Item1;152baseResponse.DisplayMessage = result.Item2;153}154if (string.IsNullOrEmpty(filter) && string.IsNullOrEmpty(search))155{156products = await _productRep.GetAsync(search: search, includeProperties: includeProperties);157}158if (products is null)159{160_logger.LogWarning("Список продуктов пуст.");161baseResponse.DisplayMessage = "Список продуктов пуст.";162}163else164{165_logger.LogInformation("Список продуктов.");166IEnumerable<ProductDTO> listProducts = _mapper.Map<IEnumerable<ProductDTO>>(products);167_logger.LogInformation("применение пагинации. /method: GetServiceAsync");168baseResponse.Result = PagedList<ProductDTO>.ToPagedList(listProducts, paging.PageNumber, paging.PageSize);169baseResponse.ParameterPaged = baseResponse.Result.Parameter;170}171_logger.LogInformation($"Ответ отправлен контролеру/ method: GetServiceAsync");172return baseResponse;173}174#endregion175
176#region Update177/// <summary>178/// Обновление продукта.179/// </summary>180/// <param name="updateModel"></param>181/// <returns>Базовый ответ.</returns>182/// <exception cref="NullReferenceException"></exception>183public async Task<IBaseResponse<ProductDTO>> UpdateServiceAsync(UpdateProductDTO updateModel)184{185_logger.LogInformation($"Обновление продукта.");186var carent = await _productRep.GetByAsync(x => x.ProductId == updateModel.ProductId);187if (carent is null)188{189_logger.LogWarning("Попытка обновить объект, которого нет в хранилище.");190_baseResponse.Status = Status.NotFound;191_baseResponse.DisplayMessage = "Попытка обновить объект, которого нет в хранилище.";192}193else194{195var product = _mapper.Map<Product>(updateModel);196if (updateModel.ImageId != null && updateModel.FileMainImage != null)197{198var image = await _cloudinary.UpdateImageAsync(updateModel.FileMainImage, updateModel.ProductId, updateModel.ImageId);199AssigningImageToProduct(image, product);200}201if (updateModel.SecondaryImagesId != null && updateModel.FileSecondaryImages != null &&202updateModel.SecondaryImagesId.Count == updateModel.FileSecondaryImages.Count)203{204var secondaryImages = await _cloudinary.UpdateImagesAsync(updateModel.FileSecondaryImages, product.ProductId, updateModel.SecondaryImagesId);205AssigningImagesToProduct(secondaryImages, product);206}207var productRep = await _productRep.UpdateAsync(product, carent);208_baseResponse.DisplayMessage = "Продукт обновился.";209_baseResponse.Result = _mapper.Map<ProductDTO>(productRep);210}211_logger.LogInformation($"Ответ отправлен контролеру/ method: UpdateServiceAsync");212return _baseResponse;213}214#endregion215
216#region Filter217/// <summary>218/// Фильтр и поиск продуктов по значению219/// </summary>220/// <param name="products"></param>221/// <param name="includeProperties"></param>222/// <param name="filter"></param>223/// <param name="search"></param>224/// <returns>Отфильтрованный список и сообщение</returns>225private async Task<(IEnumerable<Product>?, string)> FilterAndSearchAsync(IEnumerable<Product>? products, string[] includeProperties, string filter, string? search = null)226{227_logger.LogInformation($"Поиск продуктов по фильтру: {filter}. / method: FilterAsync");228DateTime date;229decimal price;230if (DateTime.TryParse(filter.ToString(), out date))231{232products = await _productRep.GetAsync(x => x.CreateDateTime.Date == date.Date, search, includeProperties: includeProperties);233
234if (products is null)235message = Message.FilterAndSearch(_logger, true, "продуктов", filter, search);236else237message = Message.FilterAndSearch(_logger, false, "продуктов", filter, search);238}239else if (Decimal.TryParse(filter.ToString(), out price))240{241products = await _productRep.GetAsync(x => x.Price == price, search, includeProperties: includeProperties);242if (products is null)243message = Message.FilterAndSearch(_logger, true, "продуктов", filter, search);244else245message = Message.FilterAndSearch(_logger, false, "продуктов", filter, search);246}247else248{249products = await _productRep.GetAsync(x => x.ProductName == filter, search, includeProperties: includeProperties);250
251if (products.Count() is 0) products = await _productRep.GetAsync(x => x.Category!.CategoryName == filter, search, includeProperties: includeProperties);252
253if (products.Count() is 0)254message = Message.FilterAndSearch(_logger, true, "продуктов", filter, search);255else256message = Message.FilterAndSearch(_logger, false, "продуктов", filter, search);257}258_logger.LogInformation($"Ответ отправлен GetServiceAsync/ method: FilterAsync");259return (products, message);260}261#endregion262
263#region Add image(s) in product264/// <summary>265/// Add image in product266/// </summary>267/// <param name="image"></param>268/// <param name="product"></param>269private void AssigningImageToProduct(Image? image, Product product)270{271if (image != null)272{273_logger.LogInformation("Изображение добавлено в API сloudinary.");274_baseResponse.DisplayMessage = "Изображение добавлено в API сloudinary.";275product.ImageId = image.ImageId;276product.ImageUrl = image.ImageUrl;277}278else279{280_logger.LogInformation("Изображение не добавлено в API сloudinary.");281_baseResponse.DisplayMessage = "Изображение не добавлено в API сloudinary.";282}283}284/// <summary>285/// Add images in product286/// </summary>287/// <param name="images"></param>288/// <param name="product"></param>289private void AssigningImagesToProduct(IList<Image>? images, Product product)290{291if (images != null)292{293_logger.LogInformation("Cписок изображений обнавлён в API сloudinary.");294_baseResponse.DisplayMessage += $"\nCписок изображений добавлен в API сloudinary.";295product.SecondaryImages = images;296}297else298{299_logger.LogInformation("Cписок изображений не обнавлён в API сloudinary.");300_baseResponse.DisplayMessage += $"\nCписок изображений не добавлен в API сloudinary.";301}302}303#endregion304}305}
306