Esempio n. 1
0
        public void Post()
        {
            var target     = new ProductsController(this._EFProductRepository, this._MockMapper);
            var newProduct = new CreateProductDto
            {
                Name        = "TestProduct01",
                Price       = 23M,
                Description = "",
                ProductTag  = new List <CreateProductTagDto>
                {
                    new CreateProductTagDto {
                        Name = "TestProduct01-Tag01"
                    },
                    new CreateProductTagDto {
                        Name = "TestProduct01-Tag02"
                    }
                },
                ProductImage = new CreateProductImageDto {
                    Url = "jysk.dk/TestProduct01/"
                }
            };
            var result   = target.Post(newProduct);
            var okResult = result as OkObjectResult;

            Assert.Equal(200, okResult.StatusCode);
            Assert.Equal(3, this._EFProductRepository.Products.Count());
            Assert.Equal(23M, this._EFProductRepository.Products.Where(p => p.Name == "TestProduct01").FirstOrDefault().Price);
        }
Esempio n. 2
0
        public async Task <IActionResult> Create([FromForm] CreateProductDto dataToCreate)
        {
            var productFromRepo = await _productRepo.GetSingleWithCondition(s => s.ProductName == dataToCreate.ProductName);

            if (productFromRepo != null)
            {
                return(BadRequest("Product Exists !!!"));
            }

            var imageUrl = string.Empty;

            if (Request.Form.Files.Count > 0)
            {
                imageUrl = await UploadFile(Request.Form.Files, dataToCreate.ProductName);
            }

            var product = _mapper.Map <Product>(dataToCreate);

            product.ImageUrl    = imageUrl;
            product.CreatedDate = DateTime.Now;
            var isInsert = await _productRepo.InsertAsync(product);

            if (isInsert != null)
            {
                return(CreatedAtRoute("GetProducts", null));
            }
            else
            {
                return(BadRequest());
            }
        }
 public ActionResult <int> CreateProduct(CreateProductDto productDto)
 {
     return(Execute(() =>
     {
         return _productService.CreateProduct(productDto);
     }));
 }
Esempio n. 4
0
        public async Task <bool> AddProductAsync(Guid userId, CreateProductDto payload)
        {
            var pictures = new List <Picture>();
            var product  = new Product
            {
                Description = payload.Description,
                Price       = payload.Price,
                Title       = payload.Title,
            };

            var picture = new Picture
            {
                Body      = payload.Picture,
                ProductId = product.Id,
                Url       = "idk, ma mai gandesc",
                Title     = product.Title + Guid.NewGuid()
            };

            var user = await UnitOfWork.Users.GetUserByIdAsync(userId);

            if (user == null)
            {
                return(false);
            }
            product.Picture = picture;
            product.Seller  = user;

            UnitOfWork.Products.Insert(product);
            return(await UnitOfWork.SaveChangesAsync());
        }
        public async Task <ActionResult> Add([FromBody] CreateProductDto input)
        {
            if (input.CategoryId <= 0)
            {
                return(BadRequest("This Category is invalid"));
            }

            var productCategory = await _unitOfWork.GetRepo <Category>().GetByID(input.CategoryId);

            if (productCategory == null)
            {
                return(NotFound("There is no category with the specified Id"));
            }

            var newProduct = Product.Create(_mapper.Map <ProductInputParameter>(input));

            productCategory.AddNewProduct(newProduct);

            if (await _unitOfWork.Complete())
            {
                return(Ok());
            }

            return(BadRequest("failed to add new product"));
        }
        private async Task <ResponseMessagesDto> UpdateProductAsync(CreateProductDto productDto)
        {
            var result = await _productRepository.UpdateAsync(new Product()
            {
                Id               = productDto.Id,
                Name             = productDto.Name,
                Description      = productDto.Description,
                ProductSubTypeId = productDto.SubTypeId
            });

            if (result != null)
            {
                return(new ResponseMessagesDto()
                {
                    Id = result.Id,
                    SuccessMessage = AppConsts.SuccessfullyUpdated,
                    Success = true,
                    Error = false,
                });
            }
            return(new ResponseMessagesDto()
            {
                Id = 0,
                ErrorMessage = AppConsts.UpdateFailure,
                Success = false,
                Error = true,
            });
        }
