Ejemplo n.º 1
0
        public async Task <IServiceResult <int> > Create(CreateProductInput input)
        {
            if (await ValidateUnit(input))
            {
                return(ServiceResult <int> .BadRequest("unit is not exists."));
            }

            if (await ValidateCategory(input))
            {
                return(ServiceResult <int> .BadRequest("category is not exists."));
            }

            if (await ValidateWarehouse(input))
            {
                return(ServiceResult <int> .BadRequest("warehouse is not exists."));
            }

            var product = new Product(
                input.Name,
                input.Description,
                input.Stock,
                input.UnitId,
                input.WarehouseId,
                input.CategoryId);

            await _databaseContext.Products.AddAsync(product);

            await _databaseContext.SaveChangesAsync();

            await _messagePublisher.PublishAsync(new ProductCreatedEvent(product.Id, product.Name));

            return(ServiceResult <int> .Ok(product.Id));
        }
Ejemplo n.º 2
0
        public async Task <OperationResult <ProductDto> > CreateAsync(CreateProductInput input)
        {
            var validationResult = await _validator.ValidateCreateProduct(input);

            if (validationResult.IsSuccess)
            {
                Product product = input.ConvertToEntity();

                product = await _repository.CreateAsync(product);

                Task overviewTask = _overviewRepository.CreateAsync(new()
                {
                    ProductId   = product.Id,
                    Description = input.Description
                });

                Task badgeTask = _badgeRepository.CreateAsync(new()
                {
                    ProductId = product.Id,
                    Badges    = Enumerable.Empty <ProductBadgeName>()
                });

                Task.WaitAll(overviewTask, badgeTask);

                return(OperationResult <ProductDto> .Success(product.ConvertToDto()));
            }
            else
            {
                return(OperationResult <ProductDto> .Fail(validationResult));
            }
        }
Ejemplo n.º 3
0
        public async Task Create(CreateProductInput input, string imageFolderPath)
        {
            var sources   = input.Description.GetBase64Sources();
            var extension = "";

            byte[] imageBytes = null;
            string imageName  = "";

            foreach (var src in sources)
            {
                extension  = src.GetExtensionFromBase64ImageSource();
                imageBytes = Convert.FromBase64String(src.GetValueFromBase64ImageSource());
                imageName  = $"{Guid.NewGuid()}.{extension}";
                Upload.ByteArrayToFile($"{imageFolderPath}/{imageName}", imageBytes);
                input.Description = input.Description.Replace(src, $"{_configuration.GetSection("Domain").Value}/{Product.IMAGE_PATH}/{imageName}");
            }

            var product = new Product(name: input.Name,
                                      productCategoryId: 1,
                                      code: "product",
                                      description: input.Description,
                                      price: input.Price,
                                      images: string.Join(";", await Task.WhenAll <string>(input.ImageFiles.Select(img => Upload.UploadImageAsync(img, imageFolderPath)))),
                                      status: input.Status,
                                      seoUrl: input.SeoUrl,
                                      metaDescription: input.MetaDescription,
                                      metaTitle: input.MetaTitle);
            await _productRepo.Create(product);
        }
Ejemplo n.º 4
0
        public async Task CreateProduct(CreateProductInput input)
        {
            var product = input.MapTo <Product>();

            product.ServiceTags = string.Join(",", input.Tags);
            await _productRepository.InsertAsync(product);
        }
