Exemple #1
0
        public async Task CreateAsync_GivenUniqueName_ShouldCreate_Category()
        {
            var name        = "NIceTest";
            var description = "some description";
            var manager     = new CategoryManager(_categoryRepository);
            var result      = await WithUnitOfWorkAsync(() => _categoryManager.CreateAsync(name, description));

            result.Id.ShouldNotBe(Guid.Empty);
            result.Name.ShouldBe(name);
            result.Description.ShouldBe(description);
        }
Exemple #2
0
        public async Task <IActionResult> AddCategory([FromBody] NewCategoryViewModel viewModel)
        {
            try
            {
                var categoryDto = new CategoryDto
                {
                    Name             = viewModel.Name,
                    UrlSlug          = viewModel.UrlSlug,
                    ParentCategoryId = viewModel.ParentCategoryId
                };

                categoryDto.Id = await _categoryManager.CreateAsync(categoryDto);

                var categoryVm = new CategoryViewModel {
                    Id               = categoryDto.Id,
                    Name             = categoryDto.Name,
                    ParentCategoryId = categoryDto.ParentCategoryId,
                    UrlSlug          = categoryDto.UrlSlug
                };
                var response = new SuccessResponse <CategoryViewModel>(categoryVm);

                return(Json(response));
            }
            catch (Exception ex)
            {
                var response = new ErrorResponse();
                response.Messages.Add(ex.Message);
                return(BadRequest(response));
            }
        }
    public virtual async Task SeedCategoriesAsync()
    {
        if (await _categoryRepository.AnyAsync(x => x.UniqueName == SampleDataConsts.FoodsCategoryUniqueName))
        {
            return;
        }

        var category = await _categoryManager.CreateAsync(null, SampleDataConsts.FoodsCategoryUniqueName, "Foods",
                                                          "Some delicious foods.", null, false);

        await _categoryRepository.InsertAsync(category, true);
    }
Exemple #4
0
        public async Task <IActionResult> CreatePost(EditChannelViewModel viewModel)
        {
            if (!ModelState.IsValid)
            {
                return(await Create(viewModel.Id));
            }

            var iconCss = viewModel.IconCss;

            if (!string.IsNullOrEmpty(iconCss))
            {
                iconCss = viewModel.IconPrefix + iconCss;
            }

            var feature = await GetCurrentFeature();

            var category = new Category()
            {
                ParentId    = viewModel.ParentId,
                FeatureId   = feature.Id,
                Name        = viewModel.Name,
                Description = viewModel.Description,
                ForeColor   = viewModel.ForeColor,
                BackColor   = viewModel.BackColor,
                IconCss     = iconCss
            };

            var result = await _categoryManager.CreateAsync(category);

            if (result.Succeeded)
            {
                await _viewProvider.ProvideUpdateAsync(result.Response, this);

                _alerter.Success(T["Category Added Successfully!"]);

                return(RedirectToAction(nameof(Index)));
            }
            else
            {
                foreach (var error in result.Errors)
                {
                    ModelState.AddModelError(string.Empty, error.Description);
                }
            }

            return(View(viewModel));
        }
Exemple #5
0
        async Task <ICommandResultBase> InstallCategoryAsync(IShellFeature feature, int sortOrder = 0)
        {
            // Validate

            if (feature == null)
            {
                throw new ArgumentNullException(nameof(feature));
            }

            if (string.IsNullOrEmpty(feature.ModuleId))
            {
                throw new ArgumentNullException(nameof(feature.ModuleId));
            }

            // Our result
            var result = new CommandResultBase();

            var icons = new DefaultIcons();

            var foreColor = "#ffffff";
            var backColor = $"#{_colorProvider.GetColor()}";
            var iconCss   = $"fal fa-{icons.GetIcon()}";

            var categoryResult = await _categoryManager.CreateAsync(new CategoryBase()
            {
                FeatureId   = feature.Id,
                ParentId    = 0,
                Name        = $"Example Category {_random.Next(0, 2000).ToString()}",
                Description = $"This is just an example category desccription.",
                ForeColor   = foreColor,
                BackColor   = backColor,
                IconCss     = iconCss,
                SortOrder   = sortOrder
            });

            if (!categoryResult.Succeeded)
            {
                return(result.Failed(result.Errors.ToArray()));
            }

            return(result.Success());
        }
        public async Task <ActionResult> Create(CategoryVM model)
        {
            if (!ModelState.IsValid)
            {
                return(View(model));
            }

            OperationResult result = await _categoryManager.CreateAsync(model.Name);

            if (result.Type == ResultType.Success)
            {
                //_toast.AddSuccessToastMessage("Category has been successfully created");
                //return View();
                return(RedirectToAction(nameof(List)));
            }

            ModelState.AddModelError(nameof(model.Name), result.BuildMessage());

            return(View(model));
        }
