예제 #1
0
        public async Task <IHttpActionResult> PostProduct(ProductDetailsDto productDetails)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            var workwrok = productDetails.ProductGroups;
            List <ProductGroup> productGroups = new List <ProductGroup>();

            foreach (var i in workwrok)
            {
                var pG = from pg in db.ProductGroups where pg.Id == i select pg;
                pG.ForEach(pg => productGroups.Add(pg));
            }

            var product = new Product(productDetails.Name, productDetails.Price, productDetails.Saleable);

            productGroups?.ForEach(e => product.ProductGroups.Add(e));

            db.Products.Add(product);
            await db.SaveChangesAsync();

            productDetails.Id = product.Id;

            return(CreatedAtRoute("DefaultApi", new { id = productDetails.Id }, productDetails));
        }
예제 #2
0
        public async Task <IHttpActionResult> GetProduct(long id)
        {
            //var product = await db.Products.Include(p => p.ProductGroups).Select(p =>
            //    new ProductDetailsDto()
            //    {
            //        Id = p.Id,
            //        Name = p.Name,
            //        Price = p.Price,
            //        Saleable = p.Saleable,
            //        ProductGroups = new List<ProductGroup>()
            //    }).SingleOrDefaultAsync(p => p.Id == id);

            var pm = await db.Products.Include(p => p.ProductGroups).SingleOrDefaultAsync(p => p.Id == id);

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

            var productDto = new ProductDetailsDto {
                Id = pm.Id, Name = pm.Name, Price = pm.Price, Saleable = pm.Saleable, ProductGroups = new List <long>()
            };

            pm.ProductGroups.ForEach(pg => productDto.ProductGroups.Add(pg.Id));

            return(Ok(productDto));
        }
예제 #3
0
        public async Task <ActionResult> Post(ProductDetailsDto product)
        {
            product.Id = Guid.NewGuid();
            await _productService.AddAsync(product);

            return(CreatedAtAction(nameof(Get), new { id = product.Id }, null));
        }
예제 #4
0
        //get product details and display in frontend
        public IEnumerable <ProductDetailsDto> GetProductDetails(int categoryId)
        {
            var productDetails = new List <ProductDetailsDto>();
            var productTypes   = appDbContext.ProductType.Where(x => x.CategoryId == categoryId).ToList();

            foreach (var productType in productTypes)
            {
                var products = appDbContext.Product.Where(x => x.ProductTypeId == productType.Id).ToList();
                foreach (var product in products)
                {
                    var type          = appDbContext.ProductType.Where(x => x.Id == product.ProductTypeId).FirstOrDefault();
                    var productDetail = new ProductDetailsDto
                    {
                        ProductType   = type.ProdType,
                        ProductId     = product.Id,
                        ProductName   = product.ProductName,
                        Specification = product.Specification,
                        Description   = product.Description,
                        Picture       = product.Picture,
                        Price         = product.Price,
                        InStock       = product.InStock
                    };
                    productDetails.Add(productDetail);
                }
            }
            var jsonstring = Newtonsoft.Json.JsonConvert.SerializeObject(productDetails);

            return(productDetails);
        }
