/// <summary>
        /// Adds a Slot to a CustomizedProduct.
        /// </summary>
        /// <param name="addSlotModelView">AddSlotModelView with the Slot's information</param>
        /// <returns>An instance of GetCustomizedProductModelView containing updated CustomizedProduct information.</returns>
        /// <exception cref="ResourceNotFoundException">Thrown when the CustomizedProduct could not be found.</exception>
        public GetCustomizedProductModelView addSlotToCustomizedProduct(AddSlotModelView addSlotModelView)
        {
            CustomizedProductRepository customizedProductRepository = PersistenceContext.repositories().createCustomizedProductRepository();

            CustomizedProduct customizedProduct = customizedProductRepository.find(addSlotModelView.customizedProductId);

            if (customizedProduct == null)
            {
                throw new ResourceNotFoundException(string.Format(ERROR_UNABLE_TO_FIND_CUSTOMIZED_PRODUCT_BY_ID, addSlotModelView.customizedProductId));
            }

            checkUserToken(customizedProduct, addSlotModelView.userAuthToken);

            CustomizedDimensions customizedDimensions = CustomizedDimensionsModelViewService.fromModelView(addSlotModelView.slotDimensions);

            customizedProduct.addSlot(customizedDimensions);

            customizedProduct = customizedProductRepository.update(customizedProduct);

            return(CustomizedProductModelViewService.fromEntity(customizedProduct));
        }
Beispiel #2
0
        public void ensureCatalogueCollectionCantBeCreatedWithProductsNotInCustomizedProductCollection()
        {
            CustomizedProductCollection customizedProductCollection = new CustomizedProductCollection("Closets Spring 2019");

            CustomizedProduct customizedProduct1 = buildCustomizedProduct("1234");

            customizedProduct1.finalizeCustomization();     //!customized products added to collections need to be finished

            customizedProductCollection.addCustomizedProduct(customizedProduct1);

            CustomizedProduct customizedProduct2 = buildCustomizedProduct("1235");

            List <CustomizedProduct> customizedProducts = new List <CustomizedProduct>()
            {
                customizedProduct1, customizedProduct2
            };

            Action createCatalogueCollection = () => new CatalogueCollection(customizedProductCollection, customizedProducts);

            Assert.Throws <ArgumentException>(createCatalogueCollection);
        }
        /// <summary>
        /// Updates an instance of Slot.
        /// </summary>
        /// <param name="updateSlotModelView">Instance of UpdateSlotModelView.</param>
        /// <returns>Instance of GetCustomizedProductModelView with updated CustomizedProduct information.</returns>
        /// <exception cref="ResourceNotFoundException">Thrown when the CustomizedProduct or the Slot could not be found.</exception>
        /// <exception cref="System.ArgumentException">Thrown when none of the CustomizedProduct's properties are updated.</exception>
        public GetCustomizedProductModelView updateSlot(UpdateSlotModelView updateSlotModelView)
        {
            CustomizedProductRepository customizedProductRepository = PersistenceContext.repositories().createCustomizedProductRepository();

            CustomizedProduct customizedProduct = customizedProductRepository.find(updateSlotModelView.customizedProductId);

            if (customizedProduct == null)
            {
                throw new ResourceNotFoundException(string.Format(ERROR_UNABLE_TO_FIND_CUSTOMIZED_PRODUCT_BY_ID, updateSlotModelView.customizedProductId));
            }

            checkUserToken(customizedProduct, updateSlotModelView.userAuthToken);

            Slot slot = customizedProduct.slots.Where(s => s.Id == updateSlotModelView.slotId).SingleOrDefault();

            if (slot == null)
            {
                throw new ResourceNotFoundException(string.Format(ERROR_UNABLE_TO_FIND_SLOT, updateSlotModelView.slotId));
            }

            bool performedAtLeastOneUpdate = false;

            if (updateSlotModelView.dimensions != null)
            {
                CustomizedDimensions updatedDimensions = CustomizedDimensionsModelViewService.fromModelView(updateSlotModelView.dimensions);

                customizedProduct.resizeSlot(slot, updatedDimensions);

                performedAtLeastOneUpdate = true;
            }

            if (!performedAtLeastOneUpdate)
            {
                throw new ArgumentException(ERROR_NO_UPDATE_PERFORMED);
            }

            customizedProduct = customizedProductRepository.update(customizedProduct);

            return(CustomizedProductModelViewService.fromEntity(customizedProduct));
        }
        public void ensureApplyRemovesDiscreteDimensions()
        {
            Color                     color     = Color.valueOf("Durpa", 100, 100, 100, 100);
            Finish                    finish    = Finish.valueOf("der alte wurfelt nicht", 35);
            Material                  material  = new Material("#12", "K6205", "12.jpg", new List <Color>(new[] { color }), new List <Finish>(new[] { finish }));
            ProductCategory           cat       = new ProductCategory("AI");
            DiscreteDimensionInterval discrete  = new DiscreteDimensionInterval(new List <double>(new[] { 50.0, 110.0, 150.0 }));
            DiscreteDimensionInterval discrete2 = new DiscreteDimensionInterval(new List <double>(new[] { 50.0, 150.0, 150.0 }));

            Measurement measurement  = new Measurement(new SingleValueDimension(200), discrete, new SingleValueDimension(50));
            Measurement measurement2 = new Measurement(new SingleValueDimension(200), discrete2, new SingleValueDimension(50));

            List <Measurement> measurements = new List <Measurement>()
            {
                measurement
            };
            List <Measurement> measurements2 = new List <Measurement>()
            {
                measurement2
            };
            Product component = new Product("#10", "Pandora of Provable Existence: Forbidden Cubicle", "10.gltf", cat, new List <Material>(new[] { material }), measurements2);
            Product product   = new Product("#9", "Pandora of Eternal Return: Pandora's Box", "9.fbx", cat, new List <Material>(new[] { material }), measurements, new List <Product>()
            {
                component
            });

            CustomizedDimensions customizedDimensions = CustomizedDimensions.valueOf(200, 110, 50);
            CustomizedMaterial   customizedMaterial   = CustomizedMaterial.valueOf(material, color, finish);
            CustomizedProduct    custom = CustomizedProductBuilder.createCustomizedProduct("12345", product, customizedDimensions).withMaterial(customizedMaterial).build();

            WidthPercentageAlgorithm algorithm = new WidthPercentageAlgorithm();
            Input minInput = Input.valueOf("Minimum Percentage", "From 0 to 1");
            Input maxInput = Input.valueOf("Maximum Percentage", "From 0 to 1");
            Dictionary <Input, string> inputs = new Dictionary <Input, string>();

            inputs.Add(minInput, "0.9");
            inputs.Add(maxInput, "1.0");
            algorithm.setInputValues(inputs);
            Assert.Null(algorithm.apply(custom, component));
        }
        public void ensureApplyRemovesValuesFromDiscreteDimensions()
        {
            Color  color  = Color.valueOf("Epigraph of the Closed Curve: Close Epigraph", 100, 100, 100, 100);
            Finish finish = Finish.valueOf("der alte wurfelt nicht", 20);

            Material                  material    = new Material("#24", "K6205", "12.jpg", new List <Color>(new[] { color }), new List <Finish>(new[] { finish }));
            ProductCategory           cat         = new ProductCategory("AI");
            DiscreteDimensionInterval discrete    = new DiscreteDimensionInterval(new List <double>(new[] { 50.0, 90.0, 100.0, 150.0 }));
            Measurement               measurement = new Measurement(new SingleValueDimension(200), discrete, new SingleValueDimension(50));

            List <Measurement> measurements = new List <Measurement>()
            {
                measurement
            };

            Product component = new Product("#13", "Mother Goose of Diffractive Recitavo: Diffraction Mother Goose", "13.glb", cat, new List <Material>(new[] { material }), measurements);
            Product product   = new Product("#12", "Mother Goose of Mutual Recursion: Recursive Mother Goose ", "12.fbx", cat, new List <Material>(new[] { material }), measurements, new List <Product>()
            {
                component
            });

            CustomizedMaterial   customizedMaterial   = CustomizedMaterial.valueOf(material, color, finish);
            CustomizedDimensions customizedDimensions = CustomizedDimensions.valueOf(200, 100, 50);
            CustomizedProduct    custom = CustomizedProductBuilder.createCustomizedProduct("12345", product, customizedDimensions).withMaterial(customizedMaterial).build();

            WidthPercentageAlgorithm algorithm = new WidthPercentageAlgorithm();
            Input minInput = Input.valueOf("Minimum Percentage", "From 0 to 1");
            Input maxInput = Input.valueOf("Maximum Percentage", "From 0 to 1");
            Dictionary <Input, string> inputs = new Dictionary <Input, string>();

            inputs.Add(minInput, "0.9");
            inputs.Add(maxInput, "1.0");
            algorithm.setInputValues(inputs);
            Product alteredProduct = algorithm.apply(custom, component);
            DiscreteDimensionInterval discreteDimension = (DiscreteDimensionInterval)alteredProduct.productMeasurements[0].measurement.width;
            DiscreteDimensionInterval expected          = new DiscreteDimensionInterval(new List <double>(new[] { 90.0, 100.0 }));

            Assert.True(discreteDimension.Equals(expected));
        }
