public async Task <Product> CreateProduct(ProductCreationModel model) { var product = _mapper.Map <Product>(model); await _productRepository.AddAsync(product); await _productRepository.SaveChangesAsync(); return(product); }
public static Product ToProduct(this ProductCreationModel productCreationModel) { return(new Product { Name = productCreationModel.Name, Description = productCreationModel.Description, Count = productCreationModel.Count, Price = productCreationModel.Price }); }
public Product MapBackToEntity(ProductCreationModel model) { return(new Product { Name = model.Name, ProductCategory = model.ProductCategory, AvaliableQuantity = model.AvaliableQuantity, Price = model.Price, Description = model.Description, }); }
public async Task <IActionResult> Post( ICommandHandler <ProductCreationModel> createProductCommand, [FromBody] ProductCreationModel productCreationModel) { if (!this.ModelState.IsValid) { return(this.BadRequest(this.ModelState)); } await createProductCommand.Execute(productCreationModel); return(this.Accepted()); }
public async Task <DataResult <Product> > CreateProductAsync(ProductCreationModel productModel) { Product product = _productMapper.MapBackToEntity(productModel); product.CreationDate = DateTime.Now; Product addedProduct = await _productRepository.AddAsync(product); await _productRepository.SaveAsync(); return(new DataResult <Product> { Data = addedProduct, ResponseMessageType = ResponseMessageType.Success }); }
public async Task <IActionResult> Create([FromBody] ProductCreationModel productModel) { if (productModel == null) { return(BadRequest()); } var operationResult = await this.productService.Create(productModel); if (operationResult.Failure) { return(CreateErrorResponse(operationResult)); } return(CreatedAtAction(nameof(Get), new { id = operationResult.Value.Id }, operationResult)); }
public async Task <IActionResult> Post([FromBody] ProductCreationModel productCreationModel) { ValidationResult validationResult = _productCreationModelValidator.Validate(productCreationModel); if (!validationResult.IsValid) { DataResult <Product> dataResult = new DataResult <Product> { ResponseMessageType = ResponseMessageType.Error, MessageDetails = "Model is invalid", Data = null }; return(BadRequest(dataResult)); } return(Ok(await _productService.CreateProductAsync(productCreationModel))); }
public async Task <Result <ProductModel> > Create(ProductCreationModel productModel) { try { var productResult = Product.Create(productModel.Name); if (productResult.Failure) { return(OperationResult.BadRequest <ProductModel>(productResult)); } if (await this.productQueryRepository.ProductExists(productModel.Name)) { return(OperationResult.NotFound <ProductModel>("Product already exists")); } this.productRepository.Add(productResult.Value); unitOfWork.Save(); var model = Mapper.Map <ProductModel>(productResult.Value); var indexResult = await indexService.IndexDocumentAsync(model); if (indexResult.Failure) { await Rollback(productResult.Value); return(OperationResult.InternalServerError <ProductModel>(indexResult)); } return(OperationResult.Created(model)); } catch (Exception ex) { return(OperationResult.InternalServerError <ProductModel>(ex)); } }
public async Task <Product> Create([FromBody] ProductCreationModel model) { return(await _productService.CreateProduct(model)); }
public ActionResult Edit(ProductCreationModel model, bool continueEditing) { if (!_permissionService.Authorize(StandardPermissionProvider.ManageProducts)) return AccessDeniedView(); var product = _productService.GetProductById(model.Id); if (product == null || product.Deleted) //No product found with the specified id return RedirectToAction("List"); //a vendor should have access only to his products if (_workContext.CurrentVendor != null && product.VendorId != _workContext.CurrentVendor.Id) return RedirectToAction("List"); if (ModelState.IsValid) { //a vendor should have access only to his products if (_workContext.CurrentVendor != null) { model.VendorId = _workContext.CurrentVendor.Id; } //vendors cannot edit "Show on home page" property if (_workContext.CurrentVendor != null && model.ShowOnHomePage != product.ShowOnHomePage) { model.ShowOnHomePage = product.ShowOnHomePage; } var prevStockQuantity = product.StockQuantity; //product product = model.ToEntity(product); product.UpdatedOnUtc = DateTime.UtcNow; _productService.UpdateProduct(product); //search engine name model.SeName = product.ValidateSeName(model.SeName, product.Name, true); _urlRecordService.SaveSlug(product, model.SeName, 0); //locales UpdateLocales(product, model); //tags SaveProductTags(product, ParseProductTags(model.ProductTags)); //ACL (customer roles) SaveProductAcl(product, model); //Stores SaveStoreMappings(product, model); //picture seo names UpdatePictureSeoNames(product); //discounts var allDiscounts = _discountService.GetAllDiscounts(DiscountType.AssignedToSkus, null, true); foreach (var discount in allDiscounts) { if (model.SelectedDiscountIds != null && model.SelectedDiscountIds.Contains(discount.Id)) { //new discount if (product.AppliedDiscounts.Count(d => d.Id == discount.Id) == 0) product.AppliedDiscounts.Add(discount); } else { //remove discount if (product.AppliedDiscounts.Count(d => d.Id == discount.Id) > 0) product.AppliedDiscounts.Remove(discount); } } _productService.UpdateProduct(product); _productService.UpdateHasDiscountsApplied(product); SaveVariant(product, model); product.Published = true; //back in stock notifications if (product.ManageInventoryMethod == ManageInventoryMethod.ManageStock && product.BackorderMode == BackorderMode.NoBackorders && product.AllowBackInStockSubscriptions && product.StockQuantity > 0 && prevStockQuantity <= 0 && product.Published && !product.Deleted) { _backInStockSubscriptionService.SendNotificationsToSubscribers(product); } //_productAttributeService.GetAllProductAttributes //activity log _customerActivityService.InsertActivity("EditProduct", _localizationService.GetResource("ActivityLog.EditProduct"), product.Name); SuccessNotification(_localizationService.GetResource("Admin.Catalog.Products.Updated")); if (continueEditing) { //selected tab SaveSelectedTabIndex(); return RedirectToAction("Edit", new { id = product.Id }); } else { return RedirectToAction("List"); } } //If we got this far, something failed, redisplay form PrepareProductModel(model, product, false, true); PrepareAclModel(model, product, true); PrepareStoresMappingModel(model, product, true); return View(model); }
public ActionResult Create(ProductCreationModel model, bool continueEditing) { if (!_permissionService.Authorize(StandardPermissionProvider.ManageProducts)) return AccessDeniedView(); if (ModelState.IsValid) { //a vendor should have access only to his products if (_workContext.CurrentVendor != null) { model.VendorId = _workContext.CurrentVendor.Id; } //vendors cannot edit "Show on home page" property if (_workContext.CurrentVendor != null && model.ShowOnHomePage) { model.ShowOnHomePage = false; } model.ShortDescription = String.Concat(model.FullDescription.Take(20)); model.SeName = model.Name.Replace(" ", "-"); //product var product = model.ToEntity(); product.CreatedOnUtc = DateTime.UtcNow; product.UpdatedOnUtc = DateTime.UtcNow; _productService.InsertProduct(product); //search engine name model.SeName = product.ValidateSeName(model.SeName, product.Name, true); _urlRecordService.SaveSlug(product, model.SeName, 0); //locales UpdateLocales(product, model); //ACL (customer roles) SaveProductAcl(product, model); //Stores SaveStoreMappings(product, model); //tags SaveProductTags(product, ParseProductTags(model.ProductTags)); //discounts var allDiscounts = _discountService.GetAllDiscounts(DiscountType.AssignedToSkus, null, true); foreach (var discount in allDiscounts) { if (model.SelectedDiscountIds != null && model.SelectedDiscountIds.Contains(discount.Id)) product.AppliedDiscounts.Add(discount); } _productService.UpdateProduct(product); _productService.UpdateHasDiscountsApplied(product); SaveVariant(product, model); //activity log _customerActivityService.InsertActivity("AddNewProduct", _localizationService.GetResource("ActivityLog.AddNewProduct"), product.Name); SuccessNotification(_localizationService.GetResource("Admin.Catalog.Products.Added")); return continueEditing ? RedirectToAction("Edit", new { id = product.Id }) : RedirectToAction("List"); } //If we got this far, something failed, redisplay form PrepareProductModel(model, null, false, true); PrepareAclModel(model, null, true); PrepareStoresMappingModel(model, null, true); return View(model); }
//create product public ActionResult Create() { if (!_permissionService.Authorize(StandardPermissionProvider.ManageProducts)) return AccessDeniedView(); var model = new ProductCreationModel(); PrepareProductModel(model, null, true, true); AddLocales(_languageService, model.Locales); PrepareAclModel(model, null, false); PrepareStoresMappingModel(model, null, false); return View(model); }
private void SaveVariant(Product product, ProductCreationModel model) { // Update list of product pictures foreach (string pictureID in model.pictureIDs.Split(',')) { if (pictureID != "" && pictureID != "0") { int PictureID = Convert.ToInt32(pictureID); if (product.ProductPictures.Where(x => x.PictureId == PictureID).Count() <= 0) { } } } foreach (var x in product.ProductPictures.ToList()) { if (model.pictureIDs.Contains(x.PictureId.ToString()) == false) { ProductPictureDelete(x.Id); } } List<ProductVariantDTO> variantObj = JsonConvert.DeserializeObject<List<ProductVariantDTO>>(model.variantTransfer); List<string> AttributeDTOList = new List<string>(); var AllProductAttributes = _productAttributeService.GetAllProductAttributes(); //get all possible attributes for incoming DTO foreach (var variant in variantObj) { foreach (var combination in variant.combinations) { if (AttributeDTOList.Where(x => x == combination.attribute).Count() == 0) { AttributeDTOList.Add(combination.attribute); } } } //get existing product variant attributes var attlist = ProductVariantAttributeListobj(new DataSourceRequest(), product.Id); var pvaValList = new List<ProductVariantAttributeValue>(); //delete all existing pva values foreach (var pva in attlist) { var pvavalues = _productAttributeService.GetProductVariantAttributeValues(pva.Id); foreach (var pvaval in pvavalues) { _productAttributeService.DeleteProductVariantAttributeValue(pvaval); } } //make sure all pvas are mapped foreach (var attribute in AttributeDTOList) { bool wasfound = false; foreach (var pva in attlist) { if (pva.ProductAttribute == attribute) { wasfound = true; } } //if not found insert new product variant attribute if (wasfound == false) { Nop.Admin.Models.Catalog.ProductModel.ProductVariantAttributeModel newPva = new Nop.Admin.Models.Catalog.ProductModel.ProductVariantAttributeModel(); var combo = variantObj.Where(x => x.combinations.Where(y => y.attribute == attribute).Count() == 1).Single(); newPva.ProductId = product.Id; newPva.ProductAttribute = attribute; newPva.IsRequired = true; newPva.TextPrompt = combo.combinations.Where(z => z.attribute == attribute).Single().textPrompt; newPva.ProductAttributeId = AllProductAttributes.Where(att => att.Name == attribute).Select(x => x.Id).Single(); ProductVariantAttributeInsert(newPva); } } //todo insert pva values for each combination in the dto for each variant var variantAttributeList = _productAttributeService.GetProductVariantAttributesByProductId(product.Id); foreach (var variant in variantAttributeList) { //variants from the dto that have this variant attribute/product attribute var obj = variantObj.Where(x => x.combinations.Where(y => y.attribute == variant.ProductAttribute.Name).Count() > 0); foreach (var dtovariant in obj) { var pvav = new ProductVariantAttributeValue() { ProductVariantAttributeId = variant.Id, AssociatedProductId = variant.ProductId, Name = variant.ProductAttribute.Name, PriceAdjustment = dtovariant.priceAdjustment, Cost = product.ProductCost, Quantity = dtovariant.quantity, IsPreSelected = true, }; _productAttributeService.InsertProductVariantAttributeValue(pvav); } } //Once all new product variant attribute values are in place generate combinations and substitue DTO data var allAttributesXml = _productAttributeParser.GenerateAllCombinations(product); foreach (var attributesXml in allAttributesXml) { var existingCombination = _productAttributeParser.FindProductVariantAttributeCombination(product, attributesXml); //already exists? if (existingCombination != null) continue; //new one var warnings = new List<string>(); warnings.AddRange(_shoppingCartService.GetShoppingCartItemAttributeWarnings(_workContext.CurrentCustomer, ShoppingCartType.ShoppingCart, product, 1, attributesXml)); if (warnings.Count != 0) continue; //save combination var combination = new ProductVariantAttributeCombination() { ProductId = product.Id, AttributesXml = attributesXml, StockQuantity = 10000, AllowOutOfStockOrders = false, Sku = null, ManufacturerPartNumber = null, Gtin = null, OverriddenPrice = null }; _productAttributeService.InsertProductVariantAttributeCombination(combination); } }