예제 #5
0
        public ActionResult <ProductDetailsDto> GetProduct(int productId)
        {
            var product = productService.GetProductById(productId);

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

            ICollection <byte[]> imagesBase64 = new List <byte[]>();

            foreach (var img in product.ProductImages)
            {
                imagesBase64.Add(img.ImageBase64);
            }

            //Could be optimized with IMapper
            ProductDetailsDto productDetails = new ProductDetailsDto
            {
                Description         = product.Description,
                Id                  = product.Id, Name = product.Name,
                Price               = product.Price,
                ProductImagesBase64 = imagesBase64
            };


            return(Ok(productDetails));
        }
        private Product MapToData(Product product, ProductDetailsDto productDetails)
        {
            product.Name     = productDetails.Name;
            product.Category = productDetails.Category;

            return(product);
        }
 public static void CopyFromEntity(ProductDetailsDto dto, Product product)
 {
     dto.product_id            = product.ProdID; // product_description
     dto.product_name          = product.ProductName;
     dto.position              = product.Position;
     dto.product_image         = ImagePathService.productImagePath + product.ProductImage;
     dto.product_image_details = ImagePathService.productImagePath + product.ProductImageDetails;
     dto.tube_price            = product.TubePrice;
     dto.tube_promo_price      = product.TubePromoPrice;
     dto.refill_price          = product.RefillPrice;
     dto.refill_promo_price    = product.RefillPromoPrice;
     dto.shipping_price        = product.ShippingPrice;
     dto.shipping_promo_price  = product.ShippingPromoPrice;
     if (product.ProductExchanges.Count > 0)
     {
         dto.has_exchange = true;
         dto.exchange     = new ExchangeDto[product.ProductExchanges.Count];
         var prdExchanges = product.ProductExchanges.ToList();
         for (int i = 0; i < product.ProductExchanges.Count; i++)
         {
             ExchangeDto exDto = new ExchangeDto();
             exDto.exchange_id          = prdExchanges[i].PrExID;
             exDto.exchange_with        = prdExchanges[i].ExchangeWith;
             exDto.exchange_quantity    = prdExchanges[i].ExchangeQuantity;
             exDto.exchange_price       = prdExchanges[i].ExchangePrice.Value;
             exDto.exchange_promo_price = prdExchanges[i].ExchangePromoPrice;
             dto.exchange[i]            = exDto;
         }
     }
 }
        public ActionResult <ProductDto> Post([FromBody] ProductDetailsDto productDetails)
        {
            var product = _productsService.Add(productDetails);

            return(Created(
                       Url.Action(nameof(Get), ControllerContext.ActionDescriptor.ControllerName, new { product.Id }),
                       product));
        }
예제 #9
0
        public async Task <ProductDetailsDto> GetProductInfo(string upcInput)
        {
            string responseString = await _httpClientService.GetHttpClientJsonResponse(_remoteUrl + upcInput);

            ProductDetailsDto productDetails = JsonConvert.DeserializeObject <ProductDetailsDto>(responseString);

            return(productDetails);
        }
예제 #10
0
        public ProductDto Add(ProductDetailsDto productDetails)
        {
            var product = MapToData(productDetails);

            _context.Products.Add(product);
            _context.SaveChanges();

            return(MapToDto(product));
        }
예제 #11
0
        public async Task <IHttpActionResult> PutProduct(long id, ProductDetailsDto productDetails)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            var ProductGroupList = productDetails.ProductGroups;
            List <ProductGroup> productGroups = new List <ProductGroup>();

            foreach (var i in ProductGroupList)
            {
                var pG = from pg in db.ProductGroups where pg.Id == i select pg;
                pG.ForEach(pg => productGroups.Add(pg));
            }

            var product = db.Products.Find(id);

            if (product != null)
            {
                product.Name     = productDetails.Name;
                product.Price    = productDetails.Price;
                product.Saleable = productDetails.Saleable;
            }

            product.ProductGroups.Clear();

            productGroups?.ForEach(e => product.ProductGroups.Add(e));

            if (id != product.Id)
            {
                return(BadRequest());
            }

            db.Set <Product>().Attach(product);
            db.Entry(product).State = EntityState.Modified;

            try
            {
                await db.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!ProductExists(id))
                {
                    return(NotFound());
                }
                else
                {
                    throw;
                }
            }

            return(StatusCode(HttpStatusCode.NoContent));
        }
예제 #12
0
        public async Task<IHttpActionResult> PutProduct(long id, ProductDetailsDto productDetails)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            var ProductGroupList = productDetails.ProductGroups;
            List<ProductGroup> productGroups = new List<ProductGroup>();

            foreach (var i in ProductGroupList)
            {
                var pG = from pg in db.ProductGroups where pg.Id == i select pg;
                pG.ForEach(pg => productGroups.Add(pg));
            }

            var product = db.Products.Find(id);

            if (product != null)
            {
                product.Name = productDetails.Name;
                product.Price = productDetails.Price;
                product.Saleable = productDetails.Saleable;
            }

            product.ProductGroups.Clear();

            productGroups?.ForEach(e => product.ProductGroups.Add(e));

            if (id != product.Id)
            {
                return BadRequest();
            }

            db.Set<Product>().Attach(product);
            db.Entry(product).State = EntityState.Modified;

            try
            {
                await db.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!ProductExists(id))
                {
                    return NotFound();
                }
                else
                {
                    throw;
                }
            }

            return StatusCode(HttpStatusCode.NoContent);
        }