Beispiel #6
0
        /// <summary>
        /// Adds a CustomizedProduct to the CatalogueCollection.
        /// </summary>
        /// <param name="addCatalogueCollectionProductModelView">AddCatalogueCollectionProductModelView with the data used </param>
        /// <returns></returns>
        /// <exception cref="ResourceNotFoundException">
        /// Thrown when no instance of CommercialCatalogue or CatalogueCollection could be found with the provided identifiers.
        /// </exception>
        /// <exception cref="System.ArgumentException">
        /// Thrown when the CustomizedProduct being added does not exist in a given CustomizedProductCollection.
        /// </exception>
        public GetCommercialCatalogueModelView addCatalogueCollectionProduct(AddCatalogueCollectionProductModelView addCatalogueCollectionProductModelView)
        {
            CommercialCatalogueRepository catalogueRepository = PersistenceContext.repositories().createCommercialCatalogueRepository();

            CommercialCatalogue commercialCatalogue = catalogueRepository.find(addCatalogueCollectionProductModelView.commercialCatalogueId);

            if (commercialCatalogue == null)
            {
                throw new ResourceNotFoundException(string.Format(CATALOGUE_NOT_FOUND_BY_ID, addCatalogueCollectionProductModelView.commercialCatalogueId));
            }

            CatalogueCollection catalogueCollection = commercialCatalogue.catalogueCollectionList
                                                      .Where(cc => cc.customizedProductCollectionId == addCatalogueCollectionProductModelView.customizedProductCollectionId).SingleOrDefault();

            if (catalogueCollection == null)
            {
                throw new ResourceNotFoundException(string.Format(
                                                        CATALOGUE_COLLECTION_NOT_FOUND_BY_ID, addCatalogueCollectionProductModelView.commercialCatalogueId,
                                                        addCatalogueCollectionProductModelView.customizedProductCollectionId)
                                                    );
            }

            //retrieve the instance of CustomizedProduct from the the CustomizedProductCollection linked to the CatalogueCollection
            CustomizedProduct customizedProduct = catalogueCollection.customizedProductCollection.collectionProducts
                                                  .Where(cp => cp.customizedProductId == addCatalogueCollectionProductModelView.customizedProductId)
                                                  .Select(cp => cp.customizedProduct).SingleOrDefault();

            if (customizedProduct == null)
            {
                throw new ArgumentException(string.Format(
                                                CUSTOMIZED_PRODUCT_NOT_FOUND_BY_ID, addCatalogueCollectionProductModelView.customizedProductId, addCatalogueCollectionProductModelView.customizedProductCollectionId
                                                ));
            }

            catalogueCollection.addCustomizedProduct(customizedProduct);
            commercialCatalogue = catalogueRepository.update(commercialCatalogue);

            return(CommercialCatalogueModelViewService.fromEntity(commercialCatalogue));
        }
        public void ensureApplyChangesContinuousDimensionsLimits()
        {
            Color                       color        = Color.valueOf("Open the Missing Link", 100, 100, 100, 100);
            Finish                      finish       = Finish.valueOf("der alte wurfelt nicht", 20);
            Material                    material     = new Material("#12", "K6205", "12.png", new List <Color>(new[] { color }), new List <Finish>(new[] { finish }));
            ProductCategory             cat          = new ProductCategory("AI");
            ContinuousDimensionInterval continuous   = new ContinuousDimensionInterval(50.0, 150.0, 20.0);
            Measurement                 measurement  = new Measurement(new SingleValueDimension(200), continuous, new SingleValueDimension(50));
            List <Measurement>          measurements = new List <Measurement>()
            {
                measurement
            };

            Product component = new Product("#19", "Altair of the Cyclic Coordinate: Time-leap Machine", "19.glb", cat, new List <Material>(new[] { material }), measurements);

            Product product = new Product("#18", "Altair of Translational Symmetry: Translational Symmetry", "18.glb", cat, new List <Material>(new[] { material }), measurements,
                                          new List <Product>()
            {
                component
            });

            CustomizedDimensions customizedDimensions = CustomizedDimensions.valueOf(200, 100, 50);
            CustomizedMaterial   customizedMaterial   = CustomizedMaterial.valueOf(material, color, finish);
            CustomizedProduct    custom = CustomizedProductBuilder.createCustomizedProduct("12345", product, customizedDimensions).withMaterial(customizedMaterial).build();

            WidthPercentageAlgorithm algorithm = new WidthPercentageAlgorithm();
            Input minInput = Input.valueOf("Minimum Percentage", "From 0 to 1");
            Input maxInput = Input.valueOf("Maximum Percentage", "From 0 to 1");
            Dictionary <Input, string> inputs = new Dictionary <Input, string>();

            inputs.Add(minInput, "0.9");
            inputs.Add(maxInput, "1.0");
            algorithm.setInputValues(inputs);
            Product alteredProduct = algorithm.apply(custom, component);

            Assert.True(alteredProduct.productMeasurements[0].measurement.width.getMinValue() == 90);
            Assert.True(alteredProduct.productMeasurements[0].measurement.width.getMaxValue() == 100);
            Assert.True(((ContinuousDimensionInterval)alteredProduct.productMeasurements[0].measurement.width).increment == 10);
        }
        public void ensureApplyFailsIfAlgorithmNotReady()
        {
            Color                       color        = Color.valueOf("Open the Steins Gate", 100, 100, 100, 100);
            Finish                      finish       = Finish.valueOf("der alte wurfelt nicht", 15);
            Material                    material     = new Material("#12", "K6205", "12.jpg", new List <Color>(new[] { color }), new List <Finish>(new[] { finish }));
            ProductCategory             cat          = new ProductCategory("AI");
            ContinuousDimensionInterval continuous1  = new ContinuousDimensionInterval(110.0, 150.0, 2.0);
            ContinuousDimensionInterval continuous2  = new ContinuousDimensionInterval(50.0, 80.0, 2.0);
            Measurement                 measurement1 = new Measurement(continuous1, continuous1, continuous1);
            Measurement                 measurement2 = new Measurement(continuous2, continuous2, continuous2);
            ContinuousDimensionInterval continuous3  = new ContinuousDimensionInterval(35.0, 45.0, 1.0);
            ContinuousDimensionInterval continuous4  = new ContinuousDimensionInterval(10.0, 20.0, 2.0);
            Measurement                 measurement3 = new Measurement(continuous3, continuous3, continuous3);
            Measurement                 measurement4 = new Measurement(continuous4, continuous4, continuous4);
            List <Measurement>          measurements = new List <Measurement>()
            {
                measurement1, measurement2
            };
            List <Measurement> measurements2 = new List <Measurement>()
            {
                measurement3, measurement4
            };

            Product component = new Product("#5", "Solitude of the Astigmatism: Entangled Sheep", "5.glb", cat, new List <Material>(new[] { material }), measurements2);
            Product product   = new Product("#4", "Solitude of the Mournful Flow: A Stray Sheep", "4.gltf", cat, new List <Material>(new[] { material }), measurements, new List <Product>()
            {
                component
            });

            CustomizedDimensions customizedDimensions = CustomizedDimensions.valueOf(110, 110, 110);
            CustomizedMaterial   customizedMaterial   = CustomizedMaterial.valueOf(material, color, finish);
            CustomizedProduct    custom = CustomizedProductBuilder.createCustomizedProduct("12345", product, customizedDimensions).withMaterial(customizedMaterial).build();

            WidthPercentageAlgorithm algorithm = new WidthPercentageAlgorithm();
            Action action = () => algorithm.apply(custom, component);

            Assert.Throws <ArgumentNullException>(action);
        }
