ProductAPI

Форк
0
305 строк · 15.0 Кб
1
namespace ProductAPI.Service.Implementations
2
{
3
    public class ProductService : BaseService<ProductService, ProductDTO>,IProductService
4
    {
5
        private readonly IProductRepository _productRep;
6
        private readonly ICloudinaryActions _cloudinary;
7
        public 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 Create
15
        /// <summary>
16
        /// Создание продукта.
17
        /// </summary>
18
        /// <param name="createModel"></param>
19
        /// <returns>Базовый ответ.</returns>
20
        public async Task<IBaseResponse<ProductDTO>> CreateServiceAsync(CreateProductDTO createModel)
21
        {
22
            _logger.LogInformation($"Создание продукта. / method: CreateServiceAsync");
23
            if (await _productRep.GetByAsync(x => x.ProductName == createModel.ProductName) != null)
24
            {
25
                _logger.LogWarning("Продукт с таким наименованием существует.");
26
                _baseResponse.DisplayMessage = "Продукт с таким наименованием существует.";
27
                _baseResponse.Status = Status.ExistsName;
28
                return _baseResponse;
29
            }
30

31
            Product product = _mapper.Map<Product>(createModel);
32
            if(createModel.FileMainImage != null && createModel.FileMainImage.Length > 0)
33
            {
34
                var image = await _cloudinary.AddImageAsync(createModel.FileMainImage, product.ProductId);
35
                AssigningImageToProduct(image, product);
36
            }
37
            if (createModel.FileSecondaryImages != null)
38
            {
39
                var secondaryImages = await _cloudinary.AddImagesAsync(createModel.FileSecondaryImages, product.ProductId);
40
                AssigningImagesToProduct(secondaryImages, product);
41
            }
42

43
            var productRep = await _productRep.CreateAsync(product);
44
            if (productRep != null)
45
            {
46
                _logger.LogInformation("Продукт создан.");
47
            }
48
            else
49
            {
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");
56
            return _baseResponse;
57
        }
58
        #endregion
59

60
        #region Delete
61
        /// <summary>
62
        /// Удаление продукта
63
        /// </summary>
64
        /// <param name="id"></param>
65
        /// <returns>Базовый ответ.</returns>
66
        public async Task<IBaseResponse<bool>> DeleteServiceAsync(int id)
67
        {
68
            _logger.LogInformation($"Удаление продукта. / method: DeleteServiceAsync");
69
            var baseResponse = new BaseResponse<bool>();
70
            _logger.LogInformation($"Поиск продукта по id: {id}. / method: DeleteServiceAsync");
71
            Product product = await _productRep.GetByAsync(x => x.ProductId == id, true);
72
            if (product is null)
73
            {
74
                _logger.LogWarning($"Продукт c id: {id} не найден.");
75
                baseResponse.DisplayMessage = $"Продукт c id: {id} не найден.";
76
                baseResponse.Result = false;
77
                _logger.LogInformation($"Ответ отправлен контролеру (false)/ method: DeleteServiceAsync");
78
                return baseResponse;
79
            }
80
            if (product.ImageId != null)
81
            {
82
                await _cloudinary.DeleteImageAsync(product.ImageId);
83
            }
84
            if (product.SecondaryImages != null)
85
            {
86
                foreach (var image in product.SecondaryImages)
87
                {
88
                    if (image != null)
89
                    {
90
                        await _cloudinary.DeleteImageAsync(image.ImageId);
91
                    }
92
                }
93
            }
94
            await _productRep.DeleteAsync(product);
95
            baseResponse.DisplayMessage = "Продукт удален.";
96
            baseResponse.Result = true;
97
            _logger.LogInformation($"Ответ отправлен контролеру (true)/ method: DeleteServiceAsync");
98
            return baseResponse;
99
        }
100
        #endregion
101

102
        #region GetById
103
        /// <summary>
104
        /// Вывод продукта
105
        /// </summary>
106
        /// <param name="id"></param>
107
        /// <returns>Базовый ответ.</returns>
108
        public async Task<IBaseResponse<ProductDTO>> GetByIdServiceAsync(int id)
109
        {
110
            _logger.LogInformation($"Поиск продукта по id: {id}. / method: GetByIdServiceAsync");
111
            Product product = await _productRep.GetByAsync(x => x.ProductId == id);
112
            if (product is null)
113
            {
114
                _logger.LogWarning($"Продукт по id [{id}] не найден.");
115
                _baseResponse.DisplayMessage = $"Продукт по id [{id}] не найден.";
116
                _baseResponse.Status = Status.NotFound;
117
            }
118
            else
119
            {
120
                _logger.LogInformation($"Вывод продукта по id [{id}]");
121
            }
122
            _baseResponse.Result = _mapper.Map<ProductDTO>(product);
123
            _logger.LogInformation($"Ответ отправлен контролеру/ method: GetByIdServiceAsync");
124
            return _baseResponse;
125
        }
126
        #endregion
127

128
        #region Get
129
        /// <summary>
130
        /// Список продуктов (возможно приминение фильра и поиска)
131
        /// </summary>
132
        /// <param name="paging"></param>
133
        /// <param name="filter"></param>
134
        /// <param name="search"></param>
135
        /// <returns>Базовый ответ.</returns>
136
        public async Task<IBaseResponse<PagedList<ProductDTO>>> GetServiceAsync(PagingQueryParameters paging, string? filter = null, string? search = null)
137
        {
138
            _logger.LogInformation($"Список продуктов. /method: GetServiceAsync");
139
            var baseResponse = new BaseResponse<PagedList<ProductDTO>>();
140
            string[] includeProperties = { nameof(ProductDTO.Category), nameof(ProductDTO.SecondaryImages) };
141
            IEnumerable<Product>? products = null;
142
            if (!string.IsNullOrEmpty(filter) && !string.IsNullOrEmpty(search))
143
            {
144
                var result = await FilterAndSearchAsync(products, includeProperties, filter, search);
145
                products = result.Item1;
146
                baseResponse.DisplayMessage = result.Item2;
147
            }
148
            if (!string.IsNullOrEmpty(filter) && string.IsNullOrEmpty(search))
149
            {
150
                var result = await FilterAndSearchAsync(products, includeProperties, filter);
151
                products = result.Item1;
152
                baseResponse.DisplayMessage = result.Item2;
153
            }
154
            if (string.IsNullOrEmpty(filter) && string.IsNullOrEmpty(search))
155
            {
156
                products = await _productRep.GetAsync(search: search, includeProperties: includeProperties);
157
            }
158
            if (products is null)
159
            {
160
                _logger.LogWarning("Список продуктов пуст.");
161
                baseResponse.DisplayMessage = "Список продуктов пуст.";
162
            }
163
            else
164
            {
165
                _logger.LogInformation("Список продуктов.");
166
                IEnumerable<ProductDTO> listProducts = _mapper.Map<IEnumerable<ProductDTO>>(products);
167
                _logger.LogInformation("применение пагинации. /method: GetServiceAsync");
168
                baseResponse.Result = PagedList<ProductDTO>.ToPagedList(listProducts, paging.PageNumber, paging.PageSize);
169
                baseResponse.ParameterPaged = baseResponse.Result.Parameter;
170
            }
171
            _logger.LogInformation($"Ответ отправлен контролеру/ method: GetServiceAsync");
172
            return baseResponse;
173
        }
174
        #endregion
175

176
        #region Update
177
        /// <summary>
178
        /// Обновление продукта.
179
        /// </summary>
180
        /// <param name="updateModel"></param>
181
        /// <returns>Базовый ответ.</returns>
182
        /// <exception cref="NullReferenceException"></exception>
183
        public async Task<IBaseResponse<ProductDTO>> UpdateServiceAsync(UpdateProductDTO updateModel)
184
        {
185
            _logger.LogInformation($"Обновление продукта.");
186
            var carent = await _productRep.GetByAsync(x => x.ProductId == updateModel.ProductId);
187
            if (carent is null)
188
            {
189
                _logger.LogWarning("Попытка обновить объект, которого нет в хранилище.");
190
                _baseResponse.Status = Status.NotFound;
191
                _baseResponse.DisplayMessage = "Попытка обновить объект, которого нет в хранилище.";
192
            }
193
            else
194
            {
195
                var product = _mapper.Map<Product>(updateModel);
196
                if (updateModel.ImageId != null && updateModel.FileMainImage != null)
197
                {
198
                    var image = await _cloudinary.UpdateImageAsync(updateModel.FileMainImage, updateModel.ProductId, updateModel.ImageId);
199
                    AssigningImageToProduct(image, product);
200
                }
201
                if (updateModel.SecondaryImagesId != null && updateModel.FileSecondaryImages != null && 
202
                    updateModel.SecondaryImagesId.Count == updateModel.FileSecondaryImages.Count)
203
                {
204
                    var secondaryImages = await _cloudinary.UpdateImagesAsync(updateModel.FileSecondaryImages, product.ProductId, updateModel.SecondaryImagesId);
205
                    AssigningImagesToProduct(secondaryImages, product);
206
                }
207
                var productRep = await _productRep.UpdateAsync(product, carent);
208
                _baseResponse.DisplayMessage = "Продукт обновился.";
209
                _baseResponse.Result = _mapper.Map<ProductDTO>(productRep);
210
            }
211
            _logger.LogInformation($"Ответ отправлен контролеру/ method: UpdateServiceAsync");
212
            return _baseResponse;
213
        }
214
        #endregion
215

216
        #region Filter
217
        /// <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>
225
        private async Task<(IEnumerable<Product>?, string)> FilterAndSearchAsync(IEnumerable<Product>? products, string[] includeProperties, string filter, string? search = null)
226
        {
227
            _logger.LogInformation($"Поиск продуктов по фильтру: {filter}. / method: FilterAsync");
228
            DateTime date;
229
            decimal price;
230
            if (DateTime.TryParse(filter.ToString(), out date))
231
            {
232
                products = await _productRep.GetAsync(x => x.CreateDateTime.Date == date.Date, search, includeProperties: includeProperties);
233

234
                if (products is null)
235
                    message = Message.FilterAndSearch(_logger, true, "продуктов", filter, search);
236
                else
237
                    message = Message.FilterAndSearch(_logger, false, "продуктов", filter, search);
238
            }
239
            else if (Decimal.TryParse(filter.ToString(), out price))
240
            {
241
                products = await _productRep.GetAsync(x => x.Price == price, search, includeProperties: includeProperties);
242
                if (products is null)
243
                    message = Message.FilterAndSearch(_logger, true, "продуктов", filter, search);
244
                else
245
                    message = Message.FilterAndSearch(_logger, false, "продуктов", filter, search);
246
            }
247
            else
248
            {
249
                products = await _productRep.GetAsync(x => x.ProductName == filter, search, includeProperties: includeProperties);
250

251
                if (products.Count() is 0)  products = await _productRep.GetAsync(x => x.Category!.CategoryName == filter, search, includeProperties: includeProperties);
252

253
                if (products.Count() is 0)
254
                    message = Message.FilterAndSearch(_logger, true, "продуктов", filter, search);
255
                else
256
                    message = Message.FilterAndSearch(_logger, false, "продуктов", filter, search);
257
            }
258
            _logger.LogInformation($"Ответ отправлен GetServiceAsync/ method: FilterAsync");
259
            return (products, message);
260
        }
261
        #endregion
262

263
        #region Add image(s) in product
264
        /// <summary>
265
        /// Add image in product
266
        /// </summary>
267
        /// <param name="image"></param>
268
        /// <param name="product"></param>
269
        private void AssigningImageToProduct(Image? image, Product product)
270
        {
271
            if (image != null)
272
            {
273
                _logger.LogInformation("Изображение добавлено в API сloudinary.");
274
                _baseResponse.DisplayMessage = "Изображение добавлено в API сloudinary.";
275
                product.ImageId = image.ImageId;
276
                product.ImageUrl = image.ImageUrl;
277
            }
278
            else
279
            {
280
                _logger.LogInformation("Изображение не добавлено в API сloudinary.");
281
                _baseResponse.DisplayMessage = "Изображение не добавлено в API сloudinary.";
282
            }
283
        }
284
        /// <summary>
285
        /// Add images in product
286
        /// </summary>
287
        /// <param name="images"></param>
288
        /// <param name="product"></param>
289
        private void AssigningImagesToProduct(IList<Image>? images, Product product)
290
        {
291
            if (images != null)
292
            {
293
                _logger.LogInformation("Cписок изображений обнавлён в API сloudinary.");
294
                _baseResponse.DisplayMessage += $"\nCписок изображений добавлен в API сloudinary.";
295
                product.SecondaryImages = images;
296
            }
297
            else
298
            {
299
                _logger.LogInformation("Cписок изображений не обнавлён в API сloudinary.");
300
                _baseResponse.DisplayMessage += $"\nCписок изображений не добавлен в API сloudinary.";
301
            }
302
        }
303
        #endregion
304
    }
305
}
306

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.