public IActionResult CreateSpecificationAttribute([ModelBinder(typeof(JsonModelBinder <SpecificationAttributeDto>))] Delta <SpecificationAttributeDto> specificaitonAttributeDelta) { // Here we display the errors if the validation has failed at some point. if (!ModelState.IsValid) { return(Error()); } // Inserting the new product var specificationAttribute = new SpecificationAttribute(); specificaitonAttributeDelta.Merge(specificationAttribute); _specificationAttributeService.InsertSpecificationAttribute(specificationAttribute); var options = new List <SpecificationAttributeOption>(); if (specificaitonAttributeDelta.Dto.SpecificationAttributeOptions?.Any() == true) { var ix = 0; foreach (var option in specificaitonAttributeDelta.Dto.SpecificationAttributeOptions) { var opt = new SpecificationAttributeOption { Name = option.Name, SpecificationAttributeId = specificationAttribute.Id, DisplayOrder = ix }; ix++; _specificationAttributeService.InsertSpecificationAttributeOption(opt); options.Add(opt); } } CustomerActivityService.InsertActivity("AddNewSpecAttribute", LocalizationService.GetResource("ActivityLog.AddNewSpecAttribute"), specificationAttribute); // Preparing the result dto of the new product var specificationAttributeDto = _dtoHelper.PrepareSpecificationAttributeDto(specificationAttribute); specificationAttributeDto.SpecificationAttributeOptions = new List <SpecificationAttributeOptionDto>(); foreach (var option in options) { specificationAttributeDto.SpecificationAttributeOptions.Add(_dtoHelper.PrepareSpecificationAttributeOptionDto(option)); } var specificationAttributesRootObjectDto = new SpecificationAttributesRootObjectDto(); specificationAttributesRootObjectDto.SpecificationAttributes.Add(specificationAttributeDto); var json = JsonFieldsSerializer.Serialize(specificationAttributesRootObjectDto, string.Empty); return(new RawJsonActionResult(json)); }
public HttpResponseMessage Add(HttpRequestMessage request, SpecificationAttributeVM model, bool continueEditing = false) { return(CreateHttpResponse(request, () => { HttpResponseMessage response = null; if (!ModelState.IsValid) { response = request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState); } else { var specificationAttribute = model.ToEntity(); _specificationAttributeService.InsertSpecificationAttribute(specificationAttribute); //activity log _customerActivityService.InsertActivity("AddNewSpecAttribute", _localizationService.GetResource("ActivityLog.AddNewSpecAttribute"), specificationAttribute.Name); _baseService.Commit(); response = request.CreateResponse <SpecificationAttribute>(HttpStatusCode.Created, specificationAttribute); if (continueEditing) { // Generate a link to the update item and set the Location header in the response. string uri = Url.Link("GetSpecificationAttributeById", new { id = specificationAttribute.Id }); response.Headers.Location = new Uri(uri); } } return response; })); }
public virtual IActionResult Create(SpecificationAttributeModel model, bool continueEditing) { if (!_permissionService.Authorize(StandardPermissionProvider.ManageAttributes)) { return(AccessDeniedView()); } if (ModelState.IsValid) { var specificationAttribute = model.ToEntity <SpecificationAttribute>(); _specificationAttributeService.InsertSpecificationAttribute(specificationAttribute); UpdateAttributeLocales(specificationAttribute, model); //activity log _customerActivityService.InsertActivity("AddNewSpecAttribute", string.Format(_localizationService.GetResource("ActivityLog.AddNewSpecAttribute"), specificationAttribute.Name), specificationAttribute); _notificationService.SuccessNotification(_localizationService.GetResource("Admin.Catalog.Attributes.SpecificationAttributes.Added")); if (!continueEditing) { return(RedirectToAction("List")); } return(RedirectToAction("Edit", new { id = specificationAttribute.Id })); } //prepare model model = _specificationAttributeModelFactory.PrepareSpecificationAttributeModel(model, null, true); //if we got this far, something failed, redisplay form return(View(model)); }
public ActionResult Create(SpecificationAttributeModel model, bool continueEditing) { if (ModelState.IsValid) { var specificationAttribute = model.ToEntity(); try { _specificationAttributeService.InsertSpecificationAttribute(specificationAttribute); } catch (Exception ex) { ModelState.AddModelError("", ex.Message); return(View(model)); } try { UpdateAttributeLocales(specificationAttribute, model); } catch (Exception ex) { continueEditing = true; NotifyError(ex.Message); } _customerActivityService.InsertActivity("AddNewSpecAttribute", T("ActivityLog.AddNewSpecAttribute"), specificationAttribute.Name); NotifySuccess(T("Admin.Catalog.Attributes.SpecificationAttributes.Added")); return(continueEditing ? RedirectToAction("Edit", new { id = specificationAttribute.Id }) : RedirectToAction("List")); } return(View(model)); }
public IActionResult CreateSpecificationAttribute([ModelBinder(typeof(JsonModelBinder <SpecificationAttributeDto>))] Delta <SpecificationAttributeDto> specificaitonAttributeDelta) { // Here we display the errors if the validation has failed at some point. if (!ModelState.IsValid) { return(Error()); } // Inserting the new product var specificationAttribute = new SpecificationAttribute(); specificaitonAttributeDelta.Merge(specificationAttribute); _specificationAttributeService.InsertSpecificationAttribute(specificationAttribute); _customerActivityService.InsertActivity("AddNewSpecAttribute", _localizationService.GetResource("ActivityLog.AddNewSpecAttribute"), specificationAttribute.Id.ToString()); // Preparing the result dto of the new product var specificationAttributeDto = _dtoHelper.PrepareSpecificationAttributeDto(specificationAttribute); var specificationAttributesRootObjectDto = new SpecificationAttributesRootObjectDto(); specificationAttributesRootObjectDto.SpecificationAttributes.Add(specificationAttributeDto); var json = _jsonFieldsSerializer.Serialize(specificationAttributesRootObjectDto, string.Empty); return(new RawJsonActionResult(json)); }
public ActionResult Create(SpecificationAttributeModel model, bool continueEditing) { if (!_permissionService.Authorize(StandardPermissionProvider.ManageAttributes)) { return(AccessDeniedView()); } if (ModelState.IsValid) { var specificationAttribute = model.ToEntity(); _specificationAttributeService.InsertSpecificationAttribute(specificationAttribute); UpdateAttributeLocales(specificationAttribute, model); //activity log _customerActivityService.InsertActivity("AddNewSpecAttribute", _localizationService.GetResource("ActivityLog.AddNewSpecAttribute"), specificationAttribute.Name); SuccessNotification(_localizationService.GetResource("Admin.Catalog.Attributes.SpecificationAttributes.Added")); if (continueEditing) { //selected tab SaveSelectedTabName(); return(RedirectToAction("Edit", new { id = specificationAttribute.Id })); } return(RedirectToAction("List")); } //If we got this far, something failed, redisplay form return(View(model)); }
/// <summary> /// Install plugin /// </summary> public override void Install() { var artistAttr = _specificationAttributeService.GetSpecificationAttributes().Where(x => x.Name == "Artist").FirstOrDefault(); if (artistAttr == null) { artistAttr = new Core.Domain.Catalog.SpecificationAttribute(); artistAttr.Name = "Artist"; _specificationAttributeService.InsertSpecificationAttribute(artistAttr); } var DefaultEnvelopeColorAttr = _specificationAttributeService.GetSpecificationAttributes().Where(x => x.Name == "DefaultEnvelopeColor").FirstOrDefault(); if (DefaultEnvelopeColorAttr == null) { DefaultEnvelopeColorAttr = new Core.Domain.Catalog.SpecificationAttribute(); DefaultEnvelopeColorAttr.Name = "DefaultEnvelopeColor"; _specificationAttributeService.InsertSpecificationAttribute(DefaultEnvelopeColorAttr); } var OrientationAttr = _specificationAttributeService.GetSpecificationAttributes().Where(x => x.Name == "Orientation").FirstOrDefault(); if (OrientationAttr == null) { OrientationAttr = new Core.Domain.Catalog.SpecificationAttribute(); OrientationAttr.Name = "Orientation"; var _specificationOptionsVertical = new Core.Domain.Catalog.SpecificationAttributeOption(); _specificationOptionsVertical.Name = "Vertical"; OrientationAttr.SpecificationAttributeOptions.Add(_specificationOptionsVertical); var _specificationOptionsHorizontal = new Core.Domain.Catalog.SpecificationAttributeOption(); _specificationOptionsHorizontal.Name = "Horizontal"; OrientationAttr.SpecificationAttributeOptions.Add(_specificationOptionsHorizontal); _specificationAttributeService.InsertSpecificationAttribute(OrientationAttr); } this.AddOrUpdatePluginLocaleResource("Plugin.ProductArtist.ArtistName", "Artist"); this.AddOrUpdatePluginLocaleResource("Plugin.ProductArtist.ArtistName.Hint", "Artist"); this.AddOrUpdatePluginLocaleResource("Plugin.Product.Atist", "Artist"); this.AddOrUpdatePluginLocaleResource("Plugin.Artist.Saved", "Artist Saved"); this.AddOrUpdatePluginLocaleResource("artistname.by", "by"); this.AddOrUpdatePluginLocaleResource("Product.Category", "Categories"); base.Install(); }
public async Task <SpecificationAttributeDto> Handle(AddSpecificationAttributeCommand request, CancellationToken cancellationToken) { var specificationAttribute = request.Model.ToEntity(); await _specificationAttributeService.InsertSpecificationAttribute(specificationAttribute); //activity log await _customerActivityService.InsertActivity("AddNewSpecAttribute", specificationAttribute.Id, _translationService.GetResource("ActivityLog.AddNewSpecAttribute"), specificationAttribute.Name); return(specificationAttribute.ToModel()); }
public virtual async Task <SpecificationAttributeDto> InsertSpecificationAttribute(SpecificationAttributeDto model) { var specificationAttribute = model.ToEntity(); await _specificationAttributeService.InsertSpecificationAttribute(specificationAttribute); //activity log await _customerActivityService.InsertActivity("AddNewSpecAttribute", specificationAttribute.Id, _localizationService.GetResource("ActivityLog.AddNewSpecAttribute"), specificationAttribute.Name); return(specificationAttribute.ToModel()); }
public IActionResult Create(SpecificationAttributeModel model, bool continueEditing) { if (ModelState.IsValid) { var specificationAttribute = model.ToEntity(); _specificationAttributeService.InsertSpecificationAttribute(specificationAttribute); //activity log _customerActivityService.InsertActivity("AddNewSpecAttribute", specificationAttribute.Id, _localizationService.GetResource("ActivityLog.AddNewSpecAttribute"), specificationAttribute.Name); SuccessNotification(_localizationService.GetResource("Admin.Catalog.Attributes.SpecificationAttributes.Added")); return(continueEditing ? RedirectToAction("Edit", new { id = specificationAttribute.Id }) : RedirectToAction("List")); } //If we got this far, something failed, redisplay form return(View(model)); }
public async Task <IActionResult> Create(SpecificationAttributeModel model, bool continueEditing) { if (ModelState.IsValid) { var specificationAttribute = model.ToEntity(); specificationAttribute.SeName = SeoExtensions.GetSeName(string.IsNullOrEmpty(specificationAttribute.SeName) ? specificationAttribute.Name : specificationAttribute.SeName, _seoSettings); await _specificationAttributeService.InsertSpecificationAttribute(specificationAttribute); //activity log await _customerActivityService.InsertActivity("AddNewSpecAttribute", specificationAttribute.Id, _localizationService.GetResource("ActivityLog.AddNewSpecAttribute"), specificationAttribute.Name); SuccessNotification(_localizationService.GetResource("Admin.Catalog.Attributes.SpecificationAttributes.Added")); return(continueEditing ? RedirectToAction("Edit", new { id = specificationAttribute.Id }) : RedirectToAction("List")); } //If we got this far, something failed, redisplay form return(View(model)); }
public ActionResult Create(SpecificationAttributeModel model, bool continueEditing) { if (!_permissionService.Authorize(StandardPermissionProvider.ManageCatalog)) { return(AccessDeniedView()); } if (ModelState.IsValid) { var specificationAttribute = model.ToEntity(); try { _specificationAttributeService.InsertSpecificationAttribute(specificationAttribute); } catch (Exception exception) { ModelState.AddModelError("", exception.Message); return(View(model)); } try { UpdateAttributeLocales(specificationAttribute, model); } catch (Exception exception) { continueEditing = true; NotifyError(exception.Message); } //activity log _customerActivityService.InsertActivity("AddNewSpecAttribute", _localizationService.GetResource("ActivityLog.AddNewSpecAttribute"), specificationAttribute.Name); NotifySuccess(_localizationService.GetResource("Admin.Catalog.Attributes.SpecificationAttributes.Added")); return(continueEditing ? RedirectToAction("Edit", new { id = specificationAttribute.Id }) : RedirectToAction("List")); } //If we got this far, something failed, redisplay form return(View(model)); }
public async Task <IActionResult> Create(SpecificationAttributeModel model, bool continueEditing) { if (ModelState.IsValid) { var specificationAttribute = model.ToEntity(); specificationAttribute.SeName = SeoExtensions.GetSeName(string.IsNullOrEmpty(specificationAttribute.SeName) ? specificationAttribute.Name : specificationAttribute.SeName, _seoSettings.ConvertNonWesternChars, _seoSettings.AllowUnicodeCharsInUrls, _seoSettings.SeoCharConversion); if (await _groupService.IsStaff(_workContext.CurrentCustomer)) { model.Stores = new string[] { _workContext.CurrentCustomer.StaffStoreId }; } await _specificationAttributeService.InsertSpecificationAttribute(specificationAttribute); //activity log await _customerActivityService.InsertActivity("AddNewSpecAttribute", specificationAttribute.Id, _translationService.GetResource("ActivityLog.AddNewSpecAttribute"), specificationAttribute.Name); Success(_translationService.GetResource("Admin.Catalog.Attributes.SpecificationAttributes.Added")); return(continueEditing ? RedirectToAction("Edit", new { id = specificationAttribute.Id }) : RedirectToAction("List")); } //If we got this far, something failed, redisplay form return(View(model)); }
private void UpdateSpecificationOption(ImportEntity importEntity) { foreach (var entity in importEntity.ProductSpecifications) { var specificationAttribute = _specificationAttributeService. GetSpecificationAttributes(). FirstOrDefault(x => x.Name.Equals(entity.Name)); if (specificationAttribute != null) { MappingAttributeSpecificationOption(entity, specificationAttribute); } else { specificationAttribute = new SpecificationAttribute(); specificationAttribute.Name = entity.Name; specificationAttribute.DisplayOrder = 0; _specificationAttributeService.InsertSpecificationAttribute(specificationAttribute); MappingAttributeSpecificationOption(entity, specificationAttribute); } } }
public JsonResult SaveCcAttribute(int productId, string attributeName, string attributeValue) { try { var specificationAttributes = _specificationAttributeService.GetProductSpecificationAttributes(productId); var prodSpecAttr = specificationAttributes.FirstOrDefault( x => x.SpecificationAttributeOption.SpecificationAttribute.Name == attributeName); if (prodSpecAttr == null) { var allSpecAttrs = _specificationAttributeService.GetSpecificationAttributes(); var currSpecAttr = allSpecAttrs.FirstOrDefault(x => x.Name == attributeName); if (currSpecAttr == null) { currSpecAttr = new SpecificationAttribute(); currSpecAttr.Name = attributeName; currSpecAttr.DisplayOrder = 0; _specificationAttributeService.InsertSpecificationAttribute(currSpecAttr); var newAttrOption = new SpecificationAttributeOption(); newAttrOption.SpecificationAttribute = currSpecAttr; newAttrOption.Name = attributeName; newAttrOption.DisplayOrder = 0; _specificationAttributeService.InsertSpecificationAttributeOption(newAttrOption); } prodSpecAttr = new ProductSpecificationAttribute { AttributeType = SpecificationAttributeType.CustomText, ProductId = productId, SpecificationAttributeOptionId = currSpecAttr.SpecificationAttributeOptions.First().Id, DisplayOrder = 0, ShowOnProductPage = false, AllowFiltering = false, CustomValue = attributeValue, }; _specificationAttributeService.InsertProductSpecificationAttribute(prodSpecAttr); } else { prodSpecAttr.CustomValue = attributeValue; prodSpecAttr.ShowOnProductPage = false; _specificationAttributeService.UpdateProductSpecificationAttribute(prodSpecAttr); } var productAttributeMappings = _productAttributeService.GetProductAttributeMappingsByProductId(productId); foreach (var attrId in _ccService.GetCcAttrIds()) { if (productAttributeMappings.All(map => map.ProductAttributeId != attrId)) { _productAttributeService.InsertProductAttributeMapping(new ProductAttributeMapping { AttributeControlType = AttributeControlType.TextBox, DefaultValue = "", DisplayOrder = 100, ProductId = productId, ProductAttributeId = attrId }); } } return(Json(new { status = "success" })); } catch (Exception ex) { var message = ex.InnerException != null ? ex.InnerException.Message : ""; return(Json(new { status = "error", message = ex.Message + " " + message })); } }
private void InstallAttributes(CcSettings settings) { var attributes = _productAttributeService.GetAllProductAttributes(); var specificationAttributes = _specificationAttributeService.GetSpecificationAttributes(); var ccIdAttribute = attributes.FirstOrDefault(x => x.Name == "CcId"); if (ccIdAttribute == null) { ccIdAttribute = new ProductAttribute() { Name = "CcId" }; _productAttributeService.InsertProductAttribute(ccIdAttribute); } var editorDefinitionSpecificationAttribute = specificationAttributes.FirstOrDefault(x => x.Name == "CC Editor"); if (editorDefinitionSpecificationAttribute == null) { editorDefinitionSpecificationAttribute = new SpecificationAttribute { Name = "CC Editor", DisplayOrder = 100 }; _specificationAttributeService.InsertSpecificationAttribute(editorDefinitionSpecificationAttribute); } var editorDefinitionSpecificationOption = editorDefinitionSpecificationAttribute.SpecificationAttributeOptions.FirstOrDefault(x => x.Name == "CC Editor"); if (editorDefinitionSpecificationOption == null) { editorDefinitionSpecificationOption = new SpecificationAttributeOption { DisplayOrder = 0, Name = "CC Editor", SpecificationAttributeId = editorDefinitionSpecificationAttribute.Id }; _specificationAttributeService.InsertSpecificationAttributeOption(editorDefinitionSpecificationOption); } var editorConfigurationSpecificationAttribute = specificationAttributes.FirstOrDefault(x => x.Name == "CC EditorConfig"); if (editorConfigurationSpecificationAttribute == null) { editorConfigurationSpecificationAttribute = new SpecificationAttribute { Name = "CC EditorConfig", DisplayOrder = 100 }; _specificationAttributeService.InsertSpecificationAttribute(editorConfigurationSpecificationAttribute); } var editorConfigurationSpecificationOption = editorDefinitionSpecificationAttribute.SpecificationAttributeOptions.FirstOrDefault(x => x.Name == "CC EditorConfig"); if (editorConfigurationSpecificationOption == null) { editorConfigurationSpecificationOption = new SpecificationAttributeOption { DisplayOrder = 0, Name = "CC EditorConfig", SpecificationAttributeId = editorConfigurationSpecificationAttribute.Id }; _specificationAttributeService.InsertSpecificationAttributeOption(editorConfigurationSpecificationOption); } // add to settings settings.CcIdAttributeId = ccIdAttribute.Id; settings.EditorDefinitionSpecificationAttributeId = editorDefinitionSpecificationAttribute.Id; settings.EditorDefinitionSpecificationOptionId = editorDefinitionSpecificationOption.Id; settings.EditorConfigurationSpecificationAttributeId = editorConfigurationSpecificationAttribute.Id; settings.EditorConfigurationSpecificationOptionId = editorConfigurationSpecificationOption.Id; }
/// <summary> /// Install plugin /// </summary> public override void Install() { var artistAttr = _specificationAttributeService.GetSpecificationAttributes().Where(x => x.Name == "Artist").FirstOrDefault(); if (artistAttr == null) { artistAttr = new Core.Domain.Catalog.SpecificationAttribute(); artistAttr.Name = "Artist"; _specificationAttributeService.InsertSpecificationAttribute(artistAttr); } var Treatment = _specificationAttributeService.GetSpecificationAttributes().Where(x => x.Name == "Treatment").FirstOrDefault(); if (Treatment == null) { Treatment = new Core.Domain.Catalog.SpecificationAttribute(); Treatment.Name = "Treatment"; var _specificationOptionsTreatmentImage = new Core.Domain.Catalog.SpecificationAttributeOption(); _specificationOptionsTreatmentImage.Name = "TreatmentImage"; Treatment.SpecificationAttributeOptions.Add(_specificationOptionsTreatmentImage); var _specificationOptionsTreatmentFill = new Core.Domain.Catalog.SpecificationAttributeOption(); _specificationOptionsTreatmentFill.Name = "TreatmentFill"; Treatment.SpecificationAttributeOptions.Add(_specificationOptionsTreatmentFill); _specificationAttributeService.InsertSpecificationAttribute(Treatment); } var TreatmentImage = _specificationAttributeService.GetSpecificationAttributes().Where(x => x.Name == "TreatmentImage").FirstOrDefault(); if (TreatmentImage == null) { TreatmentImage = new Core.Domain.Catalog.SpecificationAttribute(); TreatmentImage.Name = "TreatmentImage"; _specificationAttributeService.InsertSpecificationAttribute(TreatmentImage); } var TreatmentFill = _specificationAttributeService.GetSpecificationAttributes().Where(x => x.Name == "TreatmentFill").FirstOrDefault(); if (TreatmentFill == null) { TreatmentFill = new Core.Domain.Catalog.SpecificationAttribute(); TreatmentFill.Name = "TreatmentFill"; var _specificationOptionsTreatmentFillColor = new Core.Domain.Catalog.SpecificationAttributeOption(); _specificationOptionsTreatmentFillColor.Name = "TreatmentFillColor"; TreatmentFill.SpecificationAttributeOptions.Add(_specificationOptionsTreatmentFillColor); var _specificationOptionsTreatmentFillPattern = new Core.Domain.Catalog.SpecificationAttributeOption(); _specificationOptionsTreatmentFillPattern.Name = "TreatmentFillPattern"; TreatmentFill.SpecificationAttributeOptions.Add(_specificationOptionsTreatmentFillPattern); _specificationAttributeService.InsertSpecificationAttribute(TreatmentFill); } var TreatmentFillColor = _specificationAttributeService.GetSpecificationAttributes().Where(x => x.Name == "TreatmentFillColor").FirstOrDefault(); if (TreatmentFillColor == null) { TreatmentFillColor = new Core.Domain.Catalog.SpecificationAttribute(); TreatmentFillColor.Name = "TreatmentFillColor"; _specificationAttributeService.InsertSpecificationAttribute(TreatmentFillColor); } var TreatmentFillPattern = _specificationAttributeService.GetSpecificationAttributes().Where(x => x.Name == "TreatmentFillPattern").FirstOrDefault(); if (TreatmentFillPattern == null) { TreatmentFillPattern = new Core.Domain.Catalog.SpecificationAttribute(); TreatmentFillPattern.Name = "TreatmentFillPattern"; _specificationAttributeService.InsertSpecificationAttribute(TreatmentFillPattern); } this.AddOrUpdatePluginLocaleResource("Plugin.Prodcuts.SpecificationAttributes.ArtistName", "Artist"); this.AddOrUpdatePluginLocaleResource("Plugin.Prodcuts.SpecificationAttributes.ArtistName.Hint", "Artist"); this.AddOrUpdatePluginLocaleResource("Plugin.Prodcuts.SpecificationAttributes.Artist", "Artist"); this.AddOrUpdatePluginLocaleResource("Plugin.Prodcuts.SpecificationAttributes.Artist.Saved", "Artist Saved"); this.AddOrUpdatePluginLocaleResource("artistname.by", "by"); this.AddOrUpdatePluginLocaleResource("Product.Category", "Categories"); base.Install(); }
public async Task <ActionResult> CallApi(ConfigurationModel model) { var storeScope = this.GetActiveStoreScopeConfiguration(_storeService, _workContext); var mappingSettings = _settingService.LoadSetting <ProductMappingSettings>(storeScope); var tokenebay = EbayExtensions.GetToken(); var categoryWorldBuy = _categoryMappingRecord.Table.Where(u => u.CategoryId == model.CategoryId && u.SourceId == (int)Source.Ebay).ToList(); if (categoryWorldBuy != null) { foreach (var cateIds in categoryWorldBuy) { var clientapi1 = new HttpClient(); clientapi1.BaseAddress = new Uri("https://api.ebay.com/"); clientapi1.DefaultRequestHeaders.Clear(); clientapi1.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); clientapi1.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", tokenebay); clientapi1.Timeout = TimeSpan.FromMinutes(60); var getCategoryId = _affiliateEbayService.Get(cateIds.CategorySourceId).EbayId.ToString(); string str = "buy/browse/v1/item_summary/search?limit=200&category_ids=" + getCategoryId; if (!string.IsNullOrEmpty(model.KeyWord)) { str = str + "&q=" + model.KeyWord; } HttpResponseMessage Res1 = await clientapi1.GetAsync(str); if (Res1.IsSuccessStatusCode) { var EmpResponse1 = Res1.Content.ReadAsStringAsync().Result; var result1 = JsonConvert.DeserializeObject <SearchOutput>(EmpResponse1); int temp = int.Parse(result1.total); int value = 0; while (temp > 0) { str = str + "&offset=" + value; HttpResponseMessage Res2 = await clientapi1.GetAsync(str); if (Res2.IsSuccessStatusCode) { var EmpResponse2 = Res2.Content.ReadAsStringAsync().Result; var result2 = JsonConvert.DeserializeObject <SearchOutput>(EmpResponse2); if (result2.itemSummaries != null) { foreach (var item in result2.itemSummaries) { var checkProduct = _affiliateEbayService.GetProductBySourceId(productSourceId: item.itemId, source: (int)Source.Ebay); if (checkProduct.Id == 0) { var clientapi = new HttpClient(); clientapi.BaseAddress = new Uri("https://api.ebay.com/"); clientapi.DefaultRequestHeaders.Clear(); clientapi.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); clientapi.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", tokenebay); clientapi.Timeout = TimeSpan.FromMinutes(60); HttpResponseMessage Res = await clientapi.GetAsync("buy/browse/v1/item/" + item.itemId); if (Res.IsSuccessStatusCode) { var EmpResponse = Res.Content.ReadAsStringAsync().Result; var result = JsonConvert.DeserializeObject <ProductModelApi>(EmpResponse); if (result.price != null) { var price = Convert.ToDecimal(result.price.value); var product = new Product(); product.Name = result.title; var currencyService = EngineContext.Current.Resolve <ICurrencyService>(); product.Price = Round(currencyService.ConvertToPrimaryStoreCurrency(price * (1 + mappingSettings.AdditionalCostPercent / 100), currencyService.GetCurrencyByCode("USD")), -3); //if(result.marketingPrice == null) //{ // product.OldPrice = 0; //} //else //{ // if(result.marketingPrice.originalPrice == null) // product.OldPrice = 0; // else // product.OldPrice = Convert.ToDecimal(result.marketingPrice.originalPrice.value); //} product.ShortDescription = result.shortDescription; product.FullDescription = result.description; product.VisibleIndividually = true; product.AllowCustomerReviews = true; product.UnlimitedDownloads = true; product.MaxNumberOfDownloads = 10; product.RecurringCycleLength = 100; product.RecurringTotalCycles = 10; product.RentalPriceLength = 1; product.IsShipEnabled = true; product.NotifyAdminForQuantityBelow = 1; product.StockQuantity = 1000; product.OrderMaximumQuantity = 1000; product.OrderMinimumQuantity = 1; product.CreatedOnUtc = DateTime.UtcNow; product.UpdatedOnUtc = DateTime.UtcNow; _productService.InsertProduct(product); var productMapping = new ProductMapping(); productMapping.ProductSourceId = item.itemId; productMapping.ProductSourceLink = item.itemWebUrl; productMapping.SourceId = (int)Source.Ebay; productMapping.ProductId = product.Id; productMapping.Price = price; _productMappingService.InsertProduct(productMapping); // Thêm hình chính var imageMain = result.image.imageUrl.Split('?')[0]; System.Drawing.Image imageKey = EbayExtensions.DownloadImage(imageMain); if (imageKey != null) { var contentTypeMain = ""; var vendorPictureBinaryMain = EbayExtensions.ImageToByte(imageKey); var fileExtensionMain = Path.GetExtension(imageMain); if (!String.IsNullOrEmpty(fileExtensionMain)) { fileExtensionMain = fileExtensionMain.ToLowerInvariant(); } if (String.IsNullOrEmpty(contentTypeMain)) { switch (fileExtensionMain) { case ".bmp": contentTypeMain = MimeTypes.ImageBmp; break; case ".gif": contentTypeMain = MimeTypes.ImageGif; break; case ".jpeg": case ".jpg": case ".jpe": case ".jfif": case ".pjpeg": case ".pjp": contentTypeMain = MimeTypes.ImageJpeg; break; case ".png": contentTypeMain = MimeTypes.ImagePng; break; case ".tiff": case ".tif": contentTypeMain = MimeTypes.ImageTiff; break; default: break; } } var pictureMain = _pictureService.InsertPicture(vendorPictureBinaryMain, contentTypeMain, null); _productService.InsertProductPicture(new ProductPicture { PictureId = pictureMain.Id, ProductId = product.Id, DisplayOrder = 0, }); } int display = 1; if (result.additionalImages != null) { foreach (var ite in result.additionalImages) { var ima = ite.imageUrl.Split('?')[0]; System.Drawing.Image image = EbayExtensions.DownloadImage(ima); if (image != null) { var contentType = ""; var vendorPictureBinary = EbayExtensions.ImageToByte(image); var fileExtension = Path.GetExtension(ima); if (!String.IsNullOrEmpty(fileExtension)) { fileExtension = fileExtension.ToLowerInvariant(); } if (String.IsNullOrEmpty(contentType)) { switch (fileExtension) { case ".bmp": contentType = MimeTypes.ImageBmp; break; case ".gif": contentType = MimeTypes.ImageGif; break; case ".jpeg": case ".jpg": case ".jpe": case ".jfif": case ".pjpeg": case ".pjp": contentType = MimeTypes.ImageJpeg; break; case ".png": contentType = MimeTypes.ImagePng; break; case ".tiff": case ".tif": contentType = MimeTypes.ImageTiff; break; default: break; } } var picture = _pictureService.InsertPicture(vendorPictureBinary, contentType, null); _productService.InsertProductPicture(new ProductPicture { PictureId = picture.Id, ProductId = product.Id, DisplayOrder = display++, }); } } } //Product specification attributes if (result.localizedAspects != null) { foreach (var attributes in result.localizedAspects) { var getAttribute = _affiliateEbayService.GetSpecificationAttributeByName(attributes.name); var specificationAttribute = new SpecificationAttribute(); var specificationAttributeOption = new SpecificationAttributeOption(); if (getAttribute == null) { specificationAttribute.Name = attributes.name; specificationAttribute.DisplayOrder = 0; _specificationAttributeService.InsertSpecificationAttribute(specificationAttribute); specificationAttributeOption.DisplayOrder = 0; specificationAttributeOption.ColorSquaresRgb = null; specificationAttributeOption.Name = attributes.value; specificationAttributeOption.SpecificationAttributeId = specificationAttribute.Id; _specificationAttributeService.InsertSpecificationAttributeOption(specificationAttributeOption); } var productSpecificationAttribute = new ProductSpecificationAttribute(); productSpecificationAttribute.AttributeTypeId = (int)SpecificationAttributeType.CustomText; if (getAttribute == null) { productSpecificationAttribute.SpecificationAttributeOptionId = specificationAttributeOption.Id; } else { var options = _specificationAttributeService.GetSpecificationAttributeOptionsBySpecificationAttribute(getAttribute.Id); productSpecificationAttribute.SpecificationAttributeOptionId = options.FirstOrDefault().Id; } productSpecificationAttribute.ProductId = product.Id; productSpecificationAttribute.CustomValue = attributes.value; productSpecificationAttribute.AllowFiltering = false; productSpecificationAttribute.ShowOnProductPage = true; productSpecificationAttribute.DisplayOrder = 1; _specificationAttributeService.InsertProductSpecificationAttribute(productSpecificationAttribute); } } //categories SaveCategoryMappings(product, new List <int>() { model.CategoryId }); } } } } } } value = value + 200; temp = temp - 200; } } } SuccessNotification(_localizationService.GetResource("Admin.Catalog.Products.Added")); } else { ErrorNotification(_localizationService.GetResource("Plugins.AffiliateEbay.CallApi.Error")); } return(CallApi()); }
internal static List <SpecificationAttribute> Import(КоммерческаяИнформация source, ISpecificationAttributeService specificationAttributeService, string mappingsFile, out Dictionary <string, int> outMappings, string logFile) { logFile.Log("Начало импорта свойств"); var stats = new[] { 0, 0, 0, 0 }; // attribute: key = 1c id, value = nopcommerce id // attribute value: key = <1c attribute id>.<1c value id>, value = nopcommerce id var mappings = File.Exists(mappingsFile) ? JsonConvert.DeserializeObject <Dictionary <string, int> >(File.ReadAllText(mappingsFile)) : new Dictionary <string, int>();; var attributes = specificationAttributeService.GetSpecificationAttributes().ToList(); foreach (var attr in source.Классификатор.Свойства) { // ищем соответствие только по маппингу // потому что может быть несколько атрибутов с одинаковым названием var attribute = mappings.ContainsKey(attr.Ид) ? attributes.FirstOrDefault(a => a.Id == mappings[attr.Ид]) : null; if (attribute != null) { // для существующего только добавляем новые значения if (attr.ТипЗначений == AttrTypeDictionary) { foreach (var attrOption in attr.ВариантыЗначений) { var key = $"{attr.Ид}.{attrOption.ИдЗначения}"; var option = mappings.ContainsKey(key) ? attribute.SpecificationAttributeOptions.FirstOrDefault(o => o.Id == mappings[key]) : null; if (option == null) { // ищем по имени option = attribute.SpecificationAttributeOptions.FirstOrDefault(o => o.Name == attrOption.Значение); if (option == null) { // добавляем новое значение option = new Core.Domain.Catalog.SpecificationAttributeOption { SpecificationAttributeId = attribute.Id, Name = attrOption.Значение }; specificationAttributeService.InsertSpecificationAttributeOption(option); attribute.SpecificationAttributeOptions.Add(option); //logFile.Log($"В существующий атрибут {attribute.Name} ({attribute.Id}) добавлено значение {option.Name}"); stats[0]++; } else { // мапим существующее значение //logFile.Log($"В существующем атрибуте {attribute.Name} ({attribute.Id}) добавлено сопоставление для значения {option.Name}"); stats[1]++; } mappings[key] = option.Id; } } } continue; } // new attribute attribute = new Core.Domain.Catalog.SpecificationAttribute { Name = attr.Наименование }; specificationAttributeService.InsertSpecificationAttribute(attribute); attributes.Add(attribute); mappings[attr.Ид] = attribute.Id; //logFile.Log($"Новый атрибут {attribute.Name} ({attribute.Id})"); stats[2]++; if (attr.ТипЗначений == AttrTypeDictionary) { foreach (var attrOption in attr.ВариантыЗначений) { var key = $"{attr.Ид}.{attrOption.ИдЗначения}"; var option = new Core.Domain.Catalog.SpecificationAttributeOption { SpecificationAttributeId = attribute.Id, Name = attrOption.Значение }; specificationAttributeService.InsertSpecificationAttributeOption(option); attribute.SpecificationAttributeOptions.Add(option); mappings[key] = option.Id; //logFile.Log($"В новый атрибут {attribute.Name} ({attribute.Id}) добавлено значение {option.Name}"); stats[3]++; } } else { var key = $"{attr.Ид}."; var option = new Core.Domain.Catalog.SpecificationAttributeOption { SpecificationAttributeId = attribute.Id, Name = string.Empty }; specificationAttributeService.InsertSpecificationAttributeOption(option); attribute.SpecificationAttributeOptions.Add(option); mappings[key] = option.Id; } } File.WriteAllText(mappingsFile, JsonConvert.SerializeObject(mappings, Formatting.Indented), Encoding.UTF8); logFile.Log($"Импорт свойств завершен. Привязано: {stats[0]} атрибутов и {stats[1]} значений. Добавлено: {stats[2]} атрибутов и {stats[3]} значений."); outMappings = mappings; return(attributes); }