Esempio n. 1
0
        public IHttpActionResult GetProducts(ProductsParametersModel parameters)
        {
            if (parameters.Limit < Configurations.MinLimit || parameters.Limit > Configurations.MaxLimit)
            {
                return(Error(HttpStatusCode.BadRequest, "limit", "invalid limit parameter"));
            }

            if (parameters.Page < Configurations.DefaultPageValue)
            {
                return(Error(HttpStatusCode.BadRequest, "page", "invalid page parameter"));
            }

            var allProducts = _productApiService.GetProducts(parameters.Ids, parameters.CreatedAtMin, parameters.CreatedAtMax, parameters.UpdatedAtMin,
                                                             parameters.UpdatedAtMax, parameters.Limit, parameters.Page, parameters.SinceId, parameters.CategoryId,
                                                             parameters.VendorName, parameters.PublishedStatus)
                              .Where(p => _storeMappingService.Authorize(p));

            IList <ProductDto> productsAsDtos = allProducts.Select(product =>
            {
                return(_dtoHelper.PrepareProductDTO(product));
            }).ToList();

            var productsRootObject = new ProductsRootObjectDto()
            {
                Products = productsAsDtos
            };

            var json = _jsonFieldsSerializer.Serialize(productsRootObject, parameters.Fields);

            return(new RawJsonActionResult(json));
        }
        public void WhenCalledWithLimitParameter_GivenProductsAboveTheLimit_ShouldReturnCollectionWithCountEqualToTheLimit()
        {
            //Arange
            var expectedLimit = 5;

            //Act
            var products = _productApiService.GetProducts(limit: expectedLimit);

            // Assert
            CollectionAssert.IsNotEmpty(products);
            Assert.AreEqual(expectedLimit, products.Count);
        }
Esempio n. 3
0
        public void WhenCalledWithValidSinceId_ShouldReturnOnlyTheProductsAfterThisIdSortedById()
        {
            // Arange
            int sinceId            = 3;
            var expectedCollection = _existigProducts.Where(x => x.Id > sinceId && !x.Deleted).OrderBy(x => x.Id);

            // Act
            var products = _productApiService.GetProducts(sinceId: sinceId);

            // Assert
            CollectionAssert.IsNotEmpty(products);
            Assert.IsTrue(products.Select(x => x.Id).SequenceEqual(expectedCollection.Select(x => x.Id)));
        }
        public void WhenAskForOnlyThePublishedProducts_ShouldReturnOnlyThePublishedProductsOrderedByid()
        {
            // Arange
            var expectedProducts = _existigProducts.Where(x => x.Published && !x.Deleted).OrderBy(x => x.Id);

            // Act
            var products = _productApiService.GetProducts(publishedStatus: true);

            // Assert
            CollectionAssert.IsNotEmpty(products);
            Assert.AreEqual(expectedProducts.Count(), products.Count);
            Assert.IsTrue(products.Select(x => x.Id).SequenceEqual(expectedProducts.Select(x => x.Id)));
        }
Esempio n. 5
0
        public void WhenCalledWithIdsParameter_GivenProductsWithTheSpecifiedIds_ShouldReturnThemSortedById()
        {
            var idsCollection = new List <int>()
            {
                1, 5
            };

            var products = _productApiService.GetProducts(ids: idsCollection);

            // Assert
            CollectionAssert.IsNotEmpty(products);
            Assert.AreEqual(idsCollection[0], products[0].Id);
            Assert.AreEqual(idsCollection[1], products[1].Id);
        }
        public void WhenCalledWithPageParameter_GivenLimitedProductsCollection_ShouldReturnThePartOfTheCollectionThatCorrespondsToThePage()
        {
            //Arange
            var limit = 5;
            var page  = 6;
            var expectedCollection = new ApiList <Product>(_existigProducts.Where(x => !x.Deleted).AsQueryable(), page - 1, limit);

            //Act
            var products = _productApiService.GetProducts(limit: limit, page: page);

            // Assert
            CollectionAssert.IsNotEmpty(products);
            Assert.AreEqual(expectedCollection.Count(), products.Count);
            Assert.IsTrue(products.Select(x => x.Id).SequenceEqual(expectedCollection.Select(x => x.Id)));
        }
Esempio n. 7
0
        public void WhenCalledWithUpdatedAtMinParameter_GivenSomeProductsUpdatedAfterThatDate_ShouldReturnThemSortedById()
        {
            // Arange
            DateTime updatedAtMinDate      = _baseDate.AddMonths(5);
            var      expectedCollection    = _existigProducts.Where(x => x.UpdatedOnUtc > updatedAtMinDate && !x.Deleted).OrderBy(x => x.Id);
            var      expectedProductsCount = expectedCollection.Count();

            // Act
            var products = _productApiService.GetProducts(updatedAtMin: updatedAtMinDate);

            // Assert
            CollectionAssert.IsNotEmpty(products);
            Assert.AreEqual(expectedProductsCount, products.Count);
            Assert.IsTrue(products.Select(x => x.Id).SequenceEqual(expectedCollection.Select(x => x.Id)));
        }