Esempio n. 7
0
        public IHttpActionResult Post([FromBody] CreateProductDto dto)
        {
            if (dto == null || !ModelState.IsValid)
            {
                return(BadRequest());
            }
            var product = new Product()
            {
                Name        = dto.Name,
                Description = dto.Description,
                Price       = dto.Price,
                CategoryId  = dto.CategoryId
            };
            var addedProduct = productsRepo.Insert(product);
            var dtoRes       = new ProductDto()
            {
                Id          = addedProduct.Id,
                Name        = addedProduct.Name,
                Description = addedProduct.Description,
                CategoryId  = addedProduct.CategoryId,
                Price       = addedProduct.Price
            };

            return(Created("umbraco/backoffice/orders/productsapi/byid/" + dtoRes.Id,
                           dtoRes));
        }
Esempio n. 8
0
        public int CreateProduct(CreateProductDto productDto)
        {
            CategoryProduct categoryProduct;

            if (productDto.IdCategoryProduct == 0)
            {
                var myCategoryProduct = _genericRepository.Filter <CategoryProduct>
                                            (p => p.Name == productDto.NameCategory.ToLower()).FirstOrDefault();
                categoryProduct = myCategoryProduct == null
                    ? CategoryProduct.Create(productDto.NameCategory) : myCategoryProduct;
            }
            else
            {
                categoryProduct = _genericRepository.Filter <CategoryProduct>
                                      (p => p.IdCategoryProduct == productDto.IdCategoryProduct).FirstOrDefault();
            }

            var product = Product.Create(categoryProduct, productDto.NameProduct
                                         , productDto.Description, decimal.Parse(productDto.Price));

            for (var image = 1; image <= productDto.QuantityImages; image++)
            {
                var imageProduct = ImageProduct.Create(image);
                product.ImageProducts.Add(imageProduct);
            }
            _genericRepository.Add(product);
            _genericRepository.SaveChanges();
            return(product.IdProduct);
        }
Esempio n. 9
0
        public ProductDto AddNew(CreateProductDto product)
        {
            _createProductValidator.ValidateAndThrow(product);
            var id = _productRepository.AddNew(_mapper.Map <ProductDo>(product));

            return(GetOne(id));
        }
Esempio n. 10
0
        public IActionResult CreateProduct(CreateProductDto dto)
        {
            if (!this._productsService.CreateProduct(dto.ProductName, dto.ProductImageUrl, decimal.Parse(dto.ProductPrice), dto.ProductDescription, dto.ProductCategory).Result)
            {
                var categories = this._categoriesService.GetAllCategories()
                                 .Select(p => new SelectListItem()
                {
                    Value = p.Id,
                    Text  = p.Name.ToString()
                });

                this.ViewData["ProductCategories"] = categories;

                return(View());
            }

            if (!TryValidateModel(dto))
            {
                var categories = this._categoriesService.GetAllCategories()
                                 .Select(p => new SelectListItem()
                {
                    Value = p.Id,
                    Text  = p.Name.ToString()
                });

                this.ViewData["ProductCategories"] = categories;

                return(View());
            }

            return(Redirect("/"));
        }
