Exemplo n.º 1
0
        public void PutTest()
        {
            Product                      product            = GetProduct();
            ProductRequestModel          productRequest     = GetProductRequestModel();
            ProductResponseModel         productResponse    = GetProductResponseModel();
            ValidationResponse <Product> validationResponse = GetOkValidationResponse();

            _mockMapper
            .Setup(mapper => mapper.Map <ProductRequestModel, Product>(productRequest))
            .Returns(product);

            _mockService
            .Setup(serv => serv.Update(product))
            .Returns(validationResponse);

            _mockMapper
            .Setup(mapper => mapper.Map <Product, ProductResponseModel>(validationResponse.ResponseData))
            .Returns(productResponse);

            IActionResult actionResult = _controller.Put(_productId, productRequest);

            OkObjectResult actual     = (OkObjectResult)actionResult;
            string         actualName = ((ProductResponseModel)actual.Value).Name;

            Assert.Equal(product.Name, actualName);
            Assert.Equal(StatusCodes.Status200OK, actual.StatusCode);
        }
Exemplo n.º 2
0
        private async Task <List <ProductResponseModel> > SearchProductsWithPageSize(List <ProductsByProgramRun> offerProducts, string token)
        {
            var productReponses = new List <ProductResponseModel>();
            var tasks           = new List <Task <List <ProductResponseModel> > >();

            tasks.Add(GetProvider1ProductResponsesAsync(offerProducts, token));
            tasks.Add(_Provider2Api.SearchProducts(offerProducts));

            var completionTask = Task.WhenAll(tasks);

            try
            {
                await completionTask;
            }
            catch
            {
                _logger.LogError(string.Join(", ", completionTask.Exception.Flatten().InnerExceptions.Select(e => e.Message)));
            }

            foreach (var task in tasks)
            {
                if (task.Status == TaskStatus.RanToCompletion)
                {
                    List <ProductResponseModel> productResponses = task.Result;
                    if (productResponses != null)
                    {
                        productReponses.AddRange(productResponses);
                    }
                }
            }

            // Gets Provider2 products
            List <ProductResponseModel> provider2Products = productReponses.Where(p => p.ProductType == ProductType.Provider2).ToList();

            // Sync with Provider1 product info
            foreach (ProductResponseModel provider2Product in provider2Products)
            {
                ProductResponseModel provider1Product = productReponses.FirstOrDefault(p => p.ProductType == ProductType.Provider1 && p.ProductCode == provider2Product.ProductCode);

                if (provider1Product != null)
                {
                    provider2Product.Provider1ImageUrl = provider1Product.Provider1ImageUrl;
                }

                // Adds to failed products
                if (string.IsNullOrEmpty(provider2Product.Provider1ImageUrl) && string.IsNullOrEmpty(provider2Product.Provider2ImageUrl))
                {
                    if (_retryFaildedProductsByProgramRun)
                    {
                        _failedProducts.Add(provider2Product.ProductsByProgramRun);
                    }
                    else
                    {
                        _failedProductsLoggedToDB.Add(provider2Product.ProductsByProgramRun);
                    }
                }
            }

            return(provider2Products);
        }
Exemplo n.º 3
0
        public void PostTest()
        {
            Product              product         = GetProduct();
            ProductRequestModel  productRequest  = GetProductRequestModel();
            ProductResponseModel productResponse = GetProductResponseModel();

            _mockRepository
            .Setup(repo => repo.Add(product))
            .Returns(product);

            _mockMapper
            .Setup(mapper => mapper.Map <ProductRequestModel, Product>(productRequest))
            .Returns(product);

            _mockMapper
            .Setup(mapper => mapper.Map <Product, ProductResponseModel>(product))
            .Returns(productResponse);

            IActionResult actionResult = _controller.Post(productRequest);

            CreatedAtActionResult actual = (CreatedAtActionResult)actionResult;
            string actualName            = ((ProductResponseModel)actual.Value).Name;

            Assert.Equal(product.Name, actualName);
            Assert.Equal(StatusCodes.Status201Created, actual.StatusCode);
        }
