Пример #1
0
        public virtual IActionResult CustomLogoAdd(LogoModel logo)
        {
            if (!_permissionService.Authorize(StandardPermissionProvider.ManageWidgets))
            {
                return(AccessDeniedView());
            }

            if (!ModelState.IsValid)
            {
                return(Json(new { Result = false, Errors = GetErrorsFromModelState() }));
            }

            //Get 1st product picture we use 1st picture of product to combine with logo
            ProductPicture productPicture = _productPictureModifierService
                                            .GetFirstProductPicture(logo.ProductId);

            if (productPicture == null)
            {
                throw new Exception("Product does not have any image");
            }

            byte[] logoBinary = _pictureService.LoadPictureBinary(_pictureService.GetPictureById(logo.PictureId));

            //Get new product image which has been merged with the logo uploaded
            (int, string)mergedPicture = _logoService.MergeProductPictureWithLogo(
                logoBinary,
                logo.PictureId,
                logo.ProductId,
                ProductPictureModifierUploadType.Predefined,
                logo.Size,
                logo.Opacity,
                logo.XCoordinate,
                logo.YCoordinate,
                overrideThumb: true);

            if (logo.AttributeValueId > 0)
            {
                var existingAttributeValue = _productAttributeService.
                                             GetProductAttributeValueById(logo.AttributeValueId);

                var existingProductPicture = _productService.GetProductPicturesByProductId(logo.ProductId)
                                             .First(x => x.PictureId == existingAttributeValue.PictureId);

                //update product attribute value
                existingAttributeValue.PictureId             = mergedPicture.Item1;
                existingAttributeValue.ImageSquaresPictureId = logo.PictureId;
                _productAttributeService.UpdateProductAttributeValue(existingAttributeValue);

                //update product picture
                existingProductPicture.PictureId = mergedPicture.Item1;
                _productService.UpdateProductPicture(existingProductPicture);

                return(Json(new { Result = true, AttributeId = logo.AttributeValueId }));
            }
            //Insert the image as product picture
            _productService.InsertProductPicture(new ProductPicture
            {
                ProductId    = logo.ProductId,
                PictureId    = mergedPicture.Item1,
                DisplayOrder = ProductPictureModifierDefault.MergedPictureDisplayOrder
            });

            ProductAttribute logoAttribute = _productPictureModifierService
                                             .GetProductAttributeByName(ProductPictureModifierDefault.ProductAttributeNameForLogo)
                                             .FirstOrDefault() ?? throw new ArgumentException("Product Attribute Not Found");

            //get product's attribute for predefined logo attributes
            ProductAttributeMapping logoProductMapping = _productAttributeService
                                                         .GetProductAttributeMappingsByProductId(logo.ProductId)
                                                         .FirstOrDefault(x => x.ProductAttributeId == logoAttribute.Id);

            //create the mapping if it does not exist
            if (logoProductMapping == null)
            {
                logoProductMapping = new ProductAttributeMapping
                {
                    ProductAttributeId     = logoAttribute.Id,
                    ProductId              = logo.ProductId,
                    AttributeControlTypeId = (int)AttributeControlType.ImageSquares
                };
                _productAttributeService.InsertProductAttributeMapping(logoProductMapping);

                ////no logo attribute
                ////todo find a way to use the picture for this
                //_productAttributeService.InsertProductAttributeValue(new ProductAttributeValue
                //{
                //    ProductAttributeMappingId = logoProductMapping.Id,
                //    AttributeValueType = AttributeValueType.Simple,
                //    Name = _localizationService.GetResource("Widgets.ProductPictureModifier.Attributes.NoLogo"),
                //    ImageSquaresPictureId = 1,
                //    PictureId = productPicture.PictureId,
                //});

                //provision for manual upload by user
                Setting customUploadIconSetting = _settingService
                                                  .GetSetting(ProductPictureModifierDefault.UploadIconPictureIdSetting);
                var customUploadForLogoAttribute = new ProductAttributeValue
                {
                    ProductAttributeMappingId = logoProductMapping.Id,
                    AttributeValueType        = AttributeValueType.Simple,
                    Name = _localizationService.GetResource("Widgets.ProductPictureModifier.Attributes.Upload"),
                    ImageSquaresPictureId = int.Parse(customUploadIconSetting.Value),
                };
                _productAttributeService.InsertProductAttributeValue(customUploadForLogoAttribute);

                ProductAttribute productAttributeForCustomUpload = _productPictureModifierService
                                                                   .GetProductAttributeByName(ProductPictureModifierDefault.ProductAttributeNameForLogoUpload)
                                                                   .FirstOrDefault() ?? throw new ArgumentException("Product Attribute Not Found for Custom Upload");

                //custom upload attribute mapping with product based on condition
                var customUploadProductAttributeMapping = new ProductAttributeMapping
                {
                    ProductAttributeId              = productAttributeForCustomUpload.Id,
                    ProductId                       = logo.ProductId,
                    AttributeControlTypeId          = (int)AttributeControlType.FileUpload,
                    ValidationFileAllowedExtensions = "png",
                    ConditionAttributeXml           = _productAttributeParser.AddProductAttribute(null, logoProductMapping,
                                                                                                  customUploadForLogoAttribute.Id.ToString())
                };
                _productAttributeService.InsertProductAttributeMapping(customUploadProductAttributeMapping);
            }

            //save the actual logo attribute
            var productAttributeValue = new ProductAttributeValue
            {
                ProductAttributeMappingId = logoProductMapping.Id,
                AttributeValueType        = AttributeValueType.Simple,
                Name = "Custom Logo",
                ImageSquaresPictureId = logo.PictureId,
                PictureId             = mergedPicture.Item1,
            };

            _productAttributeService.InsertProductAttributeValue(productAttributeValue);

            //Logo Position for custom upload
            LogoPosition logoPosition = _logoPositionService.GetByProductId(logo.ProductId);

            if (logo.MarkAsDefault || IsLogoSettingNew(logoPosition))
            {
                logoPosition.Size        = logo.Size;
                logoPosition.XCoordinate = logo.XCoordinate;
                logoPosition.YCoordinate = logo.YCoordinate;
                logoPosition.Opacity     = logo.Opacity;
                _logoPositionService.Update(logoPosition);
            }

            return(Json(new { Result = true, AttributeId = productAttributeValue.Id }));
        }
 public static ProductAttributeValueDto ToDto(this ProductAttributeValue productAttributeValue)
 {
     return(productAttributeValue.MapTo <ProductAttributeValue, ProductAttributeValueDto>());
 }
Пример #3
0
        public IActionResult Post(ProductForm model)
        {
            if (!ModelState.IsValid)
            {
                return(new BadRequestObjectResult(ModelState));
            }

            var product = new Product
            {
                Name                  = model.Product.Name,
                SeoTitle              = model.Product.Name.ToUrlFriendly(),
                ShortDescription      = model.Product.ShortDescription,
                Description           = model.Product.Description,
                Specification         = model.Product.Specification,
                Price                 = model.Product.Price,
                OldPrice              = model.Product.OldPrice,
                IsPublished           = model.Product.IsPublished,
                IsFeatured            = model.Product.IsFeatured,
                BrandId               = model.Product.BrandId,
                HasOptions            = model.Product.Variations.Any() ? true : false,
                IsVisibleIndividually = true
            };

            var optionIndex = 0;

            foreach (var option in model.Product.Options)
            {
                product.AddOptionValue(new ProductOptionValue
                {
                    OptionId  = option.Id,
                    Value     = JsonConvert.SerializeObject(option.Values),
                    SortIndex = optionIndex
                });

                optionIndex++;
            }

            foreach (var attribute in model.Product.Attributes)
            {
                var attributeValue = new ProductAttributeValue
                {
                    AttributeId = attribute.Id,
                    Value       = attribute.Value
                };

                product.AddAttributeValue(attributeValue);
            }

            foreach (var categoryId in model.Product.CategoryIds)
            {
                var productCategory = new ProductCategory
                {
                    CategoryId = categoryId
                };
                product.AddCategory(productCategory);
            }

            SaveProductImages(model, product);

            MapProductVariationVmToProduct(model, product);

            _productService.Create(product);

            return(Ok());
        }
Пример #4
0
 /// <summary>
 /// Inserts a product attribute value
 /// </summary>
 /// <param name="productAttributeValue">The product attribute value</param>
 /// <returns>A task that represents the asynchronous operation</returns>
 public virtual async Task InsertProductAttributeValueAsync(ProductAttributeValue productAttributeValue)
 {
     await _productAttributeValueRepository.InsertAsync(productAttributeValue);
 }
Пример #5
0
 public static ProductAttributeValueDTO ToModel(this ProductAttributeValue entity)
 {
     return(Mapper.Map <ProductAttributeValue, ProductAttributeValueDTO>(entity));
 }
Пример #6
0
 public void AddProductAttributeValue(ProductAttributeValue productAttributeValue, Transaction transaction = null)
 {
     _productAttributeValueService.Insert(productAttributeValue, transaction);
 }
Пример #7
0
 partial void InsertProductAttributeValue(ProductAttributeValue instance);
Пример #8
0
        public async Task <IActionResult> Post(ProductForm model)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            var currentUser = await _workContext.GetCurrentUser();

            var product = new Product
            {
                Name                   = model.Product.Name,
                Slug                   = model.Product.Slug,
                MetaTitle              = model.Product.MetaTitle,
                MetaKeywords           = model.Product.MetaKeywords,
                MetaDescription        = model.Product.MetaDescription,
                Sku                    = model.Product.Sku,
                Gtin                   = model.Product.Gtin,
                ShortDescription       = model.Product.ShortDescription,
                Description            = model.Product.Description,
                Specification          = model.Product.Specification,
                Price                  = model.Product.Price,
                OldPrice               = model.Product.OldPrice,
                SpecialPrice           = model.Product.SpecialPrice,
                SpecialPriceStart      = model.Product.SpecialPriceStart,
                SpecialPriceEnd        = model.Product.SpecialPriceEnd,
                IsPublished            = model.Product.IsPublished,
                IsFeatured             = model.Product.IsFeatured,
                IsCallForPricing       = model.Product.IsCallForPricing,
                IsAllowToOrder         = model.Product.IsAllowToOrder,
                BrandId                = model.Product.BrandId,
                TaxClassId             = model.Product.TaxClassId,
                StockTrackingIsEnabled = model.Product.StockTrackingIsEnabled,
                HasOptions             = model.Product.Variations.Any() ? true : false,
                IsVisibleIndividually  = true,
                CreatedBy              = currentUser,
                LatestUpdatedBy        = currentUser
            };

            if (!User.IsInRole("admin"))
            {
                product.VendorId = currentUser.VendorId;
            }

            var optionIndex = 0;

            foreach (var option in model.Product.Options)
            {
                product.AddOptionValue(new ProductOptionValue
                {
                    OptionId    = option.Id,
                    DisplayType = option.DisplayType,
                    Value       = JsonConvert.SerializeObject(option.Values),
                    SortIndex   = optionIndex
                });

                optionIndex++;
            }

            foreach (var attribute in model.Product.Attributes)
            {
                var attributeValue = new ProductAttributeValue
                {
                    AttributeId = attribute.Id,
                    Value       = attribute.Value
                };

                product.AddAttributeValue(attributeValue);
            }

            foreach (var categoryId in model.Product.CategoryIds)
            {
                var productCategory = new ProductCategory
                {
                    CategoryId = categoryId
                };
                product.AddCategory(productCategory);
            }

            await SaveProductMedias(model, product);

            MapProductVariationVmToProduct(currentUser, model, product);
            MapProductLinkVmToProduct(model, product);

            var productPriceHistory = CreatePriceHistory(currentUser, product);

            product.PriceHistories.Add(productPriceHistory);

            _productService.Create(product);
            return(CreatedAtAction(nameof(Get), new { id = product.Id }, null));
        }
 public bool Add(ProductAttributeValue obj)
 {
     return(database.ExecuteNonQuery("AddProductAttributeValue", obj.ProductId, obj.AttributeValueId, obj.ProductId, obj.CostDifference, obj.Explain) > 0);
 }
Пример #10
0
        private void ParseDocuments(IUnitOfWork unit, int vendorID, DataSet excel, bool firstRun)
        {
            var content = (from p in excel.Tables[0].AsEnumerable().Skip(1)
                           let vpn = p.Field <string>(0)
                                     select new
            {
                UnpaddedVendorItemNumber = vpn,
                PaddedVendorItemNumber = vpn.Length <= 6 ? vpn.PadLeft(6, '0') : vpn,
                Price = p.Field <String>(3),
                PriceGroup = p.Field <String>(1),
                EAN = p.Field <String>(2)
            }).ToList();

            int counter = 0;
            int total   = content.Count();
            int totalNumberOfProductsToProcess = total;

            log.InfoFormat("Start import {0} products", total);
            var attribute = unit.Scope.Repository <ProductAttributeMetaData>().GetSingle(x => x.AttributeCode == "PriceGroup");

            foreach (var item in content)
            {
                try
                {
                    if (counter == 50)
                    {
                        counter = 0;
                        log.InfoFormat("Still need to process {0} of {1}; {2} done;", totalNumberOfProductsToProcess, total, total - totalNumberOfProductsToProcess);
                    }
                    totalNumberOfProductsToProcess--;
                    counter++;

                    decimal dec = 0;
                    decimal.TryParse(item.Price, NumberStyles.Any, CultureInfo.InvariantCulture, out dec);

                    if (dec <= 0)
                    {
                        continue;
                    }

                    if (item.Price == String.Empty)
                    {
                        continue;
                    }

                    var _vendorAssortment = unit.Scope.Repository <VendorAssortment>().GetSingle(x => (x.Product.VendorItemNumber == item.PaddedVendorItemNumber || x.Product.VendorItemNumber == item.UnpaddedVendorItemNumber) && x.VendorID == vendorID);

                    if (_vendorAssortment == null)
                    {
                        _vendorAssortment = unit.Scope.Repository <VendorAssortment>().GetSingle(x => (x.Product.VendorItemNumber == item.PaddedVendorItemNumber || x.Product.VendorItemNumber == item.UnpaddedVendorItemNumber));
                        if (_vendorAssortment == null)
                        {
                            continue;
                        }
                        else
                        {
                            var va = new VendorAssortment()
                            {
                                VendorID            = vendorID,
                                ProductID           = _vendorAssortment.ProductID,
                                CustomItemNumber    = _vendorAssortment.CustomItemNumber,
                                ShortDescription    = _vendorAssortment.ShortDescription,
                                LongDescription     = _vendorAssortment.LongDescription,
                                IsActive            = false,
                                ProductGroupVendors = _vendorAssortment.ProductGroupVendors
                            };
                            unit.Scope.Repository <VendorAssortment>().Add(va);
                            unit.Save();
                            _vendorAssortment = va;
                        }
                    }

                    var _vendorPrice = unit.Scope.Repository <VendorPrice>().GetSingle(x => x.VendorAssortmentID == _vendorAssortment.VendorAssortmentID);

                    // Remove trailing zeros and Parsing
                    //String currencyFormat = String.Format("{0:C4}", Decimal.Parse(item.Price.Replace('.', ',')));
                    var costPrice    = dec; //Decimal.Parse(currencyFormat, NumberStyles.Currency);
                    var priceWithTax = (costPrice * _taxCalculation);

                    if (_vendorPrice == null)
                    {
                        VendorPrice price = new VendorPrice()
                        {
                            VendorAssortmentID = _vendorAssortment.VendorAssortmentID,
                            Price           = priceWithTax,
                            MinimumQuantity = 0,
                            CostPrice       = costPrice,
                            TaxRate         = _taxRate
                        };

                        unit.Scope.Repository <VendorPrice>().Add(price);
                    }
                    else
                    {
                        _vendorPrice.CostPrice = costPrice;
                        _vendorPrice.TaxRate   = _taxRate;
                        _vendorPrice.Price     = null;
                    }

                    var _vendorStock = unit.Scope.Repository <VendorStock>().GetSingle(x => x.ProductID == _vendorAssortment.ProductID && x.VendorID == vendorID);

                    if (_vendorStock == null)
                    {
                        VendorStock stock = new VendorStock()
                        {
                            ProductID         = _vendorAssortment.ProductID,
                            VendorID          = vendorID,
                            QuantityOnHand    = 0,
                            VendorStockTypeID = 1
                        };

                        unit.Scope.Repository <VendorStock>().Add(stock);
                    }

                    if (firstRun)
                    {
                        #region Attribute
                        if (!string.IsNullOrEmpty(item.PriceGroup))
                        {
                            if (attribute == null)
                            {
                                log.AuditCritical("PriceGroup attribute Removed");
                            }
                            else
                            {
                                var attributevalue = attribute.ProductAttributeValues.FirstOrDefault(x => x.ProductID == _vendorAssortment.ProductID);

                                if (attributevalue == null)
                                {
                                    attributevalue = new ProductAttributeValue()
                                    {
                                        LanguageID  = 1,
                                        AttributeID = attribute.AttributeID,
                                        ProductID   = _vendorAssortment.ProductID
                                    };
                                    unit.Scope.Repository <ProductAttributeValue>().Add(attributevalue);
                                }
                                attributevalue.Value = item.PriceGroup;
                            }
                        }
                        #endregion

                        //#region Barcode
                        //var productBarcode = unit.Scope.Repository<ProductBarcode>().GetSingle(x => x.ProductID == _vendorAssortment.ProductID && x.BarcodeType == 1);

                        //if (productBarcode == null)
                        //{
                        //  productBarcode = new ProductBarcode()
                        //  {
                        //    ProductID = _vendorAssortment.ProductID,
                        //    BarcodeType = (int)BarcodeTypes.EAN,
                        //    VendorID = vendorID
                        //  };
                        //  unit.Scope.Repository<ProductBarcode>().Add(productBarcode);
                        //}
                        //productBarcode.Barcode = item.EAN;

                        //#endregion
                    }
                    unit.Save();
                }
                catch (Exception ex)
                {
                    log.AuditError("Error update price", ex);
                }
            }
        }
 public bool Edit(ProductAttributeValue obj)
 {
     return(database.ExecuteNonQuery("EditProductAttributeValue", obj.ProductId, obj.AttributeValueId, obj.Position, obj.CostDifference, obj.Explain) > 0);
 }
Пример #12
0
        public IActionResult Create(ProductForm model)
        {
            if (!ModelState.IsValid)
            {
                return new BadRequestObjectResult(ModelState);
            }

            var product = new Product
            {
                Name = model.Product.Name,
                SeoTitle = StringHelper.ToUrlFriendly(model.Product.Name),
                ShortDescription = model.Product.ShortDescription,
                Description = model.Product.Description,
                Specification = model.Product.Specification,
                Price = model.Product.Price,
                OldPrice = model.Product.OldPrice,
                IsPublished = model.Product.IsPublished,
                BrandId = model.Product.BrandId,
                HasOptions = model.Product.Variations.Any() ? true : false,
                IsVisibleIndividually = true
            };

            foreach (var option in model.Product.Options)
            {
                foreach (var value in option.Values)
                {
                    product.AddOptionValue(new ProductOptionValue
                    {
                        Value = value,
                        OptionId = option.Id
                    });
                }
            }

            foreach (var attribute in model.Product.Attributes)
            {
                var attributeValue = new ProductAttributeValue
                {
                    AttributeId = attribute.Id,
                    Value = attribute.Value
                };

                product.AddAttributeValue(attributeValue);
            }

            foreach (var categoryId in model.Product.CategoryIds)
            {
                var productCategory = new ProductCategory
                {
                    CategoryId = categoryId
                };
                product.AddCategory(productCategory);
            }

            SaveProductImages(model, product);

            MapProductVariationVmToProduct(model, product);

            productService.Create(product);

            return Ok();
        }