Esempio n. 11
0
        public bool Validate(CreateProductDto request)
        {
            if (!_context.Products.Any(x => x.Id == request.Id))
            {
                throw new EntityNotFoundException($"Product with id: {request.Id}");
            }

            if (!_context.Categories.Any(x => x.Id == request.CategoryId))
            {
                throw new EntityNotFoundException($"Category with id: {request.CategoryId}");
            }

            if (!_context.SubCategories.Any(x => x.Id == request.SubCategoryId))
            {
                throw new EntityNotFoundException($"Subcategory with id: {request.SubCategoryId}");
            }

            var y = _context.SubCategories
                    .Include(sc => sc.Category)
                    .AsQueryable()
                    .Where(sc => sc.Id == request.SubCategoryId && sc.Category.Id == request.CategoryId);

            if (y.Count() == 0)
            {
                throw new EntityMissmatchException($"Subcategory with id: {request.SubCategoryId}", $"Category with id: {request.CategoryId}");
            }

            return(true);
        }
Esempio n. 12
0
        public async Task <IHttpActionResult> Create(CreateProductDto product)
        {
            product.Id = Guid.NewGuid();
            DatabaseResponse response = await _productService.CreateProductAsync(product);

            return(Ok(ApiResponse.OkResult(true, response.Results, (DbReturnValue)response.ResponseCode)));
        }
        private async Task <ResponseMessagesDto> CreateProductAsync(CreateProductDto productDto)
        {
            var result = await _productRepository.InsertAsync(new Product()
            {
                Name             = productDto.Name,
                Description      = productDto.Description,
                ProductSubTypeId = productDto.SubTypeId,
                TenantId         = productDto.TenantId
            });

            await UnitOfWorkManager.Current.SaveChangesAsync();

            if (result.Id != 0)
            {
                return(new ResponseMessagesDto()
                {
                    Id = result.Id,
                    SuccessMessage = AppConsts.SuccessfullyInserted,
                    Success = true,
                    Error = false,
                });
            }
            return(new ResponseMessagesDto()
            {
                Id = 0,
                ErrorMessage = AppConsts.InsertFailure,
                Success = false,
                Error = true,
            });
        }
Esempio n. 14
0
        public async Task <IActionResult> PushNotifyToService([FromBody] CreateProductDto dto)
        {
            var result = string.Empty;

            var client = new ServicePartitionClient <HttpCommunicationClient>(
                _clientFactory, new Uri("fabric:/Microservices.DemoApplication/Demo.NotificationService"));

            await client.InvokeWithRetryAsync(async x =>
            {
                var token = HttpContext.Request.Headers["Authorization"].ToString();

                if (!string.IsNullOrEmpty(token))
                {
                    var beareToken = token.Split("Bearer ")[1];

                    x.HttpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", beareToken);

                    var resp = await x.HttpClient.PostAsync("/api/notification/notify", ObjToHttpContent(dto));

                    resp.EnsureSuccessStatusCode();

                    result = await resp.Content.ReadAsStringAsync();
                }
            });

            return(Ok(result));
        }
Esempio n. 15
0
        public async Task <IActionResult> Post([FromBody] CreateProductDto dto)
        {
            var entity = dto.CreateEntity();

            _repository.Add(entity);

            await _repository.UnitOfWork.SaveChangesAsync();

            using (var client = new HttpClient())
            {
                var token = HttpContext.Request.Headers["Authorization"].ToString();

                if (!string.IsNullOrEmpty(token))
                {
                    var beareToken = token.Split("Bearer ")[1];

                    client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", beareToken);

                    var resp = await client.PostAsync("http://192.168.2.99:5002/api/notification/notify", ObjToHttpContent(entity));

                    resp.EnsureSuccessStatusCode();
                }
            }

            return(new OkObjectResult(entity));
        }