Exemplo n.º 4
0
        public IActionResult Post([FromBody]ProductRequestModel createProductRequest)
        {
            Product product = _mapper.Map<ProductRequestModel, Product>(createProductRequest);
            product = _productRepository.Add(product);

            ProductResponseModel productResponse = _mapper.Map<Product, ProductResponseModel>(product);

            return CreatedAtAction("Get", new { id = productResponse.Id }, productResponse);
        }
        /// <inheritdoc />
        public async Task <ProductResponseModel> GetProductAsync(Guid id)
        {
            var product = new ProductResponseModel()
            {
                Id = id.ToString(), Name = "Awesome Product", Price = 12.34M
            };

            return(await Task.FromResult(product).ConfigureAwait(false));
        }
Exemplo n.º 6
0
        private async Task <List <ProductResponseModel> > GetProvider1ProductResponsesAsync(List <ProductsByProgramRun> offerProducts, string token)
        {
            var productReponses = new List <ProductResponseModel>();

            var tasks = new List <Task <ProductResponseModel> >();

            foreach (ProductsByProgramRun offerProduct in offerProducts)
            {
                try
                {
                    if (!_cache.TryGetValue(offerProduct.ProductCode, out ProductResponseModel productResponseDTO))
                    {
                        tasks.Add(_provider1Api.SearchProduct(offerProduct, token));
                    }
                    else
                    {
                        _logger.LogInformation($"Gets product from cache with ProductCode={offerProduct.ProductCode}");
                        productReponses.Add(productResponseDTO);
                    }
                }
                catch (Exception ex)
                {
                    _logger.LogError($"Error in Getting MemoryCache", ex);
                }
            }

            var completionTask = Task.WhenAll(tasks);

            try
            {
                await completionTask;
            }
            catch
            {
                _logger.LogError(string.Join(", ", completionTask.Exception.Flatten().InnerExceptions.Select(e => e.Message)));
            }

            foreach (var task in tasks)
            {
                if (task.Status == TaskStatus.RanToCompletion)
                {
                    ProductResponseModel provider1ProductsResponse = task.Result;
                    if (provider1ProductsResponse != null)
                    {
                        productReponses.Add(provider1ProductsResponse);

                        // Cache response objects from API
                        var cacheEntryOptions = new MemoryCacheEntryOptions().SetAbsoluteExpiration(TimeSpan.FromSeconds(60 * 60 * 1));
                        _cache.Set(provider1ProductsResponse.ProductCode, provider1ProductsResponse, cacheEntryOptions);
                    }
                }
            }

            return(productReponses);
        }
        public async Task <IActionResult> GetWithoutFilter1(long id)
        {
            Product product = await _dbContext.Products.FirstOrDefaultAsync(e => e.Id == id);

            // do your business with product

            // if you do not want to return fields use mapper

            ProductResponseModel response = product.Adapt <ProductResponseModel>();

            return(Ok(response));
        }
        /// <inheritdoc />
        public async Task <ProductCollectionResponseModel> GetProductsAsync()
        {
            var product = new ProductResponseModel()
            {
                Id = Guid.NewGuid().ToString(), Name = "Awesome Product", Price = 12.34M
            };
            var products = new ProductCollectionResponseModel()
            {
                Items = { product }
            };

            return(await Task.FromResult(products).ConfigureAwait(false));
        }
Exemplo n.º 9
0
        public IActionResult GetById(Guid id)
        {
            ValidationResponse<Product> validationResponse = _productService.GetById(id);

            if (validationResponse.Status == ValidationStatus.NotFound)
            {
                return NotFound(validationResponse.Message);
            }

            ProductResponseModel productResponse = 
                _mapper.Map<Product, ProductResponseModel>(validationResponse.ResponseData);

            return Ok(productResponse);
        }