Esempio n. 8
0
        public async Task<IActionResult> Get()
        {
            if (!await _permissionService.Authorize(PermissionSystemName.Products))
                return Forbid();

            return Ok(_productApiService.GetProducts());
        }
Esempio n. 9
0
        public void WhenCalledWithValidCategoryId_ShouldReturnOnlyTheProductsMappedToThisCategory()
        {
            // Arange
            int categoryId         = 3;
            var expectedCollection = (from product in _existigProducts
                                      join mapping in _existingCategoryMappings on product.Id equals mapping.ProductId
                                      where mapping.CategoryId == categoryId
                                      select product);

            // Act
            var products = _productApiService.GetProducts(categoryId: categoryId);

            // Assert
            CollectionAssert.IsNotEmpty(products);
            Assert.AreEqual(expectedCollection.Count(), products.Count);
            Assert.IsTrue(products.Select(x => x.Id).SequenceEqual(expectedCollection.Select(x => x.Id)));
        }
        public IActionResult Get()
        {
            if (!_permissionService.Authorize(PermissionSystemName.Products))
            {
                return(Forbid());
            }

            return(Ok(_productApiService.GetProducts()));
        }
Esempio n. 11
0
        static void Main(string[] args)
        {
            Console.InputEncoding  = Encoding.Unicode;
            Console.OutputEncoding = Encoding.Unicode;
            Console.WriteLine(DateTime.Now);
            Console.WriteLine("Дані із сервера");
            IProductApiService sp = new IProductApiService();

            foreach (var item in sp.GetProducts())
            {
                Console.WriteLine("Id: {0}\tName: {1}\tPrice:{2}",
                                  item.Id, item.Name, item.Price);
            }
            Console.WriteLine(DateTime.Now);
        }
Esempio n. 12
0
        public IActionResult GetProducts(ProductsParametersModel parameters)
        {
            var consumerKey    = Request.Headers.GetInstantCheckoutConsumerKey();
            var consumerSecret = Request.Headers.GetInstantCheckoutConsumerSecret();

            if (consumerKey == Guid.Empty || consumerSecret == Guid.Empty)
            {
                return(Unauthorized());
            }

            var storeScope = _storeContext.ActiveStoreScopeConfiguration;
            var instantCheckoutSettings = _settingService.LoadSetting <InstantCheckoutSettings>(storeScope);

            if (consumerKey != instantCheckoutSettings.ConsumerKey &&
                consumerSecret != instantCheckoutSettings.ConsumerSecret)
            {
                return(Unauthorized());
            }

            if (parameters.Limit < Configurations.MIN_LIMIT || parameters.Limit > Configurations.MAX_LIMIT)
            {
                return(Error(HttpStatusCode.BadRequest, "limit", "invalid limit parameter"));
            }

            if (parameters.Page < Configurations.DEFAULT_PAGE_VALUE)
            {
                return(Error(HttpStatusCode.BadRequest, "page", "invalid page parameter"));
            }

            var allProducts = _productApiService.GetProducts(parameters.Ids, parameters.CreatedAtMin, parameters.CreatedAtMax, parameters.UpdatedAtMin,
                                                             parameters.UpdatedAtMax, parameters.Limit, parameters.Page, parameters.SinceId,
                                                             parameters.PublishedStatus)
                              .Where(p => _storeMappingService.Authorize(p));

            IList <ProductDto> productsAsDtos = allProducts.Select(product => _dtoHelper.PrepareProductDTO(product)).ToList();

            var productsRootObject = new ProductsRootObjectDto()
            {
                Products = productsAsDtos
            };

            var json = _jsonFieldsSerializer.Serialize(productsRootObject, parameters.Fields);

            return(new RawJsonActionResult(json));
        }
Esempio n. 13
0
        public void WhenCalledWithValidVendorName_ShouldReturnOnlyTheProductsMappedToThisVendor(string vendorName)
        {
            // Arange
            var expectedCollection = (from product in _existigProducts
                                      join vendor in _existingVendors on product.VendorId equals vendor.Id
                                      where vendor.Name == vendorName && !vendor.Deleted && vendor.Active
                                      orderby product.Id
                                      select product);

            // Act
            var products = _productApiService.GetProducts(vendorName: vendorName);

            // Assert
            CollectionAssert.IsNotEmpty(products);
            Assert.AreEqual(expectedCollection.Count(), products.Count);
            Assert.IsTrue(products.Select(x => x.Id).SequenceEqual(expectedCollection.Select(x => x.Id)));
        }
        private async void BtnGetData_Click(object sender, RoutedEventArgs e)
        {
            Thread thread = new Thread(() =>
            {
                IProductApiService service = new IProductApiService();
                var list = service.GetProducts();
                foreach (var p in list)
                {
                    Product prod = new Product
                    {
                        Id    = p.Id,
                        Name  = p.Name,
                        Price = p.Price
                    };
                    products.Add(prod);
                }
            });

            thread.Start();


            ///Debug.WriteLine("-----Main thread----- {0}", Thread.CurrentThread.ManagedThreadId);
            ///ProductApiService service = new ProductApiService();
            ///var list = await service.GetProductsAsync();
            ///Debug.WriteLine("-----Main thread----- {0}", Thread.CurrentThread.ManagedThreadId);
            ///foreach (var p in list)
            ///{
            ///    Product prod = new Product
            ///    {
            ///        Id = p.Id,
            ///        Name = p.Name,
            ///        Price=p.Price
            ///    };
            ///    products.Add(prod);
            ///}
        }
