public JsonResult DeleteCcAttributes(int productId)
        {
            try
            {
                var specificationAttributes = _specificationAttributeService.GetProductSpecificationAttributes(productId);
                if (
                    specificationAttributes.Any(
                        attribute =>
                        attribute.SpecificationAttributeOptionId ==
                        _ccService.EditorDefinitionSpecificationAttributeOptionId()))
                {
                    _specificationAttributeService.DeleteProductSpecificationAttribute(
                        specificationAttributes.First(attribute =>
                                                      attribute.SpecificationAttributeOptionId ==
                                                      _ccService.EditorDefinitionSpecificationAttributeOptionId()));
                }

                if (
                    specificationAttributes.Any(
                        attribute =>
                        attribute.SpecificationAttributeOptionId ==
                        _ccService.EditorConfigurationSpecificationAttributeOptionId()))
                {
                    _specificationAttributeService.DeleteProductSpecificationAttribute(
                        specificationAttributes.First(attribute =>
                                                      attribute.SpecificationAttributeOptionId ==
                                                      _ccService.EditorConfigurationSpecificationAttributeOptionId()));
                }

                var productAttributes = _productAttributeService.GetProductAttributeMappingsByProductId(productId);
                foreach (var attrId in _ccService.GetCcAttrIds())
                {
                    if (productAttributes.Any(attr => attr.ProductAttributeId == attrId))
                    {
                        _productAttributeService.DeleteProductAttributeMapping(
                            productAttributes.First(attr => attr.ProductAttributeId == attrId));
                    }
                }

                return(Json(new { status = "success" }));
            }
            catch (Exception ex)
            {
                return(Json(new { status = "error", message = ex.Message }));
            }
        }
        public virtual void DeleteProductSpecification(ProductDto product, string id)
        {
            var productdb = _productService.GetProductById(product.Id);
            var psa       = productdb.ProductSpecificationAttributes.FirstOrDefault(x => x.Id == id);

            if (psa != null)
            {
                psa.ProductId = product.Id;
                _specificationAttributeService.DeleteProductSpecificationAttribute(psa);
            }
        }
        public async Task <bool> Handle(DeleteProductSpecificationCommand request, CancellationToken cancellationToken)
        {
            var product = await _productService.GetProductById(request.Product.Id, true);

            var psa = product.ProductSpecificationAttributes.FirstOrDefault(x => x.Id == request.Id);

            if (psa != null)
            {
                await _specificationAttributeService.DeleteProductSpecificationAttribute(psa, product.Id);
            }

            return(true);
        }
        private void UpdateProductSpecificationOption(ImportEntity importEntity)
        {
            var productFromBase         = _productService.GetProductBySku(importEntity.ProductSku);
            var allSpecificationOptions =
                _specificationAttributeService.GetSpecificationAttributes();
            var specificationMap = allSpecificationOptions.ToDictionary(i => i.Name, i => i);

            //если айди аттрибута из импорта нету в списке из связей в базе, то добавляем

            foreach (var productSpecificationAttribute in importEntity.ProductSpecifications)
            {
                if (!String.IsNullOrWhiteSpace(productSpecificationAttribute.Value))
                {
                    var importProductSpecification = _configImportCategoryEntity.ProductSpecifications.FirstOrDefault(
                        x => x.RusName.Equals(productSpecificationAttribute.Name));
                    var allowFilter =
                        importProductSpecification != null && importProductSpecification.FilterBy;
                    //пропишем айди в для specificationOptions из базы
                    GetIdForSpecificationOption(specificationMap, productSpecificationAttribute);

                    var productSpecifications =
                        _productService.GetProductBySku(importEntity.ProductSku).ProductSpecificationAttributes;


                    var productSpecificationAttributeOption =
                        productSpecifications.FirstOrDefault(
                            x => x.SpecificationAttributeOption.SpecificationAttributeId.Equals(productSpecificationAttribute.SpecificationId));

                    if (productSpecificationAttributeOption == null)
                    {
                        ProductSpecificationAttributeOptionMapping(productFromBase, productSpecificationAttribute, allowFilter);
                    }
                    else
                    {
                        _specificationAttributeService.DeleteProductSpecificationAttribute(
                            productSpecificationAttributeOption);

                        ProductSpecificationAttributeOptionMapping(productFromBase, productSpecificationAttribute, allowFilter);
                    }
                }
            }
        }