Exemplo n.º 10
0
        public static IEnumerable <ProductResponseModel> BuildProductResponse(this List <Product> products)
        {
            List <ProductResponseModel> responseModels = new List <ProductResponseModel>();

            foreach (var product in products)
            {
                var productModel = new ProductResponseModel()
                {
                    ProductId   = product.Id,
                    Title       = product.Title,
                    Description = product.Description,
                };

                if (product.User != null)
                {
                    productModel.User = new Models.User.UserModel()
                    {
                        Email       = product.User.Email,
                        FirstName   = product.User.FirstName,
                        LastName    = product.User.LastName,
                        PhoneNumber = product.User.PhoneNumber,
                        BirthDate   = product.User.BirthDate
                    };
                }

                if (product.Contact != null)
                {
                    productModel.Contact = new Models.Contact.ContactModel()
                    {
                        ContactPersonId = product.Contact.Id,
                        FirstName       = product.Contact.FirstName,
                        LastName        = product.Contact.LastName,
                        PhoneNumber     = product.Contact.PhoneNumber,
                        FaxNumber       = product.Contact.FaxNumber
                    };
                }

                if (product.ProductType != null)
                {
                    productModel.ProductType = new ProductTypeModel()
                    {
                        ProductTypeId = product.ProductType.Id,
                        ProductType   = product.ProductType.Type
                    };
                }

                responseModels.Add(productModel);
            }
            return(responseModels);
        }
Exemplo n.º 11
0
        public ProductResponseModel ToResponseModel()
        {
            ProductResponseModel p = new ProductResponseModel();

            p.Id          = Id;
            p.Name        = Name;
            p.CategoryId  = CategoryId;
            p.Price       = Price;
            p.ImageUrl    = ImageUrl;
            p.IsActive    = IsActive;
            p.Description = Description;
            p.CategoryDto = CategoryDto;
            return(p);
        }
Exemplo n.º 12
0
        public IActionResult Put(Guid id, [FromBody]ProductRequestModel productRequest)
        {
            Product product = _mapper.Map<ProductRequestModel, Product>(productRequest);
            product.Id = id;

            ValidationResponse<Product> validationResponse = _productService.Update(product);

            if(validationResponse.Status == ValidationStatus.NotFound)
            {
                return NotFound(validationResponse.Message);
            }

            ProductResponseModel productResponse = 
                _mapper.Map<Product, ProductResponseModel>(validationResponse.ResponseData);

            return Ok(productResponse);
        }
Exemplo n.º 13
0
        public static ProductResponseModel BuildProductResponse(this Product product)
        {
            var productModel = new ProductResponseModel()
            {
                ProductId   = product.Id,
                Title       = product.Title,
                Description = product.Description,
            };

            if (product.User != null)
            {
                productModel.User = new Models.User.UserModel()
                {
                    Email       = product.User.Email,
                    FirstName   = product.User.FirstName,
                    LastName    = product.User.LastName,
                    PhoneNumber = product.User.PhoneNumber,
                    BirthDate   = product.User.BirthDate
                };
            }

            if (product.Contact != null)
            {
                productModel.Contact = new Models.Contact.ContactModel()
                {
                    ContactPersonId = product.Contact.Id,
                    FirstName       = product.Contact.FirstName,
                    LastName        = product.Contact.LastName,
                    PhoneNumber     = product.Contact.PhoneNumber,
                    FaxNumber       = product.Contact.FaxNumber
                };
            }

            if (product.ProductType != null)
            {
                productModel.ProductType = new ProductTypeModel()
                {
                    ProductTypeId = product.ProductType.Id,
                    ProductType   = product.ProductType.Type
                };
            }

            return(productModel);
        }