Beispiel #9
0
        /// <summary>
        /// Updates a customized product collection by adding a new customized product to it
        /// </summary>
        /// <param name="modelView">model view with the necessary update information</param>
        /// <returns>Updated customized product collection or throws an exception if an error occurs</returns>
        public static CustomizedProductCollection update(AddCustomizedProductToCustomizedProductCollectionModelView modelView)
        {
            CustomizedProductCollectionRepository customizedProductCollectionRepository =
                PersistenceContext.repositories()
                .createCustomizedProductCollectionRepository();

            CustomizedProductCollection customizedProductCollection =
                customizedProductCollectionRepository.find(modelView.customizedProductCollectionId);

            checkIfCustomizedProductCollectionWasFound(
                customizedProductCollection, modelView.customizedProductCollectionId
                );

            CustomizedProduct customizedProduct =
                PersistenceContext.repositories()
                .createCustomizedProductRepository()
                .find(modelView.customizedProductId);

            if (customizedProduct == null)
            {
                throw new ArgumentException(
                          string.Format(
                              UNABLE_TO_FIND_CUSTOMIZED_PRODUCT,
                              modelView.customizedProductId)
                          );
            }

            customizedProductCollection.addCustomizedProduct(customizedProduct);

            CustomizedProductCollection updatedCustomizedProductCollection =
                customizedProductCollectionRepository.update(customizedProductCollection);

            checkIfUpdatedCustomizedProductCollectionWasSaved(
                updatedCustomizedProductCollection, modelView.customizedProductCollectionId
                );

            return(updatedCustomizedProductCollection);
        }
        public void ensureApplyCondensesDiscreteDimensions()
        {
            Color                     color        = Color.valueOf("Silver", 100, 100, 100, 100);
            Finish                    finish       = Finish.valueOf("der alte wurfelt nicht", 20);
            Material                  material     = new Material("#12", "K6205", "12.jpg", new List <Color>(new[] { color }), new List <Finish>(new[] { finish }));
            ProductCategory           cat          = new ProductCategory("AI");
            DiscreteDimensionInterval discrete     = new DiscreteDimensionInterval(new List <double>(new[] { 50.0, 100.0, 150.0 }));
            Measurement               measurement  = new Measurement(new SingleValueDimension(200), discrete, new SingleValueDimension(50));
            List <Measurement>        measurements = new List <Measurement>()
            {
                measurement
            };

            Product component = new Product("#21", "Rinascimento of Image Formation: Return of Phoenix", "21.glb", cat, new List <Material>(new[] { material }), measurements);
            Product product   = new Product("#20", "Rinascimento of the Unwavering Promise: Promised Rinascimento", "20.gltf", cat, new List <Material>(new[] { material }), measurements, new List <Product>()
            {
                component
            });

            CustomizedMaterial   customizedMaterial   = CustomizedMaterial.valueOf(material, color, finish);
            CustomizedDimensions customizedDimensions = CustomizedDimensions.valueOf(200, 100, 50);
            CustomizedProduct    custom = CustomizedProductBuilder.createCustomizedProduct("1235", product, customizedDimensions).withMaterial(customizedMaterial).build();

            WidthPercentageAlgorithm algorithm = new WidthPercentageAlgorithm();
            Input minInput = Input.valueOf("Minimum Percentage", "From 0 to 1");
            Input maxInput = Input.valueOf("Maximum Percentage", "From 0 to 1");
            Dictionary <Input, string> inputs = new Dictionary <Input, string>();

            inputs.Add(minInput, "0.9");
            inputs.Add(maxInput, "1.0");
            algorithm.setInputValues(inputs);
            Product alteredProduct = algorithm.apply(custom, component);

            Assert.True(alteredProduct.productMeasurements[0].measurement.width.GetType() == typeof(SingleValueDimension));
            Assert.True(((SingleValueDimension)alteredProduct.productMeasurements[0].measurement.width).value == 100);
        }
        /// <summary>
        /// Retrieves all possible components for a certain slot of a customized product
        /// </summary>
        /// <param name="customizedProductID">customized product to base restrictions on</param>
        /// <param name="slotID">selected slot</param>
        /// <returns>possible components for selected slot</returns>
        public GetPossibleComponentsModelView fetchPossibleComponents(FindPossibleComponentsModelView findComponentsMV)
        {
            CustomizedProductRepository customizedProductRepository = PersistenceContext.repositories().createCustomizedProductRepository();
            CustomizedProduct           customizedProduct           = customizedProductRepository.find(findComponentsMV.customizedProductID);

            if (customizedProduct == null)
            {
                throw new ResourceNotFoundException(string.Format(ERROR_UNABLE_TO_FIND_CUSTOMIZED_PRODUCT_BY_ID, findComponentsMV.customizedProductID));
            }

            Slot slot = customizedProduct.slots.Where(s => s.Id == findComponentsMV.slotID).SingleOrDefault();

            if (slot == null)
            {
                throw new ResourceNotFoundException(string.Format(ERROR_UNABLE_TO_FIND_SLOT, findComponentsMV.slotID));
            }
            List <Product> restrictedProducts = (List <Product>)customizedProduct.product.getRestrictedComponents(customizedProduct, slot);

            if (Collections.isEnumerableNullOrEmpty(restrictedProducts))
            {
                throw new InvalidOperationException(NO_POSSIBLE_COMPONENTS);
            }
            return(ProductModelViewService.possibleComponentsFromCollection(restrictedProducts));
        }
        public void ensureApplyCondensesContinuousDimensions()
        {
            Color    color    = Color.valueOf("Open the Steins Gate", 100, 100, 100, 100);
            Finish   finish   = Finish.valueOf("der alte wurfelt nicht", 45);
            Material material = new Material("#12", "K6205", "12.jpg", new List <Color>(new[] { color }), new List <Finish>(new[] { finish }));

            ProductCategory             cat        = new ProductCategory("AI");
            ContinuousDimensionInterval continuous = new ContinuousDimensionInterval(100.0, 150.0, 2.0);
            Measurement        measurement         = new Measurement(new SingleValueDimension(200), continuous, new SingleValueDimension(50));
            List <Measurement> measurements        = new List <Measurement>()
            {
                measurement
            };
            Product component = new Product("#5", "Solitude of the Astigmatism: Entangled Sheep", "5.gltf", cat, new List <Material>(new[] { material }), measurements);
            Product product   = new Product("#4", "Solitude of the Mournful Flow: A Stray Sheep", "4.fbx", cat, new List <Material>(new[] { material }), measurements, new List <Product>()
            {
                component
            });

            CustomizedDimensions customizedDimensions = CustomizedDimensions.valueOf(200, 100, 50);
            CustomizedMaterial   customizedMaterial   = CustomizedMaterial.valueOf(material, color, finish);
            CustomizedProduct    custom = CustomizedProductBuilder.createCustomizedProduct("12345", product, customizedDimensions).withMaterial(customizedMaterial).build();

            WidthPercentageAlgorithm algorithm = new WidthPercentageAlgorithm();
            Input minInput = Input.valueOf("Minimum Percentage", "From 0 to 1");
            Input maxInput = Input.valueOf("Maximum Percentage", "From 0 to 1");
            Dictionary <Input, string> inputs = new Dictionary <Input, string>();

            inputs.Add(minInput, "0.9");
            inputs.Add(maxInput, "1.0");
            algorithm.setInputValues(inputs);
            Product alteredProduct = algorithm.apply(custom, component);

            Assert.True(alteredProduct.productMeasurements[0].measurement.width.GetType() == typeof(SingleValueDimension));
            Assert.True(((SingleValueDimension)alteredProduct.productMeasurements[0].measurement.width).value == 100);
        }
        /// <summary>
        /// Transforms a customized product dto into a customized product via service
        /// </summary>
        /// <param name="customizedProductDTO">CustomizedProductDTO with the customized product dto being transformed</param>
        /// <returns>CustomizedProduct with the of customized products transformed from the dto</returns>
        public static CustomizedProduct transform(CustomizedProductDTO customizedProductDTO)
        {
            CustomizedProduct customizedProduct = null;

            string reference   = customizedProductDTO.reference;
            string designation = customizedProductDTO.designation;

            //Fetch the product associated to this customized product by its id
            long    productId = customizedProductDTO.productDTO.id;
            Product product   = PersistenceContext.repositories().createProductRepository().find(productId);

            //Fetch the material associated to the customized material
            long     materialId = customizedProductDTO.customizedMaterialDTO.material.id;
            Material material   = PersistenceContext.repositories().createMaterialRepository().find(materialId);

            Finish customizedFinish = customizedProductDTO.customizedMaterialDTO.finish.toEntity();
            Color  customizedColor  = customizedProductDTO.customizedMaterialDTO.color.toEntity();

            CustomizedDimensions customizedDimensions = customizedProductDTO.customizedDimensionsDTO.toEntity();
            CustomizedMaterial   customizedMaterial   = CustomizedMaterial.valueOf(material, customizedColor, customizedFinish);

            //check if the dto contains slot information

            /* if (customizedProductDTO.slotListDTO == null)
             * {
             *  customizedProduct = new CustomizedProduct(reference, designation, customizedMaterial, customizedDimensions, product);
             * }
             * else
             * {
             *  //if the dto contains slot info, then create one with slots
             *  List<Slot> slots = new SlotDTOService().transform(customizedProductDTO.slotListDTO).ToList();
             *  customizedProduct = new CustomizedProduct(reference, designation, customizedMaterial, customizedDimensions, product, slots);
             * } */

            return(customizedProduct);
        }
