Ejemplo n.º 1
0
        public async Task <ActionResult> AddProduct([FromBody] PostProductRequest productToAdd)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }
            else
            {
                GetProductDetailsResponse response = await _productCommands.AddProduct(productToAdd);

                return(CreatedAtRoute("products#getbyid", new { id = response.Id }, response));
            }
        }
        public async Task <IActionResult> PostProductAsync(PostProductRequest request)
        {
            Logger?.LogDebug("{0} has been invoked", nameof(PostProductAsync));

            var entity = request.GetProduct();

            entity.CreationUser = UserInfo.UserName;

            // Get response from business logic
            var response = await Service.CreateProductAsync(entity);

            // Return as http response
            return(response.ToHttpResponse());
        }
Ejemplo n.º 3
0
        public async Task CreateProductAsyncRaw()
        {
            IntegrationsWebAppClient client = new IntegrationsWebAppClient("api.eovportal-softtek.com/api/V2", "AllPoints");
            var action = new PostProductRequest {
                Name = "Product Name", Identifier = "MyExternalId1234", ExternalIdentifier = "MyExternalId1234"
            };
            var revert = new DeleteProductRequest {
                ExternalIdentifier = action.Identifier
            };
            var test = new HttpAction <PostProductRequest, GetProductRequest, DeleteProductRequest, ProductResponse>(client.Products.GetByExternalIdentifier, client.Products.Create, client.Products.Remove);
            await test.BeginExecute(action, new GetProductRequest { ExternalIdentifier = action.Identifier });

            await test.BeginRevert(revert, new GetProductRequest { ExternalIdentifier = action.Identifier });

            var wasReverted = test.Confirm();
        }
        public async Task <ActionResult> AddAProduct([FromBody] PostProductRequest productToAdd)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }
            else
            {
                // Add it to the domain.
                GetProductDetailsResponse response = await _productCommands.Add(productToAdd);

                // return:
                // 201 Created
                // Location header with the URL of the new thingy.
                // And a copy of what they would get if they followed that URL.
                return(CreatedAtRoute("products#getproductbyid", new { id = response.Id }, response));
            }
        }
        public void CreateInstanceAndAssignDataExpectSuccess()
        {
            var postProductRequest = new PostProductRequest();

            Assert.NotNull(postProductRequest);

            postProductRequest.Name           = "Name";
            postProductRequest.Description    = "Description";
            postProductRequest.Company        = "Company";
            postProductRequest.Price          = 1;
            postProductRequest.AgeRestriction = 1;

            Assert.Equal("Name", postProductRequest.Name);
            Assert.Equal("Description", postProductRequest.Description);
            Assert.Equal("Company", postProductRequest.Company);
            Assert.Equal(1, postProductRequest.Price);
            Assert.Equal(1, postProductRequest.AgeRestriction);
        }
Ejemplo n.º 6
0
        public static Product getObjectEntity(PostProductRequest entity)
        {
            if (entity == null)
            {
                return(new Product());
            }

            return(new Product
            {
                Id = Guid.NewGuid(),
                Code = entity.Code,
                Name = entity.Name,
                Price = entity.Price,
                Status = entity.Status,
                CreationDate = DateTime.Now,
                LastModified = DateTime.Now
            });
        }
Ejemplo n.º 7
0
        public async Task CreateProductAsyncMediumRaw()
        {
            IntegrationsWebAppClient client = new IntegrationsWebAppClient("api.eovportal-softtek.com/api/V2", "AllPoints");
            var action = new PostProductRequest {
                Name = "Product Name", Identifier = "MyExternalId12345", ExternalIdentifier = "MyExternalId12345"
            };
            var revert = new DeleteProductRequest {
                ExternalIdentifier = action.Identifier
            };
            var test = new CreateProductHttpAction(client.Products.GetByExternalIdentifier, client.Products.Create, client.Products.Remove, action);
            await test.BeginExecute();

            await test.BeginRevert();

            var wasReverted = test.Confirm();

            Assert.IsTrue(wasReverted);
        }