Пример #13
0
        private void AddOrDeleteProductAttribute(ProductForm model, Product product)
        {
            foreach (var productAttributeVm in model.Product.Attributes)
            {
                var productAttrValue =
                    product.AttributeValues.FirstOrDefault(x => x.AttributeId == productAttributeVm.Id);
                if (productAttrValue == null)
                {
                    productAttrValue = new ProductAttributeValue
                    {
                        AttributeId = productAttributeVm.Id,
                        Value = productAttributeVm.Value
                    };
                    product.AddAttributeValue(productAttrValue);
                }
                else
                {
                    productAttrValue.Value = productAttributeVm.Value;
                }
            }

            var deletedAttrValues =
               product.AttributeValues.Where(attrValue => model.Product.Attributes.All(x => x.Id != attrValue.AttributeId))
                   .ToList();

            foreach (var deletedAttrValue in deletedAttrValues)
            {
                deletedAttrValue.Product = null;
                product.AttributeValues.Remove(deletedAttrValue);
                productAttributeValueRepository.Remove(deletedAttrValue);
            }
        }
Пример #14
0
        public async Task <IActionResult> Post(ProductForm model)
        {
            if (!ModelState.IsValid)
            {
                return(new BadRequestObjectResult(ModelState));
            }

            var currentUser = await _workContext.GetCurrentUser();

            var product = new Product
            {
                Name                  = model.Product.Name,
                SeoTitle              = model.Product.Name.ToUrlFriendly(),
                ShortDescription      = model.Product.ShortDescription,
                Description           = model.Product.Description,
                Specification         = model.Product.Specification,
                Price                 = model.Product.Price,
                OldPrice              = model.Product.OldPrice,
                SpecialPrice          = model.Product.SpecialPrice,
                SpecialPriceStart     = model.Product.SpecialPriceStart,
                SpecialPriceEnd       = model.Product.SpecialPriceEnd,
                IsPublished           = model.Product.IsPublished,
                IsFeatured            = model.Product.IsFeatured,
                IsCallForPricing      = model.Product.IsCallForPricing,
                IsAllowToOrder        = model.Product.IsAllowToOrder,
                BrandId               = model.Product.BrandId,
                HasOptions            = model.Product.Variations.Any() ? true : false,
                IsVisibleIndividually = true,
                CreatedBy             = currentUser
            };

            if (!User.IsInRole("admin"))
            {
                product.VendorId = currentUser.VendorId;
            }

            if (model.Product.IsOutOfStock)
            {
                product.StockQuantity = 0;
            }
            else
            {
                product.StockQuantity = null;
            }

            var optionIndex = 0;

            foreach (var option in model.Product.Options)
            {
                product.AddOptionValue(new ProductOptionValue
                {
                    OptionId    = option.Id,
                    DisplayType = option.DisplayType,
                    Value       = JsonConvert.SerializeObject(option.Values),
                    SortIndex   = optionIndex
                });

                optionIndex++;
            }

            foreach (var attribute in model.Product.Attributes)
            {
                var attributeValue = new ProductAttributeValue
                {
                    AttributeId = attribute.Id,
                    Value       = attribute.Value
                };

                product.AddAttributeValue(attributeValue);
            }

            foreach (var categoryId in model.Product.CategoryIds)
            {
                var productCategory = new ProductCategory
                {
                    CategoryId = categoryId
                };
                product.AddCategory(productCategory);
            }

            SaveProductMedias(model, product);

            MapProductVariationVmToProduct(model, product);
            MapProductLinkVmToProduct(model, product);

            _productService.Create(product);

            return(Ok());
        }
Пример #15
0
 partial void UpdateProductAttributeValue(ProductAttributeValue instance);
Пример #16
0
        public new void SetUp()
        {
            #region Test data

            //color (dropdownlist)
            pa1 = new ProductAttribute
            {
                Id   = 1,
                Name = "Color"
            };
            pam1_1 = new ProductAttributeMapping
            {
                Id                   = 11,
                ProductId            = 1,
                TextPrompt           = "Select color:",
                IsRequired           = true,
                AttributeControlType = AttributeControlType.DropdownList,
                DisplayOrder         = 1,
                ProductAttribute     = pa1,
                ProductAttributeId   = pa1.Id
            };
            pav1_1 = new ProductAttributeValue
            {
                Id                        = 11,
                Name                      = "Green",
                DisplayOrder              = 1,
                ProductAttributeMapping   = pam1_1,
                ProductAttributeMappingId = pam1_1.Id
            };
            pav1_2 = new ProductAttributeValue
            {
                Id                        = 12,
                Name                      = "Red",
                DisplayOrder              = 2,
                ProductAttributeMapping   = pam1_1,
                ProductAttributeMappingId = pam1_1.Id
            };
            pam1_1.ProductAttributeValues.Add(pav1_1);
            pam1_1.ProductAttributeValues.Add(pav1_2);

            //custom option (checkboxes)
            pa2 = new ProductAttribute
            {
                Id   = 2,
                Name = "Some custom option"
            };
            pam2_1 = new ProductAttributeMapping
            {
                Id                   = 21,
                ProductId            = 1,
                TextPrompt           = "Select at least one option:",
                IsRequired           = true,
                AttributeControlType = AttributeControlType.Checkboxes,
                DisplayOrder         = 2,
                ProductAttribute     = pa2,
                ProductAttributeId   = pa2.Id
            };
            pav2_1 = new ProductAttributeValue
            {
                Id                        = 21,
                Name                      = "Option 1",
                DisplayOrder              = 1,
                ProductAttributeMapping   = pam2_1,
                ProductAttributeMappingId = pam2_1.Id
            };
            pav2_2 = new ProductAttributeValue
            {
                Id                        = 22,
                Name                      = "Option 2",
                DisplayOrder              = 2,
                ProductAttributeMapping   = pam2_1,
                ProductAttributeMappingId = pam2_1.Id
            };
            pam2_1.ProductAttributeValues.Add(pav2_1);
            pam2_1.ProductAttributeValues.Add(pav2_2);

            //custom text
            pa3 = new ProductAttribute
            {
                Id   = 3,
                Name = "Custom text"
            };
            pam3_1 = new ProductAttributeMapping
            {
                Id                   = 31,
                ProductId            = 1,
                TextPrompt           = "Enter custom text:",
                IsRequired           = true,
                AttributeControlType = AttributeControlType.TextBox,
                DisplayOrder         = 1,
                ProductAttribute     = pa1,
                ProductAttributeId   = pa3.Id
            };

            //option radio
            pa4 = new ProductAttribute
            {
                Id   = 4,
                Name = "Radio list"
            };
            pam4_1 = new ProductAttributeMapping
            {
                Id                   = 41,
                ProductId            = 1,
                TextPrompt           = "Select option and enter the quantity:",
                IsRequired           = true,
                AttributeControlType = AttributeControlType.RadioList,
                DisplayOrder         = 2,
                ProductAttribute     = pa4,
                ProductAttributeId   = pa4.Id
            };
            pav4_1 = new ProductAttributeValue
            {
                Id                        = 41,
                Name                      = "Option with quantity",
                DisplayOrder              = 1,
                ProductAttributeMapping   = pam4_1,
                ProductAttributeMappingId = pam4_1.Id
            };

            #endregion

            _productAttributeRepo = new Mock <IRepository <ProductAttribute> >();
            _productAttributeRepo.Setup(x => x.Table).Returns(new List <ProductAttribute> {
                pa1, pa2, pa3, pa4
            }.AsQueryable());
            _productAttributeRepo.Setup(x => x.GetById(pa1.Id)).Returns(pa1);
            _productAttributeRepo.Setup(x => x.GetById(pa2.Id)).Returns(pa2);
            _productAttributeRepo.Setup(x => x.GetById(pa3.Id)).Returns(pa3);
            _productAttributeRepo.Setup(x => x.GetById(pa4.Id)).Returns(pa4);

            _productAttributeMappingRepo = new Mock <IRepository <ProductAttributeMapping> >();
            _productAttributeMappingRepo.Setup(x => x.Table).Returns(new List <ProductAttributeMapping> {
                pam1_1, pam2_1, pam3_1, pam4_1
            }.AsQueryable());
            _productAttributeMappingRepo.Setup(x => x.GetById(pam1_1.Id)).Returns(pam1_1);
            _productAttributeMappingRepo.Setup(x => x.GetById(pam2_1.Id)).Returns(pam2_1);
            _productAttributeMappingRepo.Setup(x => x.GetById(pam3_1.Id)).Returns(pam3_1);
            _productAttributeMappingRepo.Setup(x => x.GetById(pam4_1.Id)).Returns(pam4_1);

            _productAttributeCombinationRepo = new Mock <IRepository <ProductAttributeCombination> >();
            _productAttributeCombinationRepo.Setup(x => x.Table).Returns(new List <ProductAttributeCombination>().AsQueryable());

            _productAttributeValueRepo = new Mock <IRepository <ProductAttributeValue> >();
            _productAttributeValueRepo.Setup(x => x.Table).Returns(new List <ProductAttributeValue> {
                pav1_1, pav1_2, pav2_1, pav2_2, pav4_1
            }.AsQueryable());
            _productAttributeValueRepo.Setup(x => x.GetById(pav1_1.Id)).Returns(pav1_1);
            _productAttributeValueRepo.Setup(x => x.GetById(pav1_2.Id)).Returns(pav1_2);
            _productAttributeValueRepo.Setup(x => x.GetById(pav2_1.Id)).Returns(pav2_1);
            _productAttributeValueRepo.Setup(x => x.GetById(pav2_2.Id)).Returns(pav2_2);
            _productAttributeValueRepo.Setup(x => x.GetById(pav4_1.Id)).Returns(pav4_1);

            _predefinedProductAttributeValueRepo = new Mock <IRepository <PredefinedProductAttributeValue> >();

            _eventPublisher = new Mock <IEventPublisher>();
            _eventPublisher.Setup(x => x.Publish(It.IsAny <object>()));

            var cacheManager = new TestCacheManager();

            _productAttributeService = new ProductAttributeService(cacheManager,
                                                                   _eventPublisher.Object,
                                                                   _predefinedProductAttributeValueRepo.Object,
                                                                   _productAttributeRepo.Object,
                                                                   _productAttributeCombinationRepo.Object,
                                                                   _productAttributeMappingRepo.Object,
                                                                   _productAttributeValueRepo.Object,
                                                                   new TestCacheManager());

            _context = new Mock <IDbContext>();

            _productAttributeParser = new ProductAttributeParser(_context.Object, _productAttributeService);

            _priceCalculationService = new Mock <IPriceCalculationService>();

            var workingLanguage = new Language();
            _workContext = new Mock <IWorkContext>();
            _workContext.Setup(x => x.WorkingLanguage).Returns(workingLanguage);
            _currencyService     = new Mock <ICurrencyService>();
            _localizationService = TestLocalizationService.Init();

            _taxService           = new Mock <ITaxService>();
            _priceFormatter       = new Mock <IPriceFormatter>();
            _downloadService      = new Mock <IDownloadService>();
            _webHelper            = new Mock <IWebHelper>();
            _shoppingCartSettings = new ShoppingCartSettings();

            _productAttributeFormatter = new ProductAttributeFormatter(_currencyService.Object,
                                                                       _downloadService.Object,
                                                                       _localizationService,
                                                                       _priceCalculationService.Object,
                                                                       _priceFormatter.Object,
                                                                       _productAttributeParser,
                                                                       _taxService.Object,
                                                                       _webHelper.Object,
                                                                       _workContext.Object,
                                                                       _shoppingCartSettings);
        }
Пример #17
0
 partial void DeleteProductAttributeValue(ProductAttributeValue instance);
        public new void SetUp()
        {
            #region Test data

            //color (dropdownlist)
            pa1 = new ProductAttribute
            {
                Id   = 1,
                Name = "Color",
            };
            pam1_1 = new ProductAttributeMapping
            {
                Id                   = 11,
                ProductId            = 1,
                TextPrompt           = "Select color:",
                IsRequired           = true,
                AttributeControlType = AttributeControlType.DropdownList,
                DisplayOrder         = 1,
                ProductAttribute     = pa1,
                ProductAttributeId   = pa1.Id
            };
            pav1_1 = new ProductAttributeValue
            {
                Id                        = 11,
                Name                      = "Green",
                DisplayOrder              = 1,
                ProductAttributeMapping   = pam1_1,
                ProductAttributeMappingId = pam1_1.Id
            };
            pav1_2 = new ProductAttributeValue
            {
                Id                        = 12,
                Name                      = "Red",
                DisplayOrder              = 2,
                ProductAttributeMapping   = pam1_1,
                ProductAttributeMappingId = pam1_1.Id
            };
            pam1_1.ProductAttributeValues.Add(pav1_1);
            pam1_1.ProductAttributeValues.Add(pav1_2);

            //custom option (checkboxes)
            pa2 = new ProductAttribute
            {
                Id   = 2,
                Name = "Some custom option",
            };
            pam2_1 = new ProductAttributeMapping
            {
                Id                   = 21,
                ProductId            = 1,
                TextPrompt           = "Select at least one option:",
                IsRequired           = true,
                AttributeControlType = AttributeControlType.Checkboxes,
                DisplayOrder         = 2,
                ProductAttribute     = pa2,
                ProductAttributeId   = pa2.Id
            };
            pav2_1 = new ProductAttributeValue
            {
                Id                        = 21,
                Name                      = "Option 1",
                DisplayOrder              = 1,
                ProductAttributeMapping   = pam2_1,
                ProductAttributeMappingId = pam2_1.Id
            };
            pav2_2 = new ProductAttributeValue
            {
                Id                        = 22,
                Name                      = "Option 2",
                DisplayOrder              = 2,
                ProductAttributeMapping   = pam2_1,
                ProductAttributeMappingId = pam2_1.Id
            };
            pam2_1.ProductAttributeValues.Add(pav2_1);
            pam2_1.ProductAttributeValues.Add(pav2_2);

            //custom text
            pa3 = new ProductAttribute
            {
                Id   = 3,
                Name = "Custom text",
            };
            pam3_1 = new ProductAttributeMapping
            {
                Id                   = 31,
                ProductId            = 1,
                TextPrompt           = "Enter custom text:",
                IsRequired           = true,
                AttributeControlType = AttributeControlType.TextBox,
                DisplayOrder         = 1,
                ProductAttribute     = pa1,
                ProductAttributeId   = pa3.Id
            };


            #endregion

            _productAttributeRepo = MockRepository.GenerateMock <IRepository <ProductAttribute> >();
            _productAttributeRepo.Expect(x => x.Table).Return(new List <ProductAttribute> {
                pa1, pa2, pa3
            }.AsQueryable());
            _productAttributeRepo.Expect(x => x.GetById(pa1.Id)).Return(pa1);
            _productAttributeRepo.Expect(x => x.GetById(pa2.Id)).Return(pa2);
            _productAttributeRepo.Expect(x => x.GetById(pa3.Id)).Return(pa3);

            _productAttributeMappingRepo = MockRepository.GenerateMock <IRepository <ProductAttributeMapping> >();
            _productAttributeMappingRepo.Expect(x => x.Table).Return(new List <ProductAttributeMapping> {
                pam1_1, pam2_1, pam3_1
            }.AsQueryable());
            _productAttributeMappingRepo.Expect(x => x.GetById(pam1_1.Id)).Return(pam1_1);
            _productAttributeMappingRepo.Expect(x => x.GetById(pam2_1.Id)).Return(pam2_1);
            _productAttributeMappingRepo.Expect(x => x.GetById(pam3_1.Id)).Return(pam3_1);

            _productAttributeCombinationRepo = MockRepository.GenerateMock <IRepository <ProductAttributeCombination> >();
            _productAttributeCombinationRepo.Expect(x => x.Table).Return(new List <ProductAttributeCombination>().AsQueryable());

            _productAttributeValueRepo = MockRepository.GenerateMock <IRepository <ProductAttributeValue> >();
            _productAttributeValueRepo.Expect(x => x.Table).Return(new List <ProductAttributeValue> {
                pav1_1, pav1_2, pav2_1, pav2_2
            }.AsQueryable());
            _productAttributeValueRepo.Expect(x => x.GetById(pav1_1.Id)).Return(pav1_1);
            _productAttributeValueRepo.Expect(x => x.GetById(pav1_2.Id)).Return(pav1_2);
            _productAttributeValueRepo.Expect(x => x.GetById(pav2_1.Id)).Return(pav2_1);
            _productAttributeValueRepo.Expect(x => x.GetById(pav2_2.Id)).Return(pav2_2);

            _predefinedProductAttributeValueRepo = MockRepository.GenerateMock <IRepository <PredefinedProductAttributeValue> >();

            _eventPublisher = MockRepository.GenerateMock <IEventPublisher>();
            _eventPublisher.Expect(x => x.Publish(Arg <object> .Is.Anything));

            var cacheManager = new NopNullCache();

            _productAttributeService = new ProductAttributeService(cacheManager,
                                                                   _productAttributeRepo,
                                                                   _productAttributeMappingRepo,
                                                                   _productAttributeCombinationRepo,
                                                                   _productAttributeValueRepo,
                                                                   _predefinedProductAttributeValueRepo,
                                                                   _eventPublisher);

            _productAttributeParser = new ProductAttributeParser(_productAttributeService);

            _priceCalculationService = MockRepository.GenerateMock <IPriceCalculationService>();


            var workingLanguage = new Language();
            _workContext = MockRepository.GenerateMock <IWorkContext>();
            _workContext.Expect(x => x.WorkingLanguage).Return(workingLanguage);
            _currencyService     = MockRepository.GenerateMock <ICurrencyService>();
            _localizationService = MockRepository.GenerateMock <ILocalizationService>();
            _localizationService.Expect(x => x.GetResource("GiftCardAttribute.For.Virtual")).Return("For: {0} <{1}>");
            _localizationService.Expect(x => x.GetResource("GiftCardAttribute.From.Virtual")).Return("From: {0} <{1}>");
            _localizationService.Expect(x => x.GetResource("GiftCardAttribute.For.Physical")).Return("For: {0}");
            _localizationService.Expect(x => x.GetResource("GiftCardAttribute.From.Physical")).Return("From: {0}");
            _taxService           = MockRepository.GenerateMock <ITaxService>();
            _priceFormatter       = MockRepository.GenerateMock <IPriceFormatter>();
            _downloadService      = MockRepository.GenerateMock <IDownloadService>();
            _webHelper            = MockRepository.GenerateMock <IWebHelper>();
            _shoppingCartSettings = MockRepository.GenerateMock <ShoppingCartSettings>();

            _productAttributeFormatter = new ProductAttributeFormatter(_workContext,
                                                                       _productAttributeService,
                                                                       _productAttributeParser,
                                                                       _currencyService,
                                                                       _localizationService,
                                                                       _taxService,
                                                                       _priceFormatter,
                                                                       _downloadService,
                                                                       _webHelper,
                                                                       _priceCalculationService,
                                                                       _shoppingCartSettings);
        }
Пример #19
0
	private void detach_ProductAttributeValues(ProductAttributeValue entity)
	{
		this.SendPropertyChanging();
		entity.AttributeValue = null;
	}
Пример #20
0
 public static ProductAttributeValue ToEntity(this ProductAttributeValueDTO dto, ProductAttributeValue entity)
 {
     return(Mapper.Map(dto, entity));
 }
 /// <summary>
 /// Deletes a product attribute value
 /// </summary>
 /// <param name="productAttributeValue">Product attribute value</param>
 public virtual void DeleteProductAttributeValue(ProductAttributeValue productAttributeValue)
 {
     _productAttributeValueRepository.Delete(productAttributeValue);
 }
