Ejemplo n.º 1
0
        public async Task <IActionResult> Update(int id, ProductForUpdateDTO productForUpdateDTO)
        {
            /*
             * ---------------------------------------------------------------------------
             * ZONA DE VALIDACION
             * ---------------------------------------------------------------------------
             */
            // Chequear si el producto existe
            var productDB = await _productRepository.GetProduct(id);

            if (productDB == null)
            {
                throw new Exception($"Product with id {id} does not exist");
            }


            /*
             * --------------------------------------------------------------------------
             * ZONA DE PROCESAMIENTO DE LA PETICION
             * --------------------------------------------------------------------------
             */
            _mapper.Map(productForUpdateDTO, productDB);

            if (await _productRepository.SaveAll())
            {
                return(NoContent());
            }

            throw new Exception($"Error while updating product with id: {id}");
        }
Ejemplo n.º 2
0
        // Add new tags.
        private void AddNewTags(ProductForUpdateDTO productForUpdateDTO, Product productFromRepo)
        {
            productForUpdateDTO.Tags.ToList().ForEach(tag =>
            {
                // Add the new tags to the product.
                // Behind the scenes EF will create new Tags in the DB table and associate their new IDs with the Product.

                // don't add a new tag if it already exists in the current list.
                if (!productFromRepo.ProductTags.Any(p => p.Tag.Name == tag.Name))
                {
                    Tag tagFromDb            = _tagRepo.GetTag(tag.Name);
                    ProductTag newProductTag = new ProductTag();

                    if (tagFromDb == null)
                    {
                        newProductTag.Tag = _mapper.Map <Tag>(tag);
                    }
                    else
                    {
                        newProductTag.Tag = tagFromDb;
                    }

                    newProductTag.Product   = productFromRepo;
                    newProductTag.ProductId = productFromRepo.Id;

                    productFromRepo.ProductTags.Add(newProductTag);
                }
            });
        }
Ejemplo n.º 3
0
        public async Task <IActionResult> UpdateProductForCategory(Guid categoryId,
                                                                   Guid productId,
                                                                   [FromBody] ProductForUpdateDTO product)
        {
            var productEntity = await _productService.GetProductAsync(productId, trackChanges : true);

            productEntity.UpdatedAt = DateTime.UtcNow.ToLocalTime();

            _mapper.Map(product, productEntity);

            await _productService.SaveAsync();

            return(NoContent());
        }
Ejemplo n.º 4
0
        public async Task <IActionResult> Put(int id, ProductForUpdateDTO productForUpdateDTO)
        {
            // find missing tags and remove them.
            Product productFromRepo = await FindMissingTags(id, productForUpdateDTO);

            // add new tags, if needed.
            AddNewTags(productForUpdateDTO, productFromRepo);

            // update the rest of the properties.
            _mapper.Map(productForUpdateDTO, productFromRepo);

            if (await _productRepo.SaveAsync() > 0)
            {
                return(NoContent());
            }

            throw new Exception($"Updating product with id: {id} failed on save.");
        }
Ejemplo n.º 5
0
        [HttpPut("{supplierId}/{id}")]//done
        public async Task <IActionResult> UpdateProduct(int supplierId, int id, ProductForUpdateDTO productForUpdateDTO)
        {
            if (supplierId != int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value))
            {
                return(Unauthorized());
            }
            var productFromRepo = await _repo.GetProduct(id);

            var product = _mapper.Map(productForUpdateDTO, productFromRepo);

            if (await _repo.SaveAll())
            {
                var productToReturn = _mapper.Map <ProductReturnDTO>(product);
                return(CreatedAtRoute("GetProduct", new { id = product.ProductId }, productToReturn));
            }

            throw new Exception($"حدثت مشكلة في تعديل بيانات المنتج رقم {id}");
        }
Ejemplo n.º 6
0
        public async Task <IActionResult> UpdateProduct(int id, [FromBody] ProductForUpdateDTO product)
        {
            if (product is null)
            {
                logger.LogError($"Product object sent from client is null");
                return(BadRequest("Product object is null"));
            }

            Product productEntity = await repository.Product.GetByIdAsync(id);

            if (productEntity is null)
            {
                logger.LogError($"Not found product with id: {id} in database");
                return(NotFound());
            }
            mapper.Map(product, productEntity);
            repository.Product.Update(productEntity);
            await repository.SaveAsync();

            logger.LogInfo($"Updated product with id: {id} in UpdateProduct method");
            return(NoContent());
        }
Ejemplo n.º 7
0
        // Find the missing tags and remove them from the tag collection.
        private async Task <Product> FindMissingTags(int id, ProductForUpdateDTO productForUpdateDTO)
        {
            var productFromRepo = await _productRepo.FindAsyncIncluding(t => t.Id == id, new string[] { "ProductTags.Tag" });

            // find missing rows.
            List <ProductTag> missingRows = new List <ProductTag>();

            foreach (var dbTag in productFromRepo.ProductTags)
            {
                if (!productForUpdateDTO.Tags.Any(t => t.Id == dbTag.TagId))
                {
                    missingRows.Add(dbTag);
                }
            }

            foreach (var missingRow in missingRows)
            {
                productFromRepo.ProductTags.Remove(missingRow);
            }

            return(productFromRepo);
        }
Ejemplo n.º 8
0
        public IActionResult UpdateProduct(int productId, [FromBody] ProductForUpdateDTO product)
        {
            if (product == null)
            {
                return(BadRequest());
            }

            if (!_supermarketRepository.ProductExists(productId))
            {
                return(NotFound());
            }

            // Validate data
            if (!ModelState.IsValid)
            {
                // return 422
                return(new UnprocessableEntityObjectResult(ModelState));
            }

            var productFromRepo = _supermarketRepository.GetProductById(productId);

            if (productFromRepo == null)
            {
                return(NotFound());
            }

            Mapper.Map(product, productFromRepo);

            _supermarketRepository.UpdateProduct(productId);

            if (!_supermarketRepository.Save())
            {
                throw new Exception($"Updating product {productId} failed on saving.");
            }

            return(NoContent());
        }