Ejemplo n.º 5
0
        public async Task <GetProductOutput> Create(CreateProductInput input)
        {
            var product = input.MapTo <Product>();

            product = await _productDomainService.Create(product);

            return(product.MapTo <GetProductOutput>());
        }
        public void ConvertToEntity_InputNotNull_ReturnPercentageOffIsZero()
        {
            CreateProductInput input = MockCreateProductInput();

            Product product = input.ConvertToEntity();

            Assert.Equal(0, product.PercentageOff);
        }
        public void ConvertToEntity_InputNotNull_ReturnIsActiveFalse()
        {
            CreateProductInput input = MockCreateProductInput();

            Product product = input.ConvertToEntity();

            Assert.False(product.IsActive);
        }
        public void ConvertToEntity_InputNotNull_ReturnThumbnailNull()
        {
            CreateProductInput input = MockCreateProductInput();

            Product product = input.ConvertToEntity();

            Assert.Null(product.Thumbnail);
        }
        public void ConvertToEntity_InputNotNull_ReturnSameSubCategory()
        {
            CreateProductInput input = MockCreateProductInput();

            Product product = input.ConvertToEntity();

            Assert.Equal(product.SubCategory, input.SubCategory);
        }
        public void ConvertToEntity_InputNotNull_ReturnSamePrice()
        {
            CreateProductInput input = MockCreateProductInput();

            Product product = input.ConvertToEntity();

            Assert.Equal(product.Price, input.Price);
        }
        public void ConvertToEntity_InputNotNull_ReturnStockIsZero()
        {
            CreateProductInput input = MockCreateProductInput();

            Product product = input.ConvertToEntity();

            Assert.Equal(0, product.Stock);
        }
Ejemplo n.º 12
0
        public async Task <ValidationResult> ValidateCreateProduct(CreateProductInput input)
        {
            ValidationResult validationResult = new();

            if (string.IsNullOrWhiteSpace(input.Name))
            {
                validationResult.Messages.Add(new(nameof(CreateProductInput.Name), "El nombre no puede estar vacio."));
            }
            else
            {
                Product product = _productRepository.GetByName(input.Name);
                if (product is not null)
                {
                    validationResult.Messages.Add(new(nameof(CreateProductInput.Name), "Ya existe un producto con este nombre."));
                }
            }

            if (string.IsNullOrWhiteSpace(input.Description))
            {
                validationResult.Messages.Add(new(nameof(CreateProductInput.Description), "La description no puede estar vacia."));
            }

            if (input.Price <= 0)
            {
                validationResult.Messages.Add(new(nameof(CreateProductInput.Price), "El precio debe ser mayor a cero."));
            }

            if (input.Price < input.Cost)
            {
                validationResult.Messages.Add(new(nameof(CreateProductInput.Price), "El precio no puede ser menor que el costo."));
            }



            if (string.IsNullOrWhiteSpace(input.Category))
            {
                validationResult.Messages.Add(new(nameof(CreateProductInput.Category), "Debe seleccionar una categoria."));
            }
            else
            {
                var category = await _productCategoryRepository.GetByNameAsync(input.Category);

                if (category is null)
                {
                    validationResult.Messages.Add(new(nameof(CreateProductInput.Category), "La categoria no existe."));
                }
                else if (string.IsNullOrWhiteSpace(input.SubCategory))
                {
                    validationResult.Messages.Add(new(nameof(CreateProductInput.SubCategory), "Debe seleccionar una subcategoria."));
                }
                else if (!category.SubCategories.Any(x => x == input.SubCategory))
                {
                    validationResult.Messages.Add(new(nameof(CreateProductInput.SubCategory), "La subcategoria no existe."));
                }
            }

            return(validationResult);
        }
Ejemplo n.º 13
0
        public async Task <IActionResult> Create([FromForm] CreateProductInput input)
        {
            var absolutePath = Path.Combine(_webHostEnvironment.WebRootPath, Product.IMAGE_PATH);
            await _productService.Create(input, absolutePath);

            await _dbContext.SaveChangesAsync();

            return(Ok());
        }
Ejemplo n.º 14
0
        public async Task <CreateProductOutput> CreateProduct(CreateProductInput input)
        {
            var produto          = input.MapTo <Product>();
            var createdProdutoId = await _productManager.Create(produto);

            return(new CreateProductOutput
            {
                Id = createdProdutoId
            });
        }
Ejemplo n.º 15
0
        public async Task Create(CreateProductInput input)
        {
            var tenant = AbpSession.TenantId;

            MyPassword.Core.Product.Product product = new Core.Product.Product();
            product.UpdateName(input.Name);
            product.UpdateNumber(input.Number, _policy);
            product.UpdatePrice(input.Price, _policy);
            await _productRepository.InsertAsync(product);
        }
Ejemplo n.º 16
0
 public static Product ConvertToEntity(this CreateProductInput source)
 {
     return(new()
     {
         Category = source.Category,
         Cost = source.Cost,
         Name = source.Name,
         Price = source.Price,
         SubCategory = source.SubCategory,
     });
 }
