public async Task <Product> PostProduct(ProductPostRequest product) { var productAdded = _mapper.Map <Product>(product); productAdded.createdDate = productAdded.updatedDate = DateTime.Now; if (product.ImageFiles != null) { foreach (IFormFile file in product.ImageFiles) { productAdded.Images.Add(new Image { productId = productAdded.productId, imageUrl = await _filesService.SaveFilePath(file) }); } } try { _context.Add(productAdded); await _context.SaveChangesAsync(); var productAdded4Real = await GetProductByID(productAdded.productId); return(productAdded4Real); } catch (System.Exception e) { return(null); } }
public async Task <Product> PutProduct(int id, ProductPostRequest product) { var productToBeUpdated = await _context.Products.Include(prod => prod.Category).FirstOrDefaultAsync(prod => prod.productId == id); if (productToBeUpdated is null) { return(null); } if (product.ImageFiles != null) { productToBeUpdated.Images = new List <Image>(); //reset to zero image foreach (IFormFile file in product.ImageFiles) { productToBeUpdated.Images.Add(new Image { productId = productToBeUpdated.productId, imageUrl = await _filesService.SaveFilePath(file) }); } } try { _context.Entry(productToBeUpdated).CurrentValues.SetValues(product); productToBeUpdated.updatedDate = DateTime.Now; productToBeUpdated.Category = await _context.Categories.FindAsync(product.categoryId); await _context.SaveChangesAsync(); return(productToBeUpdated); } catch (System.Exception e) { return(null); } }
public async Task UpdateDatabaseLocalToServer() { try { var dataSync = await App.DatabaseSyncronizeData.GetAll(); bool hasChanged = dataSync.Last()?.HasChanged ?? true; // Consulta a versao sincronizada para verificar se a necessidade para sincronizar if (await SyncNeeded() || hasChanged) { // Consulta a base local var products = await App.DatabaseProduct.GetAll(); // Salvar os dados da base local na base da API var request = new ProductPostRequest { Products = products }; var productResult = await _httpService.Post <ProductPostRequest, ProductPostResponse>(HttpConfiguration.URL_PRODUCT, request); // Salva a versão da base de dados sincronizada com o server await SyncDataChanged(false, productResult.Version); await App.Current.MainPage.DisplayAlert("Sincronização", "Sincronizado com sucesso.", "OK"); } } catch (Exception) { await App.Current.MainPage.DisplayAlert("Aviso", "Salvo com sucesso, será feita a sincronização quando tiver internet.", "OK"); } }
public async Task <IActionResult> Post([FromBody] ProductPostRequest request) { var productCommand = new RegisterProductCommand(request.Id, request.StockBalance, request.Name, request.Active); // await _mediator.Send(productCommand); var f = await _mediatorHandler.SendCommand(productCommand); return(Ok(f)); }
public async Task <ActionResult <IEnumerable <Product> > > PostProduct([FromForm] ProductPostRequest request) { var product = await _productService.PostProduct(request); if (product != null) { return(CreatedAtAction(nameof(GetProduct), new { id = product.productId }, product)); } else { return(NotFound()); } }
public async Task <ProductDTO> CreateAsync(ProductPostRequest model, ApiDbContext apiDbContext) { try { var productFound = apiDbContext.Products.FirstOrDefault(p => p.Code.ToUpper().Trim().Equals(model.Code.ToUpper().Trim())); if (productFound != null) { throw new Exception($"Ya existe un producto con el código {model.Code}"); } Stock stock = new Stock { Avaliable = model.Stock, UpdatedDate = DateTime.Now }; Product newProduct = new Product { Code = model.Code, Name = model.Name, Description = model.Description, IsActive = model.IsActive, Price = model.Price, Tax = model.Tax, Pvp = model.Pvp, CreationDate = DateTime.Now, ShopId = model.ShopId, ProviderId = model.ProviderId, Stock = stock }; model.CategoryIdList.ForEach(id => { newProduct.Product_Categories.Add(new Product_Category { CategoryId = id, Product = newProduct }); }); await apiDbContext.Products.AddAsync(newProduct); await apiDbContext.SaveChangesAsync(); return(ModelToDTO(newProduct)); } catch (Exception e) { throw new Exception(e.Message); } }
public async Task <ActionResult <Product> > PutProduct(int id, [FromForm] ProductPostRequest request) { var product = await _productService.PutProduct(id, request); if (product is null) { return(BadRequest()); } foreach (var prodImg in product.Images) { prodImg.imageUrl = _fileService.GetFileUrl(prodImg.imageUrl); } return(Ok(product)); }
public async Task <IActionResult> Create(ProductPostRequest model) { try { if (!ModelState.IsValid) { throw new Exception("Petición de alta inválida"); } return(Ok(await _productService.CreateAsync(model, _apiDbContext))); } catch (Exception e) { return(StatusCode(500, e.Message)); } }
/// <summary> /// Upload file handler /// </summary> /// <param name="model"></param> /// <returns></returns> private string UploadedFile(ProductPostRequest model) { string uniqueFileName = null; if (model.PhotoPath != null) { string uploadsFolder = Path.Combine(_hostingEnvironment.WebRootPath, "uploads"); uniqueFileName = Guid.NewGuid().ToString() + "_" + model.PhotoPath.FileName; string filePath = Path.Combine(uploadsFolder, uniqueFileName); using (var fileStream = new FileStream(filePath, FileMode.Create)) { model.PhotoPath.CopyTo(fileStream); } } return(uniqueFileName); }
/// <summary> /// Set default nullable field /// </summary> /// <param name="product"></param> private void SetEmptyNullableField(ProductPostRequest product) { if (string.IsNullOrEmpty(product.QuantityPerUnit)) { product.QuantityPerUnit = ""; } if (product.UnitPrice <= 0) { product.UnitPrice = -1; } if (string.IsNullOrEmpty(product.Descriptions)) { product.Descriptions = ""; } }
public ApiResponse <Product> SaveProduct([FromBody] ProductPostRequest postRequest) { Product prod = new Product() { Id = Guid.NewGuid(), Name = postRequest.ProductName, Description = postRequest.Description }; var response = new ApiResponse <Product>() { Data = prod, Error = null, Status = System.Net.HttpStatusCode.OK }; return(response); }
/// <summary> /// Validate whether exist null product field /// </summary> /// <param name="product"></param> private void CheckNotNull(ProductPostRequest product) { if (string.IsNullOrEmpty(product.ProductName)) { ModelState.AddModelError("ProductName", "Company name expected"); } if (product.CategoryID <= 0) { ModelState.AddModelError("CategoryID", "Category expected"); } if (product.SupplierID <= 0) { ModelState.AddModelError("SupplierID", "Supplier expected"); } if (ModelState.ErrorCount > 0) { throw new MissingFieldException(); } }
public IActionResult AddProduct(string name, string longDescription, string shortDescription, double originalPrice, double actualPrice, bool isLive, string?size1, string?size2, string?size3, string?size4, string?size5, int?value1, int?value2, int?value3, int?value4, int?value5, int categoryId, IFormFile file) { List <ProductQuantity> size = new List <ProductQuantity>(); int quantity = 0; if (!String.IsNullOrEmpty(size1) && value1.HasValue) { size.Add(new ProductQuantity { Size = size1, Quantity = value1.Value }); quantity += value1.Value; } if (!String.IsNullOrEmpty(size2) && value2.HasValue) { size.Add(new ProductQuantity { Size = size2, Quantity = value2.Value }); quantity += value2.Value; } if (!String.IsNullOrEmpty(size3) && value3.HasValue) { size.Add(new ProductQuantity { Size = size3, Quantity = value3.Value }); quantity += value3.Value; } if (!String.IsNullOrEmpty(size4) && value4.HasValue) { size.Add(new ProductQuantity { Size = size4, Quantity = value4.Value }); quantity += value4.Value; } if (!String.IsNullOrEmpty(size5) && value5.HasValue) { size.Add(new ProductQuantity { Size = size5, Quantity = value5.Value }); quantity += value5.Value; } ProductRequest request = new ProductRequest { Name = name, ProductSKU = Guid.NewGuid().ToString(), LongDescription = longDescription, ShortDescription = shortDescription, OriginalPrice = originalPrice, ActualPrice = actualPrice, IsLive = isLive, ImagePath = "", Size = size, CategoryId = categoryId }; ProductPostRequest productPost = new ProductPostRequest(request, file); ProductPostManager ppm = new ProductPostManager(_clientFactory, _contextAccessor); ppm.Post(request, file); return(RedirectToAction("Index")); }
public IActionResult Input(ProductPostRequest model, ProductAttribute attribute, List <ProductAttribute> lstAttribute, string id = "", string query = "") { if (query != null && query == "AddAttribute") { // Attribute POST CatalogBLL.AddProductAttribute(attribute); return(RedirectToAction("Input", new { id = id })); } else { // Product POST try { CheckNotNull(model); SetEmptyNullableField(model); string photoPath = UploadedFile(model); photoPath = string.IsNullOrEmpty(id) ? "" : string.IsNullOrEmpty(photoPath) ? CatalogBLL.GetProduct(Convert.ToInt32(id)).PhotoPath : photoPath; Product newProduct = new Product() { ProductID = model.ProductID, ProductName = model.ProductName, SupplierID = model.SupplierID, CategoryID = model.CategoryID, QuantityPerUnit = model.QuantityPerUnit, UnitPrice = model.UnitPrice, Descriptions = model.Descriptions, PhotoPath = photoPath }; // Save data into DB if (newProduct.ProductID == 0) { CatalogBLL.AddProduct(newProduct); } else { CatalogBLL.UpdateProduct(newProduct); } return(RedirectToAction("Index")); } catch (MissingFieldException) { Product errorProduct = new Product() { ProductID = model.ProductID, ProductName = model.ProductName, SupplierID = model.SupplierID, CategoryID = model.CategoryID, QuantityPerUnit = model.QuantityPerUnit, UnitPrice = model.UnitPrice, Descriptions = model.Descriptions, }; return(View(errorProduct)); } catch (Exception ex) { _logger.LogError(ex.Message + ": " + ex.StackTrace); return(View(model)); } } }
public async Task Post([FromBody] ProductPostRequest request) { await _productPostCommand.AddProductAsync(request.ProductId, request.PersonId); }