Beispiel #14
0
        /// <summary>
        /// Builds a CustomizedProductPriceModelView out of a Customized Product
        /// </summary>
        /// <param name="customizedProduct">Customized Product to build the model view out of</param>
        /// <param name="fetchCustomizedProductPriceModelView">ModelView to know if currency/area conversion is needed</param>
        /// <returns>CustomizedProductPriceModelView</returns>
        private static async Task <CustomizedProductPriceModelView> buildCustomizedProductPriceModelView(CustomizedProduct customizedProduct, FetchCustomizedProductPriceModelView fetchCustomizedProductPriceModelView,
                                                                                                         MaterialPriceTableEntry materialPriceTableEntry, FinishPriceTableEntry finishPriceTableEntry, IHttpClientFactory clientFactory)
        {
            CustomizedProductPriceModelView customizedProductPriceModelView = new CustomizedProductPriceModelView();

            string defaultCurrency        = CurrencyPerAreaConversionService.getBaseCurrency();
            string defaultArea            = CurrencyPerAreaConversionService.getBaseArea();
            bool   convertCurrencyPerArea = fetchCustomizedProductPriceModelView.currency != null && fetchCustomizedProductPriceModelView.area != null;

            customizedProductPriceModelView.customizedProductId = customizedProduct.Id;
            customizedProductPriceModelView.reference           = customizedProduct.reference;
            customizedProductPriceModelView.productId           = customizedProduct.product.Id;
            string requestedMeasurementUnit = null;

            if (convertCurrencyPerArea)
            {
                requestedMeasurementUnit = new String(fetchCustomizedProductPriceModelView.area.Where(c => Char.IsLetter(c)).ToArray());
            }
            else
            {
                requestedMeasurementUnit = new String(CurrencyPerAreaConversionService.getBaseArea().Where(c => Char.IsLetter(c)).ToArray());
            }
            customizedProductPriceModelView.customizedDimensions       = new GetCustomizedDimensionsModelView();
            customizedProductPriceModelView.customizedDimensions.unit  = requestedMeasurementUnit;
            customizedProductPriceModelView.customizedDimensions.width =
                MeasurementUnitService.convertToUnit(customizedProduct.customizedDimensions.width, requestedMeasurementUnit);
            customizedProductPriceModelView.customizedDimensions.height =
                MeasurementUnitService.convertToUnit(customizedProduct.customizedDimensions.height, requestedMeasurementUnit);
            customizedProductPriceModelView.customizedDimensions.depth =
                MeasurementUnitService.convertToUnit(customizedProduct.customizedDimensions.depth, requestedMeasurementUnit);

            customizedProductPriceModelView.customizedMaterial = new CustomizedMaterialPriceModelView();
            customizedProductPriceModelView.customizedMaterial.customizedMaterialId = customizedProduct.customizedMaterial.Id;
            customizedProductPriceModelView.customizedMaterial.materialId           = customizedProduct.customizedMaterial.material.Id;
            if (customizedProduct.customizedMaterial.finish != null)
            {
                customizedProductPriceModelView.customizedMaterial.finish             = new FinishPriceModelView();
                customizedProductPriceModelView.customizedMaterial.finish.finishId    = customizedProduct.customizedMaterial.finish.Id;
                customizedProductPriceModelView.customizedMaterial.finish.description = customizedProduct.customizedMaterial.finish.description;
                customizedProductPriceModelView.customizedMaterial.finish.shininess   = customizedProduct.customizedMaterial.finish.shininess;
                customizedProductPriceModelView.customizedMaterial.finish.price       = new PriceModelView();
                if (convertCurrencyPerArea)
                {
                    customizedProductPriceModelView.customizedMaterial.finish.price.currency =
                        fetchCustomizedProductPriceModelView.currency;
                    customizedProductPriceModelView.customizedMaterial.finish.price.area =
                        fetchCustomizedProductPriceModelView.area;
                    customizedProductPriceModelView.customizedMaterial.finish.price.value =
                        await convertPriceValue(
                            finishPriceTableEntry.price.value, fetchCustomizedProductPriceModelView.currency,
                            fetchCustomizedProductPriceModelView.area, clientFactory
                            );
                }
                else
                {
                    customizedProductPriceModelView.customizedMaterial.finish.price.currency = defaultCurrency;
                    customizedProductPriceModelView.customizedMaterial.finish.price.area     = defaultArea;
                    customizedProductPriceModelView.customizedMaterial.finish.price.value    = finishPriceTableEntry.price.value;
                }
            }
            if (customizedProduct.customizedMaterial.color != null)
            {
                customizedProductPriceModelView.customizedMaterial.color = ColorModelViewService.fromEntity(customizedProduct.customizedMaterial.color);
            }
            customizedProductPriceModelView.customizedMaterial.price = new PriceModelView();
            if (convertCurrencyPerArea)
            {
                customizedProductPriceModelView.customizedMaterial.price.currency =
                    fetchCustomizedProductPriceModelView.currency;
                customizedProductPriceModelView.customizedMaterial.price.area =
                    fetchCustomizedProductPriceModelView.area;
                customizedProductPriceModelView.customizedMaterial.price.value =
                    await convertPriceValue(
                        materialPriceTableEntry.price.value, fetchCustomizedProductPriceModelView.currency,
                        fetchCustomizedProductPriceModelView.area, clientFactory
                        );
            }
            else
            {
                customizedProductPriceModelView.customizedMaterial.price.currency = defaultCurrency;
                customizedProductPriceModelView.customizedMaterial.price.area     = defaultArea;
                customizedProductPriceModelView.customizedMaterial.price.value    = materialPriceTableEntry.price.value;
            }

            customizedProductPriceModelView.price     = new PriceModelView();
            customizedProductPriceModelView.totalArea = new AreaModelView();

            if (convertCurrencyPerArea)
            {
                customizedProductPriceModelView.price.currency = fetchCustomizedProductPriceModelView.currency;
                customizedProductPriceModelView.totalArea.area = fetchCustomizedProductPriceModelView.area;
            }
            else
            {
                customizedProductPriceModelView.price.currency = defaultCurrency;
                customizedProductPriceModelView.totalArea.area = defaultArea;
            }

            calculateTotalAreaAndPriceOfCustomizedMaterial(customizedProductPriceModelView, customizedProduct);

            return(customizedProductPriceModelView);
        }