Ejemplo n.º 17
0
 public async Task CreateOrUpdateProduct(CreateProductInput input)
 {
     if (input.Id == 0)
     {
         await CreateProduct(input);
     }
     else
     {
         await UpdateProduct(input);
     }
 }
Ejemplo n.º 18
0
        public void When_Price_IsLessThan()
        {
            CreateProductInput createProductInput = new CreateProductInput
            {
                Code  = "P1",
                Stock = 100,
                Price = -10
            };

            Assert.Throws <InvalidPriceException>(() => productService.CreateProduct(createProductInput));
        }
Ejemplo n.º 19
0
        public void When_Stock_IsLessThanZero()
        {
            CreateProductInput createProductInput = new CreateProductInput
            {
                Code  = "P1",
                Price = 100,
                Stock = -10,
            };

            Assert.Throws <InvalidStockException>(() => productService.CreateProduct(createProductInput));
        }
Ejemplo n.º 20
0
        public void When_CreateProduct_IsSuccessful()
        {
            CreateProductInput createProductInput = new CreateProductInput
            {
                Code  = "P1",
                Price = 100,
                Stock = 1000,
            };

            Assert.DoesNotThrow(() => productService.CreateProduct(createProductInput));
            mockProductRepository.Verify(x => x.CreateProduct(It.IsAny <Product>()), Times.Once());
        }
Ejemplo n.º 21
0
        private void CreateProduct(CreateProductInput createProductInput)
        {
            using (var client = new TestStart().Client)
            {
                client.DefaultRequestHeaders.Add("Accept", "application/json");
                var json = JsonConvert.SerializeObject(createProductInput);
                var data = new StringContent(json, Encoding.UTF8, "application/json");

                var response = client.PostAsync("/api/product", data);
                Assert.AreEqual(HttpStatusCode.OK, response.Result.StatusCode);
            }
        }
Ejemplo n.º 22
0
        public void When_CreateOrder_IsSuccessful()
        {
            CreateProductInput createProductInput = new CreateProductInput
            {
                Code  = "P1",
                Price = 100,
                Stock = 1000,
            };

            CreateProduct(createProductInput);

            CreateOrderInput createOrderInput = new CreateOrderInput
            {
                ProductCode = "P1",
                Quantity    = 10
            };
            var orderResponse = CreateOrder(createOrderInput);

            Assert.AreEqual(HttpStatusCode.OK, orderResponse.StatusCode);

            var getProduct = GetProduct();

            Assert.AreEqual(990, getProduct.Stock);

            CreateCampaignInput createCampaignInput = new CreateCampaignInput
            {
                Name                   = "C1",
                ProductCode            = "P1",
                TargetSalesCount       = 100,
                Duration               = 10,
                PriceManipulationLimit = 20
            };

            CreateCampaign(createCampaignInput);
            IncreaseTime();


            var orderResponse2 = CreateOrder(createOrderInput);

            Assert.AreEqual(HttpStatusCode.OK, orderResponse2.StatusCode);

            var getProduct2 = GetProduct();

            Assert.AreEqual(980, getProduct2.Stock);

            var campaignResponse = GetCampaign(createCampaignInput.Name);

            Assert.AreEqual(createCampaignInput.TargetSalesCount, campaignResponse.TargetSales);
            Assert.AreEqual(createOrderInput.Quantity, campaignResponse.TotalSales);
            Assert.AreEqual(980, campaignResponse.Turnover);
            Assert.AreEqual(98, campaignResponse.AverageItemPrice);
        }
Ejemplo n.º 23
0
        public int AddPro(CreateProductInput input)
        {
            AmazonProductService service = new AmazonProductService();
            var product = service.GetProduct(input.Url);

            product.Cashback = new Cashback()
            {
                SalesPrice = 18
            };

            var id = _productRepository.InsertOrUpdateAndGetId(product);

            return(id);
        }
Ejemplo n.º 24
0
        public ProductDto CreateProduct(CreateProductInput input)
        {
            Logger.Info("Start CreateProduct");

            var product = _objectMapper.Map <Product>(input);

            _productDomainService.ActiveProduct(product);

            _productRepository.Insert(product);

            Logger.Info("Finish CreateProduct");

            return(_objectMapper.Map <ProductDto>(product));
        }