Exemplo n.º 14
0
        public void GetByIdTest()
        {
            ValidationResponse <Product> validationResponse = GetOkValidationResponse();
            ProductResponseModel         productResponse    = GetProductResponseModel();

            _mockService
            .Setup(serv => serv.GetById(_productId))
            .Returns(validationResponse);

            _mockMapper
            .Setup(mapper => mapper.Map <Product, ProductResponseModel>(validationResponse.ResponseData))
            .Returns(productResponse);

            IActionResult actionResult = _controller.GetById(_productId);

            OkObjectResult actual   = (OkObjectResult)actionResult;
            Guid           actualId = ((ProductResponseModel)actual.Value).Id;

            Assert.Equal(_productId, actualId);
            Assert.Equal(StatusCodes.Status200OK, actual.StatusCode);
        }
        public IHttpActionResult GetProduct([FromUri] int id)
        {
            Product product = db.Products.Find(id);

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

            ProductResponseModel productResponse = new ProductResponseModel()
            {
                CategoryId   = product.CategoryId,
                CategoryName = product.Category.Name,
                CompanyId    = product.CompanyId,
                CompanyName  = product.Company.PersianName,
                Description  = product.Description,
                Id           = product.Id,
                ModelName    = product.ModelName
            };

            return(Ok(productResponse));
        }
        public IHttpActionResult GetProducts()
        {
            var products = db.Products.ToList();

            List <ProductResponseModel> productResponses = new List <ProductResponseModel>();

            foreach (var product in products)
            {
                ProductResponseModel model = new ProductResponseModel()
                {
                    CategoryId   = product.CategoryId,
                    CategoryName = product.Category.Name,
                    CompanyId    = product.CompanyId,
                    CompanyName  = product.Company.PersianName,
                    Description  = product.Description,
                    Id           = product.Id,
                    ModelName    = product.ModelName
                };
                productResponses.Add(model);
            }
            return(Ok(productResponses));
        }
Exemplo n.º 17
0
        public List <ProductResponseModel> ViewOrderedProduct()
        {
            try
            {
                List <ProductResponseModel> Products = new List <ProductResponseModel>();
                List <ProductOrder>         Result   = _context.OrderedProduct.ToList();

                if (Result != null)
                {
                    foreach (var data in Result)
                    {
                        ProductDetails OrderedProducts = _context.Products.FirstOrDefault(linq => linq.Id == data.ProductId);
                        if (OrderedProducts != null)
                        {
                            ProductResponseModel OrderedProd = new ProductResponseModel
                            {
                                Id        = OrderedProducts.Id,
                                Name      = OrderedProducts.Name,
                                Quantity  = OrderedProducts.Quantity,
                                Price     = OrderedProducts.Price,
                                Image     = OrderedProducts.Image,
                                CreatedAt = OrderedProducts.createAt,
                                ModefyAt  = OrderedProducts.ModefyAt,
                            };
                            Products.Add(OrderedProd);
                        }
                    }
                }
                if (Products != null)
                {
                    return(Products);
                }
                return(null);
            }
            catch (Exception e)
            {
                throw new ApplicationException(e.Message);
            }
        }
        /// <summary>
        /// Searchs product.
        /// </summary>
        /// <param name="productsByProgramRun">The productsByProgramRun.</param>
        /// <param name="token">The token.</param>
        /// <returns>Task{ProductResponseModel}.</returns>
        public async Task <ProductResponseModel> SearchProduct(ProductsByProgramRun productsByProgramRun, string token)
        {
            try
            {
                string           providerName = _appSettings.ProductProvider1Api.ProviderName;
                string           requestUri   = _appSettings.ProductProvider1Api.RequestUri;
                FluentUriBuilder request      = CreateRequest(requestUri);

                request.AddQueryStringParam("skip", "0");
                request.AddQueryStringParam("take", "20");
                request.AddQueryStringParam("isMember", "True");
                request.AddQueryStringParam("q", productsByProgramRun.ProductCode);

                RemoveDefaultRequestHeaders();
                _httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/vnd.mywebgrocer.product-list+json"));
                _httpClient.DefaultRequestHeaders.Add("Authorization", token);

                var response = await GetAsync <Provider1ProductsResponse>($"SearchProducts from {request.Uri}", request.Uri, CancellationToken.None, providerName);

                ProductResponseModel productResponseDTO = ConvertToProductResponseDTO(productsByProgramRun, response);

                return(productResponseDTO);
            }
            catch (Exception e)
            {
                _logger.LogError($"{nameof(SearchProduct)} Unknown error encountered when reading an object ex {e}");
            }

            return(new ProductResponseModel()
            {
                PromotionId = productsByProgramRun.PromotionId.ToString(),
                OfferId = productsByProgramRun.OfferId.ToString(),
                ProductCode = productsByProgramRun.ProductCode,
                Name = productsByProgramRun.Name,
                ProductsByProgramRun = productsByProgramRun,
                ProductType = ProductType.Provider1
            });
        }