Beispiel #15
0
        /// <summary>
        /// Calculates the price of all child customized products of a given customized product
        /// </summary>
        /// <param name="customizedProduct">Parent Customized Product</param>
        /// <param name="fetchCustomizedProductPrice">Information about currency/area conversion</param>
        /// <param name="materialPriceTableRepository">MaterialPriceTableRepository instance to fetch current material prices</param>
        /// <param name="finishPriceTableRepository">FinishPriceTableRepository instance to fetch current finish prices</param>
        /// <param name="clientFactory">Injected HTTP Client Factory</param>
        /// <returns>IEnumerable containing the prices of all child customized products</returns>
        private static async Task <IEnumerable <CustomizedProductPriceModelView> > calculatePricesOfChildCustomizedProducts(List <CustomizedProductPriceModelView> childCustomizedProductPrices, CustomizedProduct customizedProduct, FetchCustomizedProductPriceModelView fetchCustomizedProductPrice,
                                                                                                                            MaterialPriceTableRepository materialPriceTableRepository, FinishPriceTableRepository finishPriceTableRepository, IHttpClientFactory clientFactory)
        {
            foreach (Slot slot in customizedProduct.slots)
            {
                foreach (CustomizedProduct childCustomizedProduct in slot.customizedProducts)
                {
                    MaterialPriceTableEntry materialPriceTableEntry =
                        getCurrentMaterialPrice(materialPriceTableRepository, childCustomizedProduct.customizedMaterial.material.Id);

                    FinishPriceTableEntry finishPriceTableEntry = null;

                    if (childCustomizedProduct.customizedMaterial.finish != null)
                    {
                        finishPriceTableEntry = getCurrentFinishPrice(finishPriceTableRepository,
                                                                      childCustomizedProduct.customizedMaterial.material.Finishes.Where(f => f.Equals(childCustomizedProduct.customizedMaterial.finish)).SingleOrDefault().Id);
                    }

                    CustomizedProductPriceModelView childCustomizedProductPriceModelView =
                        await buildCustomizedProductPriceModelView(childCustomizedProduct, fetchCustomizedProductPrice,
                                                                   materialPriceTableEntry, finishPriceTableEntry, clientFactory);

                    childCustomizedProductPrices.Add(childCustomizedProductPriceModelView);

                    if (childCustomizedProduct.hasCustomizedProducts())
                    {
                        await calculatePricesOfChildCustomizedProducts(childCustomizedProductPrices, childCustomizedProduct,
                                                                       fetchCustomizedProductPrice, materialPriceTableRepository, finishPriceTableRepository, clientFactory);
                    }
                }
            }

            return(childCustomizedProductPrices);
        }
Beispiel #16
0
        public void ensureApplyAllRestrictionsReturnsRestrictedProduct()
        {
            ProductCategory cat = new ProductCategory("All Products");

            Color        black  = Color.valueOf("Deep Black", 0, 0, 0, 0);
            Color        white  = Color.valueOf("Blinding White", 255, 255, 255, 0);
            List <Color> colors = new List <Color>()
            {
                black, white
            };

            Finish        glossy   = Finish.valueOf("Glossy", 100);
            Finish        matte    = Finish.valueOf("Matte", 0);
            List <Finish> finishes = new List <Finish>()
            {
                glossy, matte
            };

            Material material  = new Material("#001", "Really Expensive Wood", "ola.jpg", colors, finishes);
            Material material2 = new Material("#002", "Expensive Wood", "ola.jpg", colors, finishes);

            Dimension heightDimension = new SingleValueDimension(50);
            Dimension widthDimension  = new DiscreteDimensionInterval(new List <double>()
            {
                60, 65, 70, 80, 90, 105
            });
            Dimension depthDimension = new ContinuousDimensionInterval(10, 25, 5);

            Measurement measurement = new Measurement(heightDimension, widthDimension, depthDimension);

            Product product = new Product("Test", "Shelf", "shelf.glb", cat, new List <Material>()
            {
                material, material2
            }, new List <Measurement>()
            {
                measurement
            }, ProductSlotWidths.valueOf(4, 4, 4));
            Product product2 = new Product("Test", "Shelf", "shelf.glb", cat, new List <Material>()
            {
                material, material2
            }, new List <Measurement>()
            {
                measurement
            }, ProductSlotWidths.valueOf(4, 4, 4));

            CustomizedDimensions customDimension   = CustomizedDimensions.valueOf(50, 80, 25);
            CustomizedMaterial   customMaterial    = CustomizedMaterial.valueOf(material, white, matte);
            CustomizedProduct    customizedProduct = CustomizedProductBuilder.createCustomizedProduct("reference", product, customDimension).build();

            customizedProduct.changeCustomizedMaterial(customMaterial);

            customizedProduct.finalizeCustomization();
            RestrictableImpl instance = new RestrictableImpl();

            instance.addRestriction(new Restriction("same material", new SameMaterialAndFinishAlgorithm()));

            WidthPercentageAlgorithm algorithm = new WidthPercentageAlgorithm();
            Input minInput = Input.valueOf("Minimum Percentage", "From 0 to 1");
            Input maxInput = Input.valueOf("Maximum Percentage", "From 0 to 1");
            Dictionary <Input, string> inputs = new Dictionary <Input, string>();

            inputs.Add(minInput, "0.8");
            inputs.Add(maxInput, "1.0");
            algorithm.setInputValues(inputs);
            instance.addRestriction(new Restriction("width percentage", algorithm));

            Product returned = instance.applyAllRestrictions(customizedProduct, product2);

            Assert.True(returned.productMaterials.Count == 1);
            Assert.True(returned.productMaterials[0].material.Equals(material));
            Assert.True(returned.productMeasurements[0].measurement.width.getMinValue() == 65);
            Assert.True(returned.productMeasurements[0].measurement.width.getMaxValue() == 80);
        }