Ejemplo n.º 8
0
        public async Task <IActionResult> PostProductAsync([FromBody] PostProductRequest request)
        {
            Logger?.LogDebug("'{0}' has been invoked", nameof(PostProductAsync));

            var response = new SingleResponse <Product>();

            try
            {
                var existingEntity = await DbContext
                                     .GetProductByProductNameAsync(new Product { Name = request.Name });

                if (existingEntity != null)
                {
                    ModelState.AddModelError("Name", "Product name already exists");
                }

                if (!ModelState.IsValid)
                {
                    return(BadRequest());
                }

                // Create entity from request model
                var entity = request.ToEntity();

                // Add entity to repository
                DbContext.Add(entity);

                // Save entity in database
                await DbContext.SaveChangesAsync();

                // Set the entity to response model
                response.Model = entity;
            }
            catch (Exception ex)
            {
                response.DidError     = true;
                response.ErrorMessage = "There was an internal error, please contact to technical support.";

                Logger?.LogCritical("There was an error on '{0}' invocation: {1}", nameof(PostProductAsync), ex);
            }

            return(response.ToHttpResponse());
        }
        public async Task <IActionResult> PostProductAsync([FromBody] PostProductRequest request)
        {
            ProductMapper mapper = new ProductMapper();

            this._logger?.LogDebug("'{0}' has been invoked", nameof(PostProductAsync));
            var isDuplicate = this._productService.DuplicateCheckByCode(request.Code);

            if (isDuplicate)
            {
                ModelState.AddModelError("ProductCode", "Product already exists");
            }
            if (!ModelState.IsValid)
            {
                return(BadRequest());
            }
            var entity          = mapper.ToEntity(request);
            var createdResource = await this._productService.Create(entity);

            return(this.Ok(createdResource));
        }
        public void ValidatePostProductRequestMissingPriceExpectFailure()
        {
            var postProductRequest = new PostProductRequest();

            Assert.NotNull(postProductRequest);

            postProductRequest.Name           = "Barby";
            postProductRequest.Description    = "Description";
            postProductRequest.Company        = "Mattel";
            postProductRequest.Price          = null;
            postProductRequest.AgeRestriction = 1;

            var  validationResults = new List <ValidationResult>();
            bool isValid           =
                Validator.TryValidateObject(postProductRequest, new ValidationContext(postProductRequest),
                                            validationResults, true);

            Assert.False(isValid, "The PostProductRequest instance passed the validations.");
            Assert.True(validationResults.Count == 1, "The validation results are not equal to one.");
            Assert.Equal("The product price is mandatory.", validationResults[0].ErrorMessage);
        }
        public void ValidatePostProductRequestIncorrectNameExpectFailure()
        {
            var postProductRequest = new PostProductRequest();

            Assert.NotNull(postProductRequest);

            postProductRequest.Name           = "This is a product with a very long name which will make the model to break.";
            postProductRequest.Description    = "Description";
            postProductRequest.Company        = "Company";
            postProductRequest.Price          = 1;
            postProductRequest.AgeRestriction = 1;

            var  validationResults = new List <ValidationResult>();
            bool isValid           =
                Validator.TryValidateObject(postProductRequest, new ValidationContext(postProductRequest),
                                            validationResults, true);

            Assert.False(isValid, "The PostProductRequest instance passed the validations.");
            Assert.True(validationResults.Count == 1, "The validation results are not equal to one.");
            Assert.Equal("The product name must be of 50 characters at maximum.",
                         validationResults[0].ErrorMessage);
        }
        public void ValidatePostProductRequestIncorrectAgeRangeExpectFailure()
        {
            var postProductRequest = new PostProductRequest();

            Assert.NotNull(postProductRequest);

            postProductRequest.Name           = "Barby";
            postProductRequest.Description    = "Description";
            postProductRequest.Company        = "Company";
            postProductRequest.Price          = 1;
            postProductRequest.AgeRestriction = -1;

            var  validationResults = new List <ValidationResult>();
            bool isValid           =
                Validator.TryValidateObject(postProductRequest, new ValidationContext(postProductRequest),
                                            validationResults, true);

            Assert.False(isValid, "The PostProductRequest instance passed the validations.");
            Assert.True(validationResults.Count == 1, "The validation results are not equal to one.");
            Assert.Equal("Value for AgeRestriction must be between 0 and 100",
                         validationResults[0].ErrorMessage);
        }