Ejemplo n.º 25
0
        public void When_ProductCode_IsUsed()
        {
            Product product = new Product("P1", 100, 1000);

            mockProductRepository.Setup(x => x.GetProduct("P1")).Returns(product);

            CreateProductInput createProductInput = new CreateProductInput
            {
                Code  = "P1",
                Price = 100,
                Stock = 1000
            };

            Assert.Throws <BaseServiceException>(() => productService.CreateProduct(createProductInput));
        }
Ejemplo n.º 26
0
        public async Task <Product> CreateProduct(CreateProductInput createProductInput)
        {
            try
            {
                Product _product = await _productsService.AddProduct(createProductInput);

                return(_product);
            }
            catch (Exception ex)
            {
                throw new QueryException(
                          ErrorBuilder.New()
                          .SetMessage(ex.Message)
                          .SetCode("CREATE_ERROR")
                          .Build());
            }
        }
Ejemplo n.º 27
0
 public virtual async Task UpdateProduct(CreateProductInput input)
 {
     using (_unitOfWorkManager.Current.SetTenantId(_session.TenantId))
     {
         input.TenantId = (int)_session.TenantId;
         var Product = input.MapTo <Product>();
         var query   = _ProductRepository.GetAll()
                       .Where(p => (p.ProductCode == input.ProductCode || p.ProductName == input.ProductName) && p.Id != input.Id).FirstOrDefault();
         if (query == null)
         {
             await _ProductRepository.UpdateAsync(Product);
         }
         else
         {
             throw new UserFriendlyException("Ooops!", "Duplicate Data Occured in Product ...");
         }
     }
 }
Ejemplo n.º 28
0
        private void CreateProductInputValidate(CreateProductInput createProductInput)
        {
            if (string.IsNullOrWhiteSpace(createProductInput.Code))
            {
                throw new ValidationException(nameof(createProductInput.Code));
            }
            if (_productRepository.GetProduct(createProductInput.Code) != null)
            {
                throw new BaseServiceException("This ProductCode has been used before", (int)(HttpStatusCode.BadRequest));
            }
            if (createProductInput.Price <= 0)
            {
                throw new InvalidPriceException();
            }

            if (createProductInput.Stock <= 0)
            {
                throw new InvalidStockException();
            }
        }
Ejemplo n.º 29
0
        public async Task Create(CreateProductInput input)
        {
            //_abpEditionManager.SetFeatureValueAsync()
            //    TenantManager.SetFeatureValue(2, "Count", "20");
            //    TenantManager.SetFeatureValue(3, "Count", "30");
            var a = FeatureChecker.GetValue("Count").To <int>();
            var v = 1;

            //TenantManager.SetFeatureValue()

            //添加版本
            //await _abpEditionManager.CreateAsync(new Edition("Enterprise"));
            //FeatureChecker.CheckEnabled("Product");
            // await _abpZeroFeatureValueStore.SetEditionFeatureValueAsync(1, "Product", "false");
            //var tenant = AbpSession.TenantId;
            //MyPassword.Core.Product.Product product = new Core.Product.Product();
            //product.UpdateName(input.Name);
            //product.UpdateNumber(input.Number, _policy);
            //product.UpdatePrice(input.Price, _policy);
            //await _productRepository.InsertAsync(product);
        }
        //Add new product record
        public async Task <Product> AddProduct(CreateProductInput createProductInput)
        {
            //check if product already exists
            Product product = await db.Products.FirstOrDefaultAsync(i => i.ProductName == createProductInput.ProductName);

            if (product != null)
            {
                throw new Exception("Product already exists");
            }

            Product _product = new Product
            {
                ProductName   = createProductInput.ProductName,
                UnitPrice     = createProductInput.UnitPrice,
                UnitOfMeasure = createProductInput.UnitOfMeasure,
                Currency      = createProductInput.Currency
            };
            await db.Products.AddAsync(_product);

            await db.SaveChangesAsync();

            return(product);
        }
Ejemplo n.º 31
0
 public FubuContinuation New(CreateProductInput input)
 {
     return FubuContinuation.RedirectTo(new ProductsListRequest());
 }