Esempio n. 16
0
        public void Execute(CreateProductDto request)
        {
            try
            {
                var query = Context.Products
                            .Where(p => p.product_id == request.Id)
                            .FirstOrDefault();

                query.category_id = request.CategoryId;
                query.description = request.Description;
                query.name        = request.Name;
                query.price       = request.Price;


                DeleteManufacturers.RemoveExistingProductManufacturers(request);
                DeleteSuppliers.RemoveExistingProductSuppliers(request);
                Context.SaveChanges();

                Manufacturers.Execute(request, (int)request.Id);
                Suppliers.Execute(request, (int)request.Id);
                Context.SaveChanges();
            }
            catch (CustomException e)
            {
                throw new CustomException("Doslo je do greske prilikom konekcije!");
            }
        }
        public async Task <ActionResult <Product> > CreateProduct(CreateProductDto createProductDto)
        {
            try
            {
                if (!ModelState.IsValid)
                {
                    _logger.LogError($"Валидация модели не успешна {ModelState}");
                    return(BadRequest(ModelState));
                }

                //Детектируем сайт
                if (!Uri.TryCreate(createProductDto.ProductUrl, UriKind.Absolute, out Uri productUri))
                {
                    _logger.LogError($"Не удалось преобразовать {nameof(createProductDto.ProductUrl)}={createProductDto.ProductUrl} в {typeof(Uri)}");
                    return(BadRequest($"Не удалось преобразовать {nameof(createProductDto.ProductUrl)}={createProductDto.ProductUrl} в {typeof(Uri)}"));
                }

                var siteDto = await _productWatcherManager.GetSiteByProductUrl(productUri);

                if (siteDto == null)
                {
                    _logger.LogError($"Не удалось детектировать сайт по url={productUri.AbsoluteUri}");
                    return(NotFound($"Не удалось детектировать сайт по url={productUri.AbsoluteUri}"));
                }

                Product productDto = null;

                if (siteDto.Settings.AutoGenerateSchedule)
                {
                    if (createProductDto.Scheduler != null)
                    {
                        _logger.LogError($"Нельзя задавать строгое расписание {nameof(siteDto.Settings.AutoGenerateSchedule)}={siteDto.Settings.AutoGenerateSchedule}");
                        return(BadRequest($"Нельзя задавать строгое расписание {nameof(siteDto.Settings.AutoGenerateSchedule)}={siteDto.Settings.AutoGenerateSchedule}"));
                    }

                    productDto = await _productWatcherManager.UpdateProductAutogenerateScheduler(createProductDto.ProductUrl, siteDto);
                }
                else
                {
                    if (createProductDto.Scheduler == null || !createProductDto.Scheduler.Any())
                    {
                        _logger.LogError("Нельзя создавать пустой расписание");
                        return(BadRequest("Нельзя создавать пустой расписание"));
                    }

                    productDto = await _productWatcherManager.CreateProduct(createProductDto.ProductUrl, siteDto, createProductDto.Scheduler, true);
                }

                return(CreatedAtAction(
                           nameof(GetProduct),
                           new { id = productDto.Id },
                           productDto));
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Внутренняя ошибка сервиса при обработке запроса");
                return(StatusCode(500, "Ошибка при обработке запроса"));
            }
        }
Esempio n. 18
0
        public async Task <ProductDto> Post([FromBody] CreateProductDto requestModel)
        {
            var item = await _query.CreateAsync(requestModel);

            var model = _mapper.Map <ProductDto>(item);

            return(model);
        }
Esempio n. 19
0
        public async Task <IActionResult> Post(CreateProductDto createProductDto)
        {
            var createdProduct = await _productService.CreateProductAsync(createProductDto);

            var productDto = _mapper.Map <Product, ProductDto>(createdProduct);

            return(CreatedAtRoute("GetProductById", new { id = createdProduct.Id }, productDto));
        }
Esempio n. 20
0
        public async Task <ProductDto> CreateProduct(CreateProductDto input)
        {
            Product product = Product.CreateProduct(input.Name, input.Price, input.Description);
            await _productRepository.InsertAsync(product);

            await CurrentUnitOfWork.SaveChangesAsync();

            return(ObjectMapper.Map <ProductDto>(product));
        }
Esempio n. 21
0
        public async Task UpdateProductAsync(Guid productId, CreateProductDto payload)
        {
            var product = await UnitOfWork.Products.GetByIdAsync(productId);

            _mapper.Map(payload, product);

            UnitOfWork.Products.Update(product);
            await UnitOfWork.SaveChangesAsync();
        }