Ejemplo n.º 5
0
        public IActionResult DeleteProductSpecificationAttribute(int id)
        {
            if (id <= 0)
            {
                return(Error(HttpStatusCode.BadRequest, "id", "invalid id"));
            }

            var productSpecificationAttribute = _specificationAttributeService.GetProductSpecificationAttributeById(id);

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

            _specificationAttributeService.DeleteProductSpecificationAttribute(productSpecificationAttribute);

            //activity log
            CustomerActivityService.InsertActivity("DeleteProductSpecificationAttribute", LocalizationService.GetResource("ActivityLog.DeleteProductSpecificationAttribute"), productSpecificationAttribute);

            return(new RawJsonActionResult("{}"));
        }
Ejemplo n.º 6
0
        internal static void Import(КоммерческаяИнформация source,
                                    ICategoryService categoryService,
                                    ISpecificationAttributeService specificationAttributeService,
                                    IManufacturerService manufacturerService,
                                    IProductService productService,
                                    IUrlRecordService urlRecordService,
                                    IPictureService pictureService,
                                    List <Category> categories,
                                    Dictionary <string, int> categoryMappings,
                                    List <SpecificationAttribute> attributes,
                                    Dictionary <string, int> attributesMappings,
                                    List <Manufacturer> manufacturers,
                                    Dictionary <string, int> manufacturersMappings,
                                    string mappingsFile,
                                    string logFile,
                                    ImportCatalogSettings importSettings)

        {
            logFile.Log("Начало импорта товаров");
            var stats = new[] { 0, 0 };

            var mappings = File.Exists(mappingsFile)
                ? JsonConvert.DeserializeObject <Dictionary <string, int> >(File.ReadAllText(mappingsFile))
                : new Dictionary <string, int>();

            foreach (var prod in source.Каталог.Товары)
            {
                try
                {
                    var product = mappings.ContainsKey(prod.Ид)
                        ? productService.GetProductById(mappings[prod.Ид])
                        : null;

                    var deleted = prod.Статус == "Удален";
                    if (product == null)
                    {
                        product = new Product
                        {
                            CreatedOnUtc        = DateTime.Now,
                            UpdatedOnUtc        = DateTime.Now,
                            ProductType         = ProductType.SimpleProduct,
                            ProductTemplateId   = 1,
                            VisibleIndividually = true,
                            Name                 = prod.Наименование,
                            Sku                  = prod.Артикул,
                            ShortDescription     = prod.Описание,
                            FullDescription      = prod.Описание,
                            AllowCustomerReviews = true,
                            Deleted              = deleted,
                            Published            = !deleted,
                            OrderMinimumQuantity = 1,
                            OrderMaximumQuantity = 10000
                        };
                        productService.InsertProduct(product);
                        var seName = product.ValidateSeName(null, product.Name, true);
                        urlRecordService.SaveSlug(product, seName, 0);
                        //logFile.Log($"Новый товар {product.Name} ({product.Id}): {prod.Ид}");
                        stats[0]++;
                    }
                    else
                    {
                        if (!importSettings.UpdateExisting)
                        {
                            //logFile.Log($"Пропущен товар {product.Name} ({product.Id}): {prod.Ид}");
                            stats[1]++;
                            continue;
                        }
                        product.UpdatedOnUtc = DateTime.Now;
                        product.Deleted      = deleted;
                        product.Published    = !deleted;
                        productService.UpdateProduct(product);
                        //logFile.Log($"Обновлен товар {product.Name} ({product.Id}): {prod.Ид}");
                        stats[1]++;
                    }
                    mappings[prod.Ид] = product.Id;

                    if (importSettings.OverwriteManufacturers)
                    {
                        foreach (var manufacturer in product.ProductManufacturers.ToList())
                        {
                            manufacturerService.DeleteProductManufacturer(manufacturer);
                        }
                    }
                    if (prod.Изготовитель != null && manufacturersMappings.ContainsKey(prod.Изготовитель.Ид))
                    {
                        var manufacturerId = manufacturersMappings[prod.Изготовитель.Ид];
                        var manufacturer   = product.ProductManufacturers.FirstOrDefault(m => m.ManufacturerId == manufacturerId);
                        if (manufacturer == null)
                        {
                            manufacturer = new ProductManufacturer
                            {
                                ProductId      = product.Id,
                                ManufacturerId = manufacturerId
                            };
                            manufacturerService.InsertProductManufacturer(manufacturer);
                            product.ProductManufacturers.Add(manufacturer);
                        }
                    }

                    if (importSettings.OverwriteCategories)
                    {
                        foreach (var category in product.ProductCategories.ToList())
                        {
                            categoryService.DeleteProductCategory(category);
                        }
                    }
                    if (prod.Группы != null && categoryMappings.ContainsKey(prod.Группы.Ид))
                    {
                        var categoryId = categoryMappings[prod.Группы.Ид];
                        var category   = product.ProductCategories.FirstOrDefault(c => c.CategoryId == categoryId);
                        if (category == null)
                        {
                            category = new ProductCategory
                            {
                                ProductId  = product.Id,
                                CategoryId = categoryId
                            };
                            categoryService.InsertProductCategory(category);
                            product.ProductCategories.Add(category);
                        }
                    }

                    if (importSettings.ImportSpecificationAttributes && prod.ЗначенияСвойств != null)
                    {
                        foreach (var attr in prod.ЗначенияСвойств)
                        {
                            if (attributesMappings.ContainsKey(attr.Ид))
                            {
                                var emptyOptionKey = $"{attr.Ид}.";
                                if (attributesMappings.ContainsKey(emptyOptionKey))
                                {
                                    var option = product.ProductSpecificationAttributes
                                                 .FirstOrDefault(a => a.SpecificationAttributeOptionId == attributesMappings[emptyOptionKey]);
                                    if (option == null)
                                    {
                                        option = new ProductSpecificationAttribute
                                        {
                                            ProductId         = product.Id,
                                            ShowOnProductPage = true,
                                            AllowFiltering    = false,
                                            SpecificationAttributeOptionId = attributesMappings[emptyOptionKey],
                                            AttributeType = SpecificationAttributeType.CustomText,
                                            CustomValue   = attr.Значение
                                        };
                                        specificationAttributeService.InsertProductSpecificationAttribute(option);
                                        product.ProductSpecificationAttributes.Add(option);
                                    }
                                    else if (option.CustomValue != attr.Значение)
                                    {
                                        option.CustomValue = attr.Значение;
                                        specificationAttributeService.UpdateProductSpecificationAttribute(option);
                                    }
                                }
                                else
                                {
                                    var optionKey = $"{attr.Ид}.{attr.Значение}";

                                    var option = product.ProductSpecificationAttributes
                                                 .FirstOrDefault(o => o.SpecificationAttributeOptionId == attributesMappings[optionKey]);
                                    if (option == null)
                                    {
                                        var attribute = attributes.FirstOrDefault(a => a.Id == attributesMappings[attr.Ид]);
                                        var optionIds = attribute.SpecificationAttributeOptions.Select(o => o.Id);
                                        var options   = product.ProductSpecificationAttributes
                                                        .Where(a => optionIds.Contains(a.SpecificationAttributeOptionId)).ToList();
                                        if (options != null && options.Count > 0)
                                        {
                                            foreach (var opt in options)
                                            {
                                                product.ProductSpecificationAttributes.Remove(opt);
                                                specificationAttributeService.DeleteProductSpecificationAttribute(opt);
                                            }
                                        }

                                        option = new ProductSpecificationAttribute
                                        {
                                            ProductId         = product.Id,
                                            ShowOnProductPage = true,
                                            AllowFiltering    = true,
                                            SpecificationAttributeOptionId = attributesMappings[optionKey],
                                            AttributeType = SpecificationAttributeType.Option
                                        };
                                        specificationAttributeService.InsertProductSpecificationAttribute(option);
                                        product.ProductSpecificationAttributes.Add(option);
                                    }
                                }
                            }
                        }
                    }

                    if (!string.IsNullOrEmpty(prod.Картинка))
                    {
                        // todo: compare with existing images
                        var picturePath = HttpContext.Current.Request.MapPath($"~/Content/{prod.Картинка}");
                        var picture     = LoadPicture(pictureService, picturePath, product.Name);
                        if (picture != null)
                        {
                            product.ProductPictures.Add(new ProductPicture
                            {
                                DisplayOrder = 1,
                                PictureId    = picture.Id,
                                ProductId    = product.Id
                            });
                        }
                    }

                    File.WriteAllText(mappingsFile, JsonConvert.SerializeObject(mappings, Formatting.Indented), Encoding.UTF8);
                }
                catch (Exception ex)
                {
                    logFile.Log($"Ошибка при обработке товара {prod.Ид} ({prod.Наименование}): {ex}");
                }
            }

            logFile.Log($"Импорт товаров завершен. Добавлено: {stats[0]}. Обновлено: {stats[1]}.");
        }