Beispiel #17
0
        public void ensureObjectIsNotCreatedForNullCatalogueCollection()
        {
            Color        color  = Color.valueOf("Somebody", 1, 2, 3, 4);
            List <Color> colors = new List <Color>();

            colors.Add(color);

            Finish        finish   = Finish.valueOf("once", 1);
            List <Finish> finishes = new List <Finish>();

            finishes.Add(finish);

            List <Double> values = new List <Double>();

            values.Add(500.0);

            Material        material     = new Material("told", "me", "ola.jpg", colors, finishes);
            List <Material> materialList = new List <Material>();

            materialList.Add(material);

            ProductCategory productCategory = new ProductCategory("the");

            Dimension heightDimension = new SingleValueDimension(21);
            Dimension widthDimension  = new SingleValueDimension(30);
            Dimension depthDimension  = new SingleValueDimension(17);

            Measurement        measurement  = new Measurement(heightDimension, widthDimension, depthDimension);
            List <Measurement> measurements = new List <Measurement>()
            {
                measurement
            };

            IEnumerable <Material> materialEnumerable = materialList;

            Product product = new Product("world", "is", "world.glb", productCategory, materialEnumerable,
                                          measurements);

            CustomizedMaterial   customizedMaterial   = CustomizedMaterial.valueOf(material, color, finish);
            CustomizedDimensions customizedDimensions = CustomizedDimensions.valueOf(21, 30, 17);
            CustomizedProduct    customizedProduct    = CustomizedProductBuilder
                                                        .createCustomizedProduct("reference", product, customizedDimensions)
                                                        .withMaterial(customizedMaterial).build();

            customizedProduct.finalizeCustomization();

            List <CustomizedProduct> customizedProductList = new List <CustomizedProduct>();

            customizedProductList.Add(customizedProduct);

            CustomizedProductCollection customizedProductCollection = new CustomizedProductCollection("me",
                                                                                                      customizedProductList);
            List <CustomizedProductCollection> collectionList = new List <CustomizedProductCollection>();

            collectionList.Add(customizedProductCollection);

            CatalogueCollection catalogueCollection = new CatalogueCollection(customizedProductCollection,
                                                                              customizedProductList);
            List <CatalogueCollection> catalogueCollectionList = new List <CatalogueCollection>();

            catalogueCollectionList.Add(catalogueCollection);

            CommercialCatalogue commercialCatalogue = new CommercialCatalogue("I", "ain't", catalogueCollectionList);

            Assert.Throws <ArgumentException>(() => new CommercialCatalogueCatalogueCollection(commercialCatalogue,
                                                                                               null));
        }
        public static void FillWithData(EntityDataModel model)
        {
            // allergens
            var meat = new Allergen()
            {
                Title       = "Meat",
                Description = "Dangerous to vegans"
            };

            var gluten = new Allergen()
            {
                Title       = "Gluten",
                Description = "Dangerous to sensitive people"
            };

            var cheese = new Allergen()
            {
                Title       = "Cheese",
                Description = "Dangerous diary product"
            };

            var corn = new Allergen()
            {
                Title       = "Corn",
                Description = "Dangerous diary product"
            };

            // product categories
            var pizzaCategory = new ProductCategory()
            {
                Name = "Pizza"
            };
            var burgerCategory = new ProductCategory()
            {
                Name = "Burger"
            };

            // topping categories
            var doughCategory = new ToppingCategory()
            {
                Title             = "Dough",
                Prompt            = "Please select exactly one dough",
                CategorySelection = CategorySelection.Single,
                Obligation        = Obligation.Obligatory,
                ProductCategory   = pizzaCategory,
            };

            var extrasPizzaCategory = new ToppingCategory()
            {
                Title             = "Extras",
                Prompt            = "Please select an extra topping for your pizza",
                CategorySelection = CategorySelection.Multiple,
                Obligation        = Obligation.Optional,
                ProductCategory   = pizzaCategory,
            };

            var extrasBurgerCategory = new ToppingCategory()
            {
                Title             = "Extras",
                Prompt            = "Please select an extra topping for your burger",
                CategorySelection = CategorySelection.Multiple,
                Obligation        = Obligation.Optional,
                ProductCategory   = burgerCategory,
            };

            // toppings
            var salami = new Topping()
            {
                Title           = "Salami",
                PrepareTime     = TimeSpan.FromSeconds(10),
                ToppingCategory = extrasPizzaCategory,
                Price           = 2,
                Allergens       = new List <Allergen> {
                    meat, gluten
                }
            };

            var patty = new Topping()
            {
                Title           = "Grilled Patty",
                PrepareTime     = TimeSpan.FromSeconds(130),
                ToppingCategory = extrasBurgerCategory,
                Price           = 11,
                Allergens       = new List <Allergen> {
                    meat
                }
            };

            var thinDough = new Topping()
            {
                Title           = "Thin dough",
                PrepareTime     = TimeSpan.FromSeconds(480),
                ToppingCategory = doughCategory,
                Price           = 8,
                Allergens       = new List <Allergen> {
                    gluten
                }
            };

            var thickDough = new Topping()
            {
                Title           = "Thick dough",
                PrepareTime     = TimeSpan.FromSeconds(590),
                ToppingCategory = doughCategory,
                Price           = 13,
                Allergens       = new List <Allergen> {
                    gluten
                }
            };

            // products

            var margheritta = new Product()
            {
                Title     = "Margheritta Pizza Italiano",
                Allergens = new List <Allergen> {
                    cheese, gluten
                },
                BasePrice       = 10,
                Description     = "Delicious and original italian pizza",
                PrepareTime     = TimeSpan.FromSeconds(110),
                ProductCategory = pizzaCategory,
            };

            var hawaii = new Product()
            {
                Title     = "Hawaii Pizza",
                Allergens = new List <Allergen> {
                    corn
                },
                BasePrice       = 13,
                Description     = "Astonishing hawaii pizza with a twist",
                PrepareTime     = TimeSpan.FromSeconds(140),
                ProductCategory = pizzaCategory,
            };

            var cheeseBurger = new Product()
            {
                Title           = "Cheese Burger",
                Allergens       = new List <Allergen> {
                },
                BasePrice       = 5,
                Description     = "Large burger with cheese",
                PrepareTime     = TimeSpan.FromSeconds(55),
                ProductCategory = burgerCategory,
            };

            // customers

            var pocztaPolska = new Customer()
            {
                Name      = "Poczta Polska",
                Address   = "Centrum 123",
                Email     = "*****@*****.**",
                Telephone = "123 456 789"
            };

            var google = new Customer()
            {
                Name      = "Google Polska",
                Address   = "Koszykowa 55555",
                Email     = "*****@*****.**",
                Telephone = "999 888 777"
            };

            var ted = new Customer()
            {
                Name      = "TED Polska",
                Address   = "Hoża tedowska",
                Email     = "*****@*****.**",
                Telephone = "+48 999-444-312"
            };

            // employee categories

            var chefCategory = new EmployeeCategory()
            {
                Title = "Chef"
            };

            var deliverymanCategory = new EmployeeCategory()
            {
                Title = "Deliveryman"
            };

            // intervals

            var monday = new TimeInterval()
            {
                From = DateTime.Parse("13/11/2017 8:00"),
                To   = DateTime.Parse("13/11/2017 18:00"),
            };

            var wednesday = new TimeInterval()
            {
                From = DateTime.Parse("15/11/2017 10:00"),
                To   = DateTime.Parse("15/11/2017 19:00"),
            };

            var thursday = new TimeInterval()
            {
                From = DateTime.Parse("16/11/2017 6:00"),
                To   = DateTime.Parse("16/11/2017 12:00"),
            };

            // employees

            var chef1 = new Employee()
            {
                Address   = "Mieszkalna 123",
                BirthDate = DateTime.Parse("10/10/1950"),
                Category  = chefCategory,
                Email     = "*****@*****.**",
                Name      = "John Smith",
                Salary    = 1234500,
                Telephone = "123-125-865",
                ProductCategoryCompetency = new List <ProductCategory> {
                    pizzaCategory
                },
                AvailableIntervals = new List <TimeInterval> {
                    monday, wednesday, thursday
                }
            };

            var chef2 = new Employee()
            {
                Address   = "Wypiekalna 123",
                BirthDate = DateTime.Parse("10/10/1980"),
                Category  = chefCategory,
                Email     = "*****@*****.**",
                Name      = "Adam Bezier",
                Salary    = 4624500,
                Telephone = "437-355-124",
                ProductCategoryCompetency = new List <ProductCategory> {
                    pizzaCategory, burgerCategory
                },
                AvailableIntervals = new List <TimeInterval> {
                    monday, thursday
                }
            };

            var deliveryman1 = new Employee()
            {
                Address            = "Dostarczalna 3",
                BirthDate          = DateTime.Parse("10/10/1990"),
                Category           = deliverymanCategory,
                Email              = "*****@*****.**",
                Name               = "Alfred Courier",
                Salary             = 1224500,
                Telephone          = "214-514-243",
                AvailableIntervals = new List <TimeInterval> {
                    monday, wednesday, thursday
                }
            };

            // customized products

            var customHawaii = new CustomizedProduct()
            {
                BaseProduct  = hawaii,
                CustomerWish = "mniej ananasów poproszę",
                Toppings     = new List <Topping> {
                    thinDough, salami
                },
            };

            var customBurger1 = new CustomizedProduct()
            {
                BaseProduct  = cheeseBurger,
                CustomerWish = "mniej tłuszczu poproszę",
                Toppings     = new List <Topping> {
                    patty
                },
            };

            var customBurger2 = new CustomizedProduct()
            {
                BaseProduct  = cheeseBurger,
                CustomerWish = "więcej tłuszczu poproszę",
                Toppings     = new List <Topping> {
                    patty
                },
            };

            // orders

            var order1 = new Order()
            {
                Chef             = chef1,
                Deliveryman      = deliveryman1,
                CookingDeadline  = DateTime.Parse("15/11/2017 9:00"),
                CustomerWish     = "Nie takie przypieczone",
                Customer         = google,
                DeliveryDeadline = DateTime.Parse("15/11/2017 9:30"),
                OrderCreated     = DateTime.Parse("2/11/2017 19:00"),
                OrderedProducts  = new List <CustomizedProduct> {
                    customHawaii, customBurger1
                },
                TotalPrice  = 23 + 16,
                OrderStatus = OrderStatus.Pending,
            };

            var order2 = new Order()
            {
                Chef             = chef2,
                Deliveryman      = deliveryman1,
                CookingDeadline  = DateTime.Parse("15/11/2017 13:00"),
                CustomerWish     = "Poproszę bez sera",
                Customer         = pocztaPolska,
                DeliveryDeadline = DateTime.Parse("15/11/2017 13:30"),
                OrderCreated     = DateTime.Parse("2/11/2017 14:00"),
                OrderedProducts  = new List <CustomizedProduct> {
                    customBurger2
                },
                TotalPrice  = 16,
                OrderStatus = OrderStatus.Pending,
            };

            model.Allergens.AddRange(new[] { meat, gluten, cheese });
            model.ProductCategories.AddRange(new[] { pizzaCategory, burgerCategory });
            model.ToppingCategories.AddRange(new[] { doughCategory, extrasPizzaCategory, extrasBurgerCategory });
            model.Toppings.AddRange(new[] { salami, patty, thinDough, thickDough });
            model.Products.AddRange(new[] { margheritta, hawaii, cheeseBurger });
            model.Customers.AddRange(new[] { pocztaPolska, google, ted });
            model.EmployeeCategories.AddRange(new[] { chefCategory, deliverymanCategory });
            model.Employees.AddRange(new[] { chef1, chef2, deliveryman1 });
            model.CustomizedProducts.AddRange(new[] { customHawaii, customBurger1, customBurger2 });
            model.Orders.AddRange(new[] { order1, order2 });
            model.SaveChanges();
        }
        /// <summary>
        /// Adds an instance of CustomizedProduct.
        /// </summary>
        /// <param name="addCustomizedProductModelView">AddCustomizedProductModelView containing the CustomizedProduct's information.</param>
        /// <returns>GetCustomizedProductModelView with the added CustomizedProduct's information.</returns>
        public GetCustomizedProductModelView addCustomizedProduct(AddCustomizedProductModelView addCustomizedProductModelView)
        {
            CustomizedProduct customizedProduct = CreateCustomizedProductService.create(addCustomizedProductModelView);

            return(CustomizedProductModelViewService.fromEntity(customizedProduct));
        }