Esempio n. 22
0
        public void Execute(CreateProductDto request)
        {
            Product product = CreateNewProduct(request);

            var productId = product.product_id;

            Manufacturers.Execute(request, productId);
            Suppliers.Execute(request, productId);
            Context.SaveChanges();
        }
Esempio n. 23
0
        public async Task <IActionResult> Create([FromBody] CreateProductDto newProductDto)
        {
            var response = await _services.CreateProductAsync(newProductDto);

            if (!response.Success)
            {
                return(BadRequest(response));
            }

            return(Ok(response));
        }
Esempio n. 24
0
        public void Execute(CreateProductDto request)
        {
            if (Validate(request))
            {
                var product = _context.Products
                              .Include(p => p.ProductImages)
                              .ThenInclude(pi => pi.Image)
                              .AsQueryable()
                              .Where(x => x.Id == request.Id)
                              .First();

                product.Name              = request.Name;
                product.Description       = request.Description;
                product.UnitPrice         = request.UnitPrice;
                product.UnitWeight        = request.UnitWeight;
                product.QuantityAvailable = request.QuantityAvailable;
                product.Category          = _context.Categories.Find(request.CategoryId);
                product.SubCategory       = _context.SubCategories.Find(request.SubCategoryId);
                product.DateUpdated       = DateTime.Now;

                if (request.ImagePaths.Count != 0)
                {
                    foreach (var productImage in product.ProductImages)
                    {
                        productImage.Image.Active = false;
                        productImage.Active       = false;
                    }

                    int i = 0;
                    foreach (var imagePath in request.ImagePaths)
                    {
                        var image = new Images
                        {
                            Active      = true,
                            DateCreated = DateTime.Now,
                            Path        = imagePath,
                            Alt         = request.ImageAlts[i],
                        };

                        _context.ProductImages.Add(new ProductImages
                        {
                            Active      = true,
                            DateCreated = DateTime.Now,
                            Product     = product,
                            Image       = image
                        });

                        i++;
                    }
                }

                _context.SaveChanges();
            }
        }
Esempio n. 25
0
 public IActionResult Create(CreateProductDto productDto)
 {
     try
     {
         _productService.Create(productDto);
         return(Ok());
     }
     catch (CustomException exception)
     {
         return(StatusCode(exception.ErrorDetails.StatusCode, exception.ErrorDetails));
     }
 }
        public void Execute(CreateProductDto request, int productId)
        {
            var productManufacturer = new List <ProductManufacturer>();

            request.ManufacturerId.ForEach(x => productManufacturer.Add(new ProductManufacturer
            {
                manufacturer_id = x,
                product_id      = productId
            }));

            Context.ProductManufacturers.AddRange(productManufacturer);
        }
Esempio n. 27
0
        public HttpStatusCode CreatProduct(CreateProductDto createProductDto)
        {
            Subcategory subcategory = _ctx.Subcategories.FirstOrDefault(x => x.Id == createProductDto.SubcategoryId);

            if (subcategory == null)
            {
                return(HttpStatusCode.NotFound);
            }

            var systemAttributeModel = new SystemAttribute()
            {
                CreationDate = DateTime.Now,
                IsPublished  = createProductDto.IsProductPublished,
                VersioNumber = Guid.NewGuid().ToString(),
                Version      = 1,
            };

            try
            {
                _ctx.SystemAttributes.Add(systemAttributeModel);
                _ctx.SaveChanges();
            }
            catch (Exception ex)
            {
                throw ex;
            }


            var model = new Product()
            {
                Name              = createProductDto.ProductName,
                IsPublished       = createProductDto.IsProductPublished,
                Subcategory       = subcategory,
                SubcategoryId     = subcategory.Id,
                SystemAttribute   = systemAttributeModel,
                SystemAttributeId = systemAttributeModel.Id,
                CreationDate      = DateTime.Now
            };


            try
            {
                _ctx.Products.Add(model);
                _ctx.SaveChanges();
            }
            catch (Exception ex)
            {
                return(HttpStatusCode.InternalServerError);
            }

            return(HttpStatusCode.OK);
        }