Пример #22
0
 public async Task <int> Insert(ProductAttributeValue productAttributeValue)
 {
     _productAttributeValueRepository.Create(productAttributeValue);
     return(await Context.SaveChangesAsync());
 }
 /// <summary>
 /// Inserts a product attribute value
 /// </summary>
 /// <param name="productAttributeValue">The product attribute value</param>
 public virtual void InsertProductAttributeValue(ProductAttributeValue productAttributeValue)
 {
     _productAttributeValueRepository.Insert(productAttributeValue);
 }
Пример #24
0
        public ActionResult CreateProduct(AdminEditProductViewModel model)
        {
            var cats = _categoryService.GetAllowedEditCategories(UsersRole, true);

            model.Categories = _categoryService.GetBaseSelectListCategories(cats);

            if (ModelState.IsValid)
            {
                if (model.Content == null)
                {
                    model.Content = string.Empty;
                }

                using (var unitOfWork = UnitOfWorkManager.NewUnitOfWork())
                {
                    try
                    {
                        if (model.AllAttribute != null)
                        {
                            foreach (var it in model.AllAttribute)
                            {
                                var a = _productSevice.GetAttribute(it.AttriId);
                                it.Name      = a.LangName;
                                it.ValueType = a.ValueType;
                                it.IsNull    = a.IsNull;

                                if (!a.ValueOption.IsNullEmpty() && a.ValueType == 2)
                                {
                                    dynamic json = JsonConvert.DeserializeObject(a.ValueOption);
                                    if (json != null)
                                    {
                                        it.ValueOptions = new List <string>();
                                        foreach (var itt in json)
                                        {
                                            it.ValueOptions.Add((string)itt);
                                        }
                                    }
                                }

                                //if (!a.ValueFindter.IsNullEmpty())
                                //{
                                //	dynamic json = JsonConvert.DeserializeObject(a.ValueFindter);
                                //	if (json != null)
                                //	{
                                //		it.FindterNums = new List<AdminAttributeNumberFindter>();
                                //		foreach (dynamic itt in json)
                                //		{
                                //			it.FindterNums.Add(new AdminAttributeNumberFindter { Name = (string)itt.Name });
                                //		}
                                //	}
                                //}
                            }
                        }


                        var post    = new ProductPost();
                        var product = new Product();

                        post.PostContent       = model.Content;
                        post.MembershipUser_Id = LoggedOnReadOnlyUser.Id;
                        post.Product_Id        = product.Id;
                        post.IsTopicStarter    = true;

                        product.Name              = model.Name;
                        product.Category_Id       = model.Category;
                        product.Image             = model.Image;
                        product.IsLocked          = model.IsLocked;
                        product.ProductClassId    = model.ProductClass;
                        product.MembershipUser_Id = LoggedOnReadOnlyUser.Id;
                        product.ProductPost_Id    = post.Id;

                        product.ShotContent       = string.Concat(StringUtils.ReturnAmountWordsFromString(StringUtils.StripHtmlFromString(post.PostContent), 50), "....");
                        product.isAutoShotContent = true;
                        var i = product.ShotContent.Length;
                        if (i > 450)
                        {
                            product.ShotContent = product.ShotContent.Substring(0, 440) + "...";
                        }

                        _productSevice.Add(product);
                        _productPostSevice.Add(post);

                        if (model.AllAttribute != null)
                        {
                            foreach (var it in model.AllAttribute)
                            {
                                var val = new ProductAttributeValue
                                {
                                    ProductAttributeId = it.AttriId,
                                    ProductId          = product.Id,
                                    Value = it.Value
                                };

                                _productSevice.Add(val);
                            }
                        }

                        unitOfWork.Commit();
                        // We use temp data because we are doing a redirect
                        TempData[AppConstants.MessageViewBagName] = new GenericMessageViewModel
                        {
                            Message     = "Thêm sản phẩm thành công!",
                            MessageType = GenericMessages.success
                        };

                        return(RedirectToAction("Product", new { id = model.ProductClass }));
                    }
                    catch (Exception ex)
                    {
                        unitOfWork.Rollback();
                        LoggingService.Error(ex);
                        ModelState.AddModelError("", "Xảy ra lỗi khi thêm sản phẩm");
                    }
                }
            }


            return(View(model));
        }
 /// <summary>
 /// Updates the product attribute value
 /// </summary>
 /// <param name="productAttributeValue">The product attribute value</param>
 public virtual void UpdateProductAttributeValue(ProductAttributeValue productAttributeValue)
 {
     _productAttributeValueRepository.Update(productAttributeValue);
 }
Пример #26
0
 /// <summary>
 /// Updates the product attribute value
 /// </summary>
 /// <param name="productAttributeValue">The product attribute value</param>
 /// <returns>A task that represents the asynchronous operation</returns>
 public virtual async Task UpdateProductAttributeValueAsync(ProductAttributeValue productAttributeValue)
 {
     await _productAttributeValueRepository.UpdateAsync(productAttributeValue);
 }