Beispiel #20
0
        public OperationResult ChangeCustomizedProduct(CustomizedProduct oldCustomizedProduct, CustomizedProduct newCustomizedProduct)
        {
            var cp = CustomizedProductRepository.First(c => c.CustomizedProductId == oldCustomizedProduct.CustomizedProductId);

            cp.BaseProduct  = newCustomizedProduct.BaseProduct;
            cp.Toppings     = newCustomizedProduct.Toppings;
            cp.CustomerWish = newCustomizedProduct.CustomerWish;
            DatabaseContext.SaveChanges();
            return(new OperationResult {
                IsSucceeded = true
            });
        }
        /// <summary>
        /// Updates an instance of CustomizedProduct with the data provided in the given UpdateCustomizedProductModelView.
        /// </summary>
        /// <param name="updateCustomizedProductModelView">Instance of UpdateCustomizedProductModelView containing updated CustomizedProduct information.</param>
        /// <returns>An instance of GetCustomizedProductModelView with the updated CustomizedProduct information.</returns>
        /// <exception cref="ResourceNotFoundException">Thrown when the CustomizedProduct could not be found.</exception>
        /// <exception cref="System.ArgumentException">Thrown when none of the CustomizedProduct's properties are updated.</exception>
        public GetCustomizedProductModelView updateCustomizedProduct(UpdateCustomizedProductModelView updateCustomizedProductModelView)
        {
            CustomizedProductRepository customizedProductRepository = PersistenceContext.repositories().createCustomizedProductRepository();

            CustomizedProduct customizedProduct = customizedProductRepository.find(updateCustomizedProductModelView.customizedProductId);

            if (customizedProduct == null)
            {
                throw new ResourceNotFoundException(string.Format(ERROR_UNABLE_TO_FIND_CUSTOMIZED_PRODUCT_BY_ID, updateCustomizedProductModelView.customizedProductId));
            }

            checkUserToken(customizedProduct, updateCustomizedProductModelView.userAuthToken);

            bool performedAtLeastOneUpdate = false;

            if (updateCustomizedProductModelView.reference != null)
            {
                customizedProduct.changeReference(updateCustomizedProductModelView.reference);
                performedAtLeastOneUpdate = true;
            }

            if (updateCustomizedProductModelView.designation != null)
            {
                customizedProduct.changeDesignation(updateCustomizedProductModelView.designation);
                performedAtLeastOneUpdate = true;
            }

            if (updateCustomizedProductModelView.customizedMaterial != null)
            {
                //TODO: check if only the finish or the color are being updated
                CustomizedMaterial customizedMaterial = CreateCustomizedMaterialService.create(updateCustomizedProductModelView.customizedMaterial);

                customizedProduct.changeCustomizedMaterial(customizedMaterial);
                performedAtLeastOneUpdate = true;
            }

            if (updateCustomizedProductModelView.customizedDimensions != null)
            {
                customizedProduct.changeDimensions(CustomizedDimensionsModelViewService.fromModelView(updateCustomizedProductModelView.customizedDimensions));
                performedAtLeastOneUpdate = true;
            }

            if (updateCustomizedProductModelView.customizationStatus == CustomizationStatus.FINISHED)
            {
                customizedProduct.finalizeCustomization();
                performedAtLeastOneUpdate = true;
            }

            if (!performedAtLeastOneUpdate)
            {
                throw new ArgumentException(ERROR_NO_UPDATE_PERFORMED);
            }

            customizedProduct = customizedProductRepository.update(customizedProduct);

            if (customizedProduct == null)
            {
                throw new ArgumentException(ERROR_UNABLE_TO_SAVE_CUSTOMIZED_PRODUCT);
            }

            return(CustomizedProductModelViewService.fromEntity(customizedProduct));
        }
Beispiel #22
0
        /// <summary>
        /// Applies the algorithm that restricts a component's width to a certain percentage of the customized father product's width
        /// </summary>
        /// <param name="customProduct">customized product</param>
        /// <param name="product">component product</param>
        /// <returns>component with restricted dimensions, null if the component is not compatible with any of the allowed dimensions</returns>
        public override Product apply(CustomizedProduct customProduct, Product originalProduct)
        {
            ready();
            List <Material> materials = new List <Material>();

            foreach (ProductMaterial productMaterial in originalProduct.productMaterials)
            {
                materials.Add(productMaterial.material);
            }
            List <Measurement> measurements = new List <Measurement>();

            foreach (ProductMeasurement productMeasurement in originalProduct.productMeasurements)
            {
                measurements.Add(productMeasurement.measurement);
            }

            Product copyProduct = null;

            if (originalProduct.components.Any())
            {
                List <Product> components = new List <Product>();
                foreach (Component component in originalProduct.components)
                {
                    components.Add(component.complementaryProduct);
                }
                copyProduct = new Product(originalProduct.reference, originalProduct.designation, originalProduct.modelFilename, originalProduct.productCategory, materials, measurements, components, originalProduct.slotWidths);
            }
            else
            {
                copyProduct = new Product(originalProduct.reference, originalProduct.designation, originalProduct.modelFilename, originalProduct.productCategory, materials, measurements, originalProduct.slotWidths);
            }
            double width = customProduct.customizedDimensions.width;
            double min   = getMinPercentage();

            if (min < 0)
            {
                throw new ArgumentException(MIN_PERCENTAGE_INVALID);
            }
            double max = getMaxPercentage();

            if (max < 0)
            {
                throw new ArgumentException(MAX_PERCENTAGE_INVALID);
            }
            double minWidth = width * getMinPercentage();
            double maxWidth = width * getMaxPercentage();

            List <Measurement> measurementsToRemove = new List <Measurement>();

            List <Measurement> productMeasurements = copyProduct.productMeasurements.Select(m => m.measurement).ToList();

            foreach (Measurement measurement in productMeasurements)
            {
                Dimension dimension = measurement.width;

                if (dimension.GetType() == typeof(SingleValueDimension))
                {
                    SingleValueDimension single = (SingleValueDimension)dimension;
                    if (single.value < minWidth || single.value > maxWidth)
                    {
                        measurementsToRemove.Add(measurement);
                    }
                }
                else if (dimension.GetType() == typeof(DiscreteDimensionInterval))
                {
                    DiscreteDimensionInterval discrete    = (DiscreteDimensionInterval)dimension;
                    List <DoubleValue>        valToRemove = new List <DoubleValue>();
                    foreach (double value in discrete.values)
                    {
                        if (value < minWidth || value > maxWidth)
                        {
                            valToRemove.Add(value);
                        }
                    }
                    foreach (double val in valToRemove)
                    {
                        discrete.values.Remove(val);
                    }
                    if (discrete.values.Count == 0)
                    {
                        measurementsToRemove.Add(measurement);
                    }
                    else if (discrete.values.Count == 1)
                    {
                        measurement.changeWidthDimension(new SingleValueDimension(discrete.values[0]));
                    }
                }
                else if (dimension.GetType() == typeof(ContinuousDimensionInterval))
                {
                    ContinuousDimensionInterval continuous = (ContinuousDimensionInterval)dimension;
                    if (continuous.minValue > maxWidth || continuous.maxValue < minWidth)
                    {
                        measurementsToRemove.Add(measurement);
                    }
                    else
                    {
                        double currentMin = continuous.minValue, currentMax = continuous.maxValue;
                        if (continuous.minValue < minWidth)
                        {
                            currentMin = minWidth;
                        }
                        if (continuous.maxValue > maxWidth)
                        {
                            currentMax = maxWidth;
                        }
                        if (currentMin == currentMax)
                        {
                            SingleValueDimension single = new SingleValueDimension(currentMax);
                            measurement.changeWidthDimension(single);
                        }
                        else
                        {
                            double newIncrement = continuous.increment;
                            if (currentMax - currentMin < continuous.increment)
                            {
                                newIncrement = currentMax - currentMin;
                            }
                            ContinuousDimensionInterval newContinuous = new ContinuousDimensionInterval(currentMin, currentMax, newIncrement);

                            measurement.changeWidthDimension(newContinuous);
                        }
                    }
                }
            }
            foreach (Measurement measurement in measurementsToRemove)
            {
                try {
                    copyProduct.removeMeasurement(measurement);
                } catch (InvalidOperationException) {
                    return(null);
                } catch (ArgumentException) {
                    return(null);
                }
            }
            return(copyProduct);
        }