Ejemplo n.º 13
0
        public void Should_ReturnCreatedProductResourceResponse_When_PostIsCalled()
        {
            var productServiceMock = new Mock <IProductService>();

            productServiceMock.Setup(svc => svc.Create(It.IsAny <Product>()))
            .Returns(Task.FromResult(GetCreateResult()));

            var controller = new ProductController(Mock.Of <ILogger <ProductController> >(), productServiceMock.Object);

            PostProductRequest request = new PostProductRequest()
            {
                Code       = "NCP",
                Name       = "NCP_Sample",
                TaxRate    = 18,
                UnitPrice  = 10,
                StockCount = 10
            };

            var response        = controller.PostProductAsync(request);
            var createdResource = (OkObjectResult)response.Result;

            Assert.IsType <Product>(createdResource.Value);
        }
        public async Task <GetProductDetailResponse> Add(PostProductRequest productToAdd)
        {
            var product  = _mapper.Map <Product>(productToAdd);
            var category = await _context.Categories.SingleOrDefaultAsync(c => c.Name == productToAdd.Category);

            if (category == null)
            {
                var newCategory = new Category {
                    Name = productToAdd.Category
                };
                _context.Categories.Add(newCategory);
                product.Category = newCategory;
            }
            else
            {
                product.Category = category;
            }
            product.Price = productToAdd.Cost.Value * _pricingOptions.Value.Markup;
            _context.Products.Add(product);
            await _context.SaveChangesAsync();

            return(_mapper.Map <GetProductDetailResponse>(product));
        }
        public void ValidatePostProductRequestIncorrectCompanyLengthExpectFailure()
        {
            var postProductRequest = new PostProductRequest();

            Assert.NotNull(postProductRequest);

            postProductRequest.Name        = "Barby";
            postProductRequest.Description = "Description";
            postProductRequest.Company     =
                "Prevailed sincerity behaviour to so do principle mr. As departure at no propriety zealously my. On dear rent if girl view. ";
            postProductRequest.Price          = 1;
            postProductRequest.AgeRestriction = 1;

            var  validationResults = new List <ValidationResult>();
            bool isValid           =
                Validator.TryValidateObject(postProductRequest, new ValidationContext(postProductRequest),
                                            validationResults, true);

            Assert.False(isValid, "The PostProductRequest instance passed the validations.");
            Assert.True(validationResults.Count == 1, "The validation results are not equal to one.");
            Assert.Equal("The product company must be of 50 characters at maximum.",
                         validationResults[0].ErrorMessage);
        }
        public void ValidatePostProductRequestIncorrectDescriptionLengthExpectFailure()
        {
            var postProductRequest = new PostProductRequest();

            Assert.NotNull(postProductRequest);

            postProductRequest.Name        = "Barby";
            postProductRequest.Description =
                "He my polite be object oh change. Consider no mr am overcame yourself throwing sociable children. Hastily her totally conduct may. My solid by stuff first smile fanny. Humoured how advanced mrs elegance sir who. Home sons when them dine do want to";
            postProductRequest.Company        = "Company";
            postProductRequest.Price          = 1;
            postProductRequest.AgeRestriction = 1;

            var  validationResults = new List <ValidationResult>();
            bool isValid           =
                Validator.TryValidateObject(postProductRequest, new ValidationContext(postProductRequest),
                                            validationResults, true);

            Assert.False(isValid, "The PostProductRequest instance passed the validations.");
            Assert.True(validationResults.Count == 1, "The validation results are not equal to one.");
            Assert.Equal("The product description must be of 100 characters at maximum.",
                         validationResults[0].ErrorMessage);
        }
        public async Task PostProductAsync()
        {
            // Arrange
            var userInfo   = IdentityMocker.GetWarehouseOperatorIdentity().GetUserInfo();
            var service    = ServiceMocker.GetWarehouseService(userInfo, nameof(PostProductAsync));
            var controller = new WarehouseController(null, service);
            var request    = new PostProductRequest
            {
                ProductName       = "Test product",
                ProductCategoryID = 100,
                UnitPrice         = 9.99m,
                Description       = "unit tests"
            };

            // Act
            var response = await controller.PostProductAsync(request) as ObjectResult;

            var value = response.Value as ISingleResponse <Product>;

            service.Dispose();

            // Assert
            Assert.False(value.DidError);
        }