Exemple #7
0
 public async Task CreateAsync(CreateCategoryInput input)
 {
     var @category = Category.Create(input.Title);
     await _categoryManager.CreateAsync(@category);
 }
 public async Task CreateAsync(CreateCategoryDto input)
 {
     var category = ObjectMapper.Map <Category>(input);
     await _categoryManager.CreateAsync(category);
 }
Exemple #9
0
        /// <summary>
        /// 商品信息同步
        /// </summary>
        /// <returns></returns>
        public async Task ProductSync()
        {
            string reqURL = "http://commerce.vapps.com.cn/catalog/CategoryProductJsons?categoryId=0&PageSize=1000";

            var httpClient = new HttpClient();
            CacheControlHeaderValue cacheControl = new CacheControlHeaderValue();

            cacheControl.NoCache = true;
            cacheControl.NoStore = true;
            httpClient.DefaultRequestHeaders.CacheControl = cacheControl;

            try
            {
                var response = await httpClient.GetAsync(new Uri(reqURL));

                var jsonResultString = await response.Content.ReadAsStringAsync();

                JObject products = ((JObject)JToken.Parse(jsonResultString)["data"]);
                //return value;

                var productList = products["Data"].ToList().OrderBy(p => p["Id"]);

                foreach (JObject productJson in productList)
                {
                    var productDetailResponse = await httpClient.GetAsync(new Uri($"http://commerce.vapps.com.cn/product/ProductDetailJson?productId={productJson["Id"]}"));

                    var productDetailJsonResultString = await productDetailResponse.Content.ReadAsStringAsync();

                    JObject productsDetail = (JObject)JToken.Parse(productDetailJsonResultString)["data"];

                    var sku = productsDetail["Sku"].ToString();

                    var product = await _productManager.FindBySkuAsync(sku);

                    if (product != null)
                    {
                        continue;
                    }

                    var productDto = new CreateOrUpdateProductInput()
                    {
                        Name     = productsDetail["Name"].ToString(),
                        Price    = Decimal.Parse(productsDetail["ProductPrice"]["PriceValue"].ToString()),
                        GoodCost = Decimal.Parse(productsDetail["ProductPrice"]["Cost"].ToString()),

                        //Height = Decimal.Parse(productsDetail["Height"].ToString().IsNullOrWhiteSpace() ? "0" : productsDetail["Height"].ToString()),
                        //Weight = Decimal.Parse(productsDetail["Weight"].ToString().IsNullOrWhiteSpace() ? "0" : productsDetail["Weight"].ToString()),
                        //Width = Decimal.Parse(productsDetail["Width"].ToString().IsNullOrWhiteSpace() ? "0" : productsDetail["Width"].ToString()),
                        //Length = Decimal.Parse(productsDetail["Length"].ToString().IsNullOrWhiteSpace() ? "0" : productsDetail["Length"].ToString()),
                        Sku              = sku,
                        StockQuantity    = 0,
                        ShortDescription = productsDetail["ShortDescription"].ToString(),
                    };

                    // 同步分类
                    var categoryJsons = productsDetail["Breadcrumb"]["CategoryBreadcrumb"];
                    if (!categoryJsons.IsNullOrEmpty())
                    {
                        foreach (JObject categoryJson in categoryJsons.ToList())
                        {
                            var categoryName = categoryJson["Name"].ToString();
                            var category     = await _categoryManager.FindByNameAsync(categoryName);

                            if (category == null)
                            {
                                category = new Category()
                                {
                                    Name = categoryName,
                                }
                            }
                            ;

                            if (category.Id == 0)
                            {
                                await _categoryManager.CreateAsync(category);

                                await CurrentUnitOfWork.SaveChangesAsync();
                            }

                            productDto.Categories.Add(new ProductCategoryDto()
                            {
                                Id = category.Id
                            });
                        }
                    }

                    // 图片
                    var defaultPictureUrl = ((JObject)productsDetail["DefaultPictureModel"])["FullSizeImageUrl"].ToString();
                    if (!defaultPictureUrl.IsNullOrWhiteSpace())
                    {
                        var picture = await _pictureManager.FetchPictureAsync(defaultPictureUrl, (long)DefaultGroups.ProductPicture);

                        productDto.Pictures.Add(new ProductPictureDto()
                        {
                            Id = picture.Id,
                        });
                    }

                    //商品属性
                    var attributeJsons = productsDetail["ProductAttributes"];
                    if (!attributeJsons.IsNullOrEmpty())
                    {
                        foreach (JObject attributeJson in attributeJsons.ToList())
                        {
                            var attributeName = attributeJson["Name"].ToString();

                            // 属性值
                            var attributeValueJsons = attributeJson["Values"];
                            if (attributeValueJsons.IsNullOrEmpty())
                            {
                                continue;
                            }

                            var attribute = await _productAttributeManager.FindByNameAsync(attributeName);

                            if (attribute == null)
                            {
                                attribute = new ProductAttribute()
                                {
                                    Name = attributeName,
                                };

                                await _productAttributeManager.CreateAsync(attribute);

                                await CurrentUnitOfWork.SaveChangesAsync();
                            }

                            var attributeDto = new ProductAttributeDto()
                            {
                                Id   = attribute.Id,
                                Name = attributeJson["Id"].ToString()
                            };

                            // 属性值
                            foreach (JObject attributeValueJson in attributeValueJsons.ToList())
                            {
                                var attributeValueName = attributeValueJson["Name"].ToString();

                                var pAttributeValue = await _productAttributeManager.FindPredefinedValueByNameAsync(attribute.Id, attributeValueName);

                                if (pAttributeValue == null)
                                {
                                    pAttributeValue = new PredefinedProductAttributeValue()
                                    {
                                        Name = attributeValueName,
                                        ProductAttributeId = attribute.Id,
                                    };

                                    await _productAttributeManager.CreateOrUpdatePredefinedValueAsync(pAttributeValue);

                                    await CurrentUnitOfWork.SaveChangesAsync();
                                }

                                attributeDto.Values.Add(new ProductAttributeValueDto()
                                {
                                    Id         = pAttributeValue.Id,
                                    Name       = attributeValueJson["Id"].ToString(),
                                    PictureUrl = attributeValueJson["CostAdjustment"].ToString(),
                                });
                            }

                            productDto.Attributes.Add(attributeDto);
                        }
                    }

                    // 属性组合
                    if (!productDto.Attributes.IsNullOrEmpty())
                    {
                        for (int index = 0; index < productDto.Attributes[0].Values.Count; index++)
                        {
                            var deserializeSettings = new JsonSerializerSettings {
                                ObjectCreationHandling = ObjectCreationHandling.Replace
                            };
                            var attribute = JsonConvert.DeserializeObject <ProductAttributeDto>(JsonConvert.SerializeObject(productDto.Attributes[0]), deserializeSettings);

                            attribute.Values = new List <ProductAttributeValueDto>();
                            attribute.Values.Add(productDto.Attributes[0].Values[index]);

                            //var combin = new AttributeCombinationDto();
                            //combin.Attributes.Add(attribute);

                            if (productDto.Attributes.Count() >= 2)
                            {
                                for (int i = 0; i < productDto.Attributes[1].Values.Count; i++)
                                {
                                    var attribute1 = JsonConvert.DeserializeObject <ProductAttributeDto>(JsonConvert.SerializeObject(productDto.Attributes[1]), deserializeSettings);

                                    attribute1.Values = new List <ProductAttributeValueDto>();
                                    attribute1.Values.Add(productDto.Attributes[1].Values[i]);

                                    if (productDto.Attributes.Count() >= 3)
                                    {
                                        for (int j = 0; j < productDto.Attributes[2].Values.Count; j++)
                                        {
                                            var attribute2 = JsonConvert.DeserializeObject <ProductAttributeDto>(JsonConvert.SerializeObject(productDto.Attributes[2]), deserializeSettings);

                                            attribute2.Values = new List <ProductAttributeValueDto>();
                                            attribute2.Values.Add(productDto.Attributes[2].Values[j]);

                                            var combin = new AttributeCombinationDto();
                                            combin.Attributes.Add(attribute);
                                            combin.Attributes.Add(attribute1);
                                            combin.Attributes.Add(attribute2);

                                            productDto.AttributeCombinations.Add(combin);
                                        }
                                    }
                                    else
                                    {
                                        var combin = new AttributeCombinationDto();
                                        combin.Attributes.Add(attribute);
                                        combin.Attributes.Add(attribute1);

                                        productDto.AttributeCombinations.Add(combin);
                                    }
                                }
                            }
                            else
                            {
                                var combin = new AttributeCombinationDto();
                                combin.Attributes.Add(attribute);

                                productDto.AttributeCombinations.Add(combin);
                            }
                        }
                    }

                    string combinURL = "http://commerce.vapps.com.cn/product/GetStockByDropAndDropJson";
                    foreach (var combin in productDto.AttributeCombinations)
                    {
                        var para = combin.Attributes.Select(c =>
                        {
                            return(new { ProductAttrbuteId = Convert.ToInt32(c.Name), ProductAttrbuteValueId = Convert.ToInt32(c.Values[0].Name) });
                        }).ToList();

                        var data = new
                        {
                            productId       = Convert.ToInt32(productsDetail["Id"].ToString()),
                            paramDictionary = para
                        };

                        HttpContent content = new StringContent(JsonConvert.SerializeObject(data));
                        content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json");

                        var combinResponse = await httpClient.PostAsync(new Uri(combinURL), content);

                        var combinJsonResultString = await combinResponse.Content.ReadAsStringAsync();

                        if (combinJsonResultString.IsNullOrWhiteSpace())
                        {
                            continue;
                        }

                        JObject combinDetail = ((JObject)JToken.Parse(combinJsonResultString));

                        combin.Sku = combinDetail["Sku"].ToString();
                        if (!combin.Attributes[0].Values[0].PictureUrl.IsNullOrWhiteSpace())
                        {
                            combin.OverriddenGoodCost = decimal.Parse(combin.Attributes[0].Values[0].PictureUrl);
                        }
                    }

                    await CreateOrUpdateProduct(productDto);
                }
            }
            catch (Exception ex)
            {
            }
            finally
            {
                httpClient.Dispose();
            }
        }
Exemple #10
0
 protected override async Task <Category> MapToEntityAsync(CreateUpdateCategoryDto createInput)
 {
     return(await _categoryManager.CreateAsync(createInput.ParentId, createInput.UniqueName,
                                               createInput.DisplayName, createInput.Description, createInput.MediaResources, createInput.IsHidden));
 }
Exemple #11
0
 protected virtual async Task CreateCategoryAsync(CreateOrUpdateCategoryInput input)
 {
     var catalogy = ObjectMapper.Map <Category>(input);
     await _catalogyManager.CreateAsync(catalogy);
 }
 public override async Task <CategoryDto> CreateAsync(CreateUpdateCategoryDto input)
 {
     return(await MapToGetOutputDtoAsync(await _categoryManager.CreateAsync(input.Name, input.Description)));
 }