예제 #13
0
        public async Task <ActionResult> OnGetAsync(Guid id)
        {
            Product = await _dispatcher.QueryAsync(new GetProduct(id));

            if (Product is null)
            {
                return(NotFound());
            }

            return(Page());
        }
예제 #14
0
        public async Task <IActionResult> GetProductBySlug(string slug)
        {
            var product = await _productsService.GetProductBySlug(slug);

            if (product == null)
            {
                return(StatusCodeAndDtoWrapper.BuildNotFound(new ErrorDtoResponse("Not Found")));
            }

            return(new StatusCodeAndDtoWrapper(ProductDetailsDto.Build(product)));
        }
예제 #15
0
        public async Task <IActionResult> OnGetAsync(Guid id)
        {
            Product = await _productService.GetAsync(id);

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

            return(Page());
        }
예제 #16
0
        public async Task <IActionResult> GetProductById(long id)
        {
            var product = await _productsService.FetchById(id);

            if (product == null)
            {
                return(StatusCodeAndDtoWrapper.BuildNotFound(new ErrorDtoResponse("Not Found")));
            }

            return(StatusCodeAndDtoWrapper.BuildGeneric(ProductDetailsDto.Build(product)));
        }
예제 #17
0
        public async Task <IActionResult> UpdateProduct(string slug, [FromBody] CreateOrEditProduct dto)
        {
            if (!ModelState.IsValid)
            {
                return(StatusCodeAndDtoWrapper.BuilBadRequest(ModelState));
            }


            Product product = await _productsService.Update(slug, dto);

            return(StatusCodeAndDtoWrapper.BuildSuccess(ProductDetailsDto.Build(product), "Updated successfully"));
        }
예제 #18
0
        public async Task UpdateAsync(ProductDetailsDto productDto)
        {
            var product = await _productRepository.GetAsync(productDto.Id);

            if (product == null)
            {
                throw new ArgumentException($"Product with id: '{productDto.Id}' " +
                                            "was not found", nameof(productDto.Id));
            }

            product.SetDescription(productDto.Description);
            await _productRepository.UpdateAsync(product);
        }
예제 #19
0
        public async Task Get()
        {
            var expectedId = 123;
            var response   = new ProductDetailsDto();

            _mockMediator.Setup(x => x.Send(It.Is <GetProductDetailsQuery>(q => q.Id == expectedId), It.IsAny <CancellationToken>()))
            .ReturnsAsync(response);

            var result = await _sut.Get(expectedId);

            Assert.IsAssignableFrom <OkObjectResult>(result.Result);
            Assert.AreEqual(response, ((OkObjectResult)result.Result).Value);
        }
예제 #20
0
        public void Update(Guid id, ProductDetailsDto productDetails)
        {
            var product = _context.Products.SingleOrDefault(p => p.Id == id);

            if (product == null)
            {
                throw new NotFoundException();
            }

            MapToData(product, productDetails);

            _context.SaveChanges();
        }
        public ActionResult <ProductDto> Put(Guid id, [FromBody] ProductDetailsDto productDetails)
        {
            try
            {
                _productsService.Update(id, productDetails);
            }
            catch (NotFoundException)
            {
                NotFound();
            }

            return(NoContent());
        }