Beispiel #23
0
 /// <summary>
 /// Converts an instance of CustomizedProduct into an instance of GetCustomizedProductModelView.
 /// </summary>
 /// <param name="customizedProduct">Instance of CustomizedProduct being converted.</param>
 /// <returns>Instance of GetCustomizedProductModelView.</returns>
 /// <exception cref="System.ArgumentException">Thrown when the provided instance of CustomizedProduct is null.</exception>
 public static GetCustomizedProductModelView fromEntity(CustomizedProduct customizedProduct)
 {
     return(fromEntity(customizedProduct, MeasurementUnitService.getMinimumUnit()));
 }
Beispiel #24
0
 public override Product apply(CustomizedProduct customProduct, Product product)
 {
     throw new NotImplementedException();
 }
Beispiel #25
0
 /// <summary>
 /// Calculates the surface area of material and material finish used in a customized product and it's respective prices
 /// </summary>
 /// <param name="customizedProductPriceModelView">ModelView of the customized product's price information</param>
 /// <param name="customizedProduct">Customized product whose price is being calculated</param>
 private static void calculateTotalAreaAndPriceOfCustomizedMaterial(CustomizedProductPriceModelView customizedProductPriceModelView, CustomizedProduct customizedProduct)
 {
     customizedProductPriceModelView.totalArea.value =
         calculateSurfaceAreaOfRightRectangularPrism(
             customizedProductPriceModelView.customizedDimensions.width,
             customizedProductPriceModelView.customizedDimensions.height,
             customizedProductPriceModelView.customizedDimensions.depth);
     customizedProductPriceModelView.price.value =
         calculateMaterialAndFinishPrice(
             customizedProductPriceModelView.totalArea.value,
             customizedProductPriceModelView.customizedMaterial
             );
 }
Beispiel #26
0
        /// <summary>
        /// Calculates the price
        /// </summary>
        /// <param name="fetchCustomizedProductPrice">FetchCustomizedProductModelView with the necessary information to fetch the customized product's price</param>
        /// <returns>CustomizedProductPriceModelView with the price of the customized product</returns>
        public static async Task <CustomizedProductFinalPriceModelView> calculatePrice(FetchCustomizedProductPriceModelView fetchCustomizedProductPrice, IHttpClientFactory clientFactory)
        {
            if (fetchCustomizedProductPrice.currency != null)
            {
                CurrenciesService.checkCurrencySupport(fetchCustomizedProductPrice.currency);
            }

            if (fetchCustomizedProductPrice.area != null)
            {
                AreasService.checkAreaSupport(fetchCustomizedProductPrice.area);
            }

            CustomizedProduct customizedProduct =
                PersistenceContext.repositories().createCustomizedProductRepository().find(fetchCustomizedProductPrice.id);

            if (customizedProduct == null)
            {
                throw new ResourceNotFoundException
                      (
                          string.Format(CUSTOMIZED_PRODUCT_NOT_FOUND, fetchCustomizedProductPrice.id)
                      );
            }

            if (customizedProduct.status == CustomizationStatus.PENDING)
            {
                throw new ArgumentException
                      (
                          CUSTOMIZED_PRODUCT_NOT_FINISHED
                      );
            }

            //TODO Should the fetching of prices of customized products that aren't base products be allowed?

            MaterialPriceTableRepository materialPriceTableRepository =
                PersistenceContext.repositories().createMaterialPriceTableRepository();
            FinishPriceTableRepository finishPriceTableRepository =
                PersistenceContext.repositories().createFinishPriceTableRepository();

            CustomizedProductFinalPriceModelView   customizedProductTotalPrice = new CustomizedProductFinalPriceModelView();
            List <CustomizedProductPriceModelView> customizedProductPriceList  = new List <CustomizedProductPriceModelView>();

            MaterialPriceTableEntry materialPriceTableEntry =
                getCurrentMaterialPrice(materialPriceTableRepository, customizedProduct.customizedMaterial.material.Id);

            FinishPriceTableEntry finishPriceTableEntry = null;

            if (customizedProduct.customizedMaterial.finish != null)
            {
                finishPriceTableEntry = getCurrentFinishPrice(finishPriceTableRepository,
                                                              customizedProduct.customizedMaterial.material.Finishes.Where(f => f.Equals(customizedProduct.customizedMaterial.finish)).SingleOrDefault().Id);
            }

            //TODO What should we do about doors?
            //TODO Should we consider that every component has a box geometry?
            //!For now the surface area of every product is being calculated as if it the product was a SIX FACED RIGHT RECTANGULAR PRISM

            CustomizedProductPriceModelView parentCustomizedProductModelView =
                await buildCustomizedProductPriceModelView(customizedProduct, fetchCustomizedProductPrice, materialPriceTableEntry, finishPriceTableEntry, clientFactory);

            customizedProductPriceList.Add(parentCustomizedProductModelView);

            if (customizedProduct.hasCustomizedProducts())
            {
                List <CustomizedProductPriceModelView> childCustomizedProducts = new List <CustomizedProductPriceModelView>();
                customizedProductPriceList.AddRange(await
                                                    calculatePricesOfChildCustomizedProducts(childCustomizedProducts, customizedProduct, fetchCustomizedProductPrice,
                                                                                             materialPriceTableRepository, finishPriceTableRepository, clientFactory));
            }

            customizedProductTotalPrice.customizedProducts = customizedProductPriceList;
            customizedProductTotalPrice.finalPrice         = calculateFinalPriceOfCustomizedProduct(customizedProductTotalPrice, fetchCustomizedProductPrice);

            return(customizedProductTotalPrice);
        }
Beispiel #27
0
        /// <summary>
        /// Transforms a CommercialCatalogueDTO into a CommercialCatalogue.
        /// </summary>
        /// <param name="commercialCatalogueDTO">CommercialCatalogueDTO with the CommercialCatalogue data.</param>
        /// <returns>Transformed CommercialCatalogue built with CommercialCatalogueDTO info.</returns>
        public static CommercialCatalogue transform(CommercialCatalogueDTO commercialCatalogueDTO)
        {
            string reference   = commercialCatalogueDTO.reference;
            string designation = commercialCatalogueDTO.designation;

            CommercialCatalogue newComCatalogue = null;

            //if no collections are specified, build a catalogue with just the given reference and designation.
            if (commercialCatalogueDTO.catalogueCollectionDTOs != null)
            {
                CustomizedProductCollectionRepository collectionRepository = PersistenceContext.repositories().createCustomizedProductCollectionRepository();

                CustomizedProductRepository customizedProductRepository = PersistenceContext.repositories().createCustomizedProductRepository();

                //the specified collections should have id's and not the whole collection information

                List <CatalogueCollection> catalogueCollections = new List <CatalogueCollection>();

                foreach (CatalogueCollectionDTO collectionDTO in commercialCatalogueDTO.catalogueCollectionDTOs)
                {
                    CatalogueCollection         catalogueCollection = null;
                    CustomizedProductCollection collection          = collectionRepository.find(collectionDTO.customizedProductCollectionDTO.id);

                    //the collection was not found
                    if (collection == null)
                    {
                        throw new ArgumentException(ERROR_CUSTOMIZED_PRODUCT_COLLECTION_NOT_FOUND);
                    }

                    //if no products are specified, then add all contained in the collection
                    if (collectionDTO.customizedProductDTOs == null)
                    {
                        catalogueCollection = new CatalogueCollection(collection);
                    }
                    else
                    {
                        List <CustomizedProduct> customizedProducts = new List <CustomizedProduct>();

                        foreach (CustomizedProductDTO customizedProductDTO in collectionDTO.customizedProductDTOs)
                        {
                            CustomizedProduct customizedProduct = customizedProductRepository.find(customizedProductDTO.id);

                            //the product was not found
                            if (customizedProduct == null)
                            {
                                throw new ArgumentException(ERROR_CUSTOMIZED_PRODUCT_NOT_FOUND);
                            }

                            customizedProducts.Add(customizedProduct);
                        }

                        catalogueCollection = new CatalogueCollection(collection, customizedProducts);
                    }

                    catalogueCollections.Add(catalogueCollection);
                }

                newComCatalogue = new CommercialCatalogue(reference, designation, catalogueCollections);
            }
            else
            {
                newComCatalogue = new CommercialCatalogue(reference, designation);
            }

            return(newComCatalogue);
        }