Esempio n. 28
0
        public IActionResult Post(CreateProductDto productDto)
        {
            Product clothing = new Product();

            string urlSlug = productDto.Name.ToLower().Replace(" ", "-");

            clothing.Name        = productDto.Name;
            clothing.Description = productDto.Description;
            clothing.Price       = productDto.Price;
            clothing.ImageUrl    = productDto.ImageUrl;
            clothing.UrlSlug     = urlSlug;
            try
            {
                _context.Add(clothing);
                _context.SaveChanges();


                if (productDto.CategoriesId != null)
                {
                    foreach (var categoryId in productDto.CategoriesId)
                    {
                        ProductCategory productCategory = new ProductCategory(clothing);

                        var category = _context.Categories.FirstOrDefault(x => x.Id == categoryId);

                        category.Products.Add(productCategory);
                        _context.SaveChanges();
                    }
                }
            }
            catch (Exception e)
            {
                return(BadRequest(e.GetBaseException()));
            }

            ProductDto product = new ProductDto();

            product.Id         = clothing.Id;
            product.Name       = clothing.Name;
            product.ImageUrl   = clothing.ImageUrl;
            product.Price      = clothing.Price;
            product.UrlSlug    = clothing.UrlSlug;
            product.Categories = clothing.Categories.Select(c => new Category
            {
                Id   = c.CategoryId,
                Name = c.Category.Name,
            }).ToList();



            return(CreatedAtAction(nameof(GetProduct), new { id = clothing.Id }, product));
        }
Esempio n. 29
0
        public async Task <IResult> CreateProduct(CreateProductDto productDto)
        {
            Product product = new Product
            {
                BrandId      = productDto.BrandId,
                CanNotable   = productDto.CanNotable,
                CategoryId   = productDto.CategoryId,
                Description  = productDto.Description,
                DiscountRate = productDto.DiscountRate,
                InStock      = productDto.InStock,
                IsNew        = productDto.IsNew,
                IsPopular    = productDto.IsPopular,
                Name         = productDto.Name,
                Price        = productDto.Price
            };

            product = _productDAL.Add(product);

            foreach (var colorId in productDto.ColorIds)
            {
                product.ProductColors.Add(new ProductColor(product.Id, colorId));
            }

            if (productDto.DemandTypeIds != null && productDto.DemandTypeIds.Count() != 0)
            {
                foreach (var demandTypeId in productDto.DemandTypeIds)
                {
                    product.ProductDemands.Add(new ProductDemand(product.Id, demandTypeId));
                }
            }

            if (productDto.Images != null && productDto.Images.Count() > 0)
            {
                foreach (var image in productDto.Images)
                {
                    string imageName  = Guid.NewGuid() + "." + image.FileName.Split('.')[1];
                    var    fileLocate = $"{productDto.FilePath}/{imageName}";
                    product.ProductImages.Add(new ProductImage {
                        ImageName = imageName, ProductId = product.Id
                    });

                    using (var stream = new FileStream(fileLocate, FileMode.Create))
                    {
                        image.CopyTo(stream);
                    }
                }
            }

            int result = await _uow.Complete();

            return(ResultHelper <int> .ResultReturn(result));
        }
Esempio n. 30
0
        public HttpResponseMessage Post([FromBody] CreateProductDto value)
        {
            try {
                if (value.ProductId == default(string))
                {
                    throw DomainError.Named("nullId", "Aggregate Id in cmd is null, aggregate name: {0}.", "Product");
                }
                _productApplicationService.When(value as ICreateProduct);
                var idObj = value.ProductId;

                return(Request.CreateResponse <string>(HttpStatusCode.Created, idObj));
            } catch (Exception ex) { var response = ProductsControllerUtils.GetErrorHttpResponseMessage(ex); throw new HttpResponseException(response); }
        }