public async Task <ServiceResponse <GetProductDto> > GetProductById(int productId) { Product product; try { //FirstOrDefaultAsync(x=> x.Id == productId) >>>> select with condition product = await _dBContext.Products.Include(x => x.ProductGroup).FirstOrDefaultAsync(x => x.Id == productId); } catch (System.Exception ex) { //Write log _log.LogError($"Get ProductById({productId}) is error detail: {ex.Message}"); //Return return(ResponseResult.Failure <GetProductDto>($"{productId} is error to find")); } //Validate if null if (product != null) { //mapping and return result GetProductDto productDto = _mapper.Map <GetProductDto>(product); return(ResponseResult.Success(productDto)); } else { //return not found result return(ResponseResult.Failure <GetProductDto>($"{productId} is not found")); } }
public async Task <Product> GetById(int Id) { var product = await _context.Products.FindAsync(Id); List <int> ingredientsId = await _context.IngredientFromProductProducts .Where(p => p.ProductsId == Id) .Select(p => p.IngredientsId) .ToListAsync(); GetProductDto productDto = new GetProductDto() { Id = product.Id, Name = product.Name, Description = product.Description, Price = product.Price, Discount = product.Discount }; foreach (int i in ingredientsId) { IngredientsFromProduct ingredient = await _context .IngredientsFromProducts .FindAsync(i); productDto.Ingredients .Add(new GetIngredientDto() { Id = ingredient.Id, Name = ingredient.Name }); } return(product); }
public async Task <ServiceResponse <GetProductDto> > DeleteProduct(int deleteProduct) { try { var product = _dbContext.Products.Where(x => x.Id == deleteProduct); if (product is null) { var msg = $"This Product Id {deleteProduct} not found."; _log.LogError(msg); return(ResponseResult.Failure <GetProductDto>(msg)); } _dbContext.Products.RemoveRange(product); await _dbContext.SaveChangesAsync(); var dto = new GetProductDto { Id = deleteProduct }; _log.LogInformation("Delete Product done."); return(ResponseResult.Success(dto, "success")); } catch (Exception ex) { _log.LogError(ex.Message); return(ResponseResult.Failure <GetProductDto>(ex.Message)); } }
public ProductRetrievedEvent(GetProductDto product) { if (product != null) { ProductDto = new GetProductDto(product.Id, product.Code, product.Name, product.Description, product.Photo, product.PhotoName, product.Price, product.LastUpdated, product.BlobName); } }
public GetProductQueryHandlerTest() { mapper = new Mock <IMapper>(); productRepository = new Mock <IProductRepository>(); query = new GetProductQuery(productId); queryHandler = new GetProductQueryHandler(productRepository.Object, mapper.Object); product = new Product { ProductName = productName }; productDto = new GetProductDto { ProductName = productName }; }
public async Task <FileResult> Download() { StringBuilder result = new StringBuilder(); var products = repository.GetAll(); List <GetProductDto> listProducts = new List <GetProductDto>(); foreach (var product in products) { List <int> ingredientsId = await context.IngredientFromProductProducts .Where(p => p.ProductsId == product.Id) .Select(p => p.IngredientsId) .ToListAsync(); GetProductDto productDto = new GetProductDto() { Id = product.Id, Name = product.Name, Description = product.Description, Price = product.Price, Discount = product.Discount }; foreach (int i in ingredientsId) { IngredientsFromProduct ingredient = await context .Ingredients .FindAsync(i); productDto.Ingredients .Add(new GetIngredientDto() { Id = ingredient.Id, Name = ingredient.Name }); } listProducts.Add(productDto); } result.Append("Id, Name, Description, Price, Discount\n"); foreach (GetProductDto p in listProducts) { result.Append(String.Format("{0}, {1}, {2}, {3}, {4}\n", p.Id, p.Name, p.Description, p.Price, p.Discount)); } string fileName = "Products.csv"; byte[] fileBytes = Encoding.ASCII.GetBytes(result.ToString()); return(File(fileBytes, "text/csv", fileName)); // this is the key! }
public async Task <GetProductDto> GetById(int id) { var product = await _repository.FindById(id); ThrowExceptionIfProductNotExists(product, id); var getProductDto = new GetProductDto { Id = product.Id, Title = product.Title, MinimumStock = product.MinimumStock, ProductCode = product.ProductCode, ProductCategoryId = product.ProductCategoryId }; return(getProductDto); }
public async Task <ServiceResponse <GetProductDto> > EditProduct(EditProductDto editProduct) { //Find product from id var product = await _dBContext.Products.Include(x => x.ProductGroup).FirstOrDefaultAsync(x => x.Id == editProduct.Id); //return if not found if (product == null) { return(ResponseResult.Failure <GetProductDto>($"Product Id '{editProduct.Id}' is not found")); } var productGrp = await _dBContext.ProductGroups.FirstOrDefaultAsync(x => x.Id == editProduct.ProductGroupId); if (productGrp == null) { return(ResponseResult.Failure <GetProductDto>($"ProductGroup Id {editProduct.ProductGroupId} is not found")); } //let's update data try { product.Name = editProduct.Name; product.Price = editProduct.Price; product.ProductGroupId = editProduct.ProductGroupId; product.StockCount = editProduct.StockCount; product.IsActive = editProduct.IsActive; //code update data _dBContext.Update(product); //Save update above await _dBContext.SaveChangesAsync(); //Get productDto to return GetProductDto prodDto = _mapper.Map <GetProductDto>(product); return(ResponseResult.Success(prodDto)); } catch (System.Exception ex) { //Write log _log.LogError($"Update product is error detail: {ex.Message}"); //Return return(ResponseResult.Failure <GetProductDto>($"Update product error detail: {ex.Message}")); } }
public async Task <IActionResult> GetProducts(GetProductDto getProductDto) { try { var result = await _productService.GetProductByCategoryAndProducer( getProductDto.CategoryProductId, getProductDto.ProducerId); if (!result.Any()) { return(NotFound("Nenhum produto encontrado")); } return(Ok(result)); } catch (Exception ex) { #if (!DEBUG) _logger.Fatal($"lista de produtos por categoria e fabricante no admin Usuario com id {UserId} - {ex.ToLogString(Environment.StackTrace)}"); #endif return(BadRequest($"lista de produtos por categoria e fabricante no admin Usuario com id {UserId} - {ex.ToLogString(Environment.StackTrace)}")); } }
/// <summary> /// Get product by id /// </summary> /// <param name="productId"></param> /// <returns></returns> public async Task <GetProductDto> GetProduct(string productId) { GetProductDto response = null; try { var product = _repository.Product.GetProductById(Guid.Parse(productId)); if (product != null) { response = new GetProductDto(product.Id, product.Code, product.Name, product.Description, null, product.PhotoName, product.Price, product.LastUpdated.ToString(), product.BlobName); return(await Task.Run(() => response)); } return(await Task.Run(() => response)); } catch (Exception e) { Console.WriteLine(e); return(await Task.Run(() => GetProductDto.PrepareExceptionResponse(Guid.Empty, "ERROR_SYSTEM"))); } }
public async Task <IEnumerable <GetProductDto> > GetAll() { List <Product> products = await _context.Products.ToListAsync(); List <GetProductDto> productDtos = new List <GetProductDto>(); foreach (Product product in products) { List <int> ingredientsId = await _context.IngredientFromProductProducts .Where(p => p.ProductsId == product.Id) .Select(p => p.IngredientsId) .ToListAsync(); GetProductDto productDto = new GetProductDto() { Id = product.Id, Name = product.Name, Description = product.Description, Price = product.Price, Discount = product.Discount }; foreach (int i in ingredientsId) { IngredientsFromProduct ingredient = await _context .IngredientsFromProducts .FindAsync(i); productDto.Ingredients .Add(new GetIngredientDto() { Id = ingredient.Id, Name = ingredient.Name }); } productDtos.Add(productDto); } return(productDtos); }
public async Task <ServiceResponse <GetProductDto> > AddProduct(AddProductDto newProduct) { try { //validate product var prodGrp = _dBContext.ProductGroups.FirstOrDefault(x => x.Id == newProduct.ProductGroupId); if (prodGrp is null) { return(ResponseResult.Failure <GetProductDto>($"ProductGroup Id '{newProduct.ProductGroupId}' not found")); } //Validate duplicate var prodDb = await _dBContext.Products.FirstOrDefaultAsync(x => x.Name == newProduct.Name); if (prodDb != null) { return(ResponseResult.Failure <GetProductDto>($"Product name '{newProduct.Name}' is duplicate")); } Product prod = new Product(); prod.Name = newProduct.Name; prod.Price = newProduct.Price; prod.ProductGroupId = newProduct.ProductGroupId; prod.StockCount = newProduct.StockCount; prod.IsActive = newProduct.IsActive; prod.CreateById = Guid.Parse(GetUserId()); prod.CreatedDate = Now(); //var prodDB = _mapper.Map<Product>(newProduct); _dBContext.Products.Add(prod); await _dBContext.SaveChangesAsync(); var dto = _mapper.Map <GetProductDto>(prod); //Update movement stock Models.MovementStock stockDb = new Models.MovementStock(); stockDb.ProductId = dto.Id; stockDb.MovementTypeId = 1; stockDb.Quantity = newProduct.StockCount; stockDb.QuantityOld = prod.StockCount; stockDb.CreateById = Guid.Parse(GetUserId()); stockDb.CreateDate = Now(); stockDb.ExpiredDate = Now(); stockDb.Remark = "Add new product with add StockCount"; _dBContext.MovementStocks.Add(stockDb); await _dBContext.SaveChangesAsync(); Product saveProd = await _dBContext.Products.Include(x => x.ProductGroup).FirstOrDefaultAsync(x => x.Name == prod.Name); GetProductDto prodDto = _mapper.Map <GetProductDto>(saveProd); return(ResponseResult.Success(prodDto)); } catch (System.Exception ex) { //Write log _log.LogError($"AddProduct is error detail: {ex.Message}"); //Return return(ResponseResult.Failure <GetProductDto>($"AddProduct error detail: {ex.Message}")); } }