Exemple #1
0
        public ProductResponseDto Get(ProductDto request)
        {
            var response = Repository.ProductById(request.Id)
                .TranslateTo<ProductResponseDto>();

            return response;
        }
Exemple #2
0
 public static BusinessLayer.Product FromDto(ProductDto product)
 {
     return new BusinessLayer.Product
                {
                    Id = product.Id,
                    Name = product.Name,
                    Price = product.Price,
                    Category = product.IdCategory
                };
 }
        public void InsertNewProductAttributesBinding()
        {
            using (var db = new Database(DbConnection))
            {
                var product = new ProductDto {Name = "New Product"};

                db.Insert(product);

                Assert.AreNotEqual(0, product.Id);
            }
        }
        public void InsertNewProduct()
        {
            using (var db = new Database(DbConnection))
            {
                var product = new ProductDto {Name = "New Product"};

                db.Insert("Product", "Id", product);

                Assert.AreNotEqual(0, product.Id);
            }
        }
Exemple #5
0
        public void InsertAndFetchNewId()
        {
            using (IDbConnection dbConnection = new SqliteConnectionFactory().Create())
            {
                var insertProduct = new InsertProduct();
                var product = new ProductDto {Name = "New Product"};

                product.Id = (int) dbConnection.Query<Int64>(insertProduct.Query(product)).Single();

                Assert.AreNotEqual(0, product.Id);
            }
        }
        public void DeleteProduct()
        {
            using (IDbConnection dbConnection = SqliteConnectionFactory.Create())
            {
                var product = new ProductDto {Name = "New Product"};

                dbConnection.Insert(product);

                dbConnection.Delete<ProductDto>(dto => dto.Id == dbConnection.LastInsertId());

                Assert.IsNull(dbConnection.SingleById<ProductDto>(1));
            }
        }
        public void Get_Calls_ProductById(ProductDto productDto)
        {
            var mockRepo = new Mock<IRepository>();

            var sut = new ProductsService
            {
                Repository = mockRepo.Object
            };

            var response = sut.Get(productDto);

            mockRepo.Verify(a => a.ProductById(productDto.Id), Times.AtLeastOnce());
        }
Exemple #8
0
        public void SelectProductDtoById()
        {
            using (IDbConnection dbConnection = new SqliteConnectionFactory().Create())
            {
                var product1 = new ProductDto {Name = "Product #1"};
                dbConnection.Execute(new InsertProduct().Query(product1));

                QueryObject byId = new SelectProduct().ById(1);
                ProductDto productDto = dbConnection.Query<ProductDto>(byId).SingleOrDefault();

                Assert.AreEqual(1, productDto.Id);
                Assert.AreEqual("Product #1", productDto.Name);
            }
        }
        public void InsertAndFetchNewId()
        {
            using (IDbConnection dbConnection = SqliteConnectionFactory.Create())
            {
                var product = new ProductDto {Name = "New Product"};

                dbConnection.Insert(product);

                var result = dbConnection
                    .Select<ProductDto>(p => p.Name == product.Name)
                    .First();

                Assert.AreNotEqual(0, result.Id);
            }
        }
        public void UpdateProductByUpdateOnly()
        {
            using (IDbConnection dbConnection = SqliteConnectionFactory.Create())
            {
                var product = new ProductDto {Name = "New Product"};

                dbConnection.Insert(product);

                product.Name = "Changed name";

                dbConnection.UpdateOnly(product, dto => new {dto.Name}, dto => dto.Id == 1);

                Assert.NotNull(dbConnection.Single<ProductDto>(dto => dto.Name == product.Name));
            }
        }
        public void UpdateProductName()
        {
            using (IDbConnection dbConnection = new SqliteConnectionFactory().Create())
            {
                var insertProduct = new InsertProduct();
                var product = new ProductDto {Name = "Product Name"};
                product.Id = (int) dbConnection.Query<Int64>(insertProduct.Query(product)).Single();

                var updateProduct = new UpdateProduct();
                dbConnection.Execute(updateProduct.NameForAllProducts("new name"));

                var selectProduct = new SelectProduct();
                ProductDto result = dbConnection.Query<ProductDto>(selectProduct.ById(product.Id)).Single();

                StringAssert.AreEqualIgnoringCase("new name", result.Name);
            }
        }
        public void AddItem(ProductDto.ProductDto product, int quantity)
        {
            CartLineDto line = lineCollection
                .Where(p => p.Product.ProductId == product.ProductId)
                .FirstOrDefault();

            if (line == null)
            {
                lineCollection.Add(new CartLineDto
                {
                    Product = product,
                    Quantity = quantity
                });
            }
            else
            {
                line.Quantity += quantity;
            }
        }