예제 #22
0
        public async Task <IActionResult> Create(string name, string description, int price, int stock,
                                                 List <IFormFile> images)
        {
            if (!(await _usersService.IsAdmin()))
            {
                return(StatusCodeAndDtoWrapper.BuildUnauthorized("Only admin user can create prodcuts"));
            }

            // If the user sends `images` POST param then the list<IFormFile> will be populated, if the user sends `images[]` instead, then it will be empty
            // this is why I populate that list with this little trick
            if (images?.Count == 0)
            {
                images = Request.Form.Files.GetFiles("images[]").ToList();
            }

            List <Tag>      tags       = new List <Tag>();
            List <Category> categories = new List <Category>();

            foreach (string formKey in Request.Form.Keys)
            {
                Regex regex = new Regex("tags|categories\\[(?<name>\\w+)\\]");
                Match match = regex.Match(formKey);
                if (match.Success && formKey.StartsWith("tag"))
                {
                    var tagName = match.Groups["name"].Value;
                    tags.Add(new Tag
                    {
                        Name        = tagName,
                        Description = Request.Form[key: formKey].ToString()
                    });
                }

                if (match.Success && formKey.StartsWith("cate"))
                {
                    var categoryName = match.Groups["name"].Value;
                    categories.Add(new Category
                    {
                        Name        = categoryName,
                        Description = Request.Form[key: formKey].ToString()
                    });
                }
            }


            Product product = await _productsService.Create(name, description, price, stock, tags, categories, images);

            return(StatusCodeAndDtoWrapper.BuildSuccess(ProductDetailsDto.Build(product)));
        }
 public async Task InsertProductDetails(int WaybillId, int OrderRefID, ProductDetailsDto ProductDetailsDto)
 {
     await Repository.InsertAsync(new OrderDetails
     {
         OrderRefID   = OrderRefID,
         WaybillId    = WaybillId,
         ProductSKU   = ProductDetailsDto.ProductSKU,
         ProductImage = ProductDetailsDto.ProductImage,
         ProductName  = ProductDetailsDto.ProductName,
         Description  = ProductDetailsDto.Description,
         Quantity     = ProductDetailsDto.Quantity,
         UnitCost     = ProductDetailsDto.UnitCost,
         CurrenyCode  = ProductDetailsDto.CurrenyCode,
         Returndate   = ProductDetailsDto.Returndate,
         Canceldate   = ProductDetailsDto.Canceldate,
     });
 }
예제 #24
0
        public static ProductDetailsDto ToProductDetailsDto(this ProductDetails product)
        {
            var result = new ProductDetailsDto();

            result.Id               = product.Id;
            result.Name             = product.Name;
            result.Description      = product.Description;
            result.ShortDescription = product.ShortDescription;
            result.ReleaseDate      = product.ReleaseDate;
            result.Model            = product.Model;
            result.Dimensions       = product.Dimensions;
            result.Price            = product.Price;
            result.Code             = product.Code;
            result.Brand            = product.Brand;
            result.Image            = product.Image;
            return(result);
        }
        public void AddOrUpdateProduct(ProductDetailsDto product)
        {
            ProductDetails entityProduct = new ProductDetails();

            if (product.Code != null)
            {
                entityProduct = productDetailsRepository.GetAll().FirstOrDefault(it => it.Code == product.Code);
                entityProduct.FromProductDetailsDto(product);
                productDetailsRepository.Update(entityProduct);
            }
            else
            {
                product.Code = Guid.NewGuid().ToString();;
                //  entityProduct = productDetailsRepository.GetAll().FirstOrDefault(it => it.TokenGuid == product.TokenGuid);
                entityProduct.FromProductDetailsDto(product);
                productDetailsRepository.Insert(entityProduct);
            }
            productDetailsRepository.Save();
        }
예제 #26
0
        public async Task <IHttpActionResult> PutProductAsync(int id, ProductDetailsDto product)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            //try
            //{
            //    db.Entry(productReviewMapper.Map<Product>(product)).State = EntityState.Modified;
            //}
            //catch (Exception ex)
            //{
            //    if (!ProductExists(id))
            //    {
            //        return NotFound();
            //    }
            //    else
            //    {
            //        throw;
            //    }
            //}

            try
            {
                await db.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!ProductExists(id))
                {
                    return(NotFound());
                }
                else
                {
                    throw;
                }
            }

            return(StatusCode(HttpStatusCode.NoContent));
        }
예제 #27
0
        public async Task given_valid_data_product_should_be_created()
        {
            var httpClient = _factory.CreateClient();

            var productDto = new ProductDetailsDto
            {
                Id          = Guid.NewGuid(),
                Name        = "iphone",
                Category    = "phones",
                Price       = 4000,
                Description = "test"
            };

            var response = await httpClient.PostAsJsonAsync("/api/products", productDto);

            response.EnsureSuccessStatusCode();
            response.StatusCode.Should().Be(HttpStatusCode.Created);
            var productUrl = response.Headers.Location?.ToString();

            productUrl.Should().NotBeEmpty();
        }