Пример #27
0
        private void DoProcess(List <TrdPartyProductModel> data, List <Attributes> atts, Objects.DataAccess.UnitOfWork.IUnitOfWork unit)
        {
            var config = GetConfiguration();

            var vendorID_NL = vendors.First(x => x.Value == "NL").Key;
            var vendorID_BE = vendors.First(x => x.Value == "BE").Key;

            var repoBrandVendor = unit.Scope.Repository <BrandVendor>();

            var prodRepo = unit.Scope.Repository <Product>().Include(c => c.ProductMedias, c => c.ProductBarcodes, c => c.ProductDescriptions);
            var productAttributeGroups = unit.Scope.Repository <ProductAttributeGroupMetaData>().GetAll(g => g.VendorID == vendorID_NL || g.VendorID == vendorID_BE).ToList();
            var repoAssortment         = unit.Scope.Repository <VendorAssortment>().Include(c => c.VendorPrices);
            var stockRepo                = unit.Scope.Repository <VendorStock>();
            var repoAttributeGroup       = unit.Scope.Repository <ProductAttributeGroupMetaData>();
            var repoAttributeGroupName   = unit.Scope.Repository <ProductAttributeGroupName>();
            var repoAttributeValue       = unit.Scope.Repository <ProductAttributeValue>();
            var repotAttributeName       = unit.Scope.Repository <ProductAttributeName>();
            var repoAttribute            = unit.Scope.Repository <ProductAttributeMetaData>().Include(c => c.ProductAttributeNames, c => c.ProductAttributeValues);
            var repoVendor               = unit.Scope.Repository <ProductGroupVendor>();
            var prodDescriptionRepo      = unit.Scope.Repository <ProductDescription>();
            var priceRepo                = unit.Scope.Repository <VendorPrice>();
            var productGroupLanguageRepo = unit.Scope.Repository <ProductGroupLanguage>();
            var productGroupMappingRepo  = unit.Scope.Repository <ProductGroupMapping>();

            //var products = prodRepo.GetAll(x => x.SourceVendorID == VendorID).ToList();
            var vendorassortments = repoAssortment.GetAll(x => x.VendorID == vendorID_NL || x.VendorID == vendorID_BE).ToList();
            var productAttributes = repoAttribute.GetAll(g => g.VendorID == vendorID_NL || g.VendorID == vendorID_BE).ToList();

            var productGroupVendorRecords = repoVendor.GetAll(pc => pc.VendorID == vendorID_NL || pc.VendorID == vendorID_BE).ToList();
            var brands              = repoBrandVendor.GetAll(bv => bv.VendorID == vendorID_NL || bv.VendorID == vendorID_BE).ToList();
            var brandEnts           = unit.Scope.Repository <Brand>().GetAll();
            var products            = prodRepo.GetAll(x => x.SourceVendorID == vendorID_NL || x.SourceVendorID == vendorID_BE).ToList();
            var vendorStock         = stockRepo.GetAll(x => x.VendorID == vendorID_NL || x.VendorID == vendorID_BE).ToList();
            var productDescriptions = prodDescriptionRepo.GetAll().ToList();

            var productGroupLanguages = productGroupLanguageRepo.GetAll().ToList();
            var prodAttributeGroups   = repoAttributeGroup.GetAll(g => g.VendorID == vendorID_NL || g.VendorID == vendorID_BE).ToList();
            var productGroupMapping   = productGroupMappingRepo.GetAll(x => x.ConnectorID == 2).ToList();

            int counter = 0;
            int total   = data.Count();
            int totalNumberOfProductsToProcess = total;

            log.InfoFormat("Start import {0} products", total);
            bool firstVendor = true;

            foreach (var VendorID in vendors.Keys)
            {
                ProductStatusVendorMapper mapper = new ProductStatusVendorMapper(unit.Scope.Repository <VendorProductStatus>(), VendorID);
                var vendor = unit.Scope.Repository <Vendor>().GetSingle(x => x.VendorID == VendorID);

                foreach (var product in data)
                {
                    if (string.IsNullOrEmpty(product.Artnr))
                    {
                        continue;
                    }
                    try
                    {
                        if (counter == 100)
                        {
                            counter = 0;
                            log.InfoFormat("Still need to process {0} of {1}; {2} done for {3};", totalNumberOfProductsToProcess, total, total - totalNumberOfProductsToProcess, VendorID);
                        }

                        totalNumberOfProductsToProcess--;
                        counter++;

                        var brand   = brandEnts.FirstOrDefault(c => c.Name.ToLower() == product.BrandName.Trim().ToLower());
                        int brandID = 0;

                        if (brand == null)
                        {
                            var vbrand = brands.FirstOrDefault(vb => vb.VendorBrandCode.Trim() == product.BrandName.Trim());

                            if (vbrand == null)
                            {
                                vbrand = new BrandVendor
                                {
                                    VendorID        = VendorID,
                                    VendorBrandCode = product.BrandName.Trim(),
                                    BrandID         = unmappedID,
                                    Name            = product.BrandName.Trim()
                                };

                                brands.Add(vbrand);

                                repoBrandVendor.Add(vbrand);
                            }
                            brandID = vbrand.BrandID;
                        }
                        else
                        {
                            brandID = brand.BrandID;
                        }

                        var item = products.FirstOrDefault(p => p.VendorItemNumber.Trim() == product.Artnr.Trim() && p.BrandID == brandID);
                        if (item == null)
                        {
                            item = new Product
                            {
                                VendorItemNumber = product.Artnr.Trim(),
                                BrandID          = brandID,
                                SourceVendorID   = VendorID
                            };
                            prodRepo.Add(item);
                            products.Add(item);
                            unit.Save();
                        }

                        if (firstVendor)
                        {
                            var productDescription = productDescriptions.FirstOrDefault(pd => pd.Product.VendorItemNumber == item.VendorItemNumber && pd.LanguageID == 1 && (pd.VendorID == vendor.VendorID || (vendor.ParentVendorID.HasValue && pd.VendorID == vendor.VendorID)));

                            if (productDescription == null)
                            {
                                //create ProductDescription
                                productDescription = new ProductDescription
                                {
                                    Product    = item,
                                    LanguageID = languageID,
                                    VendorID   = VendorID,
                                };

                                prodDescriptionRepo.Add(productDescription);
                                productDescriptions.Add(productDescription);
                            }

                            if (string.IsNullOrEmpty(productDescription.ProductName))
                            {
                                productDescription.ProductName = product.Product;
                                productDescription.ModelName   = product.Product;
                            }

                            if (!string.IsNullOrEmpty(product.ShortDescription))
                            {
                                productDescription.ShortContentDescription = product.ShortDescription.Cap(1000);
                            }

                            if (string.IsNullOrEmpty(productDescription.LongContentDescription))
                            {
                                productDescription.LongContentDescription = product.LongDescription;
                            }

                            if (string.IsNullOrEmpty(productDescription.LongSummaryDescription))
                            {
                                productDescription.LongSummaryDescription = product.LongDescription;
                            }
                        }

                        var assortment = vendorassortments.FirstOrDefault(x => x.Product.VendorItemNumber == item.VendorItemNumber.Trim() && x.VendorID == VendorID);
                        if (assortment == null)
                        {
                            assortment = new VendorAssortment
                            {
                                VendorID         = VendorID,
                                Product          = item,
                                ShortDescription = product.Try(c => c.ShortDescription.Cap(1000), string.Empty),//.ShortDescription // .Length > 150 ? product.ShortDescription.Substring(0, 150) : product.ShortDescription,
                                CustomItemNumber = product.Artnr.Trim(),
                                IsActive         = true,
                                LongDescription  = product.LongDescription
                            };
                            vendorassortments.Add(assortment);
                            repoAssortment.Add(assortment);
                        }

                        var productGroups = new string[4];
                        productGroups[0] = product.BrandName;
                        productGroups[1] = product.Chapter;
                        productGroups[2] = product.Category;
                        productGroups[3] = product.Subcategory;

                        var pgvs = assortment.ProductGroupVendors != null?assortment.ProductGroupVendors.ToList() : new List <ProductGroupVendor>();

                        ProductGroupMapping parentpgm = null;

                        for (int i = 0; i < productGroups.Length; i++)
                        {
                            var groupCode = productGroups[i];

                            if (string.IsNullOrEmpty(groupCode))
                            {
                                continue;
                            }

                            var productGroup = productGroupLanguages.FirstOrDefault(x => x.Name == groupCode.Trim());
                            if (productGroup == null)
                            {
                                var pg = new Concentrator.Objects.Models.Products.ProductGroup()
                                {
                                    Score = 0
                                };

                                unit.Scope.Repository <Concentrator.Objects.Models.Products.ProductGroup>().Add(pg);

                                productGroup = new ProductGroupLanguage()
                                {
                                    ProductGroup = pg,
                                    LanguageID   = 1,
                                    Name         = groupCode.Trim()
                                };

                                productGroupLanguages.Add(productGroup);
                                productGroupLanguageRepo.Add(productGroup);
                                unit.Save();
                            }

                            //var productGroupVendor = productGroupVendorRecords.Where(pg => pg.GetType().GetProperty(string.Format("VendorProductGroupCode{0}", i + 1)).GetValue(pg, null) != null
                            //        && pg.GetType().GetProperty(string.Format("VendorProductGroupCode{0}", i + 1)).GetValue(pg, null).ToString() == groupCode.Trim()).FirstOrDefault();

                            var productGroupVendor = productGroupVendorRecords.FirstOrDefault(x => x.ProductGroupID == productGroup.ProductGroupID);

                            if (productGroupVendor == null)
                            {
                                productGroupVendor = new ProductGroupVendor
                                {
                                    ProductGroupID = productGroup.ProductGroupID,
                                    VendorID       = VendorID,
                                    VendorName     = groupCode.Trim(),
                                };

                                productGroupVendor.GetType().GetProperty(string.Format("VendorProductGroupCode{0}", i + 1)).SetValue(productGroupVendor, groupCode.Trim().Cap(50), null);

                                repoVendor.Add(productGroupVendor);
                                productGroupVendorRecords.Add(productGroupVendor);
                            }

                            if (productGroupVendor.VendorAssortments == null)
                            {
                                productGroupVendor.VendorAssortments = new List <VendorAssortment>();
                            }

                            var assortmentRelation = productGroupVendor.VendorAssortments.Count == 0 ? null : productGroupVendor.VendorAssortments.Where(c => c.Product != null && c.Product.VendorItemNumber == item.VendorItemNumber.Trim() && c.VendorID == VendorID).FirstOrDefault();
                            if (assortmentRelation == null)
                            {
                                productGroupVendor.VendorAssortments.Add(assortment);
                            }
                            else
                            {
                                pgvs.Remove(productGroupVendor);
                            }

                            if (productGroupVendor.ProductGroupID > 0)
                            {
                                ProductGroupMapping pgm = null;

                                if (parentpgm != null)
                                {
                                    pgm = productGroupMapping.FirstOrDefault(x => x.ProductGroupID == productGroupVendor.ProductGroupID && x.ParentProductGroupMappingID == parentpgm.ProductGroupMappingID);
                                }
                                else
                                {
                                    pgm = productGroupMapping.FirstOrDefault(x => x.ProductGroupID == productGroupVendor.ProductGroupID);
                                }

                                if (pgm == null)
                                {
                                    pgm = new ProductGroupMapping()
                                    {
                                        ConnectorID         = 2,
                                        ProductGroupID      = productGroupVendor.ProductGroupID,
                                        FlattenHierarchy    = false,
                                        FilterByParentGroup = parentpgm != null ? true : false,
                                        Depth = i,
                                        Score = 0
                                    };

                                    if (parentpgm != null)
                                    {
                                        pgm.ParentProductGroupMappingID = parentpgm.ProductGroupMappingID;
                                    }

                                    unit.Scope.Repository <ProductGroupMapping>().Add(pgm);
                                    unit.Save();
                                    productGroupMapping.Add(pgm);
                                }
                                parentpgm = pgm;
                            }
                        }

                        pgvs.ForEach(pg =>
                        {
                            productGroupVendorRecords.Remove(pg);
                        });

                        if (firstVendor)
                        {
                            if (!string.IsNullOrEmpty(product.PriceGroup))
                            {
                                atts.Add(new Attributes()
                                {
                                    AttArtnr = product.Artnr.Trim(),
                                    Feature  = "PriceGroup",
                                    Value    = product.PriceGroup
                                });
                            }

                            if (!string.IsNullOrEmpty(product.Features))
                            {
                                atts.Add(new Attributes()
                                {
                                    AttArtnr = product.Artnr.Trim(),
                                    Feature  = "Features",
                                    Value    = product.Features
                                });
                            }

                            if (!string.IsNullOrEmpty(product.NEW))
                            {
                                atts.Add(new Attributes()
                                {
                                    AttArtnr = product.Artnr.Trim(),
                                    Feature  = "New",
                                    Value    = product.NEW
                                });
                            }

                            var attributes = atts.Where(x => x.AttArtnr != null && (x.AttArtnr.Trim() == product.Artnr.Trim())).ToList();

                            if (attributes != null && attributes.Count > 0)
                            {
                                foreach (var att in attributes)
                                {
                                    string AttributeCode        = "General",
                                             AttributeGroupCode = att.Feature,
                                             AttributeValue     = att.Value;

                                    if (!string.IsNullOrEmpty(AttributeGroupCode) && !string.IsNullOrEmpty(AttributeValue))
                                    {
                                        var productAttributeMetadata = productAttributes.FirstOrDefault(c => c.ProductAttributeNames.Any(l => l.Name == AttributeGroupCode) && c.VendorID == VendorID);
                                        if (productAttributeMetadata == null)
                                        {
                                            productAttributeMetadata = new ProductAttributeMetaData
                                            {
                                                AttributeCode = att.Feature,
                                                Index         = 0,
                                                IsVisible     = true,
                                                NeedsUpdate   = true,
                                                VendorID      = VendorID,
                                                IsSearchable  = false
                                            };
                                            productAttributes.Add(productAttributeMetadata);
                                            repoAttribute.Add(productAttributeMetadata);
                                        }

                                        var attributeGroup = productAttributeMetadata.ProductAttributeGroupMetaData;
                                        if (attributeGroup == null)
                                        {
                                            attributeGroup = new ProductAttributeGroupMetaData
                                            {
                                                Index     = 0,
                                                GroupCode = "TechnicalData",
                                                VendorID  = VendorID
                                            };
                                            repoAttributeGroup.Add(attributeGroup);
                                            productAttributeMetadata.ProductAttributeGroupMetaData = attributeGroup;
                                        }
                                        productAttributeMetadata.ProductAttributeGroupID = attributeGroup.ProductAttributeGroupID;

                                        var attributeGroupName = attributeGroup.ProductAttributeGroupNames.FirstOrDefault(c => c.LanguageID == 1);
                                        if (attributeGroupName == null)
                                        {
                                            attributeGroupName = new ProductAttributeGroupName
                                            {
                                                Name       = AttributeCode,
                                                LanguageID = languageID,
                                                ProductAttributeGroupMetaData = attributeGroup
                                            };
                                            repoAttributeGroupName.Add(attributeGroupName);
                                            attributeGroup.ProductAttributeGroupNames.Add(attributeGroupName);
                                        }



                                        var attributeName = productAttributeMetadata.ProductAttributeNames.FirstOrDefault(c => c.LanguageID == 1);
                                        if (attributeName == null)
                                        {
                                            attributeName = new ProductAttributeName
                                            {
                                                ProductAttributeMetaData = productAttributeMetadata,
                                                LanguageID = 1,
                                                Name       = AttributeGroupCode
                                            };
                                            repotAttributeName.Add(attributeName);
                                            productAttributeMetadata.ProductAttributeNames.Add(attributeName);
                                        }

                                        var attributeValue = productAttributeMetadata.ProductAttributeValues.FirstOrDefault(c => c.Value == AttributeValue && c.ProductID == item.ProductID);
                                        if (attributeValue == null && !string.IsNullOrEmpty(AttributeValue))
                                        {
                                            attributeValue = new ProductAttributeValue
                                            {
                                                Value = AttributeValue,
                                                ProductAttributeMetaData = productAttributeMetadata,
                                                LanguageID = 1,
                                                Product    = item
                                            };
                                            productAttributeMetadata.ProductAttributeValues.Add(attributeValue);
                                            repoAttributeValue.Add(attributeValue);
                                        }
                                    }
                                }
                            }
                        }

                        var stock = vendorStock.FirstOrDefault(c => c.Product.VendorItemNumber == item.VendorItemNumber.Trim() && c.VendorID == VendorID);

                        if (stock == null)
                        {
                            stock = new VendorStock
                            {
                                Product           = item,
                                QuantityOnHand    = 0,
                                VendorID          = VendorID,
                                VendorStockTypeID = 1
                            };
                            vendorStock.Add(stock);
                            stockRepo.Add(stock);
                        }



                        if (assortment.VendorPrices == null)
                        {
                            assortment.VendorPrices = new List <VendorPrice>();
                        }


                        var vendorPrice = assortment.VendorPrices.FirstOrDefault();
                        //create vendorPrice with vendorAssortmentID
                        if (vendorPrice == null)
                        {
                            vendorPrice = new VendorPrice
                            {
                                VendorAssortment = assortment,
                                CommercialStatus = "S",
                                MinimumQuantity  = 0
                            };
                            priceRepo.Add(vendorPrice);
                            assortment.VendorPrices.Add(vendorPrice);
                        }

                        decimal taxRate   = 19;
                        decimal price     = 0;
                        decimal costPrice = 0;

                        switch (vendors[VendorID])
                        {
                        case "NL":
                            taxRate = 19;
                            Decimal.TryParse(product.VATExclNL, out costPrice);
                            Decimal.TryParse(product.NLincl, out price);
                            break;

                        case "BE":
                            taxRate = 21;
                            Decimal.TryParse(product.VATExclBE, out costPrice);
                            Decimal.TryParse(product.BEincl, out price);
                            break;
                        }

                        vendorPrice.Price     = price;
                        vendorPrice.CostPrice = costPrice;
                        vendorPrice.TaxRate   = taxRate;

                        if (product.Image != null)
                        {
                            if (item.ProductMedias == null)
                            {
                                item.ProductMedias = new List <ProductMedia>();
                            }
                            if (!item.ProductMedias.Any(pi => pi.VendorID == VendorID && pi.MediaUrl == product.Image))
                            {
                                unit.Scope.Repository <ProductMedia>().Add(new ProductMedia
                                {
                                    VendorID = VendorID,
                                    MediaUrl = product.Image,
                                    TypeID   = 1, // image
                                    Product  = item,
                                    Sequence = 0
                                });
                            }
                        }


                        if (product.EAN != null || product.Barcode != null)
                        {
                            if (item.ProductBarcodes == null)
                            {
                                item.ProductBarcodes = new List <ProductBarcode>();
                            }
                            if (!item.ProductBarcodes.Any(pb => pb.Barcode.Trim() == product.EAN.Trim()))
                            {
                                unit.Scope.Repository <ProductBarcode>().Add(new ProductBarcode
                                {
                                    Product     = item,
                                    Barcode     = product.EAN != null ? product.EAN : product.Barcode != null ? product.Barcode : "",
                                    BarcodeType = (int)BarcodeTypes.Default,
                                    VendorID    = VendorID
                                });
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        log.AuditError("Error import products for Sennheiser 3rdParty", ex);
                    }
                }
                firstVendor = false;
            }
        }
        /// <summary>
        /// Get a price adjustment of a product attribute value
        /// </summary>
        /// <param name="product">Product</param>
        /// <param name="value">Product attribute value</param>
        /// <param name="customer">Customer</param>
        /// <param name="productPrice">Product price (null for using the base product price)</param>
        /// <returns>Price adjustment</returns>
        public virtual decimal GetProductAttributeValuePriceAdjustment(Product product, ProductAttributeValue value, Customer customer, decimal?productPrice = null)
        {
            if (value == null)
            {
                throw new ArgumentNullException(nameof(value));
            }

            var adjustment = decimal.Zero;

            switch (value.AttributeValueType)
            {
            case AttributeValueType.Simple:
                //simple attribute
                if (value.PriceAdjustmentUsePercentage)
                {
                    if (!productPrice.HasValue)
                    {
                        productPrice = GetFinalPrice(product, customer);
                    }

                    adjustment = (decimal)((float)productPrice * (float)value.PriceAdjustment / 100f);
                }
                else
                {
                    adjustment = value.PriceAdjustment;
                }

                break;

            case AttributeValueType.AssociatedToProduct:
                //bundled product
                var associatedProduct = _productService.GetProductById(value.AssociatedProductId);
                if (associatedProduct != null)
                {
                    adjustment = GetFinalPrice(associatedProduct, customer) * value.Quantity;
                }

                break;

            default:
                break;
            }

            return(adjustment);
        }
Пример #29
0
        private void ParseDocuments(IUnitOfWork unit, XDocument[] products, XDocument cont)
        {
            #region Xml Data

            //products = new XDocument[1];
            //products[0] = XDocument.Load(@"C:\Lenmar\test.xml");

            var itemContent = (from content in cont.Root.Elements("item")
                               let attributes = content.Elements().Where(x => AttributeMapping.Contains(x.Name.LocalName))
                                                where content.Element("LenmarSKU") != null && content.Element("Description") != null && content.Element("Manufacturer") != null
                                                select new
            {
                LenmarSKU = content.Element("LenmarSKU").Value,
                ShortContentDescription = content.Element("Description").Value,
                GroupCode = content.Element("Manufacturer").Value,
                CostPrice = content.Element("BC_euro_cost") != null ? content.Element("BC_euro_cost").Value : "0",
                dynamic = attributes
            }).ToList();
            XNamespace xName = "http://logictec.com/schemas/internaldocuments";


            var itemProducts = (from d in products
                                from itemproduct in d.Elements(xName + "Envelope").Elements("Messages").Elements(xName + "Price")
                                let c = itemContent.Where(x => x.LenmarSKU == itemproduct.Element("SupplierSku").Value).FirstOrDefault()
                                        select new
            {
                VendorBrandCode = itemproduct.Element("MfgName").Value,
                VendorName = itemproduct.Element("MfgName").Value,
                SupplierSKU = itemproduct.Element("SupplierSku").Value,
                CustomItemNr = itemproduct.Element("MfgSKU").Value,
                ShortDescription = itemproduct.Element("ProductName").Value,
                Price = itemproduct.Element("MSRP").Value,
                Status = itemproduct.Element("Active").Value,
                CostPrice = c != null ? c.CostPrice : itemproduct.Element("Price").Value,
                QuantityOnHand = itemproduct.Element("Inventory").Value,
                VendorProductGroupCode1 = itemproduct.Element("Category1").Value,
                VendorProductGroupCode2 = itemproduct.Element("Category2").Value,
                VendorProductGroupCode3 = itemproduct.Element("Category3").Value,
                VendorProductGroupCode4 = itemproduct.Element("Category4").Value,
                VendorProductGroupCode5 = itemproduct.Element("Category5").Value,
                Barcode = itemproduct.Element("UPCCode").Value,
                ShortContentDescription = c != null ? c.ShortContentDescription : string.Empty
            }).ToList();

            #endregion

            var _brandVendorRepo       = unit.Scope.Repository <BrandVendor>();
            var _productRepo           = unit.Scope.Repository <Product>();
            var _assortmentRepo        = unit.Scope.Repository <VendorAssortment>();
            var productGroupVendorRepo = unit.Scope.Repository <ProductGroupVendor>();
            var _prodDescriptionRepo   = unit.Scope.Repository <ProductDescription>();
            var _attrGroupRepo         = unit.Scope.Repository <ProductAttributeGroupMetaData>();
            var _attrGroupName         = unit.Scope.Repository <ProductAttributeGroupName>();
            var _attrRepo      = unit.Scope.Repository <ProductAttributeMetaData>();
            var _attrNameRepo  = unit.Scope.Repository <ProductAttributeName>();
            var _attrValueRepo = unit.Scope.Repository <ProductAttributeValue>();
            var _mediaRepo     = unit.Scope.Repository <ProductMedia>();
            var _priceRepo     = unit.Scope.Repository <VendorPrice>();
            var _stockRepo     = unit.Scope.Repository <VendorStock>();
            var _barcodeRepo   = unit.Scope.Repository <ProductBarcode>();

            var brands                     = _brandVendorRepo.GetAll(bv => bv.VendorID == VendorID).ToList();
            var productGroups              = productGroupVendorRepo.GetAll(g => g.VendorID == VendorID).ToList();
            var productAttributes          = _attrRepo.GetAll(g => g.VendorID == VendorID).ToList();
            var productAttributeGroups     = _attrGroupRepo.GetAll().ToList();
            var currentProductGroupVendors = productGroupVendorRepo.GetAll(g => g.VendorID == VendorID).ToList();

            ProductStatusVendorMapper mapper = new ProductStatusVendorMapper(unit.Scope.Repository <VendorProductStatus>(), VendorID);

            var unusedVendorAssortmentItems = _assortmentRepo.GetAll(x => x.VendorID == VendorID && x.IsActive == true).ToList();

            int counter = 0;
            int total   = itemProducts.Count();
            int totalNumberOfProductsToProcess = total;
            log.InfoFormat("Start import {0} products", total);

            foreach (var product in itemProducts)
            {
                if (counter == 50)
                {
                    counter = 0;
                    log.InfoFormat("Still need to process {0} of {1}; {2} done;", totalNumberOfProductsToProcess, total, total - totalNumberOfProductsToProcess);
                }
                totalNumberOfProductsToProcess--;
                counter++;

                try
                {
                    #region BrandVendor

                    Product prod = null;
                    //check if brandvendor exists in db
                    var brandVendor = brands.FirstOrDefault(vb => vb.VendorBrandCode == product.VendorBrandCode);

                    if (brandVendor == null) //if brandvendor does not exist
                    {
                        //create new brandVendor
                        brandVendor = new BrandVendor
                        {
                            BrandID         = unmappedID,
                            VendorID        = VendorID,
                            VendorBrandCode = product.VendorBrandCode,
                            Name            = product.VendorBrandCode
                        };
                        _brandVendorRepo.Add(brandVendor);
                        brands.Add(brandVendor);
                    }

                    //use BrandID to create product and retreive ProductID

                    var BrandID = brandVendor.BrandID;

                    var prods = _productRepo.GetAll(p => p.VendorItemNumber == product.SupplierSKU && (p.BrandID == BrandID || p.BrandID < 0)).ToList();
                    prod = prods.OrderByDescending(x => x.BrandID).FirstOrDefault();

                    if (prods.Count() > 1)
                    {
                        try
                        {
                            _stockRepo.Delete(prods.Where(x => x.BrandID < 0).SelectMany(x => x.VendorStocks));
                            unit.Save();
                            _productRepo.Delete(prods.Where(x => x.BrandID < 0));
                            unit.Save();
                        }
                        catch (Exception ex)
                        {
                        }
                    }

                    //if product does not exist (usually true)
                    if (prod == null)
                    {
                        prod = new Product
                        {
                            VendorItemNumber = product.SupplierSKU,
                            SourceVendorID   = VendorID
                        };
                        _productRepo.Add(prod);
                    }
                    prod.BrandID = BrandID;
                    unit.Save();

                    #endregion

                    #region VendorAssortMent

                    var productID = prod.ProductID;

                    if (prod.VendorAssortments == null)
                    {
                        prod.VendorAssortments = new List <VendorAssortment>();
                    }
                    var vendorAssortment = prod.VendorAssortments.FirstOrDefault(va => va.VendorID == VendorID);

                    //if vendorAssortMent does not exist
                    if (vendorAssortment == null)
                    {
                        //create vendorAssortMent with productID
                        vendorAssortment = new VendorAssortment
                        {
                            Product          = prod,
                            CustomItemNumber = product.CustomItemNr,
                            VendorID         = VendorID
                        };
                        _assortmentRepo.Add(vendorAssortment);
                    }
                    vendorAssortment.IsActive         = true;
                    vendorAssortment.ShortDescription =
                        product.ShortDescription.Length > 150
                                       ? product.ShortDescription.Substring(0, 150)
                                       : product.ShortDescription;
                    vendorAssortment.LongDescription = "";

                    unusedVendorAssortmentItems.Remove(vendorAssortment);

                    #endregion

                    #region VendorPrice

                    if (vendorAssortment.VendorPrices == null)
                    {
                        vendorAssortment.VendorPrices = new List <VendorPrice>();
                    }
                    var vendorPrice = vendorAssortment.VendorPrices.FirstOrDefault();
                    //create vendorPrice with vendorAssortmentID
                    if (vendorPrice == null)
                    {
                        vendorPrice = new VendorPrice
                        {
                            VendorAssortment = vendorAssortment
                        };
                        _priceRepo.Add(vendorPrice);
                    }

                    vendorPrice.Price                = Decimal.Parse(product.Price) / 119;
                    vendorPrice.TaxRate              = (Decimal)19.00;
                    vendorPrice.CommercialStatus     = product.Status;
                    vendorPrice.MinimumQuantity      = 0;
                    vendorPrice.CostPrice            = Decimal.Parse(product.CostPrice) / 100;
                    vendorPrice.ConcentratorStatusID = mapper.SyncVendorStatus(product.Status, -1);

                    #endregion

                    #region VendorStock

                    //var vendorStock = vendorAssortment.VendorStock.FirstOrDefault();
                    var vendorStock = _stockRepo.GetSingle(c => c.ProductID == vendorAssortment.ProductID && c.VendorID == vendorAssortment.VendorID);
                    //create vendorStock with productID
                    if (vendorStock == null)
                    {
                        vendorStock = new VendorStock
                        {
                            Product = prod
                        };
                        _stockRepo.Add(vendorStock);
                    }

                    vendorStock.StockStatus          = product.Status;
                    vendorStock.QuantityOnHand       = int.Parse(product.QuantityOnHand);
                    vendorStock.VendorID             = VendorID;
                    vendorStock.VendorStockTypeID    = 1;
                    vendorStock.VendorStatus         = product.Status;
                    vendorStock.ConcentratorStatusID = mapper.SyncVendorStatus(product.Status, -1);

                    #endregion

                    #region ProductGroupVendor

                    //var vendorProductGroupAssortments = (from c in context.VendorProductGroupAssortments
                    //                                     where
                    //                                       c.VendorAssortment == vendorAssortment
                    //                                     select c).ToList();

                    //create vendorGroup five times, each time with a different VendorProductGroupCode on a different level if not exist
                    string vendorProductGroupCode1 = string.IsNullOrEmpty(product.VendorProductGroupCode1) ? "Battery" : product.VendorProductGroupCode1;

                    var productGroupVendor1 =
                        productGroups.FirstOrDefault(pg => pg.VendorProductGroupCode1 == vendorProductGroupCode1);

                    if (productGroupVendor1 == null)
                    {
                        productGroupVendor1 = new ProductGroupVendor
                        {
                            ProductGroupID          = unmappedID,
                            VendorID                = VendorID,
                            VendorName              = product.VendorName,
                            VendorProductGroupCode1 = vendorProductGroupCode1,

                            VendorAssortments = new List <VendorAssortment>()
                        };
                        productGroupVendorRepo.Add(productGroupVendor1);
                        productGroups.Add(productGroupVendor1);
                    }


                    #region sync

                    if (currentProductGroupVendors.Contains(productGroupVendor1))
                    {
                        currentProductGroupVendors.Remove(productGroupVendor1);
                    }
                    #endregion



                    if (!productGroupVendor1.VendorAssortments.Any(c => c == vendorAssortment))
                    {
                        productGroupVendor1.VendorAssortments.Add(vendorAssortment);
                    }

                    if (!string.IsNullOrEmpty(product.VendorProductGroupCode2))
                    {
                        var productGroupVendor2 =
                            productGroups.FirstOrDefault(pg => pg.VendorProductGroupCode2 == product.VendorProductGroupCode2);

                        if (productGroupVendor2 == null)
                        {
                            productGroupVendor2 = new ProductGroupVendor
                            {
                                ProductGroupID          = unmappedID,
                                VendorID                = VendorID,
                                VendorName              = product.VendorName,
                                VendorProductGroupCode2 = product.VendorProductGroupCode2,
                                VendorAssortments       = new List <VendorAssortment>()
                            };

                            productGroupVendorRepo.Add(productGroupVendor2);
                            productGroups.Add(productGroupVendor2);
                        }


                        #region sync

                        if (currentProductGroupVendors.Contains(productGroupVendor2))
                        {
                            currentProductGroupVendors.Remove(productGroupVendor2);
                        }
                        #endregion

                        var vendorProductGroupAssortment2 =
                            productGroupVendor2.VendorAssortments.FirstOrDefault(c => c.VendorAssortmentID == vendorAssortment.VendorAssortmentID);

                        if (vendorProductGroupAssortment2 == null)
                        {
                            productGroupVendor2.VendorAssortments.Add(vendorAssortment);
                        }
                    }

                    if (!string.IsNullOrEmpty(product.VendorProductGroupCode3))
                    {
                        var productGroupVendor3 =
                            productGroups.FirstOrDefault(pg => pg.VendorProductGroupCode3 == product.VendorProductGroupCode3);

                        if (productGroupVendor3 == null)
                        {
                            productGroupVendor3 = new ProductGroupVendor
                            {
                                ProductGroupID          = unmappedID,
                                VendorID                = VendorID,
                                VendorName              = product.VendorName,
                                VendorProductGroupCode3 = product.VendorProductGroupCode3,
                                VendorAssortments       = new List <VendorAssortment>()
                            };

                            productGroupVendorRepo.Add(productGroupVendor3);
                            productGroups.Add(productGroupVendor3);
                        }


                        #region sync

                        if (currentProductGroupVendors.Contains(productGroupVendor3))
                        {
                            currentProductGroupVendors.Remove(productGroupVendor3);
                        }
                        #endregion

                        var vendorProductGroupAssortment3 =
                            productGroupVendor3.VendorAssortments.FirstOrDefault(c => c.VendorAssortmentID == vendorAssortment.VendorAssortmentID);

                        if (vendorProductGroupAssortment3 == null)
                        {
                            productGroupVendor3.VendorAssortments.Add(vendorAssortment);
                        }
                    }

                    if (!string.IsNullOrEmpty(product.VendorProductGroupCode4))
                    {
                        var productGroupVendor4 =
                            productGroups.FirstOrDefault(pg => pg.VendorProductGroupCode4 == product.VendorProductGroupCode4);

                        if (productGroupVendor4 == null)
                        {
                            productGroupVendor4 = new ProductGroupVendor
                            {
                                ProductGroupID          = unmappedID,
                                VendorID                = VendorID,
                                VendorName              = product.VendorName,
                                VendorProductGroupCode4 = product.VendorProductGroupCode4,
                                VendorAssortments       = new List <VendorAssortment>()
                            };

                            productGroupVendorRepo.Add(productGroupVendor4);
                            productGroups.Add(productGroupVendor4);
                        }


                        #region sync

                        if (currentProductGroupVendors.Contains(productGroupVendor4))
                        {
                            currentProductGroupVendors.Remove(productGroupVendor4);
                        }
                        #endregion

                        var vendorProductGroupAssortment4 =
                            productGroupVendor4.VendorAssortments.FirstOrDefault(c => c.VendorAssortmentID == vendorAssortment.VendorAssortmentID);

                        if (vendorProductGroupAssortment4 == null)
                        {
                            productGroupVendor4.VendorAssortments.Add(vendorAssortment);
                        }
                    }

                    if (!string.IsNullOrEmpty(product.VendorProductGroupCode5))
                    {
                        var productGroupVendor5 =
                            productGroups.FirstOrDefault(pg => pg.VendorProductGroupCode5 == product.VendorProductGroupCode5);

                        if (productGroupVendor5 == null)
                        {
                            productGroupVendor5 = new ProductGroupVendor
                            {
                                ProductGroupID          = unmappedID,
                                VendorID                = VendorID,
                                VendorName              = product.VendorName,
                                VendorProductGroupCode5 = product.VendorProductGroupCode5,
                                VendorAssortments       = new List <VendorAssortment>()
                            };

                            productGroupVendorRepo.Add(productGroupVendor5);
                            productGroups.Add(productGroupVendor5);
                        }


                        #region sync

                        if (currentProductGroupVendors.Contains(productGroupVendor5))
                        {
                            currentProductGroupVendors.Remove(productGroupVendor5);
                        }

                        #endregion
                        var vendorProductGroupAssortment5 =
                            productGroupVendor5.VendorAssortments.FirstOrDefault(c => c.VendorAssortmentID == vendorAssortment.VendorAssortmentID);

                        if (vendorProductGroupAssortment5 == null)
                        {
                            productGroupVendor5.VendorAssortments.Add(vendorAssortment);
                        }
                    }

                    if (!string.IsNullOrEmpty(product.VendorBrandCode))
                    {
                        var brandProductGroupvendor =
                            productGroups.FirstOrDefault(pg => pg.BrandCode == product.VendorBrandCode && pg.VendorProductGroupCode1 == null && pg.VendorProductGroupCode2 == null && pg.VendorProductGroupCode3 == null && pg.VendorProductGroupCode4 == null && pg.VendorProductGroupCode5 == null);

                        if (brandProductGroupvendor == null)
                        {
                            brandProductGroupvendor = new ProductGroupVendor
                            {
                                ProductGroupID = unmappedID,
                                VendorID       = VendorID,
                                VendorName     = product.VendorName,
                                BrandCode      = product.VendorBrandCode
                            };

                            productGroupVendorRepo.Add(brandProductGroupvendor);
                            productGroups.Add(brandProductGroupvendor);
                        }


                        #region sync

                        if (currentProductGroupVendors.Contains(brandProductGroupvendor))
                        {
                            currentProductGroupVendors.Remove(brandProductGroupvendor);
                        }

                        #endregion
                        var brandProductGroupAssortment =
                            brandProductGroupvendor.VendorAssortments.FirstOrDefault(c => c.VendorAssortmentID == vendorAssortment.VendorAssortmentID);

                        if (brandProductGroupAssortment == null)
                        {
                            brandProductGroupvendor.VendorAssortments.Add(vendorAssortment);
                        }
                    }

                    #endregion

                    #region ProductBarcode
                    if (prod.ProductBarcodes == null)
                    {
                        prod.ProductBarcodes = new List <ProductBarcode>();
                    }
                    if (!prod.ProductBarcodes.Any(pb => pb.Barcode.Trim() == product.Barcode))
                    {
                        //create ProductBarcode if not exists
                        _barcodeRepo.Add(new ProductBarcode
                        {
                            Product     = prod,
                            Barcode     = product.Barcode,
                            VendorID    = VendorID,
                            BarcodeType = (int)BarcodeTypes.Default
                        });
                    }

                    #endregion

                    #region ProductDescription
                    if (prod.ProductDescriptions == null)
                    {
                        prod.ProductDescriptions = new List <ProductDescription>();
                    }
                    var productDescription =
                        prod.ProductDescriptions.FirstOrDefault(pd => pd.LanguageID == languageID && pd.VendorID == VendorID);

                    if (productDescription == null)
                    {
                        //create ProductDescription
                        productDescription = new ProductDescription
                        {
                            Product    = prod,
                            LanguageID = languageID,
                            VendorID   = VendorID
                        };

                        _prodDescriptionRepo.Add(productDescription);
                    }
                    productDescription.ShortContentDescription = product.ShortContentDescription;

                    #endregion

                    foreach (var content in itemContent.Where(x => x.LenmarSKU == product.SupplierSKU))
                    {
                        #region ProductAttributeGroupMetaData

                        var productAttributeGroupMetaData =
                            productAttributeGroups.FirstOrDefault(c => c.GroupCode == content.GroupCode);
                        //create ProductAttributeGroupMetaData if not exists
                        if (productAttributeGroupMetaData == null)
                        {
                            productAttributeGroupMetaData = new ProductAttributeGroupMetaData
                            {
                                Index     = 0,
                                GroupCode = content.GroupCode,
                                VendorID  = VendorID
                            };
                            _attrGroupRepo.Add(productAttributeGroupMetaData);
                            productAttributeGroups.Add(productAttributeGroupMetaData);
                        }
                        #endregion

                        #region ProductAttributeGroupName
                        if (productAttributeGroupMetaData.ProductAttributeGroupNames == null)
                        {
                            productAttributeGroupMetaData.ProductAttributeGroupNames = new List <ProductAttributeGroupName>();
                        }
                        var productAttributeGroupName =
                            productAttributeGroupMetaData.ProductAttributeGroupNames.FirstOrDefault(c => c.LanguageID == languageID);
                        //create ProductAttributeGroupName if not exists
                        if (productAttributeGroupName == null)
                        {
                            productAttributeGroupName = new ProductAttributeGroupName
                            {
                                Name = "General",
                                ProductAttributeGroupMetaData = productAttributeGroupMetaData,
                                LanguageID = languageID
                            };
                            _attrGroupName.Add(productAttributeGroupName);
                        }

                        #endregion

                        #region ProductAttributeMetaData

                        //create ProductAttributeMetaData as many times that there are entrys in content.dynamic
                        foreach (var element in content.dynamic)
                        {
                            var productAttributeMetaData =
                                productAttributes.FirstOrDefault(c => c.AttributeCode == element.Name.ToString());
                            //create ProductAttributeMetaData if not exists
                            if (productAttributeMetaData == null)
                            {
                                productAttributeMetaData = new ProductAttributeMetaData
                                {
                                    ProductAttributeGroupMetaData = productAttributeGroupMetaData,
                                    AttributeCode = element.Name.ToString(),
                                    Index         = 0,
                                    IsVisible     = true,
                                    NeedsUpdate   = true,
                                    VendorID      = VendorID,
                                    IsSearchable  = false
                                };
                                _attrRepo.Add(productAttributeMetaData);
                                productAttributes.Add(productAttributeMetaData);
                            }

                            #endregion

                            #region ProductAttributeName
                            if (productAttributeMetaData.ProductAttributeNames == null)
                            {
                                productAttributeMetaData.ProductAttributeNames = new List <ProductAttributeName>();
                            }
                            var productAttributeName =
                                productAttributeMetaData.ProductAttributeNames.FirstOrDefault(c => c.LanguageID == languageID);
                            //create ProductAttributeName with generated productAttributeMetaData.AttributeID if not exists
                            if (productAttributeName == null)
                            {
                                productAttributeName = new ProductAttributeName
                                {
                                    ProductAttributeMetaData = productAttributeMetaData,
                                    LanguageID = languageID,
                                    Name       = element.Name.ToString()
                                };
                                _attrNameRepo.Add(productAttributeName);
                            }

                            #endregion

                            #region ProductAttributeValue

                            if (productAttributeMetaData.ProductAttributeValues == null)
                            {
                                productAttributeMetaData.ProductAttributeValues = new List <ProductAttributeValue>();
                            }
                            var productAttributeValue =
                                productAttributeMetaData.ProductAttributeValues.FirstOrDefault(c => c.ProductID == prod.ProductID);
                            //create ProductAttributeValue with generated productAttributeMetaData.AttributeID
                            if (productAttributeValue == null)
                            {
                                productAttributeValue = new ProductAttributeValue
                                {
                                    ProductAttributeMetaData = productAttributeMetaData,
                                    Product    = prod,
                                    Value      = element.Value,
                                    LanguageID = languageID
                                };
                                _attrValueRepo.Add(productAttributeValue);
                            }

                            #endregion
                        }
                    }
                    unit.Save();
                }
                catch (Exception ex)
                {
                    log.ErrorFormat("product: {0} error: {1}", product.SupplierSKU, ex.StackTrace);
                }
            }
            #region delete unused vendorProductGroups
            foreach (var vProdVendor in currentProductGroupVendors)
            {
                if (vProdVendor.ProductGroupID == -1)
                {
                    productGroupVendorRepo.Add(vProdVendor);
                }
            }
            unit.Save();

            unusedVendorAssortmentItems.ForEach(x => x.IsActive = false);
            unit.Save();

            #endregion
        }
Пример #30
0
        public void TestInitialize()
        {
            _productRepo = new MongoDBRepositoryTest <Product>();
            //dropdown list: adding 2 options "atributes" that can be selected via DropDownList
            pa1 = new ProductAttribute {
                Id   = "1",
                Name = "Color"
            };
            pam1_1 = new ProductAttributeMapping {
                Id                   = "11",
                ProductId            = "1",
                TextPrompt           = "Select color:",
                IsRequired           = true,
                AttributeControlType = AttributeControlType.DropdownList,
                DisplayOrder         = 1,
                ProductAttributeId   = pa1.Id
            };
            pav1_1 = new ProductAttributeValue {
                Id           = "11",
                Name         = "Green",
                DisplayOrder = 1,
                ProductAttributeMappingId = pam1_1.Id
            };
            pav1_2 = new ProductAttributeValue {
                Id           = "12",
                Name         = "Red",
                DisplayOrder = 2,
                ProductAttributeMappingId = pam1_1.Id
            };
            //adding colors (as product atributes)
            pam1_1.ProductAttributeValues.Add(pav1_1);
            pam1_1.ProductAttributeValues.Add(pav1_2);

            //checkboxes - adding 2 options that can be ticked via CheckBox'es
            pa2 = new ProductAttribute {
                Id   = "2",
                Name = "Some custom option",
            };
            pam2_1 = new ProductAttributeMapping {
                Id                   = "21",
                ProductId            = "1",
                TextPrompt           = "Select at least one option:",
                IsRequired           = true,
                AttributeControlType = AttributeControlType.Checkboxes,
                DisplayOrder         = 2,
                ProductAttributeId   = pa2.Id
            };
            pav2_1 = new ProductAttributeValue {
                Id           = "21",
                Name         = "Option 1",
                DisplayOrder = 1,
                ProductAttributeMappingId = pam2_1.Id
            };
            pav2_2 = new ProductAttributeValue {
                Id           = "22",
                Name         = "Option 2",
                DisplayOrder = 2,
                ProductAttributeMappingId = pam2_1.Id
            };
            pam2_1.ProductAttributeValues.Add(pav2_1);
            pam2_1.ProductAttributeValues.Add(pav2_2);

            //adds custom text (user can add its own text)
            pa3 = new ProductAttribute {
                Id   = "3",
                Name = "Custom text",
            };
            pam3_1 = new ProductAttributeMapping {
                Id                   = "31",
                ProductId            = "1",
                TextPrompt           = "Enter custom text:",
                IsRequired           = true,
                AttributeControlType = AttributeControlType.TextBox,
                DisplayOrder         = 1,
                ProductAttributeId   = pa3.Id
            };

            _product = new Product();
            _product.ProductAttributeMappings.Add(pam1_1);
            _product.ProductAttributeMappings.Add(pam2_1);
            _product.ProductAttributeMappings.Add(pam3_1);
            _productRepo.Insert(_product); //26 april

            var tempEventPublisher = new Mock <IMediator>();
            {
                //tempEventPublisher.Setup(x => x.Publish(It.IsAny<object>()));
                _eventPublisher = tempEventPublisher.Object;
            }

            var cacheManager = new TestMemoryCacheManager(new Mock <IMemoryCache>().Object, _eventPublisher);

            _productAttributeRepo = new Mock <IRepository <ProductAttribute> >().Object;

            _productAttributeService = new ProductAttributeService(cacheManager,
                                                                   _productAttributeRepo,
                                                                   _productRepo,
                                                                   _eventPublisher);
            _productAttributeParser  = new ProductAttributeParser();
            _priceCalculationService = new Mock <IPriceCalculationService>().Object;

            var tempWorkContext = new Mock <IWorkContext>();

            {
                var workingLanguage = new Language();
                tempWorkContext.Setup(x => x.WorkingLanguage).Returns(workingLanguage);
                _workContext = tempWorkContext.Object;
            }
            _currencyService = new Mock <ICurrencyService>().Object;
            var tempLocalizationService = new Mock <ILocalizationService>();

            {
                tempLocalizationService.Setup(x => x.GetResource("GiftCardAttribute.For.Virtual")).Returns("For: {0} <{1}>");
                tempLocalizationService.Setup(x => x.GetResource("GiftCardAttribute.From.Virtual")).Returns("From: {0} <{1}>");
                tempLocalizationService.Setup(x => x.GetResource("GiftCardAttribute.For.Physical")).Returns("For: {0}");
                tempLocalizationService.Setup(x => x.GetResource("GiftCardAttribute.From.Physical")).Returns("From: {0}");
                _localizationService = tempLocalizationService.Object;
            }

            _taxService           = new Mock <ITaxService>().Object;
            _priceFormatter       = new Mock <IPriceFormatter>().Object;
            _downloadService      = new Mock <IDownloadService>().Object;
            _webHelper            = new Mock <IWebHelper>().Object;
            _shoppingCartSettings = new Mock <ShoppingCartSettings>().Object;
            _productService       = new Mock <IProductService>().Object;

            _productAttributeFormatter = new ProductAttributeFormatter(_workContext,
                                                                       _productAttributeService,
                                                                       _productAttributeParser,
                                                                       _currencyService,
                                                                       _localizationService,
                                                                       _taxService,
                                                                       _priceFormatter,
                                                                       _downloadService,
                                                                       _webHelper,
                                                                       _priceCalculationService,
                                                                       _productService,
                                                                       _shoppingCartSettings);
        }
Пример #31
0
        protected override void Process()
        {
            int vendorID = int.Parse(GetConfiguration().AppSettings.Settings["NederlofVendorID"].Value);
            var dir      = GetConfiguration().AppSettings.Settings["NederlofFiles"].Value;

            List <NederLofData> productData = new List <NederLofData>();
            //string destinationPath = Path.Combine(GetConfiguration().AppSettings.Settings["FTPImageDirectory"].Value, "Products");

            bool   networkDrive = false;
            string drive        = GetConfiguration().AppSettings.Settings["FTPImageDirectory"].Value;

            //string drive = @"\\SOL\Company_Shares\Database Backup";
            bool.TryParse(GetConfiguration().AppSettings.Settings["IsNetworkDrive"].Value, out networkDrive);

            if (networkDrive)
            {
                NetworkDrive oNetDrive = new NetworkDrive();
                try
                {
                    drive = @"H:\";
                    oNetDrive.LocalDrive = "H:";
                    oNetDrive.ShareName  = drive;
                    oNetDrive.MapDrive("Diract", "Concentrator01");
                    //oNetDrive.MapDrive();
                }
                catch (Exception err)
                {
                    log.AuditError("Invalid network drive", err);
                }
                oNetDrive = null;
            }
            string destinationPath = Path.Combine(drive, "Concentrator", "Products");

            foreach (var f in Directory.GetFiles(dir))
            {
                XDocument xdoc = null;
                using (StreamReader reader = new StreamReader(f))
                {
                    xdoc = XDocument.Parse(reader.ReadToEnd());
                };

                XNamespace xName = "http://www.graphit.nl/xmlns/netpublishpro/entity-info/1.4";

                //-		xdoc.Elements().Elements(xName + "object").First().Elements(xName + "field").FirstOrDefault().Element(xName + "value")	<value xmlns="http://www.graphit.nl/xmlns/netpublishpro/entity-info/1.4">15 mei 2008 9:21:21 CEST</value>	System.Xml.Linq.XElement

                var fields            = xdoc.Elements().Elements(xName + "object").Elements(xName + "field").Select(x => x.Attribute("name").Value).Distinct().ToList();
                var itemFields        = xdoc.Elements().Elements(xName + "object").Elements(xName + "items").Elements(xName + "item").Elements(xName + "field").Select(x => x.Attribute("name").Value).Distinct().ToList();
                var productInfoFields = xdoc.Elements().Elements(xName + "object").Elements(xName + "objects").Where(x => x.Attribute("classname").Value == "Jumbo_Product_lanquage").Elements(xName + "object").Elements(xName + "field").Select(x => x.Attribute("name").Value).Distinct().ToList();

                var products = (from pr in xdoc.Elements().Elements(xName + "object")
                                select new NederLofData
                {
                    File = f,
                    barcode = pr.Elements(xName + "field").FirstOrDefault(x => x.Attribute("name").Value == "Barcode") != null ? pr.Elements(xName + "field").FirstOrDefault(x => x.Attribute("name").Value == "Barcode").Element(xName + "value").Value : string.Empty,
                    VendorItemNumber = pr.Elements(xName + "field").FirstOrDefault(x => x.Attribute("name").Value == "Product code") != null ? pr.Elements(xName + "field").FirstOrDefault(x => x.Attribute("name").Value == "Product code").Element(xName + "value").Value : string.Empty,
                    Pieces = pr.Elements(xName + "field").FirstOrDefault(x => x.Attribute("name").Value == "Pieces") != null ? pr.Elements(xName + "field").FirstOrDefault(x => x.Attribute("name").Value == "Pieces").Element(xName + "value").Value : string.Empty,
                    productName = pr.Elements(xName + "field").FirstOrDefault(x => x.Attribute("name").Value == "Product name") != null ? pr.Elements(xName + "field").FirstOrDefault(x => x.Attribute("name").Value == "Product name").Element(xName + "value").Value : string.Empty,
                    Age = pr.Elements(xName + "field").FirstOrDefault(x => x.Attribute("name").Value == "Age") != null ? pr.Elements(xName + "field").FirstOrDefault(x => x.Attribute("name").Value == "Age").Element(xName + "value").Value : string.Empty,
                    Group = pr.Elements(xName + "field").FirstOrDefault(x => x.Attribute("name").Value == "Group") != null ? pr.Elements(xName + "field").FirstOrDefault(x => x.Attribute("name").Value == "Group").Element(xName + "value").Value : string.Empty,
                    NrOfPlayers = pr.Elements(xName + "field").FirstOrDefault(x => x.Attribute("name").Value == "Nr. of Players") != null ? pr.Elements(xName + "field").FirstOrDefault(x => x.Attribute("name").Value == "Nr. of Players").Element(xName + "value").Value : string.Empty,
                    Package = pr.Elements(xName + "field").FirstOrDefault(x => x.Attribute("name").Value == "Package") != null ? pr.Elements(xName + "field").FirstOrDefault(x => x.Attribute("name").Value == "Package").Element(xName + "value").Value : string.Empty,
                    Size3D = pr.Elements(xName + "field").FirstOrDefault(x => x.Attribute("name").Value == "Size 3D") != null ? pr.Elements(xName + "field").FirstOrDefault(x => x.Attribute("name").Value == "Size 3D").Element(xName + "value").Value : string.Empty,
                    Sound = pr.Elements(xName + "field").FirstOrDefault(x => x.Attribute("name").Value == "Sound") != null ? pr.Elements(xName + "field").FirstOrDefault(x => x.Attribute("name").Value == "Sound").Element(xName + "value").Value : string.Empty,
                    Type = pr.Elements(xName + "field").FirstOrDefault(x => x.Attribute("name").Value == "Type") != null ? pr.Elements(xName + "field").FirstOrDefault(x => x.Attribute("name").Value == "Type").Element(xName + "value").Value : string.Empty,
                    Weight = pr.Elements(xName + "field").FirstOrDefault(x => x.Attribute("name").Value == "Weight") != null ? pr.Elements(xName + "field").FirstOrDefault(x => x.Attribute("name").Value == "Weight").Element(xName + "value").Value : string.Empty,
                    PlayingTime = pr.Elements(xName + "field").FirstOrDefault(x => x.Attribute("name").Value == "Playing time") != null ? pr.Elements(xName + "field").FirstOrDefault(x => x.Attribute("name").Value == "Playing time").Element(xName + "value").Value : string.Empty,
                    Batteries = pr.Elements(xName + "field").FirstOrDefault(x => x.Attribute("name").Value == "Batteries") != null ? pr.Elements(xName + "field").FirstOrDefault(x => x.Attribute("name").Value == "Batteries").Element(xName + "value").Value : string.Empty,
                    Size2D = pr.Elements(xName + "field").FirstOrDefault(x => x.Attribute("name").Value == "Size 2D") != null ? pr.Elements(xName + "field").FirstOrDefault(x => x.Attribute("name").Value == "Size 2D").Element(xName + "value").Value : string.Empty,
                    ProductInfo = pr.Elements(xName + "objects").Where(x => x.Attribute("classname").Value == "Jumbo_Product_lanquage").Elements(xName + "object").Select(x => new NederlofProductLanguageInfo
                    {
                        ContentStatus = x.Elements(xName + "field").FirstOrDefault(y => y.Attribute("name").Value == "Content status") != null ? x.Elements(xName + "field").FirstOrDefault(y => y.Attribute("name").Value == "Content status").Element(xName + "value").Value : string.Empty,
                        Created = x.Elements(xName + "field").FirstOrDefault(y => y.Attribute("name").Value == "Created") != null ? x.Elements(xName + "field").FirstOrDefault(y => y.Attribute("name").Value == "Created").Element(xName + "value").Value : string.Empty,
                        Description = x.Elements(xName + "field").FirstOrDefault(y => y.Attribute("name").Value == "Catalog Description") != null ? x.Elements(xName + "field").FirstOrDefault(y => y.Attribute("name").Value == "Catalog Description").Element(xName + "value").Value : string.Empty,
                        BusinessDescription = x.Elements(xName + "field").FirstOrDefault(y => y.Attribute("name").Value == "B to B Description") != null ? x.Elements(xName + "field").FirstOrDefault(y => y.Attribute("name").Value == "B to B Description").Element(xName + "value").Value : string.Empty,
                        InternetDescription = x.Elements(xName + "field").FirstOrDefault(y => y.Attribute("name").Value == "Internet Description") != null ? x.Elements(xName + "field").FirstOrDefault(y => y.Attribute("name").Value == "Internet Description").Element(xName + "value").Value : string.Empty,
                        Language = x.Elements(xName + "field").FirstOrDefault(y => y.Attribute("name").Value == "Language") != null ? x.Elements(xName + "field").FirstOrDefault(y => y.Attribute("name").Value == "Language").Element(xName + "value").Value : string.Empty,
                        ProductName = x.Elements(xName + "field").FirstOrDefault(y => y.Attribute("name").Value == "Product name") != null ? x.Elements(xName + "field").FirstOrDefault(y => y.Attribute("name").Value == "Product name").Element(xName + "value").Value : string.Empty
                    }).ToList(),
                    ProductMedia = pr.Elements(xName + "items").Elements(xName + "item").Select(x => new NederlofProductMedia
                    {
                        Description = x.Elements(xName + "field").FirstOrDefault(y => y.Attribute("name").Value == "File Description").Element(xName + "value").Value,
                        Extension = x.Elements(xName + "field").FirstOrDefault(y => y.Attribute("name").Value == "Extension Win").Element(xName + "value").Value,
                        FileName = x.Elements(xName + "field").FirstOrDefault(y => y.Attribute("name").Value == "Filename").Element(xName + "value").Value,
                        FileSize = x.Elements(xName + "field").FirstOrDefault(y => y.Attribute("name").Value == "File Size").Element(xName + "value").Value,
                        Height = x.Elements(xName + "field").FirstOrDefault(y => y.Attribute("name").Value == "Height").Element(xName + "value").Value,
                        HorizontalResolution = x.Elements(xName + "field").FirstOrDefault(y => y.Attribute("name").Value == "Horizontal Resolution").Element(xName + "value").Value,
                        Path = !x.Elements(xName + "field").FirstOrDefault(y => y.Attribute("name").Value == "Path").Element(xName + "value").Value.Contains("_NPE_")
                              ? x.Elements(xName + "field").FirstOrDefault(y => y.Attribute("name").Value == "Path").Element(xName + "value").Value.Substring(27)
                              : (x.Elements(xName + "field").FirstOrDefault(y => y.Attribute("name").Value == "Path").Element(xName + "value").Value.Contains("Database1") ?
                                 x.Elements(xName + "field").FirstOrDefault(y => y.Attribute("name").Value == "Path").Element(xName + "value").Value.Substring(43)
                               : x.Elements(xName + "field").FirstOrDefault(y => y.Attribute("name").Value == "Path").Element(xName + "value").Value.Substring(48)),
                        ThumbnailSize = x.Elements(xName + "field").FirstOrDefault(y => y.Attribute("name").Value == "Thumbnail Size").Value,
                        VerticalResolution = x.Elements(xName + "field").FirstOrDefault(y => y.Attribute("name").Value == "Vertical Resolution").Element(xName + "value").Value,
                        Width = x.Elements(xName + "field").FirstOrDefault(y => y.Attribute("name").Value == "Width").Element(xName + "value").Value,
                        MediaType = x.Elements(xName + "field").FirstOrDefault(y => y.Attribute("name").Value == "KInd of product") == null ? "PDF" : x.Elements(xName + "field").FirstOrDefault(y => y.Attribute("name").Value == "KInd of product").Element(xName + "value").Value
                    }).ToList()
                }).ToList();

                productData.AddRange(products);
            }


            using (IUnitOfWork unit = GetUnitOfWork())
            {
                //DataLoadOptions options = new DataLoadOptions();
                //options.LoadWith<ProductGroupVendor>(x => x.VendorProductGroupAssortments);
                //options.LoadWith<VendorAssortment>(x => x.VendorPrice);
                //options.LoadWith<Product>(x => x.ProductBarcodes);
                //options.LoadWith<ProductGroupLanguage>(x => x.ProductGroup);
                //ctx.LoadOptions = options;

                List <ProductAttributeMetaData> attributes;
                SetupAttributes(unit, AttributeMapping, out attributes, vendorID);

                int generalAttributegroupID = GetGeneralAttributegroupID(unit);

                var productAttributes = (from g in unit.Scope.Repository <ProductAttributeMetaData>().GetAll()
                                         where g.VendorID == vendorID
                                         select g).ToList();

                var productAttributeGroups = unit.Scope.Repository <ProductAttributeGroupMetaData>().GetAll(g => g.VendorID == vendorID).ToList();


                var attributeList = productAttributes.ToDictionary(x => x.AttributeCode, y => y.AttributeID);

                int counter = 0;
                int total   = productData.Count;
                int totalNumberOfProductsToProcess = total;
                log.InfoFormat("Start import {0} products", total);



                foreach (var product in productData)
                {
                    try
                    {
                        var currLanguage = 2;

                        if (counter == 100)
                        {
                            counter = 0;
                            log.InfoFormat("Still need to process {0} of {1}; {2} done;", totalNumberOfProductsToProcess, total, total - totalNumberOfProductsToProcess);
                        }
                        totalNumberOfProductsToProcess--;
                        counter++;

                        #region Product
                        string barcode = product.barcode;

                        var item = unit.Scope.Repository <Product>().GetSingle(p => p.VendorItemNumber == barcode && p.VendorAssortments.Any(y => y.CustomItemNumber == product.VendorItemNumber));

                        if (item == null)
                        {
                            log.DebugFormat("No product found for vendoritemnumber {0} and customitemnumber {1}", barcode, product.VendorItemNumber);
                            continue;
                        }

                        #endregion Product

                        #region ProductBarcode
                        if (item.ProductBarcodes == null)
                        {
                            item.ProductBarcodes = new List <ProductBarcode>();
                        }
                        if (!item.ProductBarcodes.Any(pb => pb.Barcode.Trim() == barcode))
                        {
                            //create ProductBarcode if not exists
                            unit.Scope.Repository <ProductBarcode>().Add(new ProductBarcode
                            {
                                Product     = item,
                                Barcode     = barcode,
                                VendorID    = vendorID,
                                BarcodeType = (int)BarcodeTypes.Default
                            });
                        }

                        #endregion

                        #region Images

                        var maxSeq        = (item.ProductMedias.Max(p => (int?)p.Sequence) ?? 0);
                        var mediaTypeList = unit.Scope.Repository <MediaType>().GetAll().ToList();

                        product.ProductMedia.ForEach((imgUrl, idx) =>
                        {
                            var fullImagePath = Path.Combine(destinationPath, imgUrl.Path);

                            if (File.Exists(fullImagePath))
                            {
                                MediaType mType = unit.Scope.Repository <MediaType>().GetSingle(x => x.Type == imgUrl.MediaType);
                                if (mType == null)
                                {
                                    mType = new MediaType()
                                    {
                                        Type = imgUrl.MediaType
                                    };
                                    unit.Scope.Repository <MediaType>().Add(mType);
                                    mediaTypeList.Add(mType);
                                }

                                string imagePath = @"Products\" + imgUrl.Path;

                                if (item.ProductMedias == null)
                                {
                                    item.ProductMedias = new List <ProductMedia>();
                                }
                                if (!item.ProductMedias.Any(pi => pi.VendorID == vendorID && pi.MediaPath == imagePath))
                                {
                                    unit.Scope.Repository <ProductMedia>().Add(new ProductMedia
                                    {
                                        VendorID  = vendorID,
                                        MediaPath = imagePath,
                                        MediaType = mType,
                                        Product   = item,
                                        Sequence  = maxSeq,
                                        //Resolution = getRes(fullImagePath),//imgUrl.HorizontalResolution + "x" + imgUrl.VerticalResolution,
                                        Size        = (int)Math.Round(new FileInfo(fullImagePath).Length / 1024d, 0),
                                        Description = imgUrl.Description
                                    });
                                    maxSeq++;
                                }
                            }
                            else
                            {
                                log.AuditWarning(string.Format("Could not find media: {0} in file {1}", fullImagePath, product.File));
                            }
                        });
                        #endregion

                        //#region Images
                        //if (item.ProductMedias == null) item.ProductMedias = new List<ProductMedia>();
                        //var maxSeq = (item.ProductMedias.Max(p => (int?)p.Sequence) ?? 0);

                        //product.ProductMedia.ForEach((imgUrl, idx) =>
                        //{
                        //  var fullImagePath = Path.Combine(destinationPath, imgUrl.Path);

                        //  if (File.Exists(fullImagePath))
                        //  {

                        //    if (!item.ProductMedias.Any(pi => pi.VendorID == vendorID && pi.MediaPath == imgUrl.Path))
                        //    {
                        //      unit.Scope.Repository<ProductMedia>().Add(new ProductMedia
                        //      {
                        //        VendorID = vendorID,
                        //        MediaPath = imgUrl.Path,
                        //        TypeID = 1,
                        //        Product = item,
                        //        Sequence = maxSeq,
                        //        Resolution = getRes(fullImagePath),//imgUrl.HorizontalResolution + "x" + imgUrl.VerticalResolution,
                        //        Size = (int)Math.Round(new FileInfo(fullImagePath).Length / 1024d, 0),
                        //        Description = imgUrl.Description
                        //      });
                        //      maxSeq++;
                        //    }
                        //  }
                        //  else
                        //    log.DebugFormat("Could not find image: {0}", fullImagePath);
                        //});
                        //#endregion

                        #region Descriptions
                        foreach (var pInf in product.ProductInfo)
                        {
                            int languageID = 1;

                            if (pInf.Language == "Dutch")
                            {
                                languageID = 2;
                            }
                            else if (pInf.Language == "French")
                            {
                                languageID = 3;
                            }
                            else if (pInf.Language == "International" || pInf.Language == "English")
                            {
                                languageID = 1;
                            }
                            else if (pInf.Language == "German")
                            {
                                languageID = 4;
                            }
                            else
                            {
                                log.DebugFormat("Unkown language {0}", pInf.Language);
                            }

                            if (item.ProductDescriptions == null)
                            {
                                item.ProductDescriptions = new List <ProductDescription>();
                            }

                            var desc = item.ProductDescriptions.FirstOrDefault(pd => pd.LanguageID == languageID && pd.VendorID == vendorID);
                            if (desc == null)
                            {
                                desc = new ProductDescription
                                {
                                    VendorID   = vendorID,
                                    LanguageID = languageID,
                                    Product    = item,
                                    ShortContentDescription = pInf.Description,
                                    ShortSummaryDescription = pInf.BusinessDescription,
                                    LongContentDescription  = pInf.InternetDescription,
                                    ProductName             = pInf.ProductName
                                };
                                unit.Scope.Repository <ProductDescription>().Add(desc);
                            }
                            else
                            {
                                if (string.IsNullOrEmpty(desc.ShortContentDescription))
                                {
                                    desc.ShortContentDescription = pInf.Description;
                                }

                                if (string.IsNullOrEmpty(desc.ShortSummaryDescription))
                                {
                                    desc.ShortSummaryDescription = pInf.BusinessDescription;
                                }

                                if (string.IsNullOrEmpty(desc.LongContentDescription))
                                {
                                    desc.LongContentDescription = pInf.InternetDescription;
                                }

                                if (string.IsNullOrEmpty(desc.ProductName))
                                {
                                    desc.ProductName = pInf.ProductName;
                                }
                            }
                        }


                        #endregion Descriptions

                        #region Attributes
                        var attributeValueRepo = unit.Scope.Repository <ProductAttributeValue>();

                        var productAttributeValues = attributeValueRepo.GetAll(x => x.ProductID == item.ProductID && x.ProductAttributeMetaData.VendorID == vendorID).ToList();

                        foreach (var attr in AttributeMapping)
                        {
                            var prop = product.GetType().GetProperty(attr).GetValue(product, null);
                            if (prop == null)
                            {
                                prop = string.Empty;
                            }

                            int metaId = -1;
                            attributeList.TryGetValue(attr, out metaId);

                            var val = productAttributeValues.Where(pam => pam.LanguageID == 1 && pam.AttributeID == metaId).FirstOrDefault();
                            if (val == null)
                            {
                                var pval = new ProductAttributeValue
                                {
                                    AttributeID = metaId,
                                    LanguageID  = 1,
                                    ProductID   = item.ProductID
                                };
                                attributeValueRepo.Add(pval);
                                val = pval;
                            }

                            var value = prop.ToString();

                            val.Value = value != null?value.ToString() : String.Empty;
                        }

                        #endregion

                        unit.Save();
                    }
                    catch (Exception ex)
                    {
                        log.AuditError("Error JDE product Import", ex);
                    }
                }

                //}
                log.AuditInfo("Products processing finished. Processed " + (total - totalNumberOfProductsToProcess) + " products");
            }

            if (networkDrive)
            {
                NetworkDrive oNetDrive = new NetworkDrive();
                try
                {
                    oNetDrive.LocalDrive = "H:";
                    oNetDrive.UnMapDrive();
                }
                catch (Exception err)
                {
                    log.AuditError("Error unmap drive" + err.InnerException);
                }
                oNetDrive = null;
            }
        }
Пример #32
0
        /// <summary>
        /// Create a copy of product with all depended data
        /// </summary>
        /// <param name="product">The product to copy</param>
        /// <param name="newName">The name of product duplicate</param>
        /// <param name="isPublished">A value indicating whether the product duplicate should be published</param>
        /// <param name="copyImages">A value indicating whether the product images should be copied</param>
        /// <param name="copyAssociatedProducts">A value indicating whether the copy associated products</param>
        /// <returns>Product copy</returns>
        public virtual Product CopyProduct(Product product, string newName,
                                           bool isPublished = true, bool copyImages = true, bool copyAssociatedProducts = true)
        {
            if (product == null)
            {
                throw new ArgumentNullException("product");
            }

            if (String.IsNullOrEmpty(newName))
            {
                throw new ArgumentException("Product name is required");
            }

            //product download & sample download
            int downloadId       = product.DownloadId;
            int sampleDownloadId = product.SampleDownloadId;

            if (product.IsDownload)
            {
                var download = _downloadService.GetDownloadById(product.DownloadId);
                if (download != null)
                {
                    var downloadCopy = new Download
                    {
                        DownloadGuid   = Guid.NewGuid(),
                        UseDownloadUrl = download.UseDownloadUrl,
                        DownloadUrl    = download.DownloadUrl,
                        DownloadBinary = download.DownloadBinary,
                        ContentType    = download.ContentType,
                        Filename       = download.Filename,
                        Extension      = download.Extension,
                        IsNew          = download.IsNew,
                    };
                    _downloadService.InsertDownload(downloadCopy);
                    downloadId = downloadCopy.Id;
                }

                if (product.HasSampleDownload)
                {
                    var sampleDownload = _downloadService.GetDownloadById(product.SampleDownloadId);
                    if (sampleDownload != null)
                    {
                        var sampleDownloadCopy = new Download
                        {
                            DownloadGuid   = Guid.NewGuid(),
                            UseDownloadUrl = sampleDownload.UseDownloadUrl,
                            DownloadUrl    = sampleDownload.DownloadUrl,
                            DownloadBinary = sampleDownload.DownloadBinary,
                            ContentType    = sampleDownload.ContentType,
                            Filename       = sampleDownload.Filename,
                            Extension      = sampleDownload.Extension,
                            IsNew          = sampleDownload.IsNew
                        };
                        _downloadService.InsertDownload(sampleDownloadCopy);
                        sampleDownloadId = sampleDownloadCopy.Id;
                    }
                }
            }

            // product
            var productCopy = new Product
            {
                ProductTypeId          = product.ProductTypeId,
                ParentGroupedProductId = product.ParentGroupedProductId,
                VisibleIndividually    = product.VisibleIndividually,
                Name                 = newName,
                ShortDescription     = product.ShortDescription,
                FullDescription      = product.FullDescription,
                VendorId             = product.VendorId,
                ProductTemplateId    = product.ProductTemplateId,
                AdminComment         = product.AdminComment,
                ShowOnHomePage       = product.ShowOnHomePage,
                MetaKeywords         = product.MetaKeywords,
                MetaDescription      = product.MetaDescription,
                MetaTitle            = product.MetaTitle,
                AllowCustomerReviews = product.AllowCustomerReviews,
                LimitedToStores      = product.LimitedToStores,
                Sku = product.Sku,
                ManufacturerPartNumber = product.ManufacturerPartNumber,
                Gtin                             = product.Gtin,
                IsGiftCard                       = product.IsGiftCard,
                GiftCardType                     = product.GiftCardType,
                RequireOtherProducts             = product.RequireOtherProducts,
                RequiredProductIds               = product.RequiredProductIds,
                AutomaticallyAddRequiredProducts = product.AutomaticallyAddRequiredProducts,
                IsDownload                       = product.IsDownload,
                DownloadId                       = downloadId,
                UnlimitedDownloads               = product.UnlimitedDownloads,
                MaxNumberOfDownloads             = product.MaxNumberOfDownloads,
                DownloadExpirationDays           = product.DownloadExpirationDays,
                DownloadActivationType           = product.DownloadActivationType,
                HasSampleDownload                = product.HasSampleDownload,
                SampleDownloadId                 = sampleDownloadId,
                HasUserAgreement                 = product.HasUserAgreement,
                UserAgreementText                = product.UserAgreementText,
                IsRecurring                      = product.IsRecurring,
                RecurringCycleLength             = product.RecurringCycleLength,
                RecurringCyclePeriod             = product.RecurringCyclePeriod,
                RecurringTotalCycles             = product.RecurringTotalCycles,
                IsRental                         = product.IsRental,
                RentalPriceLength                = product.RentalPriceLength,
                RentalPricePeriod                = product.RentalPricePeriod,
                IsShipEnabled                    = product.IsShipEnabled,
                IsFreeShipping                   = product.IsFreeShipping,
                ShipSeparately                   = product.ShipSeparately,
                AdditionalShippingCharge         = product.AdditionalShippingCharge,
                DeliveryDateId                   = product.DeliveryDateId,
                IsTaxExempt                      = product.IsTaxExempt,
                TaxCategoryId                    = product.TaxCategoryId,
                IsTelecommunicationsOrBroadcastingOrElectronicServices = product.IsTelecommunicationsOrBroadcastingOrElectronicServices,
                ManageInventoryMethod         = product.ManageInventoryMethod,
                UseMultipleWarehouses         = product.UseMultipleWarehouses,
                WarehouseId                   = product.WarehouseId,
                StockQuantity                 = product.StockQuantity,
                DisplayStockAvailability      = product.DisplayStockAvailability,
                DisplayStockQuantity          = product.DisplayStockQuantity,
                MinStockQuantity              = product.MinStockQuantity,
                LowStockActivityId            = product.LowStockActivityId,
                NotifyAdminForQuantityBelow   = product.NotifyAdminForQuantityBelow,
                BackorderMode                 = product.BackorderMode,
                AllowBackInStockSubscriptions = product.AllowBackInStockSubscriptions,
                OrderMinimumQuantity          = product.OrderMinimumQuantity,
                OrderMaximumQuantity          = product.OrderMaximumQuantity,
                AllowedQuantities             = product.AllowedQuantities,
                AllowAddingOnlyExistingAttributeCombinations = product.AllowAddingOnlyExistingAttributeCombinations,
                DisableBuyButton      = product.DisableBuyButton,
                DisableWishlistButton = product.DisableWishlistButton,
                AvailableForPreOrder  = product.AvailableForPreOrder,
                PreOrderAvailabilityStartDateTimeUtc = product.PreOrderAvailabilityStartDateTimeUtc,
                CallForPrice = product.CallForPrice,
                Price        = product.Price,
                OldPrice     = product.OldPrice,
                ProductCost  = product.ProductCost,
                SpecialPrice = product.SpecialPrice,
                SpecialPriceStartDateTimeUtc = product.SpecialPriceStartDateTimeUtc,
                SpecialPriceEndDateTimeUtc   = product.SpecialPriceEndDateTimeUtc,
                CustomerEntersPrice          = product.CustomerEntersPrice,
                MinimumCustomerEnteredPrice  = product.MinimumCustomerEnteredPrice,
                MaximumCustomerEnteredPrice  = product.MaximumCustomerEnteredPrice,
                Weight = product.Weight,
                Length = product.Length,
                Width  = product.Width,
                Height = product.Height,
                AvailableStartDateTimeUtc = product.AvailableStartDateTimeUtc,
                AvailableEndDateTimeUtc   = product.AvailableEndDateTimeUtc,
                DisplayOrder = product.DisplayOrder,
                Published    = isPublished,
                Deleted      = product.Deleted,
                CreatedOnUtc = DateTime.UtcNow,
                UpdatedOnUtc = DateTime.UtcNow
            };

            //validate search engine name
            _productService.InsertProduct(productCopy);

            //search engine name
            _urlRecordService.SaveSlug(productCopy, productCopy.ValidateSeName("", productCopy.Name, true), 0);

            var languages = _languageService.GetAllLanguages(true);

            //localization
            foreach (var lang in languages)
            {
                var name = product.GetLocalized(x => x.Name, lang.Id, false, false);
                if (!String.IsNullOrEmpty(name))
                {
                    _localizedEntityService.SaveLocalizedValue(productCopy, x => x.Name, name, lang.Id);
                }

                var shortDescription = product.GetLocalized(x => x.ShortDescription, lang.Id, false, false);
                if (!String.IsNullOrEmpty(shortDescription))
                {
                    _localizedEntityService.SaveLocalizedValue(productCopy, x => x.ShortDescription, shortDescription, lang.Id);
                }

                var fullDescription = product.GetLocalized(x => x.FullDescription, lang.Id, false, false);
                if (!String.IsNullOrEmpty(fullDescription))
                {
                    _localizedEntityService.SaveLocalizedValue(productCopy, x => x.FullDescription, fullDescription, lang.Id);
                }

                var metaKeywords = product.GetLocalized(x => x.MetaKeywords, lang.Id, false, false);
                if (!String.IsNullOrEmpty(metaKeywords))
                {
                    _localizedEntityService.SaveLocalizedValue(productCopy, x => x.MetaKeywords, metaKeywords, lang.Id);
                }

                var metaDescription = product.GetLocalized(x => x.MetaDescription, lang.Id, false, false);
                if (!String.IsNullOrEmpty(metaDescription))
                {
                    _localizedEntityService.SaveLocalizedValue(productCopy, x => x.MetaDescription, metaDescription, lang.Id);
                }

                var metaTitle = product.GetLocalized(x => x.MetaTitle, lang.Id, false, false);
                if (!String.IsNullOrEmpty(metaTitle))
                {
                    _localizedEntityService.SaveLocalizedValue(productCopy, x => x.MetaTitle, metaTitle, lang.Id);
                }

                //search engine name
                _urlRecordService.SaveSlug(productCopy, productCopy.ValidateSeName("", name, false), lang.Id);
            }

            //product tags
            foreach (var productTag in product.ProductTags)
            {
                productCopy.ProductTags.Add(productTag);
            }
            _productService.UpdateProduct(product);

            //product pictures
            //variable to store original and new picture identifiers
            var originalNewPictureIdentifiers = new Dictionary <int, int>();

            if (copyImages)
            {
                foreach (var productPicture in product.ProductPictures)
                {
                    var picture     = productPicture.Picture;
                    var pictureCopy = _pictureService.InsertPicture(
                        _pictureService.LoadPictureBinary(picture),
                        picture.MimeType,
                        _pictureService.GetPictureSeName(newName),
                        picture.AltAttribute,
                        picture.TitleAttribute);
                    _productService.InsertProductPicture(new ProductPicture
                    {
                        ProductId    = productCopy.Id,
                        PictureId    = pictureCopy.Id,
                        DisplayOrder = productPicture.DisplayOrder
                    });
                    originalNewPictureIdentifiers.Add(picture.Id, pictureCopy.Id);
                }
            }

            // product <-> warehouses mappings
            foreach (var pwi in product.ProductWarehouseInventory)
            {
                var pwiCopy = new ProductWarehouseInventory
                {
                    ProductId        = productCopy.Id,
                    WarehouseId      = pwi.WarehouseId,
                    StockQuantity    = pwi.StockQuantity,
                    ReservedQuantity = 0,
                };

                productCopy.ProductWarehouseInventory.Add(pwiCopy);
            }
            _productService.UpdateProduct(productCopy);

            // product <-> categories mappings
            foreach (var productCategory in product.ProductCategories)
            {
                var productCategoryCopy = new ProductCategory
                {
                    ProductId         = productCopy.Id,
                    CategoryId        = productCategory.CategoryId,
                    IsFeaturedProduct = productCategory.IsFeaturedProduct,
                    DisplayOrder      = productCategory.DisplayOrder
                };

                _categoryService.InsertProductCategory(productCategoryCopy);
            }

            // product <-> manufacturers mappings
            foreach (var productManufacturers in product.ProductManufacturers)
            {
                var productManufacturerCopy = new ProductManufacturer
                {
                    ProductId         = productCopy.Id,
                    ManufacturerId    = productManufacturers.ManufacturerId,
                    IsFeaturedProduct = productManufacturers.IsFeaturedProduct,
                    DisplayOrder      = productManufacturers.DisplayOrder
                };

                _manufacturerService.InsertProductManufacturer(productManufacturerCopy);
            }

            // product <-> releated products mappings
            foreach (var relatedProduct in _productService.GetRelatedProductsByProductId1(product.Id, true))
            {
                _productService.InsertRelatedProduct(
                    new RelatedProduct
                {
                    ProductId1   = productCopy.Id,
                    ProductId2   = relatedProduct.ProductId2,
                    DisplayOrder = relatedProduct.DisplayOrder
                });
            }

            // product <-> cross sells mappings
            foreach (var csProduct in _productService.GetCrossSellProductsByProductId1(product.Id, true))
            {
                _productService.InsertCrossSellProduct(
                    new CrossSellProduct
                {
                    ProductId1 = productCopy.Id,
                    ProductId2 = csProduct.ProductId2,
                });
            }

            // product specifications
            foreach (var productSpecificationAttribute in product.ProductSpecificationAttributes)
            {
                var psaCopy = new ProductSpecificationAttribute
                {
                    ProductId       = productCopy.Id,
                    AttributeTypeId = productSpecificationAttribute.AttributeTypeId,
                    SpecificationAttributeOptionId = productSpecificationAttribute.SpecificationAttributeOptionId,
                    CustomValue       = productSpecificationAttribute.CustomValue,
                    AllowFiltering    = productSpecificationAttribute.AllowFiltering,
                    ShowOnProductPage = productSpecificationAttribute.ShowOnProductPage,
                    DisplayOrder      = productSpecificationAttribute.DisplayOrder
                };
                _specificationAttributeService.InsertProductSpecificationAttribute(psaCopy);
            }

            //store mapping
            var selectedStoreIds = _storeMappingService.GetStoresIdsWithAccess(product);

            foreach (var id in selectedStoreIds)
            {
                _storeMappingService.InsertStoreMapping(productCopy, id);
            }


            // product <-> attributes mappings
            var associatedAttributes      = new Dictionary <int, int>();
            var associatedAttributeValues = new Dictionary <int, int>();

            foreach (var productAttributeMapping in _productAttributeService.GetProductAttributeMappingsByProductId(product.Id))
            {
                var productAttributeMappingCopy = new ProductAttributeMapping
                {
                    ProductId                       = productCopy.Id,
                    ProductAttributeId              = productAttributeMapping.ProductAttributeId,
                    TextPrompt                      = productAttributeMapping.TextPrompt,
                    IsRequired                      = productAttributeMapping.IsRequired,
                    AttributeControlTypeId          = productAttributeMapping.AttributeControlTypeId,
                    DisplayOrder                    = productAttributeMapping.DisplayOrder,
                    ValidationMinLength             = productAttributeMapping.ValidationMinLength,
                    ValidationMaxLength             = productAttributeMapping.ValidationMaxLength,
                    ValidationFileAllowedExtensions = productAttributeMapping.ValidationFileAllowedExtensions,
                    ValidationFileMaximumSize       = productAttributeMapping.ValidationFileMaximumSize,
                    DefaultValue                    = productAttributeMapping.DefaultValue,
                };
                _productAttributeService.InsertProductAttributeMapping(productAttributeMappingCopy);
                //save associated value (used for combinations copying)
                associatedAttributes.Add(productAttributeMapping.Id, productAttributeMappingCopy.Id);

                // product attribute values
                var productAttributeValues = _productAttributeService.GetProductAttributeValues(productAttributeMapping.Id);
                foreach (var productAttributeValue in productAttributeValues)
                {
                    int attributeValuePictureId = 0;
                    if (originalNewPictureIdentifiers.ContainsKey(productAttributeValue.PictureId))
                    {
                        attributeValuePictureId = originalNewPictureIdentifiers[productAttributeValue.PictureId];
                    }
                    var attributeValueCopy = new ProductAttributeValue
                    {
                        ProductAttributeMappingId = productAttributeMappingCopy.Id,
                        AttributeValueTypeId      = productAttributeValue.AttributeValueTypeId,
                        AssociatedProductId       = productAttributeValue.AssociatedProductId,
                        Name             = productAttributeValue.Name,
                        ColorSquaresRgb  = productAttributeValue.ColorSquaresRgb,
                        PriceAdjustment  = productAttributeValue.PriceAdjustment,
                        WeightAdjustment = productAttributeValue.WeightAdjustment,
                        Cost             = productAttributeValue.Cost,
                        Quantity         = productAttributeValue.Quantity,
                        IsPreSelected    = productAttributeValue.IsPreSelected,
                        DisplayOrder     = productAttributeValue.DisplayOrder,
                        PictureId        = attributeValuePictureId,
                    };
                    _productAttributeService.InsertProductAttributeValue(attributeValueCopy);

                    //save associated value (used for combinations copying)
                    associatedAttributeValues.Add(productAttributeValue.Id, attributeValueCopy.Id);

                    //localization
                    foreach (var lang in languages)
                    {
                        var name = productAttributeValue.GetLocalized(x => x.Name, lang.Id, false, false);
                        if (!String.IsNullOrEmpty(name))
                        {
                            _localizedEntityService.SaveLocalizedValue(attributeValueCopy, x => x.Name, name, lang.Id);
                        }
                    }
                }
            }
            //attribute combinations
            foreach (var combination in _productAttributeService.GetAllProductAttributeCombinations(product.Id))
            {
                //generate new AttributesXml according to new value IDs
                string newAttributesXml        = "";
                var    parsedProductAttributes = _productAttributeParser.ParseProductAttributeMappings(combination.AttributesXml);
                foreach (var oldAttribute in parsedProductAttributes)
                {
                    if (associatedAttributes.ContainsKey(oldAttribute.Id))
                    {
                        var newAttribute = _productAttributeService.GetProductAttributeMappingById(associatedAttributes[oldAttribute.Id]);
                        if (newAttribute != null)
                        {
                            var oldAttributeValuesStr = _productAttributeParser.ParseValues(combination.AttributesXml, oldAttribute.Id);
                            foreach (var oldAttributeValueStr in oldAttributeValuesStr)
                            {
                                if (newAttribute.ShouldHaveValues())
                                {
                                    //attribute values
                                    int oldAttributeValue = int.Parse(oldAttributeValueStr);
                                    if (associatedAttributeValues.ContainsKey(oldAttributeValue))
                                    {
                                        var newAttributeValue = _productAttributeService.GetProductAttributeValueById(associatedAttributeValues[oldAttributeValue]);
                                        if (newAttributeValue != null)
                                        {
                                            newAttributesXml = _productAttributeParser.AddProductAttribute(newAttributesXml,
                                                                                                           newAttribute, newAttributeValue.Id.ToString());
                                        }
                                    }
                                }
                                else
                                {
                                    //just a text
                                    newAttributesXml = _productAttributeParser.AddProductAttribute(newAttributesXml,
                                                                                                   newAttribute, oldAttributeValueStr);
                                }
                            }
                        }
                    }
                }
                var combinationCopy = new ProductAttributeCombination
                {
                    ProductId             = productCopy.Id,
                    AttributesXml         = newAttributesXml,
                    StockQuantity         = combination.StockQuantity,
                    AllowOutOfStockOrders = combination.AllowOutOfStockOrders,
                    Sku = combination.Sku,
                    ManufacturerPartNumber = combination.ManufacturerPartNumber,
                    Gtin                        = combination.Gtin,
                    OverriddenPrice             = combination.OverriddenPrice,
                    NotifyAdminForQuantityBelow = combination.NotifyAdminForQuantityBelow
                };
                _productAttributeService.InsertProductAttributeCombination(combinationCopy);
            }

            //tier prices
            foreach (var tierPrice in product.TierPrices)
            {
                _productService.InsertTierPrice(
                    new TierPrice
                {
                    ProductId      = productCopy.Id,
                    StoreId        = tierPrice.StoreId,
                    CustomerRoleId = tierPrice.CustomerRoleId,
                    Quantity       = tierPrice.Quantity,
                    Price          = tierPrice.Price
                });
            }

            // product <-> discounts mapping
            foreach (var discount in product.AppliedDiscounts)
            {
                productCopy.AppliedDiscounts.Add(discount);
                _productService.UpdateProduct(productCopy);
            }


            //update "HasTierPrices" and "HasDiscountsApplied" properties
            _productService.UpdateHasTierPricesProperty(productCopy);
            _productService.UpdateHasDiscountsApplied(productCopy);


            //associated products
            if (copyAssociatedProducts)
            {
                var associatedProducts = _productService.GetAssociatedProducts(product.Id, showHidden: true);
                foreach (var associatedProduct in associatedProducts)
                {
                    var associatedProductCopy = CopyProduct(associatedProduct, string.Format("Copy of {0}", associatedProduct.Name),
                                                            isPublished, copyImages, false);
                    associatedProductCopy.ParentGroupedProductId = productCopy.Id;
                    _productService.UpdateProduct(productCopy);
                }
            }

            return(productCopy);
        }
Пример #33
0
        public virtual IActionResult ApplyToRelatedProducts(int id)
        {
            if (!_permissionService.Authorize(StandardPermissionProvider.ManageAttributes))
            {
                return(AccessDeniedView());
            }

            //try to get a predefined product attribute value with the specified id
            var preProductAttributeValue = _productAttributeService.GetPredefinedProductAttributeValueById(id)
                                           ?? throw new ArgumentException("No predefined product attribute value found with the specified id");

            //try to get all products which use current product attribute
            var products = _productService.GetProductsByProductAtributeId(preProductAttributeValue.ProductAttributeId);

            foreach (var product in products)
            {
                var productAttributeMappings = _productAttributeService.GetProductAttributeMappingsByProductId(product.Id);
                if (productAttributeMappings == null)
                {
                    continue;
                }

                var productAttributeMapping = productAttributeMappings.FirstOrDefault(o => o.ProductAttributeId == preProductAttributeValue.ProductAttributeId);
                if (productAttributeMapping == null)
                {
                    continue;
                }

                var attributeValues = _productAttributeService.GetProductAttributeValues(productAttributeMapping.Id);
                if (attributeValues == null)
                {
                    continue;
                }

                var attributeValue = attributeValues.FirstOrDefault(o => o.Name == preProductAttributeValue.Name);
                if (attributeValue != null)
                {
                    attributeValue.AttributeValueType           = AttributeValueType.Simple;
                    attributeValue.PriceAdjustment              = preProductAttributeValue.PriceAdjustment;
                    attributeValue.PriceAdjustmentUsePercentage = preProductAttributeValue.PriceAdjustmentUsePercentage;
                    attributeValue.WeightAdjustment             = preProductAttributeValue.WeightAdjustment;
                    attributeValue.Cost                  = preProductAttributeValue.Cost;
                    attributeValue.IsPreSelected         = preProductAttributeValue.IsPreSelected;
                    attributeValue.DisplayOrder          = preProductAttributeValue.DisplayOrder;
                    attributeValue.ImageSquaresPictureId = preProductAttributeValue.ImageSquaresPictureId;
                    attributeValue.FormulaKey            = preProductAttributeValue.FormulaKey;
                    attributeValue.FormulaValue          = preProductAttributeValue.FormulaValue;

                    //attributeValue.

                    _productAttributeService.UpdateProductAttributeValue(attributeValue);
                }
                else
                {
                    attributeValue = new ProductAttributeValue
                    {
                        ProductAttributeMappingId = productAttributeMapping.Id,
                        AttributeValueType        = AttributeValueType.Simple,
                        Name            = preProductAttributeValue.Name,
                        PriceAdjustment = preProductAttributeValue.PriceAdjustment,
                        PriceAdjustmentUsePercentage = preProductAttributeValue.PriceAdjustmentUsePercentage,
                        WeightAdjustment             = preProductAttributeValue.WeightAdjustment,
                        Cost                  = preProductAttributeValue.Cost,
                        IsPreSelected         = preProductAttributeValue.IsPreSelected,
                        DisplayOrder          = preProductAttributeValue.DisplayOrder,
                        ImageSquaresPictureId = preProductAttributeValue.ImageSquaresPictureId,
                        FormulaKey            = preProductAttributeValue.FormulaKey,
                        FormulaValue          = preProductAttributeValue.FormulaValue
                    };
                    _productAttributeService.InsertProductAttributeValue(attributeValue);
                }

                //localization
                var languages = _languageService.GetAllLanguages(true);
                foreach (var lang in languages)
                {
                    var name = _localizationService.GetLocalized(preProductAttributeValue, x => x.Name, lang.Id, false, false);
                    if (!string.IsNullOrEmpty(name))
                    {
                        _localizedEntityService.SaveLocalizedValue(attributeValue, x => x.Name, name, lang.Id);
                    }
                }
            }

            return(RedirectToAction("Edit", new { id = preProductAttributeValue.ProductAttributeId }));
        }
Пример #34
0
        /// <summary>
        /// Copy attributes mapping
        /// </summary>
        /// <param name="product">Product</param>
        /// <param name="productCopy">New product</param>
        /// <param name="originalNewPictureIdentifiers">Identifiers of pictures</param>
        protected virtual void CopyAttributesMapping(Product product, Product productCopy, Dictionary <int, int> originalNewPictureIdentifiers)
        {
            var associatedAttributes      = new Dictionary <int, int>();
            var associatedAttributeValues = new Dictionary <int, int>();

            //attribute mapping with condition attributes
            var oldCopyWithConditionAttributes = new List <ProductAttributeMapping>();

            //all product attribute mapping copies
            var productAttributeMappingCopies = new Dictionary <int, ProductAttributeMapping>();

            var languages = _languageService.GetAllLanguages(true);

            foreach (var productAttributeMapping in _productAttributeService.GetProductAttributeMappingsByProductId(product.Id))
            {
                var productAttributeMappingCopy = new ProductAttributeMapping
                {
                    ProductId                       = productCopy.Id,
                    ProductAttributeId              = productAttributeMapping.ProductAttributeId,
                    TextPrompt                      = productAttributeMapping.TextPrompt,
                    IsRequired                      = productAttributeMapping.IsRequired,
                    AttributeControlTypeId          = productAttributeMapping.AttributeControlTypeId,
                    DisplayOrder                    = productAttributeMapping.DisplayOrder,
                    ValidationMinLength             = productAttributeMapping.ValidationMinLength,
                    ValidationMaxLength             = productAttributeMapping.ValidationMaxLength,
                    ValidationFileAllowedExtensions = productAttributeMapping.ValidationFileAllowedExtensions,
                    ValidationFileMaximumSize       = productAttributeMapping.ValidationFileMaximumSize,
                    DefaultValue                    = productAttributeMapping.DefaultValue
                };
                _productAttributeService.InsertProductAttributeMapping(productAttributeMappingCopy);
                //localization
                foreach (var lang in languages)
                {
                    var textPrompt = _localizationService.GetLocalized(productAttributeMapping, x => x.TextPrompt, lang.Id, false, false);
                    if (!string.IsNullOrEmpty(textPrompt))
                    {
                        _localizedEntityService.SaveLocalizedValue(productAttributeMappingCopy, x => x.TextPrompt, textPrompt,
                                                                   lang.Id);
                    }
                }

                productAttributeMappingCopies.Add(productAttributeMappingCopy.Id, productAttributeMappingCopy);

                if (!string.IsNullOrEmpty(productAttributeMapping.ConditionAttributeXml))
                {
                    oldCopyWithConditionAttributes.Add(productAttributeMapping);
                }

                //save associated value (used for combinations copying)
                associatedAttributes.Add(productAttributeMapping.Id, productAttributeMappingCopy.Id);

                // product attribute values
                var productAttributeValues = _productAttributeService.GetProductAttributeValues(productAttributeMapping.Id);
                foreach (var productAttributeValue in productAttributeValues)
                {
                    var attributeValuePictureId = 0;
                    if (originalNewPictureIdentifiers.ContainsKey(productAttributeValue.PictureId))
                    {
                        attributeValuePictureId = originalNewPictureIdentifiers[productAttributeValue.PictureId];
                    }

                    var attributeValueCopy = new ProductAttributeValue
                    {
                        ProductAttributeMappingId = productAttributeMappingCopy.Id,
                        AttributeValueTypeId      = productAttributeValue.AttributeValueTypeId,
                        AssociatedProductId       = productAttributeValue.AssociatedProductId,
                        Name            = productAttributeValue.Name,
                        ColorSquaresRgb = productAttributeValue.ColorSquaresRgb,
                        PriceAdjustment = productAttributeValue.PriceAdjustment,
                        PriceAdjustmentUsePercentage = productAttributeValue.PriceAdjustmentUsePercentage,
                        WeightAdjustment             = productAttributeValue.WeightAdjustment,
                        Cost = productAttributeValue.Cost,
                        CustomerEntersQty = productAttributeValue.CustomerEntersQty,
                        Quantity          = productAttributeValue.Quantity,
                        IsPreSelected     = productAttributeValue.IsPreSelected,
                        DisplayOrder      = productAttributeValue.DisplayOrder,
                        PictureId         = attributeValuePictureId,
                    };
                    //picture associated to "iamge square" attribute type (if exists)
                    if (productAttributeValue.ImageSquaresPictureId > 0)
                    {
                        var origImageSquaresPicture =
                            _pictureService.GetPictureById(productAttributeValue.ImageSquaresPictureId);
                        if (origImageSquaresPicture != null)
                        {
                            //copy the picture
                            var imageSquaresPictureCopy = _pictureService.InsertPicture(
                                _pictureService.LoadPictureBinary(origImageSquaresPicture),
                                origImageSquaresPicture.MimeType,
                                origImageSquaresPicture.SeoFilename,
                                origImageSquaresPicture.AltAttribute,
                                origImageSquaresPicture.TitleAttribute);
                            attributeValueCopy.ImageSquaresPictureId = imageSquaresPictureCopy.Id;
                        }
                    }

                    _productAttributeService.InsertProductAttributeValue(attributeValueCopy);

                    //save associated value (used for combinations copying)
                    associatedAttributeValues.Add(productAttributeValue.Id, attributeValueCopy.Id);

                    //localization
                    foreach (var lang in languages)
                    {
                        var name = _localizationService.GetLocalized(productAttributeValue, x => x.Name, lang.Id, false, false);
                        if (!string.IsNullOrEmpty(name))
                        {
                            _localizedEntityService.SaveLocalizedValue(attributeValueCopy, x => x.Name, name, lang.Id);
                        }
                    }
                }
            }

            //copy attribute conditions
            foreach (var productAttributeMapping in oldCopyWithConditionAttributes)
            {
                var oldConditionAttributeMapping = _productAttributeParser
                                                   .ParseProductAttributeMappings(productAttributeMapping.ConditionAttributeXml).FirstOrDefault();

                if (oldConditionAttributeMapping == null)
                {
                    continue;
                }

                var oldConditionValues =
                    _productAttributeParser.ParseProductAttributeValues(productAttributeMapping.ConditionAttributeXml,
                                                                        oldConditionAttributeMapping.Id);

                if (!oldConditionValues.Any())
                {
                    continue;
                }

                var newAttributeMappingId        = associatedAttributes[oldConditionAttributeMapping.Id];
                var newConditionAttributeMapping = productAttributeMappingCopies[newAttributeMappingId];

                var newConditionAttributeXml = string.Empty;

                foreach (var oldConditionValue in oldConditionValues)
                {
                    newConditionAttributeXml = _productAttributeParser.AddProductAttribute(newConditionAttributeXml,
                                                                                           newConditionAttributeMapping, associatedAttributeValues[oldConditionValue.Id].ToString());
                }

                var attributeMappingId = associatedAttributes[productAttributeMapping.Id];
                var conditionAttribute = productAttributeMappingCopies[attributeMappingId];
                conditionAttribute.ConditionAttributeXml = newConditionAttributeXml;

                _productAttributeService.UpdateProductAttributeMapping(conditionAttribute);
            }

            //attribute combinations
            foreach (var combination in _productAttributeService.GetAllProductAttributeCombinations(product.Id))
            {
                //generate new AttributesXml according to new value IDs
                var newAttributesXml        = string.Empty;
                var parsedProductAttributes = _productAttributeParser.ParseProductAttributeMappings(combination.AttributesXml);
                foreach (var oldAttribute in parsedProductAttributes)
                {
                    if (!associatedAttributes.ContainsKey(oldAttribute.Id))
                    {
                        continue;
                    }

                    var newAttribute = _productAttributeService.GetProductAttributeMappingById(associatedAttributes[oldAttribute.Id]);

                    if (newAttribute == null)
                    {
                        continue;
                    }

                    var oldAttributeValuesStr = _productAttributeParser.ParseValues(combination.AttributesXml, oldAttribute.Id);

                    foreach (var oldAttributeValueStr in oldAttributeValuesStr)
                    {
                        if (newAttribute.ShouldHaveValues())
                        {
                            //attribute values
                            var oldAttributeValue = int.Parse(oldAttributeValueStr);
                            if (!associatedAttributeValues.ContainsKey(oldAttributeValue))
                            {
                                continue;
                            }

                            var newAttributeValue = _productAttributeService.GetProductAttributeValueById(associatedAttributeValues[oldAttributeValue]);

                            if (newAttributeValue != null)
                            {
                                newAttributesXml = _productAttributeParser.AddProductAttribute(newAttributesXml,
                                                                                               newAttribute, newAttributeValue.Id.ToString());
                            }
                        }
                        else
                        {
                            //just a text
                            newAttributesXml = _productAttributeParser.AddProductAttribute(newAttributesXml,
                                                                                           newAttribute, oldAttributeValueStr);
                        }
                    }
                }

                //picture
                originalNewPictureIdentifiers.TryGetValue(combination.PictureId, out var combinationPictureId);

                var combinationCopy = new ProductAttributeCombination
                {
                    ProductId             = productCopy.Id,
                    AttributesXml         = newAttributesXml,
                    StockQuantity         = combination.StockQuantity,
                    AllowOutOfStockOrders = combination.AllowOutOfStockOrders,
                    Sku = combination.Sku,
                    ManufacturerPartNumber = combination.ManufacturerPartNumber,
                    Gtin                        = combination.Gtin,
                    OverriddenPrice             = combination.OverriddenPrice,
                    NotifyAdminForQuantityBelow = combination.NotifyAdminForQuantityBelow,
                    PictureId                   = combinationPictureId
                };
                _productAttributeService.InsertProductAttributeCombination(combinationCopy);

                //quantity change history
                _productService.AddStockQuantityHistoryEntry(productCopy, combination.StockQuantity,
                                                             combination.StockQuantity,
                                                             message: string.Format(_localizationService.GetResource("Admin.StockQuantityHistory.Messages.CopyProduct"), product.Id), combinationId: combination.Id);
            }
        }
Пример #35
0
        public ActionResult CreateProduct(AdminEditProductViewModel model)
        {
            var cats = _categoryService.GetAllowedEditCategories(UsersRole, true);

            model.Categories = _categoryService.GetBaseSelectListCategories(cats);

            if (ModelState.IsValid)
            {
                using (var unitOfWork = UnitOfWorkManager.NewUnitOfWork())
                {
                    try
                    {
                        foreach (var it in model.AllAttribute)
                        {
                            var a = _productSevice.GetAttribute(it.AttriId);
                            it.Name      = a.LangName;
                            it.ValueType = a.ValueType;
                            it.IsNull    = a.IsNull;
                        }

                        var post    = new ProductPost();
                        var product = new Product();

                        if (model.Files != null)
                        {
                            // Before we save anything, check the user already has an upload folder and if not create one
                            var uploadFolderPath = HostingEnvironment.MapPath(string.Concat(SiteConstants.Instance.UploadFolderPath, product.Id));
                            if (!Directory.Exists(uploadFolderPath))
                            {
                                Directory.CreateDirectory(uploadFolderPath);
                            }

                            // Loop through each file and get the file info and save to the users folder and Db
                            var file = model.Files[0];
                            if (file != null)
                            {
                                // If successful then upload the file
                                var uploadResult = AppHelpers.UploadFile(file, uploadFolderPath, LocalizationService, true);

                                if (!uploadResult.UploadSuccessful)
                                {
                                    TempData[AppConstants.MessageViewBagName] = new GenericMessageViewModel
                                    {
                                        Message     = uploadResult.ErrorMessage,
                                        MessageType = GenericMessages.danger
                                    };
                                    return(View(model));
                                }

                                // Save avatar to user
                                model.Image = uploadResult.UploadedFileName;
                            }
                        }

                        post.PostContent       = model.Content;
                        post.MembershipUser_Id = LoggedOnReadOnlyUser.Id;
                        post.Product_Id        = product.Id;
                        post.IsTopicStarter    = true;

                        product.Name              = model.Name;
                        product.Category_Id       = model.Category;
                        product.Image             = model.Image;
                        product.IsLocked          = model.IsLocked;
                        product.ProductClassId    = model.ProductClass;
                        product.MembershipUser_Id = LoggedOnReadOnlyUser.Id;
                        product.ProductPost_Id    = post.Id;

                        product.ShotContent       = string.Concat(StringUtils.ReturnAmountWordsFromString(StringUtils.StripHtmlFromString(post.PostContent), 50), "....");
                        product.isAutoShotContent = true;

                        if (model.Files != null)
                        {
                            // Before we save anything, check the user already has an upload folder and if not create one
                            var uploadFolderPath = HostingEnvironment.MapPath(string.Concat(SiteConstants.Instance.UploadFolderPath, product.Id));
                            if (!Directory.Exists(uploadFolderPath))
                            {
                                Directory.CreateDirectory(uploadFolderPath);
                            }

                            // Loop through each file and get the file info and save to the users folder and Db
                            var file = model.Files[0];
                            if (file != null)
                            {
                                // If successful then upload the file
                                var uploadResult = AppHelpers.UploadFile(file, uploadFolderPath, LocalizationService, true);

                                if (!uploadResult.UploadSuccessful)
                                {
                                    TempData[AppConstants.MessageViewBagName] = new GenericMessageViewModel
                                    {
                                        Message     = uploadResult.ErrorMessage,
                                        MessageType = GenericMessages.danger
                                    };
                                    return(View(model));
                                }

                                // Save avatar to user
                                product.Image = uploadResult.UploadedFileName;
                            }
                        }

                        _productSevice.Add(product);
                        _productPostSevice.Add(post);

                        foreach (var it in model.AllAttribute)
                        {
                            var val = new ProductAttributeValue
                            {
                                ProductAttributeId = it.AttriId,
                                ProductId          = product.Id,
                                Value = it.Value
                            };

                            _productSevice.Add(val);
                        }

                        unitOfWork.Commit();
                        // We use temp data because we are doing a redirect
                        TempData[AppConstants.MessageViewBagName] = new GenericMessageViewModel
                        {
                            Message     = "Thêm sản phẩm thành công!",
                            MessageType = GenericMessages.success
                        };

                        return(RedirectToAction("Product", new { id = model.ProductClass }));
                    }
                    catch (Exception ex)
                    {
                        unitOfWork.Rollback();
                        LoggingService.Error(ex);
                        ModelState.AddModelError("", "Xảy ra lỗi khi thêm sản phẩm");
                    }
                }
            }


            return(View(model));
        }
Пример #36
0
 public void AddAttributeValue(ProductAttributeValue attributeValue)
 {
     attributeValue.Product = this;
     AttributeValues.Add(attributeValue);
 }
Пример #37
0
        public async Task AddFeaturesToMasterProductAsync(int newProductId, int masterProductId, List <ProductNewValue> relatives)
        {
            int pictureIndex = 0,
                displayIndex = 0;

            //Add new Color attributes
            var colorAttribute = await _context.ProductAttribute.FindAsync(
                _configuration.GetValue <int>("AttributeRecordIds:ColorAttributeId"));

            var newAttributeMapping = new ProductProductAttributeMapping
            {
                DisplayOrder           = 0,
                IsRequired             = true,
                ProductId              = newProductId,
                TextPrompt             = colorAttribute.Name,
                ProductAttributeId     = colorAttribute.Id,
                AttributeControlTypeId = _configuration.GetValue <int>("AttributeRecordIds:AttributeControlTypeId"),
            };

            _context.ProductProductAttributeMapping.Add(newAttributeMapping);

            await _context.SaveChangesAsync();

            foreach (var relativeProduct in relatives)
            {
                var otherProduct = await GetFirstOrDefaultWithIncludesAsync(relativeProduct.ProductId);

                if (otherProduct == null)
                {
                    continue;
                }

                var prictureId = otherProduct.ProductPictureMapping.OrderByDescending(o => o.DisplayOrder).FirstOrDefault()?.PictureId ?? 0;

                foreach (var pictureMapping in otherProduct.ProductPictureMapping)
                {
                    _context.ProductPictureMapping.Add(new ProductPictureMapping
                    {
                        ProductId    = newProductId,
                        DisplayOrder = ++pictureIndex,
                        PictureId    = pictureMapping.PictureId,
                    });
                }

                var attributeValue = new ProductAttributeValue
                {
                    PictureId            = prictureId,
                    AttributeValueTypeId = 0,
                    DisplayOrder         = displayIndex++,
                    Name = relativeProduct.ColorName,
                    ImageSquaresPictureId     = prictureId,
                    ProductAttributeMappingId = newAttributeMapping.Id,
                    IsPreSelected             = relativeProduct.ProductId == masterProductId,
                };

                _context.ProductAttributeValue.Add(attributeValue);

                await _context.SaveChangesAsync();

                _context.ProductAttributeCombination.Add(new ProductAttributeCombination
                {
                    PictureId       = prictureId,
                    ProductId       = newProductId,
                    Sku             = relativeProduct.SkuCode,
                    OverriddenPrice = otherProduct.Price,
                    StockQuantity   = otherProduct.StockQuantity,
                    AttributesXml   = $"<Attributes><ProductAttribute ID=\"{newAttributeMapping.Id}\"><ProductAttributeValue><Value>{attributeValue.Id}</Value></ProductAttributeValue></ProductAttribute></Attributes>"
                });
            }

            await _context.SaveChangesAsync();
        }