Exemple #13
0
        public void ProductMapperMapsToExpectedProperties()
        {
            // Arrange
            var mapper = new ProductMapper();
            var productDto = new ProductDto()
            {
                ID = "sp-001",
                Price = 10m,
                ProductName = "Super Product"
            };

            // Act
            Product product = mapper.Map(productDto);

            // Assert
            Assert.AreEqual(10m, product.BasePrice);
            Assert.AreEqual("sp-001", product.ID);
            Assert.AreEqual("Super Product", product.Name);
        }
Exemple #14
0
        public void SelectAllProductsDto()
        {
            using (IDbConnection dbConnection = new SqliteConnectionFactory().Create())
            {
                var product1 = new ProductDto {Name = "Product #1"};
                dbConnection.Execute(new InsertProduct().Query(product1));

                var product2 = new ProductDto {Name = "Product #2"};
                dbConnection.Execute(new InsertProduct().Query(product2));

                var product3 = new ProductDto {Name = "Product #3"};
                dbConnection.Execute(new InsertProduct().Query(product3));

                QueryObject all = new SelectProduct().All();

                IEnumerable<ProductDto> productDtos = dbConnection.Query<ProductDto>(all);

                Assert.AreEqual(3, productDtos.Count());
            }
        }
Exemple #15
0
        public ProductDto UpdateProduct(string eisSku, ProductDto model)
        {
            try
            {
                var existingProduct = _context.products.Find(eisSku);
                if (existingProduct == null)
                {
                    return(model);
                }

                // reflect the changes from model
                var oldUpcCode = existingProduct.UPC;
                Mapper.Map(model, existingProduct);

                // if this product is Shadow product, let's not update its UPC
                if (existingProduct.SkuType == SkuType.Shadow)
                {
                    existingProduct.UPC = oldUpcCode;
                }

                existingProduct.ModifiedBy = model.ModifiedBy;
                existingProduct.Modified   = DateTime.UtcNow;

                // save the changes first for the product
                _context.SaveChanges();

                if (existingProduct.SkuType == SkuType.Normal)
                {
                    // let's check if the product has shadow products
                    var shadows = _context.shadows.Where(x => x.ParentSKU == model.EisSKU).ToList();

                    // update its shadow products' supplier price, seller price and the quantity as well
                    // and also update its UPC code
                    if (shadows.Any())
                    {
                        var parentSellerPrice = (decimal)model.SellerPrice;
                        var parentWeight      = Convert.ToInt32(model.AccurateWeight);

                        foreach (var shadow in shadows)
                        {
                            // get the shadow product details
                            var shadowProduct = _context.products.FirstOrDefault(x => x.EisSKU == shadow.ShadowSKU);
                            shadowProduct.UPC         = model.UPC;
                            shadowProduct.SellerPrice = parentSellerPrice * shadow.FactorQuantity;

                            var accurateWeight = parentWeight * shadow.FactorQuantity;
                            shadowProduct.AccurateWeight     = accurateWeight;
                            shadowProduct.AccurateWeightUnit = model.AccurateWeightUnit;
                            shadowProduct.GuessedWeight      = accurateWeight;
                            shadowProduct.GuessedWeightUnit  = model.GuessedWeightUnit;

                            var accurateRate = getShippingRate(accurateWeight);
                            shadowProduct.AccurateShipping = accurateRate.ToString();
                            shadowProduct.GuessedShipping  = accurateRate.ToString();
                            shadowProduct.ModifiedBy       = model.ModifiedBy;
                            shadowProduct.Modified         = DateTime.UtcNow;
                        }

                        // let's save the changes
                        _context.SaveChanges();
                    }
                }
            }
            catch (DbEntityValidationException ex)
            {
                var errorMsg = EisHelper.ParseDbEntityValidationException(ex);
                _logger.LogError(LogEntryType.ProductService, errorMsg, ex.StackTrace);
                throw ex;
            }
            catch (Exception ex)
            {
                _logger.LogError(LogEntryType.ProductService, EisHelper.GetExceptionMessage(ex), ex.StackTrace);
                throw ex;
            }

            return(model);
        }
        public Product GetProductById(int id)
        {
            ProductDto productDto = _productDao.GetProductById(id);

            return(Product.FromDto(productDto));
        }
