Ejemplo n.º 1
0
        public IActionResult Edit(int?id, ProductEditViewModel model)
        {
            if (!ModelState.IsValid)
            {
                return(RedirectToAction(nameof(Edit), new { id }));
            }

            var product = id.HasValue ? _productRepository.GetById(id.Value) : new Product();

            if (product == null)
            {
                this.SetNotice($"Product #{id} was not found");
                return(RedirectToAction(nameof(Index)));
            }

            var offerChanged = (product.Stock != model.Stock || product.Price != model.Price);

            model.ApplyToEntity(product);

            if (_productRepository.Persist(product))
            {
                if (offerChanged)
                {
                    _publishEndpoint.Publish(new OfferUpdatedEvent()
                    {
                        Price = model.Price, Stock = model.Stock
                    });
                }

                this.SetNotice($"Saved product #{product.Id}");
                return(RedirectToAction(nameof(Edit), new { id = id ?? product.Id }));
            }
            else
            {
                this.SetNotice($"Failed to save product");
                return(RedirectToAction(nameof(Index)));
            }
        }