Esempio n. 15
0
        public IActionResult GetShippings([FromBody] ShippingsParametersModel parameters)
        {
            var consumerKey    = Request.Headers.GetInstantCheckoutConsumerKey();
            var consumerSecret = Request.Headers.GetInstantCheckoutConsumerSecret();

            if (consumerKey == Guid.Empty || consumerSecret == Guid.Empty)
            {
                return(Unauthorized());
            }

            var storeScope = _storeContext.ActiveStoreScopeConfiguration;
            var instantCheckoutSettings = _settingService.LoadSetting <InstantCheckoutSettings>(storeScope);

            if (consumerKey != instantCheckoutSettings.ConsumerKey &&
                consumerSecret != instantCheckoutSettings.ConsumerSecret)
            {
                return(Unauthorized());
            }

            if (parameters.Ids == null && parameters.Ids.Any(x => x <= 0))
            {
                return(Error(HttpStatusCode.BadRequest, "id", "invalid id"));
            }

            var allProducts = _productApiService.GetProducts(parameters.Ids)
                              .Where(p => _storeMappingService.Authorize(p));

            var cart = new List <ShoppingCartItem> {
            };

            foreach (var product in allProducts)
            {
                cart.Add(new ShoppingCartItem
                {
                    Customer   = _workContext.CurrentCustomer,
                    CustomerId = _workContext.CurrentCustomer.Id,
                    ProductId  = product.Id,
                    Product    = product,
                    Quantity   = 1 //TODO ADD Proper Quantity by Product Check Shipping By Weight
                });
            }

            var model = new ShippingOptionsViewModel();


            var country = _countryService.GetCountryByTwoLetterIsoCode(parameters.CountryCode);
            var state   = _stateProvinceService.GetStateProvinceByAbbreviation(parameters.StateCode);
            var address = new Address
            {
                CountryId       = country.Id,
                Country         = country,
                StateProvinceId = state != null ? state.Id : 0,
                StateProvince   = state != null ? state : null,
                ZipPostalCode   = parameters.ZipCode,
            };

            var getShippingOptionResponse = _shippingService.GetShippingOptions(cart, address, _workContext.CurrentCustomer, storeId: _storeContext.CurrentStore.Id);

            if (getShippingOptionResponse.Success)
            {
                if (getShippingOptionResponse.ShippingOptions.Any())
                {
                    foreach (var shippingOption in getShippingOptionResponse.ShippingOptions)
                    {
                        //calculate discounted and taxed rate
                        var shippingRate = _orderTotalCalculationService.AdjustShippingRate(shippingOption.Rate, cart, out var _);
                        shippingRate = _taxService.GetShippingPrice(shippingRate, _workContext.CurrentCustomer);
                        shippingRate = _currencyService.ConvertFromPrimaryStoreCurrency(shippingRate, _workContext.WorkingCurrency);

                        model.ShippingOptions.Add(new ShippingOptionModel
                        {
                            Name        = shippingOption.Name,
                            Description = shippingOption.Description,
                            Price       = shippingRate,
                            Plugin      = shippingOption.ShippingRateComputationMethodSystemName
                        });
                    }
                }
            }
            else
            {
                foreach (var error in getShippingOptionResponse.Errors)
                {
                    model.Warnings.Add(error);
                }
            }

            if (_shippingSettings.AllowPickupInStore)
            {
                var pickupPointsResponse = _shippingService.GetPickupPoints(address, _workContext.CurrentCustomer, storeId: _storeContext.CurrentStore.Id);
                if (pickupPointsResponse.Success)
                {
                    if (pickupPointsResponse.PickupPoints.Any())
                    {
                        var soModel = new ShippingOptionModel
                        {
                            Name        = _localizationService.GetResource("Checkout.PickupPoints"),
                            Description = _localizationService.GetResource("Checkout.PickupPoints.Description"),
                        };
                        var pickupFee = pickupPointsResponse.PickupPoints.Min(x => x.PickupFee);
                        if (pickupFee > 0)
                        {
                            pickupFee = _taxService.GetShippingPrice(pickupFee, _workContext.CurrentCustomer);
                            pickupFee = _currencyService.ConvertFromPrimaryStoreCurrency(pickupFee, _workContext.WorkingCurrency);
                        }
                        soModel.Price  = pickupFee;
                        soModel.Plugin = "Pickup.PickupInStore";
                        model.ShippingOptions.Add(soModel);
                    }
                }
                else
                {
                    foreach (var error in pickupPointsResponse.Errors)
                    {
                        model.Warnings.Add(error);
                    }
                }
            }

            return(Ok(model));
        }