Exemple #17
0
 public QueryObject Query(ProductDto product)
 {
     return new QueryObject(@"insert into Product(Name) values (@Name);
                              SELECT last_insert_rowid();", new {product.Name});
 }
        private async Task seedDatabaseForProduct(IProductRepository repository, IRepository <Category> categoryRepository, IRepository <Option> optionRepository)
        {
            //Per fare presto (essendo un progettino di dimostrazione)
            //Popolo il database nel caos in cui non trovo nessun prodotto
            //Utilizzo direttamente ListAll per fare prima a scrivere il codice anche se sarà piu lento
            var products = await repository.ListAllAsync();

            var category = await categoryRepository.ListAllAsync();

            var option = await optionRepository.ListAllAsync();

            if (products.Count > 0 ||
                category.Count > 0 ||
                option.Count > 0)
            {
                return;
            }



            var categoryDto = new CategoryDto
            {
                Name        = "Abiti Estivi",
                Description = "Ogni tipo di abito per l'estate",
                CategoryId  = 1
            };
            var catOne = (await Category.CreateCategoryAsync(categoryDto, null)).ValidatedObject;

            categoryRepository.Add(catOne);
            await categoryRepository.SaveChangeAsync(); //Fatto ogni volta per garantirmi l'id crescente

            categoryDto = new CategoryDto
            {
                Name        = "Abiti Invernali",
                Description = "Ogni tipo di abito invernale",
                CategoryId  = 2
            };
            var catTwo = (await Category.CreateCategoryAsync(categoryDto, null)).ValidatedObject;

            categoryRepository.Add(catTwo);
            await categoryRepository.SaveChangeAsync(); //Fatto ogni volta per garantirmi l'id crescente

            categoryDto = new CategoryDto
            {
                Name        = "Scarpe",
                Description = "Tutte le scarpe",
                CategoryId  = 3
            };
            var catThree = (await Category.CreateCategoryAsync(categoryDto, null)).ValidatedObject;

            categoryRepository.Add(catThree);
            await categoryRepository.SaveChangeAsync(); //Fatto ogni volta per garantirmi l'id crescente


            var dto = new ProductDto
            {
                Name        = "Pantanoni Lana",
                Description = "Pantaloni di lana economici",
                CategoryId  = 2
            };
            var productOne = (await Product.CreateProductAsync(dto, null)).ValidatedObject;

            repository.Add(productOne);
            await repository.SaveChangeAsync(); //Fatto ogni volta per garantirmi l'id crescente

            dto = new ProductDto
            {
                Name        = "Maglione Lana",
                Description = "Maglione di lana economici",
                CategoryId  = 2
            };
            var productTwo = (await Product.CreateProductAsync(dto, null)).ValidatedObject;

            repository.Add(productTwo);
            await repository.SaveChangeAsync(); //Fatto ogni volta per garantirmi l'id crescente

            dto = new ProductDto
            {
                Name        = "Camicia estiva",
                Description = "Camicia leggera",
                CategoryId  = 1
            };
            var productThree = (await Product.CreateProductAsync(dto, null)).ValidatedObject;

            repository.Add(productThree);
            await repository.SaveChangeAsync(); //Fatto ogni volta per garantirmi l'id crescente

            dto = new ProductDto
            {
                Name        = "Pantaloncini",
                Description = "Pantaloncini ottimi",
                CategoryId  = 1
            };
            var productFour = (await Product.CreateProductAsync(dto, null)).ValidatedObject;

            repository.Add(productFour);
            await repository.SaveChangeAsync(); //Fatto ogni volta per garantirmi l'id crescente

            dto = new ProductDto
            {
                Name        = "Scarpa",
                Description = "Scarpa per ogni stagione",
                CategoryId  = 3
            };
            var productFive = (await Product.CreateProductAsync(dto, null)).ValidatedObject;

            repository.Add(productFive);
            await repository.SaveChangeAsync(); //Fatto ogni volta per garantirmi l'id crescente

            dto = new ProductDto
            {
                Name        = "ScarpaSenzaOptioni",
                Description = "Scarpa usata senza optioni",
                CategoryId  = 3
            };
            var productSix = (await Product.CreateProductAsync(dto, null)).ValidatedObject;

            repository.Add(productSix);
            await repository.SaveChangeAsync(); //Fatto ogni volta per garantirmi l'id crescente



            var optionDto = new OptionDto
            {
                Name        = "Colore",
                Description = "Colore associato"
            };
            var option1 = (await Option.CreateOptionAsync(optionDto, null)).ValidatedObject;

            optionRepository.Add(option1);
            await optionRepository.SaveChangeAsync(); //Fatto ogni volta per garantirmi l'id crescente

            optionDto = new OptionDto
            {
                Name        = "Taglia",
                Description = "Taglia associata"
            };
            var option2 = (await Option.CreateOptionAsync(optionDto, null)).ValidatedObject;

            optionRepository.Add(option2);
            await optionRepository.SaveChangeAsync(); //Fatto ogni volta per garantirmi l'id crescente

            optionDto = new OptionDto
            {
                Name        = "Ricamo",
                Description = "Tipologia di ricamo"
            };
            var option3 = (await Option.CreateOptionAsync(optionDto, null)).ValidatedObject;

            optionRepository.Add(option3);
            await optionRepository.SaveChangeAsync(); //Fatto ogni volta per garantirmi l'id crescente

            optionDto = new OptionDto
            {
                Name        = "Misura",
                Description = "Misara in cm"
            };
            var option4 = (await Option.CreateOptionAsync(optionDto, null)).ValidatedObject;

            optionRepository.Add(option4);
            await optionRepository.SaveChangeAsync(); //Fatto ogni volta per garantirmi l'id crescente

            optionDto = new OptionDto
            {
                Name        = "OptioneMaiUsata",
                Description = "DescOption5"
            };
            var option5 = (await Option.CreateOptionAsync(optionDto, null)).ValidatedObject;

            optionRepository.Add(option5);
            await optionRepository.SaveChangeAsync(); //Fatto ogni volta per garantirmi l'id crescente


            //repository.LinkCategory(productOne, catOne);
            //repository.LinkCategory(productFour, catOne);
            //repository.LinkCategory(productTwo, catTwo);
            //repository.LinkCategory(productFive, catTwo);
            //repository.LinkCategory(productThree, catThree);


            repository.LinkOption(productOne, option1);
            repository.LinkOption(productTwo, option1);
            repository.LinkOption(productThree, option1);
            repository.LinkOption(productFour, option1);
            repository.LinkOption(productFive, option1);

            repository.LinkOption(productOne, option2);
            repository.LinkOption(productTwo, option2);
            repository.LinkOption(productThree, option2);
            repository.LinkOption(productFour, option2);

            repository.LinkOption(productOne, option3);
            repository.LinkOption(productTwo, option3);
            repository.LinkOption(productThree, option3);
            repository.LinkOption(productFour, option3);

            repository.LinkOption(productFive, option4);


            await optionRepository.SaveChangeAsync();
        }
Exemple #19
0
 private object findRowWithProduct(ProductDto product)
 {
     foreach (DataGridViewRow row in zamowienieDataGridView.Rows)
     {
         if (row.Tag == product)
             return row;
     }
     return null;
 }
Exemple #20
0
        public ActionResult SaveProduct(ProductDto product)
        {
            var success = !String.IsNullOrWhiteSpace(product.GenericName);
            var message = String.Empty;
            product.DisplayName = "dopamine Dynatra infusievloeistof 5 mL ampul";

            return this.Direct(new { success, data = product, message });
        }
        public void SetUp()
        {
            _fixture = new Fixture();

            _product = _fixture.Create <ProductDto>();
        }
Exemple #22
0
        public static ProductDto GetParacetamolDto()
        {
            var subst = new ProductSubstanceDto
                            {
                                Id = Guid.NewGuid().ToString(),
                                Name = "paracetamol",
                                Quantity = 500,
                                SortOrder = 1,
                                Substance = "paracetamol",
                                UnitAbbreviation = "mg",
                                UnitDivisor = 1000,
                                UnitGroupAllowConversion = true,
                                UnitGroupName = "massa",
                                UnitIsReference = false,
                                UnitMultiplier = 1/1000,
                                UnitName = "milligram"
                            };

            var route = new RouteDto
                            {
                                Id = Guid.NewGuid().ToString(),
                                Name = "oraal",
                                Abbreviation = "or"
                            };

            var dto = new ProductDto
                          {
                              BrandName = "",
                              GenericName = "paracetamol",
                              DisplayName = "paracetamol 500 mg tablet",
                              Id = Guid.NewGuid().ToString(),
                              Name = DisplayName,
                              PackageAbbreviation = "tabl",
                              PackageName = "tablet",
                              ProductCode = "2",
                              Quantity = 1M,
                              Routes = new List<RouteDto> { route },
                              ShapeName = "tablet",
                              Substances = new List<ProductSubstanceDto> {subst},
                              UnitAbbreviation = "stuk",
                              UnitDivisor = 1,
                              UnitGroupAllowConversion = false,
                              UnitGroupName = "verpakking",
                              UnitIsReference = false,
                              UnitMultiplier = 1,
                              UnitName = "stuk"
                          };
            return dto;
        }
        private async Task <ProductDto> GetAllGategoriesAsync(ProductDto product)
        {
            product.Categories = await _productAppService.GetAllCategories();

            return(product);
        }
 public static void VerifyImageUnchanged(this ProductDto dto, ProductDto originalDto)
 {
     Assert.That(dto.ImageLocation, Is.EqualTo(originalDto.ImageLocation));
     Assert.That(dto.PrimaryImage, Is.EqualTo(originalDto.PrimaryImage));
 }
Exemple #25
0
        public void ConfirmOrderAsync_MultipleConcurrentReservations_ExecutesCorrectly()
        {
            var       productId            = Guid.NewGuid();
            var       customerId           = Guid.NewGuid();
            const int storedAmount         = 100;
            const int reservedAmount       = 1;
            const int numberOfReservations = 10;
            var       returnedProduct      = new Song {
                Id = productId, StoredUnits = storedAmount
            };
            var returnedProductDto = new ProductDto {
                Id = productId, StoredUnits = storedAmount
            };
            var OrderCreateDto = new OrderCreateDto
            {
                RatingDto = new RatingDto {
                    Id = Guid.NewGuid(), CustomerId = customerId, Issued = DateTime.Now, TotalPrice = 8000
                },
                RateSongs = new List <RateSongDto>
                {
                    new RateSongDto {
                        Id = Guid.NewGuid(), Product = returnedProductDto, Value = reservedAmount
                    }
                }
            };

            var mockManager            = new FacadeMockManager();
            var productRepositoryMock  = mockManager.ConfigureGetAndUpdateRepositoryMock(returnedProduct, nameof(Song.StoredUnits));
            var customerRepositoryMock = mockManager.ConfigureGetRepositoryMock(new Artist {
                Id = customerId
            });
            var OrderRepositoryMock    = mockManager.ConfigureCreateRepositoryMock <Rating>(nameof(Rating.CustomerId));
            var RateSongRepositoryMock = mockManager.ConfigureRepositoryMock <RateSong>();
            var OrderQueryMock         = mockManager.ConfigureQueryObjectMock <RatingDto, Rating, RatingFilterDto>(null);
            var RateSongQueryMock      = mockManager.ConfigureQueryObjectMock <RateSongDto, RateSong, RateSongFilterDto>(null);
            var reservationService     = new ReservationService(FacadeMockManager.ConfigureRealMapper(), productRepositoryMock.Object);

            async Task ReservationAction(Guid cId, int reservedUnits) => await reservationService.ReserveProduct(new ProductReservationDto
            {
                CustomerId     = cId,
                ProductId      = productId,
                ReservedAmount = reservedUnits,
                Expiration     = DateTime.Now.Add(new TimeSpan(1, 0, 0))
            });

            var tasks = new Task[10];

            for (var i = 0; i < numberOfReservations - 1; i++)
            {
                var amount = i;
                tasks[i] = Task.Run(() => ReservationAction(Guid.NewGuid(), amount));
            }
            tasks[numberOfReservations - 1] = Task.Run(() => ReservationAction(customerId, reservedAmount));
            Task.WaitAll(tasks);

            var OrderFacade = CreateOrderFacade(productRepositoryMock, RateSongQueryMock, OrderQueryMock, OrderRepositoryMock, RateSongRepositoryMock, customerRepositoryMock, reservationService);

            OrderFacade.ConfirmOrderAsync(OrderCreateDto, () => Debug.WriteLine("Order confirmed.")).Wait();

            Assert.AreEqual(storedAmount - reservedAmount, mockManager.CapturedUpdatedStoredUnits);
            Assert.AreEqual(customerId, mockManager.CapturedCreatedId);
        }
        private void PrepareProductAttributes(IEnumerable <ProductAttributeMapping> productAttributeMappings, ProductDto productDto)
        {
            if (productDto.ProductAttributeMappings == null)
            {
                productDto.ProductAttributeMappings = new List <ProductAttributeMappingDto>();
            }

            foreach (var productAttributeMapping in productAttributeMappings)
            {
                ProductAttributeMappingDto productAttributeMappingDto = PrepareProductAttributeMappingDto(productAttributeMapping);

                if (productAttributeMappingDto != null)
                {
                    productDto.ProductAttributeMappings.Add(productAttributeMappingDto);
                }
            }
        }
        private void PrepareProductImages(IEnumerable <ProductPicture> productPictures, ProductDto productDto)
        {
            if (productDto.Images == null)
            {
                productDto.Images = new List <ImageMappingDto>();
            }

            // Here we prepare the resulted dto image.
            foreach (var productPicture in productPictures)
            {
                ImageDto imageDto = PrepareImageDto(productPicture.Picture);

                if (imageDto != null)
                {
                    ImageMappingDto productImageDto = new ImageMappingDto();
                    productImageDto.Id         = productPicture.Id;
                    productImageDto.Position   = productPicture.DisplayOrder;
                    productImageDto.Src        = imageDto.Src;
                    productImageDto.Attachment = imageDto.Attachment;

                    productDto.Images.Add(productImageDto);
                }
            }
        }
        public async Task <IActionResult> Put([FromBody] ProductDto productDto)
        {
            await _unitOfWork.UpdateAsync(productDto);

            return(Ok());
        }
        public async Task <IActionResult> Post([FromBody] ProductDto newProduct)
        {
            var isAdded = await _unitOfWork.AddAsync(newProduct);

            return(Ok(isAdded));
        }
Exemple #30
0
 public IHttpActionResult UpdateProduct(ProductDto dto) => Ok();
Exemple #31
0
 public void CreateProduct(ProductDto productDto)
 {
     productRepository.Add(productDto.MappingProduct());
 }
Exemple #32
0
        public static ProductDto GetDopamineDto()
        {
            var subst = new ProductSubstanceDto
            {
                Id = Guid.NewGuid().ToString(),
                Name = "dopamine",
                Quantity = 200,
                SortOrder = 1,
                Substance = "dopamine",
                UnitAbbreviation = "mg",
                UnitDivisor = 1000,
                UnitGroupAllowConversion = true,
                UnitGroupName = "massa",
                UnitIsReference = false,
                UnitMultiplier = 1 / 1000,
                UnitName = "milligram"
            };

            var dto = new ProductDto
            {
                BrandName = "Dynatra",
                GenericName = "dopamine",
                DisplayName = "dopamine 200 mg (Dynatra) 5 mL infusievloeistof per ampul",
                Id = Guid.NewGuid().ToString(),
                Name = DisplayName,
                PackageAbbreviation = "amp",
                PackageName = "ampul",
                ProductCode = "1",
                Quantity = 5M,
                Routes = new List<RouteDto> { RouteTestFixtures.GetRouteIvDto() },
                ShapeName = "infusievloeistof",
                Substances = new List<ProductSubstanceDto> { subst },
                UnitAbbreviation = "mL",
                UnitDivisor = 1000,
                UnitGroupAllowConversion = true,
                UnitGroupName = "volume",
                UnitIsReference = false,
                UnitMultiplier = 1 / 1000,
                UnitName = "milliliter"
            };
            return dto;
        }
Exemple #33
0
 public void DeleteProduct(ProductDto productDto)
 {
     productRepository.Delete(productDto.MappingProduct());
 }
Exemple #34
0
        private int checkStringIsValidQuantity(string quantityString, ProductDto product)
        {
            var quantity = int.Parse(quantityString);
            if (quantity <= 0)
                throw new ArgumentException("Liczba nie może być <= 0!");
            if (quantity > product.OnStock)
                throw new ArgumentException("W magazynie nie ma wystarczającej liczby sztuk produktu");

            return quantity;
        }
Exemple #35
0
 public void UpdateProduct(ProductDto productDto)
 {
     productRepository.Update(productDto.MappingProduct());
 }
        private void PrepareProductAttributeCombinations(ICollection <ProductAttributeCombination> productAttributeCombinations, ProductDto productDto)
        {
            if (productDto.ProductAttributeCombinations == null)
            {
                productDto.ProductAttributeCombinations = new List <ProductAttributeCombinationDto>();
            }

            foreach (var combination in productAttributeCombinations)
            {
                productDto.ProductAttributeCombinations.Add(new ProductAttributeCombinationDto()
                {
                    Records                     = _genericAttributeService.GetAttribute <List <int> >(combination, "nop.product.attribute.combination.records"),
                    Id                          = combination.Id,
                    StockQuantity               = combination.StockQuantity,
                    Gtin                        = combination.Gtin,
                    Sku                         = combination.Sku,
                    AllowOutOfStockOrders       = combination.AllowOutOfStockOrders,
                    ManufacturerPartNumber      = combination.ManufacturerPartNumber,
                    NotifyAdminForQuantityBelow = combination.NotifyAdminForQuantityBelow,
                    OverriddenPrice             = combination.OverriddenPrice
                });
            }
        }
 public void AddProduct(ProductDto productdto)
 {
     product = productdto;
 }
        private static void AssertCreateFails(decimal quantity, Substance subst, Unit substUnit, Route route, int order,
            Shape shape, ProductDto dto, Package package, decimal prodQuantity, Unit unit)
        {
            try
            {
                Product.Create(dto)
                    .Shape(shape)
                    .Package(package)
                    .Quantity(unit, prodQuantity)
                    .Substance(order, subst, quantity, substUnit)
                    .Route(route);

                Assert.Fail();
            }
            catch (System.Exception e)
            {
                Assert.IsNotInstanceOfType(e, typeof (AssertFailedException));
            }
        }
Exemple #39
0
        public FileStreamResult ViewImage(ProductDto value)
        {
            string id = value.PictureId;

            return(__productService.ViewProduct(id));
        }
        public void PrepareProductSpecificationAttributes(IEnumerable <ProductSpecificationAttribute> productSpecificationAttributes, ProductDto productDto)
        {
            if (productDto.ProductSpecificationAttributes == null)
            {
                productDto.ProductSpecificationAttributes = new List <ProductSpecificationAttributeDto>();
            }

            foreach (var productSpecificationAttribute in productSpecificationAttributes)
            {
                ProductSpecificationAttributeDto productSpecificationAttributeDto = PrepareProductSpecificationAttributeDto(productSpecificationAttribute);

                if (productSpecificationAttributeDto != null)
                {
                    productDto.ProductSpecificationAttributes.Add(productSpecificationAttributeDto);
                }
            }
        }
 public static void VerifyTaxUnchanged(this ProductDto dto, ProductDto originalDto)
 {
     Assert.That(dto.TaxCodeId, Is.EqualTo(originalDto.TaxCodeId));
     Assert.That(dto.IsTaxable, Is.EqualTo(originalDto.IsTaxable));
 }
Exemple #42
0
        /// <summary>
        /// Show particular order's details : Customer Name (first name and Last name), Ordered Date and a table to show the items ordered with its price.
        /// In the table , it include list of product(item) name, unit price, quantity and total price of per item. At the end of the table include a Total of Subtotal.
        /// </summary>
        /// <param name="Orderid">OrderID</param>
        /// <returns>A simiilar to invoice form, customer information and table showed items in the order.</returns>
        //GET: Order/Details/5
        public ActionResult Details(int id)
        {
            ///Send orderResponse to find that order data;
            ShowOrder           ViewModel     = new ShowOrder();
            string              orderUrl      = "orderdata/findorder/" + id;
            HttpResponseMessage orderResponse = client.GetAsync(orderUrl).Result;

            if (orderResponse.IsSuccessStatusCode)
            {
                //Step 1: find Order information
                //if requested is OK, place the selected orderid's data into OrderDto
                OrderDto SelectedOrder = orderResponse.Content.ReadAsAsync <OrderDto>().Result;

                //Step 2: find the customer information for that makes the order
                ////if requested is OK, place the selected matched customerid's data into CustomerDto
                string customerUrl = "CustomerData/FindCustomer/" + SelectedOrder.CustomerID;
                HttpResponseMessage customerResponse = client.GetAsync(customerUrl).Result;

                if (customerResponse.IsSuccessStatusCode)
                {
                    CustomerDto customer = customerResponse.Content.ReadAsAsync <CustomerDto>().Result;
                    SelectedOrder.Customer = customer;
                }

                ViewModel.Order = SelectedOrder;

                //Step 3: find the product information that is listed in this order thru the briding table "OrderItems"
                ////if requested is OK, add the list of items according to the order, contains details cusch as product name, amount, and price into OrderItemsDto
                string orderItemsUrl = "OrderItemsData/FindItemsOfOrder/" + id;
                HttpResponseMessage orderItemsResponse = client.GetAsync(orderItemsUrl).Result;

                if (orderItemsResponse.IsSuccessStatusCode)
                {
                    List <OrderItemDto>      orderItemDtos = new List <OrderItemDto>();
                    IEnumerable <OrderItems> orderItems    = orderItemsResponse.Content.ReadAsAsync <IEnumerable <OrderItems> >().Result;
                    foreach (OrderItems item in orderItems)
                    {
                        string productUrl = "ProductData/FindProduct/" + item.ProductID;
                        HttpResponseMessage productResponse = client.GetAsync(productUrl).Result;
                        if (productResponse.IsSuccessStatusCode)
                        {
                            ProductDto   product      = productResponse.Content.ReadAsAsync <ProductDto>().Result;
                            OrderItemDto orderItemDto = new OrderItemDto
                            {
                                Product      = product,
                                ProductPrice = (double)item.ProductPrice,
                                Amount       = (decimal)item.Amount
                            };
                            orderItemDtos.Add(orderItemDto);
                        }
                    }

                    ViewModel.OrderItems = orderItemDtos;
                }
                //In the ViewModel, it should now contains all three entity information and ready to be call out to display to customer.
                return(View(ViewModel));
            }
            else
            {
                return(RedirectToAction("Error"));
            }
        }
        public IProductList FindByCategory(IUser currentUser, IProductListInputModel query)
        {
            // Find the list of products
            string url = "ProductService.svc/rest/ListProducts2?";

            url += addUserUrlDetails(currentUser);

            url += "&statusSeed=" + _configuration["Storm:StatusSeed"];

            if (query.CategoryIds != null)
            {
                url += "&categorySeed=" + string.Join(",", query.CategoryIds);
            }

            if (query.FlagIds != null)
            {
                url += "&flagSeed=" + string.Join(",", query.FlagIds);
            }
            if (!string.IsNullOrEmpty(query.Query))
            {
                url += "&searchString=" + System.Web.HttpUtility.UrlEncode(query.Query);
            }

            url += "&pageNo=" + (query.PageNumber > 0 ? query.PageNumber : 1);
            url += "&pageSize=" + (query.PageSize > 0?query.PageSize:PageSize);
            url += "&asVariants=1";

            var productList = _connectionManager.GetResult <StormProductList>(url);

            ProductListDto result = new ProductListDto();

            result.ProductCount = productList.ItemCount;
            result.PageSize     = PageSize;
            result.PageNumber   = (query.PageNumber > 0 ? query.PageNumber : 1);
            result.Products     = new List <IProduct>();

            Dictionary <string, ProductDto> variants = new Dictionary <string, ProductDto>();

            foreach (var item in productList.Items)
            {
                ProductDto p = (ProductDto)_productBuilder.BuildFromItem(item);

                if (!string.IsNullOrEmpty(p.GroupByKey))
                {
                    if (variants.ContainsKey(p.GroupByKey))
                    {
                        variants[p.GroupByKey].Variants.Add((VariantDto)p.PrimaryVariant);
                    }
                    else
                    {
                        variants[p.GroupByKey] = p;
                        result.Products.Add(p);
                    }
                }
                else
                {
                    result.Products.Add(p);
                }
            }

            return(result);
        }
        public ActionResult SaveProduct(ProductDto product)
        {
            var success = true;
            var message = String.Empty;

            try
            {
                ProductServices.WithDto(product).Get();
            }
            catch (Exception e)
            {
                success = false;
                message = e.ToString();
            }
            return this.Direct(new { success, data = product, message });
        }
 public void RemoveLine(ProductDto.ProductDto product)
 {
     lineCollection.RemoveAll(l => l.Product.ProductId == product.ProductId);
 }
 public static void VerifyStockCountUnchanged(this ProductDto dto, ProductDto originalDto)
 {
     Assert.That(dto.StockCount, Is.EqualTo(originalDto.StockCount));
 }
 private void IsolateController()
 {
     _dto = Isolate.Fake.Instance<ProductDto>();
     _controller = new ProductController();
 }
Exemple #48
0
 public IActionResult OnPutProduct(ProductDto productDto) => UpsertProduct(productDto);
 public void Execute(ProductDto request)
 {
     _productValidation.ValidateAndThrow(request);
     _context.Write(request);
 }
        private void PrepareProductImages(IEnumerable <ProductPicture> productPictures, ProductDto productDto)
        {
            if (productDto.Images == null)
            {
                productDto.Images = new List <ImageMappingDto>();
            }

            // Here we prepare the resulted dto image.
            foreach (var productPicture in productPictures)
            {
                var imageDto = PrepareImageDto(productPicture.Picture);

                if (imageDto != null)
                {
                    var productImageDto = new ImageMappingDto
                    {
                        Id         = productPicture.Id,
                        Position   = productPicture.DisplayOrder,
                        Src        = imageDto.Src,
                        Attachment = imageDto.Attachment,
                        Alt        = productPicture.Picture.AltAttribute,
                        Title      = productPicture.Picture.TitleAttribute,
                        PictureId  = productPicture.PictureId
                    };

                    productDto.Images.Add(productImageDto);
                }
            }
        }
Exemple #51
0
 private static void AddOneRoute(ProductDto dto)
 {
     dto.Routes = new List<RouteDto>
                      {
                          new RouteDto {Abbreviation = "iv", Name = "intraveneus"}
                      };
 }
Exemple #52
0
 public Task InsertAsync(string id, ProductDto product)
 {
     Products.Add(product);
     return(Task.CompletedTask);
 }
        public IHttpActionResult UpdateProduct([ModelBinder(typeof(JsonModelBinder <ProductDto>))] Delta <ProductDto> productDelta)
        {
            // Here we display the errors if the validation has failed at some point.
            if (!ModelState.IsValid)
            {
                return(Error());
            }

            // We do not need to validate the product id, because this will happen in the model binder using the dto validator.
            int productId = int.Parse(productDelta.Dto.Id);

            Product product = _productApiService.GetProductById(productId);

            if (product == null)
            {
                return(Error(HttpStatusCode.NotFound, "product", "not found"));
            }

            productDelta.Merge(product);

            product.UpdatedOnUtc = DateTime.UtcNow;
            _productService.UpdateProduct(product);

            UpdateProductPictures(product, productDelta.Dto.Images);

            UpdateProductTags(product, productDelta.Dto.Tags);

            UpdateProductManufacturers(product, productDelta.Dto.ManufacturerIds);

            UpdateAssociatedProducts(product, productDelta.Dto.AssociatedProductIds);

            // Update the SeName if specified
            if (productDelta.Dto.SeName != null)
            {
                var seName = product.ValidateSeName(productDelta.Dto.SeName, product.Name, true);
                _urlRecordService.SaveSlug(product, seName, 0);
            }

            UpdateDiscountMappings(product, productDelta.Dto.DiscountIds);

            UpdateStoreMappings(product, productDelta.Dto.StoreIds);

            UpdateAclRoles(product, productDelta.Dto.RoleIds);

            _productService.UpdateProduct(product);

            _customerActivityService.InsertActivity("UpdateProduct",
                                                    _localizationService.GetResource("ActivityLog.UpdateProduct"), product.Name);

            // Preparing the result dto of the new product
            ProductDto productDto = product.ToDto();

            MapAdditionalPropertiesToDTO(product, productDto);

            var productsRootObject = new ProductsRootObjectDto();

            productsRootObject.Products.Add(productDto);

            var json = _jsonFieldsSerializer.Serialize(productsRootObject, string.Empty);

            return(new RawJsonActionResult(json));
        }
 public void Delete(ProductDto input)
 {
     _productManager.Delete(input.Id);
 }
 public static void VerifyPriceUnchanged(this ProductDto dto, ProductDto originalDto)
 {
     Assert.That(dto.CostPrice, Is.EqualTo(originalDto.CostPrice));
     Assert.That(dto.Price, Is.EqualTo(originalDto.Price));
 }