예제 #28
0
        public GetProductDetailsResponse GetProductDetails(GetProductDetailsRequest request)
        {
            GetProductDetailsResponse response = new GetProductDetailsResponse();

            try
            {
                if (request.is_admin)
                {
                    if (!AgentAdminServices.CheckAdmin(request.user_id, request.auth_token, response))
                    {
                        //_userServices.MakeNouserResponse(response);
                        return(response);
                    }
                }
                else
                {
                    if (!_userServices.CheckAuthUser(request.user_id, request.auth_token))
                    {
                        _userServices.MakeNouserResponse(response);
                        return(response);
                    }
                }

                using (ProductDao dao = new ProductDao())
                {
                    ProductDetailsDto dto = new ProductDetailsDto();
                    Product           prd = dao.FindProductById(request.product_id);
                    ProductHelper.CopyFromEntity(dto, prd);
                    response.product_details = dto;
                    response.code            = 0;
                    response.has_resource    = 1;
                    response.message         = MessagesSource.GetMessage("has.prod.details");
                }
            }
            catch (Exception ex)
            {
                response.MakeExceptionResponse(ex);
            }
            return(response);
        }
예제 #29
0
        public IDataResult <ProductDetailsDto> GetProductDetailsById(int productId)
        {
            var product           = _productDao.Get(p => p.Id == productId);
            var productCategory   = _categoryDao.Get(c => c.Id == product.CategoryId);
            var productDetailsDto = new ProductDetailsDto
            {
                ProductId          = product.Id,
                ProductName        = product.Name,
                ProductDescription = product.Description,
                ProductPrice       = product.UnitPrice,
                ProductCost        = product.UnitCost,
                ProductQuantity    = product.UnitCount,
            };

            if (productCategory != null)
            {
                productDetailsDto.CategoryId   = productCategory.Id;
                productDetailsDto.CategoryName = productCategory.Name;
            }

            return(new SuccessDataResult <ProductDetailsDto>(productDetailsDto));
        }
예제 #30
0
        public IHttpActionResult Get(int?id)
        {
            if (id.IsNullOrDefault())
            {
                var products = _productRepository.Get();
                var result   = new List <ProductDetailsDto>();
                Mapper.Map(products.ToList(), result);
                return(Ok(result));
            }

            else
            {
                var product = _productRepository.Get(id.Value);
                if (product == null)
                {
                    return(NotFound());
                }

                var result = new ProductDetailsDto();
                Mapper.Map(product, result);
                return(Ok(result));
            }
        }
예제 #31
0
        public async Task<IHttpActionResult> GetProduct(long id)
        {
            //var product = await db.Products.Include(p => p.ProductGroups).Select(p =>
            //    new ProductDetailsDto()
            //    {
            //        Id = p.Id,
            //        Name = p.Name,
            //        Price = p.Price,
            //        Saleable = p.Saleable,
            //        ProductGroups = new List<ProductGroup>()
            //    }).SingleOrDefaultAsync(p => p.Id == id);

            var pm = await db.Products.Include(p => p.ProductGroups).SingleOrDefaultAsync(p => p.Id == id);

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

            var productDto = new ProductDetailsDto {Id = pm.Id, Name = pm.Name, Price = pm.Price, Saleable = pm.Saleable, ProductGroups = new List<long>()};
            pm.ProductGroups.ForEach(pg => productDto.ProductGroups.Add(pg.Id));

            return Ok(productDto);
        }
예제 #32
0
        public async Task<IHttpActionResult> PostProduct(ProductDetailsDto productDetails)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            var workwrok = productDetails.ProductGroups;
            List<ProductGroup> productGroups = new List<ProductGroup>();

            foreach (var i in workwrok)
            {
                var pG = from pg in db.ProductGroups where pg.Id == i select pg;
                pG.ForEach(pg => productGroups.Add(pg));
            }

            var product = new Product(productDetails.Name, productDetails.Price, productDetails.Saleable);
            
            productGroups?.ForEach(e => product.ProductGroups.Add(e));

            db.Products.Add(product);
            await db.SaveChangesAsync();

            productDetails.Id = product.Id;

            return CreatedAtRoute("DefaultApi", new { id = productDetails.Id }, productDetails);
        }
예제 #33
0
 public async Task AddAsync(ProductDetailsDto productDto)
 {
     var product = new Product(productDto.Id, productDto.Name,
                               productDto.Category, productDto.Price, productDto.Description);
     await _productRepository.AddAsync(product);
 }