Ejemplo n.º 18
0
        public async Task CreateOfferingProductAndPublish()
        {
            string platformIdentifier = PlatformId;
            string platformName       = ServiceConstants.FMPPlatformName;
            string platformHostName   = PlatformHost;
            string productSku         = "SKU300";
            string productExternalId  = ProductExternalId;
            string offeringFullName   = "Put the cloth";
            string offeringCategory   = "externalDev";
            IntegrationsWebAppClient integrationsClientV2 = new IntegrationsWebAppClient(ServiceConstants.IntegrationsAPIUrl, platformName);
            IntegrationsWebAppClient integrationsClientV1 = new IntegrationsWebAppClient(ServiceConstants.IntegrationsAPIUrl, platformIdentifier);

            PostProductRequest createProductRequest = new PostProductRequest
            {
                Identifier         = productExternalId,
                AlternateSkus      = null,
                BrandSku           = "4WW3274",
                Cost               = 11,
                DisplayProductCode = productSku,
                IsOcm              = false,
                IsPurchaseable     = true,
                Name               = "product test name",
                OemRelationships   = new List <ProductOem>
                {
                    new ProductOem
                    {
                        OemName = "name",
                        Type    = 2,
                        OemSku  = "pika"
                    }
                },
                ProductCode     = productSku,
                ProductLeadType = 2,
                Prop65Message   = new ProductProp65Message
                {
                    MessageBody = "This product has been created through a test automation tool"
                },
                SearchKeywords = "test",
                Shipping       = new ProductShippingAttributes()
                {
                    FreightClass      = 179,
                    IsFreeShip        = true,
                    IsFreightOnly     = false,
                    IsQuickShip       = true,
                    WeightActual      = 6.72m,
                    WeightDimensional = 20.62m,
                    Height            = 9.61m,
                    Width             = 16.48m,
                    Length            = 9.60m
                },
                Specs = new List <ProductSpecification>
                {
                    new ProductSpecification
                    {
                        Name  = "pika pika",
                        Value = "chu shock"
                    }
                },
            };

            HttpResponseExtended <ProductResponse> createProductResponse = await integrationsClientV2.Products.Create(createProductRequest);

            Assert.IsNotNull(createProductResponse, $"{nameof(createProductResponse)} is null");
            Assert.IsTrue(createProductResponse.Success == true, $"Product status code is {createProductResponse.StatusCode}");
            Assert.IsNotNull(createProductResponse.Result.ExternalIdentifier, $"{nameof(createProductResponse.Result.ExternalIdentifier)} is null");

            OfferingRequest createOfferingRequest = new OfferingRequest
            {
                Identifier = OfferingExternalId,
                CatalogId  = "externalDev",
                Links      = new List <OfferingLink>
                {
                    new OfferingLink
                    {
                        Label     = "hot side catalog",
                        Url       = "http://tevin.info/unbranded-steel-chicken/primary/bypass",
                        Reference = "20"
                    }
                },
                CategoryIds = new List <string>//TODO: add a real category should be an external identifier
                {
                    offeringCategory
                },
                Description  = "Description for this test offering e2e",
                FullName     = offeringFullName,
                HomeCategory = offeringCategory,
                HtmlPage     = new HtmlPage
                {
                    H1    = $"H1 {offeringFullName}",
                    Title = $"Title {offeringFullName}",
                    Meta  = $"Meta {offeringFullName}",
                    Url   = $"{offeringFullName.ToLower().Replace(" ", "-")}"
                },
                IsPreviewAble = true,
                IsPublishAble = true,
                ProductId     = createProductResponse.Result.ExternalIdentifier
            };

            HttpResponseExtended <OfferingResponse> createOfferingResponse = await integrationsClientV2.Offering.Create(createOfferingRequest);

            Assert.IsNotNull(createOfferingResponse, $"{nameof(createOfferingResponse)} is null");
            Assert.IsTrue(createOfferingResponse.Success, $"Offering response status is {createOfferingResponse.StatusCode}");

            //Publish merchandise
            PublishMerchandiseRequest publishMerchandiseRequest = new PublishMerchandiseRequest
            {
                Hostname         = platformHostName,
                PromoteOnSuccess = true,
                ClearUnusedCache = true
            };

            HttpResponse <PublishMerchandiseResponse> publishMerchandiseResponse = await integrationsClientV1.PublishMerchandise.Publish(publishMerchandiseRequest);

            Assert.IsNotNull(publishMerchandiseResponse, $"{nameof(publishMerchandiseResponse)} is null");
            Assert.IsNull(publishMerchandiseResponse.Message, publishMerchandiseResponse.Message);

            //publish content request
            PublishContentRequest publishContentRequest = new PublishContentRequest
            {
                Hostname = platformHostName
            };

            //HttpResponse<PublishContentResponse> publishContentResponse = await integrationsClientV1.PublishContent.Publish(publishContentRequest);

            //Assert.IsNotNull(publishContentResponse, $"{nameof(publishContentResponse)}");
        }
        public void CreateNewInstanceExpectSuccess()
        {
            var postProductRequest = new PostProductRequest();

            Assert.NotNull(postProductRequest);
        }