private void BulkImport(int vendorID, DataSet content, int?parentVendorID, Vendor vendor) { using (var unit = GetUnitOfWork()) { if (content.Tables[0].AsEnumerable().Count() < 1000) { return; } var dataList = (from d in content.Tables[0].AsEnumerable() let DefaultVendorID = parentVendorID.HasValue ? parentVendorID.Value : vendorID select new Concentrator.Objects.Vendors.Bulk.VendorAssortmentBulk.VendorAssortmentItem { #region BrandVendor BrandVendors = new List <VendorAssortmentBulk.VendorImportBrand>() { new VendorAssortmentBulk.VendorImportBrand() { VendorID = DefaultVendorID, VendorBrandCode = VendorImportUtility.SetDataSetValue("Brand", d) ?? string.Empty, ParentBrandCode = null, Name = VendorImportUtility.SetDataSetValue("Brand", d) ?? string.Empty, } }, #endregion #region GeneralProductInfo VendorProduct = new VendorAssortmentBulk.VendorProduct { VendorItemNumber = VendorImportUtility.SetDataSetValue("VendorItemNumber", d), CustomItemNumber = VendorImportUtility.SetDataSetValue("ShortItemNumber", d), ShortDescription = VendorImportUtility.SetDataSetValue("Description1", d), LongDescription = VendorImportUtility.SetDataSetValue("Description2", d), LineType = VendorImportUtility.SetDataSetValue("LineType", d), LedgerClass = d.Table.Columns.Contains("LedgerClass") ? VendorImportUtility.SetDataSetValue("LedgerClass", d) : null, ProductDesk = d.Table.Columns.Contains("ProductDesk") ? VendorImportUtility.SetDataSetValue("ProductDesk", d) : null, ExtendedCatalog = d.Table.Columns.Contains("Extendedcatalog") ? VendorImportUtility.SetDataSetValue("Extendedcatalog", d) : null, VendorID = vendorID, DefaultVendorID = DefaultVendorID, VendorBrandCode = VendorImportUtility.SetDataSetValue("Brand", d), Barcode = VendorImportUtility.SetDataSetValue("Barcode", d), VendorProductGroupCode1 = VendorImportUtility.SetDataSetValue("ProductGroup", d), VendorProductGroupCodeName1 = string.Empty, VendorProductGroupCode2 = VendorImportUtility.SetDataSetValue("ProductSubGroup", d), VendorProductGroupCodeName2 = string.Empty, VendorProductGroupCode3 = VendorImportUtility.SetDataSetValue("ProductSubSubGroup", d), VendorProductGroupCodeName3 = string.Empty, VendorProductGroupCode4 = null, VendorProductGroupCodeName4 = null, VendorProductGroupCode5 = null, VendorProductGroupCodeName5 = null, VendorProductGroupCode6 = null, VendorProductGroupCodeName6 = null, VendorProductGroupCode7 = null, VendorProductGroupCodeName7 = null, VendorProductGroupCode8 = null, VendorProductGroupCodeName8 = null, VendorProductGroupCode9 = null, VendorProductGroupCodeName9 = null, VendorProductGroupCode10 = null, VendorProductGroupCodeName10 = null }, #endregion #region RelatedProducts RelatedProducts = new List <VendorAssortmentBulk.VendorImportRelatedProduct>(), #endregion #region Attribures VendorImportAttributeValues = new List <VendorAssortmentBulk.VendorImportAttributeValue>(), #endregion #region Prices VendorImportPrices = new List <Concentrator.Objects.Vendors.Bulk.VendorAssortmentBulk.VendorImportPrice>() { new Concentrator.Objects.Vendors.Bulk.VendorAssortmentBulk.VendorImportPrice() { VendorID = vendorID, DefaultVendorID = DefaultVendorID, CustomItemNumber = VendorImportUtility.SetDataSetValue("ShortItemNumber", d), Price = VendorImportUtility.SetDataSetValue("UnitPrice", d, "0"), CostPrice = VendorImportUtility.SetDataSetValue("CostPrice", d, "0"), TaxRate = VendorImportUtility.SetDataSetValue("TaxRate", d, "0"), MinimumQuantity = VendorImportUtility.SetDataSetValue("MinimumQuantity", d).Try(x => int.Parse(x) < 0 ? 0 : int.Parse(x), 0), CommercialStatus = VendorImportUtility.SetDataSetValue("CommercialStatus", d, "S") } }, #endregion #region Stock VendorImportStocks = new List <Concentrator.Objects.Vendors.Bulk.VendorAssortmentBulk.VendorImportStock>() { new Concentrator.Objects.Vendors.Bulk.VendorAssortmentBulk.VendorImportStock() { VendorID = vendorID, DefaultVendorID = DefaultVendorID, CustomItemNumber = VendorImportUtility.SetDataSetValue("ShortItemNumber", d), QuantityOnHand = VendorImportUtility.SetDataSetValue("QuantityOnHand", d).Try(x => int.Parse(x), 0), StockType = "Assortment", StockStatus = VendorImportUtility.SetDataSetValue("StockStatus", d) } }, #endregion }); //var dataList = (from d in content.Tables[0].AsEnumerable() // let defaultVendorID = parentVendorID.HasValue ? parentVendorID.Value : vendorID // select new Concentrator.Objects.Vendors.Bulk.VendorAssortmentBulk.VendorAssortmentItem // { // #region BrandVendor // BrandVendors = new List<Concentrator.Objects.Vendors.Bulk.VendorAssortmentBulk.VendorImportBrand>() // { // new Concentrator.Objects.Vendors.Bulk.VendorAssortmentBulk.VendorImportBrand(){ // Name = VendorImportUtility.SetDataSetValue("Brand", d), // VendorBrandCode = VendorImportUtility.SetDataSetValue("Brand", d), // VendorID = defaultVendorID // } // }, // #endregion // #region GeneralProductInfo // VendorProduct = new VendorAssortmentBulk.VendorProduct // { // VendorItemNumber = VendorImportUtility.SetDataSetValue("VendorItemNumber", d), // CustomItemNumber = VendorImportUtility.SetDataSetValue("ShortItemNumber", d), // ShortDescription = VendorImportUtility.SetDataSetValue("Description1", d), // LongDescription = VendorImportUtility.SetDataSetValue("Description2", d), // LineType = VendorImportUtility.SetDataSetValue("LineType", d), // LedgerClass = d.Table.Columns.Contains("LedgerClass") ? VendorImportUtility.SetDataSetValue("LedgerClass", d) : null, // ProductDesk = d.Table.Columns.Contains("ProductDesk") ? VendorImportUtility.SetDataSetValue("ProductDesk", d) : null, // ExtendedCatalog = d.Table.Columns.Contains("Extendedcatalog") ? VendorImportUtility.SetDataSetValue("Extendedcatalog", d) : null, // VendorID = vendorID, // DefaultVendorID = defaultVendorID, // VendorBrandCode = VendorImportUtility.SetDataSetValue("Brand", d), // Barcode = VendorImportUtility.SetDataSetValue("Barcode", d), // VendorProductGroupCode1 = VendorImportUtility.SetDataSetValue("ProductGroup", d), // VendorProductGroupCode2 = VendorImportUtility.SetDataSetValue("ProductSubGroup", d), // VendorProductGroupCode3 = VendorImportUtility.SetDataSetValue("ProductSubSubGroup", d) // }, // // VendorImportPrices = new List<Concentrator.Objects.Vendors.Bulk.VendorAssortmentBulk.VendorImportPrice>() // // { // // new Concentrator.Objects.Vendors.Bulk.VendorAssortmentBulk.VendorImportPrice(){ // // VendorID = vendorID, // // DefaultVendorID = defaultVendorID, // // CustomItemNumber = VendorImportUtility.SetDataSetValue("ShortItemNumber", d), // // Price = d.Field<decimal>("UnitPrice"), // // CostPrice = (d.Table.Columns.Contains("CostPrice") ? d.Field<decimal?>("CostPrice") : 0) ?? 0, // // TaxRate = (decimal)(d.Field<double>("TaxRate")), // // MinimumQuantity = (d.Field<int>("MinimumQuantity") > 0 ? d.Field<int>("MinimumQuantity") : 0), // //CommercialStatus = d.Field<string>("CommercialStatus") // // } // // } // #endregion // }); log.Debug("dataset to object"); string vendorBrandID = vendor.VendorSettings.GetValueByKey("BrandID", string.Empty); if (!string.IsNullOrEmpty(vendorBrandID)) { dataList = dataList.Where(x => x.VendorProduct.VendorBrandCode == vendorBrandID); } using (var vendorAssortmentBulk = new VendorAssortmentBulk(dataList, vendorID, parentVendorID)) { vendorAssortmentBulk.Init(unit.Context); vendorAssortmentBulk.Sync(unit.Context); } } }
public void Process() { var config = GetConfiguration(); //Local directory files var LocalDir = config.AppSettings.Settings["LocalImportDir"].Value; if (!Directory.Exists(LocalDir)) { Directory.CreateDirectory(LocalDir); } #if DEBUG var activeTitlesFile = Path.Combine(LocalDir, "ttlingv2.zip"); var activeTitlesUpdateFile = Path.Combine(LocalDir, "ttladdch.zip"); var annotationsFile = Path.Combine(LocalDir, "antingrm-13.zip"); var seriesFile = Path.Combine(LocalDir, "SERIES.txt"); var categoriesFile = Path.Combine(LocalDir, "catg2.txt"); var familiesFile = Path.Combine(LocalDir, "family-13.zip"); var stockFile = Path.Combine(LocalDir, "*****@*****.**"); #else var Username = config.AppSettings.Settings["FtpUsername"].Value; var Password = config.AppSettings.Settings["FtpPassword"].Value; var FtpUrl = config.AppSettings.Settings["FtpUrl"].Value; FtpManager ftp = new FtpManager(FtpUrl, null, Username, Password, false, true, log); var categoriesFile = ftp.DownloadToDisk(LocalDir, config.AppSettings.Settings["Categories"].Value); var annotationsFile = ftp.DownloadToDisk(LocalDir, config.AppSettings.Settings["Annotations"].Value); var activeTitlesFile = ftp.DownloadToDisk(LocalDir, config.AppSettings.Settings["Titles"].Value); var activeTitlesUpdateFile = ftp.DownloadToDisk(LocalDir, config.AppSettings.Settings["TitlesUpdate"].Value); var seriesFile = ftp.DownloadToDisk(LocalDir, config.AppSettings.Settings["Series"].Value); var familiesFile = ftp.DownloadToDisk(LocalDir, config.AppSettings.Settings["Familys"].Value); var stockFile = ftp.DownloadToDisk(LocalDir, config.AppSettings.Settings["Stock"].Value); #endif var VendorID = Int32.Parse(config.AppSettings.Settings["VendorID"].Value); var DefaultVendorID = Int32.Parse(config.AppSettings.Settings["VendorID"].Value); // var ftp.OpenFile( using (var unit = GetUnitOfWork()) { #region Setup List <ProductAttributeMetaData> attributes; SetupAttributes(unit, AttributeMapping, out attributes, null); var productAttributes = unit.Scope.Repository <ProductAttributeMetaData>().GetAll(c => c.VendorID == DefaultVendorID).ToList(); var attributeList = productAttributes.ToDictionary(x => x.AttributeCode, y => y.AttributeID); #endregion try { #if !DEBUG FileStream activeFiles_Stream = File.Open(activeTitlesFile, FileMode.Open, FileAccess.Read, FileShare.None); var assortmentFile = Unzip(activeFiles_Stream, LocalDir, "ttlingv2.txt"); FileStream annotations_Stream = File.Open(annotationsFile, FileMode.Open, FileAccess.Read, FileShare.None); var annotations = Unzip(annotations_Stream, LocalDir, "ANTINGRM.TXT"); FileStream fam_Stream = File.Open(familiesFile, FileMode.Open, FileAccess.Read, FileShare.None); var families = Unzip(fam_Stream, LocalDir, "FAMILY-13.DAT"); FileStream stock_Stream = File.Open(stockFile, FileMode.Open, FileAccess.Read, FileShare.None); var stocks = Unzip(stock_Stream, LocalDir, "*****@*****.**"); #else var assortmentFile = @"G:\Ingram\Import\ttlingv2.txt"; var annotations = @"G:\Ingram\Import\ANTINGRM.TXT"; var families = @"G:\Ingram\Import\FAMILY-13.DAT"; var stocks = @"G:\Ingram\Import\[email protected]"; #endif #region Assortment var assortment = (from a in ReadFrom(assortmentFile) where a.Length > 400 select new Concentrator.Objects.Vendors.Bulk.VendorAssortmentBulk.VendorAssortmentItem { #region BrandVendor BrandVendors = new List <VendorAssortmentBulk.VendorImportBrand>() { new VendorAssortmentBulk.VendorImportBrand() { VendorID = DefaultVendorID, VendorBrandCode = a.Substring(225, 40).Trim(), //UITGEVER_ID ParentBrandCode = null, Name = a.Substring(225, 40).Trim() //row["Publisher Imprint"].ToString().Trim() //UITGEVER_NM } }, #endregion #region GeneralProductInfo VendorProduct = new VendorAssortmentBulk.VendorProduct { VendorItemNumber = a.Substring(442, 17).Trim(), //EAN CustomItemNumber = a.Substring(442, 17).Trim(), //EAN ShortDescription = a.Substring(161, 30).Trim(), //ShortTitle LongDescription = "", LineType = null, LedgerClass = null, ProductDesk = null, ExtendedCatalog = null, VendorID = VendorID, DefaultVendorID = DefaultVendorID, VendorBrandCode = a.Substring(225, 40).Trim(), //Contributor 1 Barcode = a.Substring(442, 17).Trim(), //EAN VendorProductGroupCode1 = a.Substring(212, 9).Trim(), //Series ID VendorProductGroupCodeName1 = string.Empty, //a.Substring(221, 4).Trim(),//series number VendorProductGroupCode2 = a.Substring(459, 4).Trim(), // Ingram subject VendorProductGroupCodeName2 = "" //GEEN NAAM }, #endregion #region RelatedProducts RelatedProducts = new List <VendorAssortmentBulk.VendorImportRelatedProduct>(), //getRelatedProducts(row, families, VendorID), #endregion #region Attributes VendorImportAttributeValues = new List <VendorAssortmentBulk.VendorImportAttributeValue>(), #endregion #region Images VendorImportImages = new List <VendorAssortmentBulk.VendorImportImage>(), #endregion #region Prices VendorImportPrices = new List <Concentrator.Objects.Vendors.Bulk.VendorAssortmentBulk.VendorImportPrice>() { new Concentrator.Objects.Vendors.Bulk.VendorAssortmentBulk.VendorImportPrice() { VendorID = VendorID, DefaultVendorID = DefaultVendorID, CustomItemNumber = a.Substring(442, 17).Trim(), //EAN Price = "0", //row.Price.ToString().Trim(), //ADVIESPRIJS CostPrice = "0", //row.Price.ToString().Trim(), //NETTOPRIJS TaxRate = "19", //TODO: Calculate this! MinimumQuantity = 0, CommercialStatus = "" //STADIUM_LEVENSCYCLUS_KD } }, #endregion #region Stock VendorImportStocks = new List <Concentrator.Objects.Vendors.Bulk.VendorAssortmentBulk.VendorImportStock>() { new Concentrator.Objects.Vendors.Bulk.VendorAssortmentBulk.VendorImportStock() { VendorID = VendorID, DefaultVendorID = DefaultVendorID, CustomItemNumber = a.Substring(442, 17).Trim(), //EAN QuantityOnHand = 0, StockType = "Assortment", StockStatus = ""//GetProductStatusName(row.Price["Publisher Status Code"].ToString().Trim())//STADIUM_LEVENSCYCLUS_KD } }, #endregion }).Take(100000); using (VendorAssortmentBulk bulkExport = new VendorAssortmentBulk(assortment, VendorID, DefaultVendorID)) { bulkExport.IncludeBrandMapping = true; bulkExport.Init(unit.Context); bulkExport.Sync(unit.Context); } #endregion #region RawBulk var Description = (from r in ReadFrom(annotations) select new tempDescriptionsModel { EAN = r.Substring(0, 12).Trim(), Text = r.Substring(15).Trim() }); var Category = (from r in ReadFrom(categoriesFile) select new tempCategoriesModel { IngramSubjectCode = r.Substring(1, 4).Trim(), IngramSubjectDescription = r.Substring(8, 59).Trim() }); var RelatedProduct = (from r in ReadFrom(families) select new tempRelatedProductsModel { EAN = r.Substring(0, 12).Trim(), FamilyID = r.Substring(13, 7).Trim(), ItemID = r.Substring(20, 3).Trim() }); var Series = (from r in ReadFrom(seriesFile) select new tempSeriesModel { SeriesID = r.Substring(1, 9).Trim(), Text = r.Substring(13).Replace('"', ' ') }); var StockandPrice = (from r in ReadFrom(stocks) select new tempStockandPriceModel { EAN = r.Substring(1, 13), Price = ((Int32.Parse(r.Substring(150, 7)) * 0.75) / 100).ToString("0.00", CultureInfo.InvariantCulture), CostPrice = ((Int32.Parse(r.Substring(157, 7)) * 0.75) / 100).ToString("0.00", CultureInfo.InvariantCulture), QuantityOnHand = (Int32.Parse(r.Substring(38, 7).Trim()) + Int32.Parse(r.Substring(45, 7).Trim()) + Int32.Parse(r.Substring(52, 7).Trim()) + Int32.Parse(r.Substring(59, 7).Trim())).ToString(), CommercialStatus = GetProductStatusName(r.Substring(178, 2).ToString().Trim()) }); var rawDate = new RawBulkModel() { Categories = Category, Descriptions = Description, RelatedProducts = RelatedProduct, Series = Series, StockandPrice = StockandPrice }; using (RawBulk rawbulk = new RawBulk(rawDate, VendorID)) { rawbulk.Init(unit.Context); rawbulk.Sync(unit.Context); } #endregion } catch (Exception ex) { } } }
private Boolean ProcessPricatLines(Vendor vendor, IEnumerable <PricatLine> pricatLines) { var noneMappableSizes = pricatLines .Select(pricatLine => new { BrandCode = pricatLine.Brand, ModelName = pricatLine.Model, GroupCode = pricatLine.ArticleGroupCode, Size = pricatLine.SizeSupplier }) .Distinct() .Where(item => TranslateSize(item.BrandCode, item.ModelName, item.GroupCode, item.Size) == null) .ToArray(); if (noneMappableSizes.Any()) { foreach (var noneMappableSize in noneMappableSizes) { TraceWarning("The combination Brand: '{0}', Model: '{1}' (or empty), Group: '{2}' (or empty), Size: '{3}' does not exists." , noneMappableSize.BrandCode , noneMappableSize.ModelName , noneMappableSize.GroupCode , noneMappableSize.Size); } return(false); } var noneMappableColors = pricatLines .Select(pricatLine => pricatLine.ColorCode) .Distinct() .Where(colorCode => !PricatColorMapping.ContainsKey(colorCode)) .ToArray(); if (noneMappableColors.Any()) { foreach (var noneMappableColor in noneMappableColors) { TraceWarning("The color code '{0}' is not mapped to color filter.", noneMappableColor); } return(false); } var existBarcodes = ( from pricat in pricatLines join currentBarcode in Unit.Scope.Repository <ProductBarcode>().GetAll() on pricat.ArticleID equals currentBarcode.Barcode where String.Join(" ", pricat.SupplierCode , pricat.ColorCode , _pricatLineProcessor.TranslateSize(PricatSizes, pricat.Brand, pricat.Model, pricat.ArticleGroupCode, pricat.SizeSupplier) .Trim()) != currentBarcode.Product.VendorItemNumber select new { pricatBarcode = pricat.ArticleID, pricatSku = String.Join(" ", pricat.SupplierCode , pricat.ColorCode , _pricatLineProcessor.TranslateSize(PricatSizes, pricat.Brand, pricat.Model, pricat.ArticleGroupCode, pricat.SizeSupplier).Trim()) , currentSku = currentBarcode.Product.VendorItemNumber } ) .ToArray(); if (existBarcodes.Any()) { foreach (var item in existBarcodes) { TraceWarning( "Error during processing Pricat File, Barcode '{0}' mapped to sku '{1}' in file '{2}' already exists within the Concentrator. It is currently mapped to sku '{3}'" , item.pricatBarcode , item.pricatSku , _currentRemoteFileName , item.currentSku); } return(false); } var vendorAssortmentItems = new List <VendorAssortmentBulk.VendorAssortmentItem>(); foreach (var pricatLineGroup in pricatLines .GroupBy(pricatLine => String.Join(" ", pricatLine.SupplierCode, pricatLine.ColorCode)) .Where(pricatLineGroup => pricatLineGroup.Any())) { var productGroupCode = pricatLineGroup.Select(pricatLine => pricatLine.ArticleGroupCode).First(); foreach ( var vendorAssortmentItem in _pricatLineProcessor.ProcessPricatGroupedLines(Unit, TraceSource, vendor, pricatLineGroup.Key, DefaultLanguage, pricatLineGroup.OrderBy(line => line.Number), ProductAttributes, PricatColorMapping, PricatSizes)) { vendorAssortmentItems.Add(vendorAssortmentItem); } } TraceVerbose("Bulk importing {0} products...", vendorAssortmentItems.Count); try { var bulkConfig = new VendorAssortmentBulkConfiguration { IsPartialAssortment = true }; using (var vendorAssortmentBulk = new VendorAssortmentBulk(vendorAssortmentItems, vendor.VendorID, DefaultVendor.VendorID, bulkConfig)) { vendorAssortmentBulk.Init(Unit.Context); vendorAssortmentBulk.Sync(Unit.Context); } } catch (SqlException exception) { TraceError("Failed to bulk import the products. {0}", exception.Message); return(false); } catch (Exception exception) { TraceError("Failed to bulk import the products. {0}", exception.Message); return(false); } return(true); }
private void ParseDocuments(Objects.DataAccess.UnitOfWork.IUnitOfWork unit, XDocument[] products, XDocument cont) { #region Xml Data //products = new XDocument[1]; //products[0] = XDocument.Load(@"C:\Lenmar\test.xml"); log.AuditInfo("Start parsing items"); var itemContent = (from content in cont.Root.Elements("item") let atts = 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 = atts }).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(); log.AuditInfo("Finished parsing items"); #endregion SetupAttributes(unit, AttributeMapping.ToArray(), out attributes, VendorID); //Used for VendorImportAttributeValues var productAttributes = unit.Scope.Repository <ProductAttributeMetaData>().GetAll(c => c.VendorID == VendorID).ToList(); attributeList = productAttributes.ToDictionary(x => x.AttributeCode, y => y.AttributeID); List <Concentrator.Objects.Vendors.Bulk.VendorAssortmentBulk.VendorAssortmentItem> assortmentList = new List <Concentrator.Objects.Vendors.Bulk.VendorAssortmentBulk.VendorAssortmentItem>(); int counter = 0; int total = itemProducts.Count(); int totalNumberOfProductsToProcess = total; log.InfoFormat("Start processing {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++; var assortment = new Concentrator.Objects.Vendors.Bulk.VendorAssortmentBulk.VendorAssortmentItem { #region BrandVendor BrandVendors = new List <VendorAssortmentBulk.VendorImportBrand>() { new VendorAssortmentBulk.VendorImportBrand() { VendorID = VendorID, VendorBrandCode = product.VendorBrandCode.Trim(), ParentBrandCode = null, Name = product.VendorBrandCode.Trim() } }, #endregion #region GeneralProductInfo VendorProduct = new VendorAssortmentBulk.VendorProduct { VendorItemNumber = product.SupplierSKU.Trim(), //EAN CustomItemNumber = product.CustomItemNr.Trim(), //EAN ShortDescription = product.ShortDescription.Length > 150 ? product.ShortDescription.Substring(0, 150) : product.ShortDescription, LongDescription = "", LineType = null, LedgerClass = null, ProductDesk = null, ExtendedCatalog = null, VendorID = VendorID, DefaultVendorID = DefaultVendorID, VendorBrandCode = product.VendorBrandCode.Trim(), //UITGEVER_ID Barcode = product.Try(x => x.Barcode, string.Empty), //EAN VendorProductGroupCode1 = string.IsNullOrEmpty(product.VendorProductGroupCode1) ? "Battery" : product.VendorProductGroupCode1, VendorProductGroupCodeName1 = product.VendorName, VendorProductGroupCode2 = !string.IsNullOrEmpty(product.VendorProductGroupCode2) ? product.VendorProductGroupCode2 : null, VendorProductGroupCodeName2 = product.VendorName, VendorProductGroupCode3 = !string.IsNullOrEmpty(product.VendorProductGroupCode3) ? product.VendorProductGroupCode3 : null, VendorProductGroupCodeName3 = product.VendorName, VendorProductGroupCode4 = !string.IsNullOrEmpty(product.VendorProductGroupCode4) ? product.VendorProductGroupCode4 : null, VendorProductGroupCodeName4 = product.VendorName, VendorProductGroupCode5 = !string.IsNullOrEmpty(product.VendorBrandCode) ? product.VendorBrandCode : null, VendorProductGroupCodeName5 = product.VendorName }, #endregion #region RelatedProducts RelatedProducts = new List <VendorAssortmentBulk.VendorImportRelatedProduct>() { }, #endregion #region Attributes VendorImportAttributeValues = (from content in itemContent.Where(x => x.LenmarSKU == product.SupplierSKU) from att in content.dynamic let attributeID = attributeList.ContainsKey(att.Name.ToString()) ? attributeList[att.Name.ToString()] : -1 let value = att.Value.ToString() where !string.IsNullOrEmpty(value) select new Concentrator.Objects.Vendors.Bulk.VendorAssortmentBulk.VendorImportAttributeValue { VendorID = VendorID, DefaultVendorID = DefaultVendorID, CustomItemNumber = product.CustomItemNr.Trim(), //EAN AttributeID = attributeID, Value = value, LanguageID = "1", AttributeCode = att.Name.ToString(), }).ToList(), #endregion #region Prices VendorImportPrices = new List <Concentrator.Objects.Vendors.Bulk.VendorAssortmentBulk.VendorImportPrice>() { new Concentrator.Objects.Vendors.Bulk.VendorAssortmentBulk.VendorImportPrice() { VendorID = VendorID, DefaultVendorID = DefaultVendorID, CustomItemNumber = product.CustomItemNr.Trim(), //EAN Price = (Decimal.Parse(product.Price) / 119).ToString("0.00", CultureInfo.InvariantCulture), CostPrice = (Decimal.Parse(product.CostPrice) / 100).ToString("0.00", CultureInfo.InvariantCulture), //NETTOPRIJS TaxRate = "19", MinimumQuantity = 0, CommercialStatus = product.Status } }, #endregion #region Stock VendorImportStocks = new List <Concentrator.Objects.Vendors.Bulk.VendorAssortmentBulk.VendorImportStock>() { new Concentrator.Objects.Vendors.Bulk.VendorAssortmentBulk.VendorImportStock() { VendorID = VendorID, DefaultVendorID = DefaultVendorID, CustomItemNumber = product.CustomItemNr.Trim(), //EAN QuantityOnHand = int.Parse(product.QuantityOnHand), StockType = "Assortment", StockStatus = product.Status } }, #endregion #region Descriptions VendorProductDescriptions = new List <VendorAssortmentBulk.VendorProductDescription>() { new VendorAssortmentBulk.VendorProductDescription() { VendorID = VendorID, LanguageID = languageID, DefaultVendorID = VendorID, CustomItemNumber = product.CustomItemNr.Trim(), //EAN LongContentDescription = string.Empty, ShortContentDescription = product.ShortContentDescription != string.Empty ? product.ShortContentDescription.Length > 1000 ?product.ShortContentDescription.Substring(0, 1000) : product.ShortContentDescription : product.ShortDescription, ProductName = product.ShortDescription } } #endregion }; // assortment will be added to the list defined outside of this loop assortmentList.Add(assortment); } // Creates a new instance of VendorAssortmentBulk(Passes in the AssortmentList defined above, vendorID and DefaultVendorID) using (var vendorAssortmentBulk = new VendorAssortmentBulk(assortmentList, VendorID, DefaultVendorID)) { vendorAssortmentBulk.Init(unit.Context); vendorAssortmentBulk.Sync(unit.Context); } }
protected override void Process() { var defaultVendorIDSetting = GetConfiguration().AppSettings.Settings["VendorID"]; if (defaultVendorIDSetting == null) { throw new Exception("Setting VendorID is missing"); } DefaultVendorID = Int32.Parse(defaultVendorIDSetting.Value); var vendorIdsToProcess = GetConfiguration().AppSettings.Settings["VendorIDs"]; if (vendorIdsToProcess == null) { throw new Exception("Setting VendorIDs is missing"); } _vendorIDs = vendorIdsToProcess.Value.Split(',').Select(x => Convert.ToInt32(x)).ToArray(); var attributes = new List <ProductAttributeMetaData>(); using (var unit = GetUnitOfWork()) { try { InitAttributeMapping(); SetupAttributes(unit, _attributeMapping, DefaultVendorID, out attributes); } catch (Exception e) { log.Debug(e.InnerException); } foreach (var vendorID in _vendorIDs) { _configuredAttributes = new Dictionary <string, List <string> >(); var repositoryProductTypes = new ProductTypeRepository((IServiceUnitOfWork)unit, DefaultVendorID); var repositoryModels = new ProductModelRepository((IServiceUnitOfWork)unit, DefaultVendorID); bool useAdvicePrice = false; var useAdvicePriceSetting = unit.Scope.Repository <VendorSetting>().GetSingle(c => c.VendorID == vendorID && c.SettingKey == USE_ADVICE_PRICE_FROM_XML_SETTING_KEY); if (useAdvicePriceSetting != null) { bool.TryParse(useAdvicePriceSetting.Value, out useAdvicePrice); } var ReturnCostsVendorItemNumber = unit.Scope.Repository <VendorSetting>().GetSingle(c => c.VendorID == vendorID && c.SettingKey == "ReturnCostsProduct"); if (ReturnCostsVendorItemNumber != null) { ReturnVendorItemNumber = ReturnCostsVendorItemNumber.Value; } var ShipmentCostsVendorItemNumber = unit.Scope.Repository <VendorSetting>().GetSingle(c => c.VendorID == vendorID && c.SettingKey == "ShipmentCostsProduct"); if (ShipmentCostsVendorItemNumber != null) { ShipmentVendorItemNumber = ShipmentCostsVendorItemNumber.Value; } foreach (var attributeMapping in _attributeMapping) { attributeMapping.VendorID = vendorID; } var xmlAssortmentRepository = new XmlAssortmentRepository(vendorID, unit, log); foreach (var assortment in xmlAssortmentRepository.GetAssortment(vendorID)) { var assortmentList = new List <VendorAssortmentBulk.VendorAssortmentItem>(); var stockPerProduct = (from p in unit.Scope.Repository <Product>().GetAll(c => c.SourceVendorID == vendorID) let stock = p.VendorStocks.FirstOrDefault(c => c.VendorID == vendorID) where stock != null select new { p.VendorItemNumber, stock.QuantityOnHand }).ToDictionary(c => c.VendorItemNumber, c => c.QuantityOnHand); var productGroup = assortment.Assortments.GroupBy(c => c.ConfigurableVendorItemNumber).ToList(); foreach (var configurableProductGroup in productGroup) { var first = configurableProductGroup.First(); var isConfigurableProductAWebsiteProduct = configurableProductGroup.Select(x => x.Website).Contains("WEB"); var type = first.TypeCode; var typeObject = repositoryProductTypes.Get(type); var modelObject = repositoryModels.Get(first.ModelCode); #region "Configurable Product" var configurableProduct = new VendorAssortmentBulk.VendorAssortmentItem(); if (first.ConfigurableVendorItemNumber != ShipmentVendorItemNumber && first.ConfigurableVendorItemNumber != ReturnVendorItemNumber) { #region BrandVendor configurableProduct.BrandVendors = new List <VendorAssortmentBulk.VendorImportBrand>() { new VendorAssortmentBulk.VendorImportBrand() { VendorID = DefaultVendorID, VendorBrandCode = first.Brand, Name = first.Brand } }; #endregion #region GeneralProductInfo configurableProduct.VendorProduct = new VendorAssortmentBulk.VendorProduct { VendorID = vendorID, DefaultVendorID = DefaultVendorID, CustomItemNumber = configurableProductGroup.Key, VendorItemNumber = configurableProductGroup.Key, VendorBrandCode = first.Brand, IsConfigurable = 1, VendorProductGroupCode1 = first.ProductGroupCode1, VendorProductGroupCodeName1 = first.ProductGroupCode1, VendorProductGroupCode2 = first.ProductGroupCode2, VendorProductGroupCodeName2 = first.ProductGroupCode2, VendorProductGroupCode3 = first.ProductGroupCode3, VendorProductGroupCodeName3 = first.ProductGroupCode3, VendorProductGroupCode4 = first.Brand, VendorProductGroupCodeName4 = first.Brand, ShortDescription = first.ShortDescription, LongDescription = first.LongDescription, Barcode = String.Empty }; #endregion #region ProductDescription configurableProduct.VendorProductDescriptions = new List <VendorAssortmentBulk.VendorProductDescription>() { new Concentrator.Objects.Vendors.Bulk.VendorAssortmentBulk.VendorProductDescription() { VendorID = vendorID, DefaultVendorID = DefaultVendorID, CustomItemNumber = first.ConfigurableVendorItemNumber, LanguageID = 1, ProductName = first.ShortDescription, ShortContentDescription = first.ShortDescription, LongContentDescription = first.LongDescription } }; #endregion #region Attributes configurableProduct.VendorImportAttributeValues = new List <VendorAssortmentBulk.VendorImportAttributeValue>() { new VendorAssortmentBulk.VendorImportAttributeValue() { AttributeCode = "Season", Value = first.ProductGroupCode2, AttributeID = attributes.FirstOrDefault(c => c.AttributeCode == "Season").AttributeID, CustomItemNumber = first.ConfigurableVendorItemNumber, DefaultVendorID = DefaultVendorID, LanguageID = null, VendorID = ConcentratorVendorID }, new Concentrator.Objects.Vendors.Bulk.VendorAssortmentBulk.VendorImportAttributeValue() { AttributeCode = "IsBra", Value = typeObject == null ? "false" : typeObject.IsBra.ToString(), AttributeID = attributes.FirstOrDefault(c => c.AttributeCode == "IsBra").AttributeID, CustomItemNumber = first.ConfigurableVendorItemNumber, DefaultVendorID = DefaultVendorID, LanguageID = null, VendorID = ConcentratorVendorID }, new Concentrator.Objects.Vendors.Bulk.VendorAssortmentBulk.VendorImportAttributeValue() { AttributeCode = "Group", Value = typeObject == null ? type : typeObject.ProductType.ToString(), AttributeID = attributes.FirstOrDefault(c => c.AttributeCode == "Group").AttributeID, CustomItemNumber = first.ConfigurableVendorItemNumber, DefaultVendorID = DefaultVendorID, LanguageID = null, VendorID = ConcentratorVendorID } }; #region ProductType Translation Attributes if (typeObject != null) //add translations { foreach (var translation in typeObject.Translations) { configurableProduct.VendorImportAttributeValues.Add(new VendorAssortmentBulk.VendorImportAttributeValue { AttributeCode = "Type", Value = translation.Value, AttributeID = attributes.FirstOrDefault(c => c.AttributeCode == "Type").AttributeID, CustomItemNumber = first.ConfigurableVendorItemNumber, DefaultVendorID = DefaultVendorID, LanguageID = translation.Key.ToString(), VendorID = ConcentratorVendorID }); } } #endregion #region Model Translation if (modelObject != null) { configurableProduct.VendorImportAttributeValues.Add(new Concentrator.Objects.Vendors.Bulk.VendorAssortmentBulk.VendorImportAttributeValue() { AttributeCode = "Model", Value = modelObject.Translation, AttributeID = attributes.FirstOrDefault(c => c.AttributeCode == "Model").AttributeID, CustomItemNumber = first.ConfigurableVendorItemNumber, DefaultVendorID = DefaultVendorID, LanguageID = null, VendorID = ConcentratorVendorID }); } #endregion #endregion #region Prices configurableProduct.VendorImportPrices = new List <Concentrator.Objects.Vendors.Bulk.VendorAssortmentBulk.VendorImportPrice>() { new Concentrator.Objects.Vendors.Bulk.VendorAssortmentBulk.VendorImportPrice() { VendorID = vendorID, DefaultVendorID = DefaultVendorID, CustomItemNumber = configurableProductGroup.Key, CommercialStatus = isConfigurableProductAWebsiteProduct ? "Active" : "Non-Web", Price = "0" } }; #endregion #region VendorStock configurableProduct.VendorImportStocks = new List <VendorAssortmentBulk.VendorImportStock>() { new VendorAssortmentBulk.VendorImportStock() { VendorID = vendorID, DefaultVendorID = DefaultVendorID, CustomItemNumber = configurableProductGroup.Key, StockType = "Webshop", StockStatus = "NonStock" } }; #endregion assortmentList.Add(configurableProduct); configurableProduct.RelatedProducts = new List <VendorAssortmentBulk.VendorImportRelatedProduct>(); var otherProductsFromModel = assortment.Assortments.Where(c => c.ModelCode == first.ModelCode && c.TypeCode != first.ModelCode) .Select(c => c.ConfigurableVendorItemNumber) .Distinct() .ToList(); var otherProductsFromModelAndSameType = new List <string>(); var otherProductsFromModelAndDifferentType = new List <string>(); foreach (var product in otherProductsFromModel) { //var typeRelated = product.Split(new char[] {'-'}, StringSplitOptions.RemoveEmptyEntries)[1]; var typeObjectRelated = repositoryProductTypes.Get(type); if (typeObjectRelated != null && typeObject != null) { if (typeObjectRelated.IsBra == typeObject.IsBra) { otherProductsFromModelAndSameType.Add(product); } else { otherProductsFromModelAndDifferentType.Add(product); } } } foreach (var relatedFromType in otherProductsFromModelAndSameType) { configurableProduct.RelatedProducts.Add(new VendorAssortmentBulk.VendorImportRelatedProduct() { CustomItemNumber = configurableProductGroup.Key, DefaultVendorID = DefaultVendorID, VendorID = vendorID, RelatedCustomItemNumber = relatedFromType, IsConfigured = 0, RelatedProductType = "ModelType" }); } foreach (var relatedFromType in otherProductsFromModelAndDifferentType) { configurableProduct.RelatedProducts.Add(new VendorAssortmentBulk.VendorImportRelatedProduct() { CustomItemNumber = configurableProductGroup.Key, DefaultVendorID = DefaultVendorID, VendorID = vendorID, RelatedCustomItemNumber = relatedFromType, IsConfigured = 0, RelatedProductType = "ModelTypeCross" }); } } #endregion var isBra = typeObject != null && typeObject.IsBra; foreach (var simpleItem in configurableProductGroup) { var cupsizeProduct = false; #region "Simple Product" var simpleProduct = new VendorAssortmentBulk.VendorAssortmentItem(); #region "Brand" simpleProduct.BrandVendors = new List <VendorAssortmentBulk.VendorImportBrand>() { new VendorAssortmentBulk.VendorImportBrand() { VendorID = DefaultVendorID, VendorBrandCode = simpleItem.Brand, Name = simpleItem.Brand } }; #endregion #region "Vendor Product" simpleProduct.VendorProduct = new VendorAssortmentBulk.VendorProduct { VendorID = vendorID, DefaultVendorID = DefaultVendorID, CustomItemNumber = simpleItem.SimpleVendorItemNumber, VendorItemNumber = simpleItem.SimpleVendorItemNumber, VendorBrandCode = first.Brand, IsConfigurable = 0, VendorProductGroupCode1 = simpleItem.ProductGroupCode1, VendorProductGroupCodeName1 = simpleItem.ProductGroupCode1, VendorProductGroupCode2 = simpleItem.ProductGroupCode2, VendorProductGroupCodeName2 = simpleItem.ProductGroupCode2, VendorProductGroupCode3 = simpleItem.ProductGroupCode3, VendorProductGroupCodeName3 = simpleItem.ProductGroupCode3, VendorProductGroupCode4 = first.Brand, VendorProductGroupCodeName4 = first.Brand, ShortDescription = simpleItem.ShortDescription, LongDescription = simpleItem.LongDescription, Barcode = simpleItem.Barcode, ParentProductCustomItemNumber = configurableProductGroup.Key }; #endregion #region "Product Description" simpleProduct.VendorProductDescriptions = new List <VendorAssortmentBulk.VendorProductDescription>() { new Concentrator.Objects.Vendors.Bulk.VendorAssortmentBulk.VendorProductDescription() { VendorID = vendorID, DefaultVendorID = DefaultVendorID, CustomItemNumber = simpleItem.SimpleVendorItemNumber, LanguageID = 1, ProductName = simpleItem.ShortDescription, ShortContentDescription = simpleItem.ShortDescription, LongContentDescription = simpleItem.LongDescription } }; #endregion #region "Attribute" simpleProduct.VendorImportAttributeValues = new List <VendorAssortmentBulk.VendorImportAttributeValue>() { new Concentrator.Objects.Vendors.Bulk.VendorAssortmentBulk.VendorImportAttributeValue() { AttributeCode = "Color", Value = simpleItem.ColourcodeSupplier, AttributeID = attributes.FirstOrDefault(c => c.AttributeCode == "Color").AttributeID, CustomItemNumber = simpleItem.SimpleVendorItemNumber, DefaultVendorID = DefaultVendorID, LanguageID = null, VendorID = ConcentratorVendorID }, new Concentrator.Objects.Vendors.Bulk.VendorAssortmentBulk.VendorImportAttributeValue() { AttributeCode = "Group", Value = typeObject == null ? type : typeObject.ProductType.ToString(), AttributeID = attributes.FirstOrDefault(c => c.AttributeCode == "Group").AttributeID, CustomItemNumber = simpleItem.SimpleVendorItemNumber, DefaultVendorID = DefaultVendorID, LanguageID = null, VendorID = ConcentratorVendorID } }; if (!string.IsNullOrEmpty(simpleItem.SubsizeSupplier)) { simpleProduct.VendorImportAttributeValues.Add(new VendorAssortmentBulk.VendorImportAttributeValue() { AttributeCode = "Size", Value = string.Format("{0}{1}", simpleItem.SizeSupplier, simpleItem.SubsizeSupplier), AttributeID = attributes.FirstOrDefault(c => c.AttributeCode == "Size").AttributeID, CustomItemNumber = simpleItem.SimpleVendorItemNumber, DefaultVendorID = DefaultVendorID, LanguageID = null, VendorID = ConcentratorVendorID }); cupsizeProduct = true; } else { simpleProduct.VendorImportAttributeValues.Add(new VendorAssortmentBulk.VendorImportAttributeValue() { AttributeCode = "Size", Value = simpleItem.SizeSupplier, AttributeID = attributes.FirstOrDefault(c => c.AttributeCode == "Size").AttributeID, CustomItemNumber = simpleItem.SimpleVendorItemNumber, DefaultVendorID = DefaultVendorID, LanguageID = null, VendorID = ConcentratorVendorID }); } if (isBra) { simpleProduct.VendorImportAttributeValues.Add(new VendorAssortmentBulk.VendorImportAttributeValue() { AttributeCode = "TopSize", Value = string.Format("{0}{1}", simpleItem.SizeSupplier, simpleItem.SubsizeSupplier), AttributeID = attributes.FirstOrDefault(c => c.AttributeCode == "TopSize").AttributeID, CustomItemNumber = simpleItem.SimpleVendorItemNumber, DefaultVendorID = DefaultVendorID, // 50 LanguageID = null, VendorID = ConcentratorVendorID // 48 }); } else { simpleProduct.VendorImportAttributeValues.Add(new VendorAssortmentBulk.VendorImportAttributeValue() { AttributeCode = "BottomSize", Value = simpleItem.SizeSupplier, AttributeID = attributes.FirstOrDefault(c => c.AttributeCode == "BottomSize").AttributeID, CustomItemNumber = simpleItem.SimpleVendorItemNumber, DefaultVendorID = DefaultVendorID, // 50 LanguageID = null, VendorID = ConcentratorVendorID // 48 }); } #endregion #region "Price" simpleProduct.VendorImportPrices = new List <Concentrator.Objects.Vendors.Bulk.VendorAssortmentBulk.VendorImportPrice>() { new Concentrator.Objects.Vendors.Bulk.VendorAssortmentBulk.VendorImportPrice() { VendorID = vendorID, DefaultVendorID = DefaultVendorID, CustomItemNumber = simpleItem.SimpleVendorItemNumber, CommercialStatus = simpleItem.Website.Equals("WEB") ? "Active" : "Non-Web", Price = (useAdvicePrice ? simpleItem.AdvicePrice : simpleItem.LabellingPrice).ToString(CultureInfo.InvariantCulture), CostPrice = (useAdvicePrice ? simpleItem.AdvicePrice : simpleItem.LabellingPrice).ToString(CultureInfo.InvariantCulture) } }; #endregion #region "Stock" if (!stockPerProduct.ContainsKey(simpleItem.SimpleVendorItemNumber)) { simpleProduct.VendorImportStocks = new List <VendorAssortmentBulk.VendorImportStock>() { new VendorAssortmentBulk.VendorImportStock() { VendorID = vendorID, DefaultVendorID = DefaultVendorID, CustomItemNumber = simpleItem.SimpleVendorItemNumber, StockType = "Webshop", StockStatus = "ENA" } }; } else { simpleProduct.VendorImportStocks = new List <VendorAssortmentBulk.VendorImportStock>(); } #endregion assortmentList.Add(simpleProduct); if (first.ConfigurableVendorItemNumber != ShipmentVendorItemNumber && first.ConfigurableVendorItemNumber != ReturnVendorItemNumber) { configurableProduct.RelatedProducts.Add(new VendorAssortmentBulk.VendorImportRelatedProduct() { CustomItemNumber = first.ConfigurableVendorItemNumber, DefaultVendorID = DefaultVendorID, IsConfigured = 1, VendorID = vendorID, RelatedCustomItemNumber = simpleItem.SimpleVendorItemNumber, RelatedProductType = "Configured product" }); AddConfiguredAttributes(configurableProduct, cupsizeProduct); } #endregion } } try { var bulkConfig = new VendorAssortmentBulkConfiguration { IsPartialAssortment = IsPartialAssortment }; using (var vendorAssortmentBulk = new VendorAssortmentBulk(assortmentList, vendorID, DefaultVendorID, bulkConfig)) { vendorAssortmentBulk.Init(unit.Context); vendorAssortmentBulk.Sync(unit.Context); } } catch (Exception ex) { log.AuditError(ex.Message); } foreach (var productAttributeConfiguration in _configuredAttributes) { var product = unit.Scope.Repository <Product>().GetSingle(c => c.VendorItemNumber == productAttributeConfiguration.Key && c.IsConfigurable); foreach (var code in productAttributeConfiguration.Value) { var ent = product.ProductAttributeMetaDatas.FirstOrDefault(c => c.AttributeCode == code); if (ent == null) { var attr = unit.Scope.Repository <ProductAttributeMetaData>().GetSingle(c => c.AttributeCode == code); product.ProductAttributeMetaDatas.Add(attr); } } } unit.Save(); CopyArticleInformationToTnt(assortment.FileName); } } } }
public void ProcessData(AuditLog4Net.Adapter.IAuditLogAdapter log, Dictionary <ShopProduct, ShopLanguage> prods) { using (var unit = GetUnitOfWork()) { var itemProducts = (from a in prods.Keys select new AtomBlockProduct { ProductName = a.Title, AllowedForSale = a.AllowedForSale, Currency = a.Pricing.Currency, Price = a.Pricing.Advise, CostPrice = a.Pricing.Purchase, IsActive = a.IsActive, VendorItemNumber = a.ArticleNumber, ProductID = a.Identifier, ProductGroupcode1 = a.Genre, ProductGroupCodes = a.Pegi, Barcode = a.EAN, Language = prods[a].Name, BrandName = a.Publisher, Description = a.Description ?? string.Empty, Docs = a.Documents, ReleaseDate = a.ReleaseDate, Attributes = new AtomBlockProductAttribute { DownloadSize = a.DownloadSize, ReleaseDate = a.ReleaseDate, Genre = a.Genre.Name, Pegi = a.Pegi, SystemRequirements = a.SystemRequirements, DrmType = a.DrmType.Name }, ShortDescription = a.Punchline }).ToList(); SetupAttributes(unit, AttributeMapping.ToArray(), out attributes, VendorID); //Used for VendorImportAttributeValues var productAttributes = unit.Scope.Repository <ProductAttributeMetaData>().GetAll(c => c.VendorID == VendorID).ToList(); attributeList = productAttributes.ToDictionary(x => x.AttributeCode, y => y.AttributeID); List <Concentrator.Objects.Vendors.Bulk.VendorAssortmentBulk.VendorAssortmentItem> assortmentList = new List <Concentrator.Objects.Vendors.Bulk.VendorAssortmentBulk.VendorAssortmentItem>(); int counter = 0; int total = itemProducts.Count(); int totalNumberOfProductsToProcess = total; log.InfoFormat("Start processing {0} products", total); foreach (var product in itemProducts) { var languageID = 0; switch (product.Language) { case "nl-NL": languageID = 2; break; case "en-GB": languageID = 1; break; default: continue; } if (counter == 50) { counter = 0; log.InfoFormat("Still need to process {0} of {1}; {2} done;", totalNumberOfProductsToProcess, total, total - totalNumberOfProductsToProcess); } totalNumberOfProductsToProcess--; counter++; var assortment = new Concentrator.Objects.Vendors.Bulk.VendorAssortmentBulk.VendorAssortmentItem { #region BrandVendor BrandVendors = new List <VendorAssortmentBulk.VendorImportBrand>() { new VendorAssortmentBulk.VendorImportBrand() { VendorID = VendorID, VendorBrandCode = product.BrandName.Trim(), ParentBrandCode = null, Name = product.BrandName.Trim() } }, #endregion #region GeneralProductInfo VendorProduct = new VendorAssortmentBulk.VendorProduct { VendorItemNumber = product.ProductID.Trim(), //EAN CustomItemNumber = product.ProductID.Trim(), //EAN ShortDescription = product.Description != null ? product.Description.Length > 150 ? product.Description.Substring(0, 150) : product.Description : string.Empty, LongDescription = product.Description != null ? product.Description.Length > 1000 ? product.Description.Substring(0, 1000) : product.Description : string.Empty, LineType = null, LedgerClass = null, ProductDesk = null, ExtendedCatalog = null, VendorID = VendorID, DefaultVendorID = DefaultVendorID, VendorBrandCode = product.BrandName.Trim(), //UITGEVER_ID Barcode = product.Try(x => x.Barcode, string.Empty), //EAN VendorProductGroupCode1 = product.Try(x => x.ProductGroupcode1.Name, string.Empty), VendorProductGroupCodeName1 = product.Try(x => x.ProductGroupcode1.Name, string.Empty), }, #endregion #region RelatedProducts RelatedProducts = new List <VendorAssortmentBulk.VendorImportRelatedProduct>() { //new Concentrator.Objects.Vendors.Bulk.VendorAssortmentBulk.VendorImportRelatedProduct //{ // VendorID = VendorID, // DefaultVendorID = DefaultVendorID, // CustomItemNumber = product.ProductID.Trim(), //EAN // RelatedProductType = string.Empty, // RelatedCustomItemNumber = string.Empty //} }, #endregion #region Attributes VendorImportAttributeValues = GetProductAttributeValues(product, languageID, VendorID, unit), #endregion #region Prices VendorImportPrices = new List <Concentrator.Objects.Vendors.Bulk.VendorAssortmentBulk.VendorImportPrice>() { new Concentrator.Objects.Vendors.Bulk.VendorAssortmentBulk.VendorImportPrice() { VendorID = VendorID, DefaultVendorID = DefaultVendorID, CustomItemNumber = product.ProductID.Trim(), //EAN Price = ((Decimal)product.Price / 100).ToString("0.00", CultureInfo.InvariantCulture), CostPrice = decimal.Round((product.CostPrice / 100), 4).ToString("0.00", CultureInfo.InvariantCulture), //NETTOPRIJS TaxRate = "19", //TODO: Calculate this! MinimumQuantity = 0, CommercialStatus = product.AllowedForSale ? "AllowedForSale" : "NotAllowedForSale" } }, #endregion #region Stock VendorImportStocks = new List <Concentrator.Objects.Vendors.Bulk.VendorAssortmentBulk.VendorImportStock>() { new Concentrator.Objects.Vendors.Bulk.VendorAssortmentBulk.VendorImportStock() { VendorID = VendorID, DefaultVendorID = DefaultVendorID, CustomItemNumber = product.ProductID.Trim(), //EAN QuantityOnHand = 1, StockType = "Assortment", StockStatus = product.ReleaseDate.HasValue ? product.ReleaseDate > DateTime.Now ? "Pre Release" : product.AllowedForSale ? "InStock" : "OutOfStock" : product.AllowedForSale ? "InStock" : "OutOfStock" } }, #endregion #region Descriptions VendorProductDescriptions = new List <VendorAssortmentBulk.VendorProductDescription>() { new VendorAssortmentBulk.VendorProductDescription() { VendorID = VendorID, LanguageID = languageID, DefaultVendorID = VendorID, CustomItemNumber = product.ProductID.Trim(), //EAN LongContentDescription = product.Description, ShortContentDescription = product.Description != string.Empty ? product.Description.Length > 1000 ? product.Description.Substring(0, 1000) : product.Description : product.ShortDescription, ProductName = product.ProductName } } #endregion }; // assortment will be added to the list defined outside of this loop assortmentList.Add(assortment); } // Creates a new instance of VendorAssortmentBulk(Passes in the AssortmentList defined above, vendorID and DefaultVendorID) using (var vendorAssortmentBulk = new VendorAssortmentBulk(assortmentList, VendorID, DefaultVendorID)) { vendorAssortmentBulk.Init(unit.Context); vendorAssortmentBulk.Sync(unit.Context); } } }
private void BulkImport(int vendorID, DataSet content, int?parentVendorID) { using (var unit = GetUnitOfWork()) { //var itemProducts = (from d in ds.Tables[0].AsEnumerable() // select new // { // EAN = d.Field<string>("EAN"), // Brand = d.Field<string>("Brand"), // Original_Partnumber = d.Field<string>("Original Partnumber"), // Distributor_Partnumber = d.Field<string>("Distributor Partnumber"), // Product_Name = d.Field<string>("Product Name"), // Groep_L1 = d.Field<string>("Groep_L1"), // Groep_L2 = d.Field<string>("Groep_L2"), // Groep_L3 = d.Field<string>("Groep_L3"), // }).ToList(); var dataList = (from d in content.Tables[0].AsEnumerable() let defaultVendorID = parentVendorID.HasValue ? parentVendorID.Value : vendorID select new Concentrator.Objects.Vendors.Bulk.VendorAssortmentBulk.VendorAssortmentItem { #region BrandVendor BrandVendors = new List <Concentrator.Objects.Vendors.Bulk.VendorAssortmentBulk.VendorImportBrand>() { new Concentrator.Objects.Vendors.Bulk.VendorAssortmentBulk.VendorImportBrand() { Name = SetDataSetValue("Brand", d), VendorBrandCode = SetDataSetValue("Brand", d), VendorID = defaultVendorID } }, #endregion #region GeneralProductInfo VendorProduct = new VendorAssortmentBulk.VendorProduct { CustomItemNumber = SetDataSetValue("Distributor Partnumber", d), VendorItemNumber = SetDataSetValue("Original Partnumber", d), ShortDescription = SetDataSetValue("Original Partnumber", d), LongDescription = null, LineType = null, LedgerClass = null, ProductDesk = null, ExtendedCatalog = null, VendorID = vendorID, DefaultVendorID = defaultVendorID, VendorBrandCode = SetDataSetValue("Brand", d), Barcode = SetDataSetValue("EAN", d), VendorProductGroupCode1 = SetDataSetValue("Groep_L1", d), VendorProductGroupCodeName1 = string.Empty, VendorProductGroupCode2 = SetDataSetValue("Groep_L2", d), VendorProductGroupCodeName2 = string.Empty, VendorProductGroupCode3 = SetDataSetValue("Groep_L3", d), VendorProductGroupCodeName3 = string.Empty, }, #endregion #region RelatedProducts RelatedProducts = new List <VendorAssortmentBulk.VendorImportRelatedProduct>(), #endregion #region Attribures VendorImportAttributeValues = new List <VendorAssortmentBulk.VendorImportAttributeValue>(), #endregion #region Prices VendorImportPrices = new List <Concentrator.Objects.Vendors.Bulk.VendorAssortmentBulk.VendorImportPrice>() { new Concentrator.Objects.Vendors.Bulk.VendorAssortmentBulk.VendorImportPrice() { VendorID = vendorID, DefaultVendorID = vendorID, CustomItemNumber = SetDataSetValue("Distributor Partnumber", d), Price = "0", CostPrice = "0", TaxRate = "19", MinimumQuantity = 0, CommercialStatus = "S" } }, #endregion #region Stock VendorImportStocks = new List <Concentrator.Objects.Vendors.Bulk.VendorAssortmentBulk.VendorImportStock>() { new Concentrator.Objects.Vendors.Bulk.VendorAssortmentBulk.VendorImportStock() { VendorID = vendorID, DefaultVendorID = vendorID, CustomItemNumber = SetDataSetValue("Distributor Partnumber", d), QuantityOnHand = 0, StockType = "Assortment", StockStatus = "S" } }, #endregion }); log.Debug("dataset to object"); using (var vendorAssortmentBulk = new VendorAssortmentBulk(dataList, vendorID, parentVendorID)) { vendorAssortmentBulk.Init(unit.Context); vendorAssortmentBulk.Sync(unit.Context); } } }
private void GetContent() { using (var unit = GetUnitOfWork()) { //Config settings KeyValueConfigurationCollection config = GetConfiguration().AppSettings.Settings; List <ProductAttributeMetaData> attributes; SetupAttributes(unit, AttributeMapping, out attributes, VendorID); //Used for VendorImportAttributeValues var productAttributes = unit.Scope.Repository <ProductAttributeMetaData>().GetAll(c => c.VendorID == VendorID).ToList(); var attributeList = productAttributes.ToDictionary(x => x.AttributeCode, y => y.AttributeID); //Will contain all the columns in a row string[] column = new string[88]; string[] lines = null; #if !DEBUG // Connection to ftp folder FtpManager manager = new FtpManager(config["CentraalBoekhuisFtpUrl"].Value, config["CentraalBoekhuisFilePath"].Value, config["CentraalBoekhuisUser"].Value, config["CentraalBoekhuisPassword"].Value, false, true, log); // Gets the first file in the folder var data = manager.FirstOrDefault().Data; // Stream reader to read the file using (StreamReader reader = new StreamReader(data, Encoding.UTF8)) { lines = reader.ReadToEnd().Split('\n'); }; #else var directory = config["CentraalBoekhuisDirectory"].Value; var fileName = config["CentraalBoekhuisFile"].Value; String fullPath = Path.Combine(directory, fileName); lines = File.ReadAllLines(fullPath); #endif List <Concentrator.Objects.Vendors.Bulk.VendorAssortmentBulk.VendorAssortmentItem> assortmentList = new List <Concentrator.Objects.Vendors.Bulk.VendorAssortmentBulk.VendorAssortmentItem>(); // Loops through all the rows lines.ForEach((line, idx) => { // Line is a row of data seperated by semicolons. The values will be split and added to the column array column = line.Split(';'); //Creates a list of type VendorAssortmentItem var assortment = new Concentrator.Objects.Vendors.Bulk.VendorAssortmentBulk.VendorAssortmentItem { #region BrandVendor BrandVendors = new List <VendorAssortmentBulk.VendorImportBrand>() { new VendorAssortmentBulk.VendorImportBrand() { VendorID = VendorID, VendorBrandCode = column[3].Trim(), //UITGEVER_ID ParentBrandCode = null, Name = column[4].Trim() //UITGEVER_NM } }, #endregion #region GeneralProductInfo VendorProduct = new VendorAssortmentBulk.VendorProduct { VendorItemNumber = column[0].Trim(), //EAN CustomItemNumber = column[0].Trim(), //EAN ShortDescription = column[2].Trim(), //Subtitel LongDescription = column[84].Trim(), LineType = null, LedgerClass = null, ProductDesk = null, ExtendedCatalog = null, VendorID = VendorID, DefaultVendorID = VendorID, VendorBrandCode = column[3].Trim(), //UITGEVER_ID Barcode = column[0].Trim(), //EAN VendorProductGroupCode1 = column[9].Trim(), //REEKS_NR VendorProductGroupCodeName1 = column[8].Trim(), //REEKS_NM VendorProductGroupCode2 = column[7].Trim(), //BOEKSOORT_KD VendorProductGroupCodeName2 = null //GEEN NAAM }, #endregion #region RelatedProducts RelatedProducts = new List <VendorAssortmentBulk.VendorImportRelatedProduct>() { new Concentrator.Objects.Vendors.Bulk.VendorAssortmentBulk.VendorImportRelatedProduct { VendorID = VendorID, DefaultVendorID = DefaultVendorID, CustomItemNumber = column[0].Trim(), //EAN RelatedProductType = column[19].Trim(), //ISBN_FYSIEK_BOEK RelatedCustomItemNumber = column[19].Trim(), //ISBN_FYSIEK_BOEK } }, #endregion #region Attributes VendorImportAttributeValues = (from attr in AttributeMapping let prop = column.Contains(attr)//d.Field<object>(attr) let attributeID = attributeList.ContainsKey(attr) ? attributeList[attr] : 2 let value = prop.ToString() where !string.IsNullOrEmpty(value) select new Concentrator.Objects.Vendors.Bulk.VendorAssortmentBulk.VendorImportAttributeValue { VendorID = VendorID, DefaultVendorID = DefaultVendorID, CustomItemNumber = column[0].Trim(), //EAN AttributeID = attributeID, Value = value, LanguageID = "1", AttributeCode = attr, }).ToList(), #endregion #region Prices VendorImportPrices = new List <Concentrator.Objects.Vendors.Bulk.VendorAssortmentBulk.VendorImportPrice>() { new Concentrator.Objects.Vendors.Bulk.VendorAssortmentBulk.VendorImportPrice() { VendorID = VendorID, DefaultVendorID = DefaultVendorID, CustomItemNumber = column[0].Trim(), //EAN Price = column[24].Trim(), //ADVIESPRIJS CostPrice = column[25].Trim(), //NETTOPRIJS TaxRate = "19", //TODO: Calculate this! MinimumQuantity = 0, CommercialStatus = column[18].Trim() //STADIUM_LEVENSCYCLUS_KD } }, #endregion #region Stock VendorImportStocks = new List <Concentrator.Objects.Vendors.Bulk.VendorAssortmentBulk.VendorImportStock>() { new Concentrator.Objects.Vendors.Bulk.VendorAssortmentBulk.VendorImportStock() { VendorID = VendorID, DefaultVendorID = DefaultVendorID, CustomItemNumber = column[0].Trim(), //EAN QuantityOnHand = 0, StockType = "Assortment", StockStatus = column[18].Trim()//STADIUM_LEVENSCYCLUS_KD } }, #endregion }; // assortment will be added to the list defined outside of this loop assortmentList.Add(assortment); }); // Creates a new instance of VendorAssortmentBulk(Passes in the AssortmentList defined above, vendorID and DefaultVendorID) using (var vendorAssortmentBulk = new VendorAssortmentBulk(assortmentList, VendorID, VendorID)) { vendorAssortmentBulk.Init(unit.Context); vendorAssortmentBulk.Sync(unit.Context); } } }
private Boolean ProcessFile(Stream fileStream) { using (var document = new ExcelPackage(fileStream)) { var worksheet = document.Workbook.Worksheets.First(); if (VerifyWorksheet(worksheet)) { TraceVerbose("Loading existing product vendor assortment data..."); var vendorBySkuLookup = Unit.Scope.Repository <VendorAssortment>() .Include(vendorAssortment => vendorAssortment.Product) .GetAll(vendorAssortment => vendorAssortment.Product.IsConfigurable) .ToLookup(vendorAssortment => vendorAssortment.CustomItemNumber, vendorAssortment => vendorAssortment.VendorID); TraceVerbose("Loading product content processors..."); var productContentRecordProcessors = GetType() .GetNestedTypes(BindingFlags.Instance | BindingFlags.NonPublic) .Where(type => type.BaseType == typeof(ProductContentRecordProcessor)) .Select(processorType => Activator.CreateInstance(processorType, DefaultVendor) as ProductContentRecordProcessor) .ToArray(); TraceVerbose("Loading product content records..."); var productContentRecords = GetProductContentRecords(worksheet).ToArray(); var vendorAssortmentDictionary = new Dictionary <Int32, IList <VendorAssortmentBulk.VendorAssortmentItem> >(); var progressStopwatch = Stopwatch.StartNew(); for (var index = 0; index < productContentRecords.Length; index++) { var productContentRecord = productContentRecords[index]; var customItemNumber = String.Format("{0} {1}", productContentRecord[HeaderName].Substring(3), productContentRecord[HeaderColor]); foreach (var vendorID in vendorBySkuLookup[customItemNumber]) { var vendorAssortmentItem = new VendorAssortmentBulk.VendorAssortmentItem(); foreach (var productContentProcessor in productContentRecordProcessors) { productContentProcessor.CustomItemNumber = customItemNumber; productContentProcessor.LanguageID = DefaultLanguage.LanguageID; productContentProcessor.VendorAssortment = vendorAssortmentItem; productContentProcessor.VendorID = vendorID; productContentProcessor.Process(productContentRecord); } if (!vendorAssortmentDictionary.ContainsKey(vendorID)) { vendorAssortmentDictionary[vendorID] = new List <VendorAssortmentBulk.VendorAssortmentItem>(); } vendorAssortmentDictionary[vendorID].Add(vendorAssortmentItem); } if (progressStopwatch.ElapsedMilliseconds > 1000L || productContentRecords.Length - 1 == index) { TraceVerbose("Progress: {0:P2}", (index + 1D) / productContentRecords.Length); progressStopwatch.Restart(); } } foreach (var vendorID in vendorAssortmentDictionary.Keys) { TraceVerbose("Bulk importing vendor '{0}'...", Unit.Scope.Repository <Vendor>().GetSingle(vendor => vendor.VendorID == vendorID).Name); var bulkConfig = new VendorAssortmentBulkConfiguration { IsPartialAssortment = true }; using (var vendorAssortmentBulk = new VendorAssortmentBulk(vendorAssortmentDictionary[vendorID], vendorID, vendorID, bulkConfig)) { vendorAssortmentBulk.Init(Unit.Context); vendorAssortmentBulk.Sync(Unit.Context); } } return(true); } } return(false); }
protected override void ExecuteVendorTask() { _monitoring = new FeeblMonitoring(); _monitoring.Notify(Name, 0); if (Location.IsNullOrWhiteSpace()) { TraceError("The connector setting '{0}' does not exists or is empty!", Constants.Vendor.Setting.Location); } else { var locationInfo = new DirectoryInfo(Location); if (!locationInfo.FullName.EndsWith("$") && !locationInfo.Exists) { TraceError("The directory '{0}' does not exists!", locationInfo.FullName); } else if (!locationInfo.FullName.EndsWith("$") && !locationInfo.HasAccess(FileSystemRights.FullControl)) { TraceError("The user '{0}' has insufficient access over the directory '{1}'!", WindowsIdentity.GetCurrent().Name, locationInfo.FullName); } else if (ProductAttributeHelper.Bind(PropertyStore, Context, TraceSource)) { Languages = Unit.Scope .Repository <Language>() .GetAll(language => language.Name == Constants.Language.English) .ToArray(); TariffVendors = Unit.Scope .Repository <Vendor>() .Include(vendor => vendor.VendorSettings) .GetAll(vendor => vendor.ParentVendorID == VendorID) .AsEnumerable() .Where(vendor => vendor.GetVendorSetting(Constants.Vendor.Setting.IsTariff, false) && !vendor.GetVendorSetting(Constants.Vendor.Setting.CountryCode).IsNullOrWhiteSpace() && !vendor.GetVendorSetting(Constants.Vendor.Setting.CurrencyCode).IsNullOrWhiteSpace()) .ToDictionary(GetTariffCode); var files = locationInfo.GetFiles("*.csv", SearchOption.TopDirectoryOnly); TraceInformation("Found {0} CSV-files for import!", files.Length); foreach (var fileInfo in files) { TraceInformation("Importing the file '{0}'...", fileInfo); var articles = GetArticles(fileInfo.FullName); if (articles != null) { var enumerableArticles = articles as Article[] ?? articles.ToArray(); ImportTariffVendors(enumerableArticles); var vendorAssortmentItems = GetVendorAssortments(enumerableArticles).ToArray(); var success = true; foreach (var vendorAssortmentGrouping in vendorAssortmentItems.GroupBy(vendorAssortmentItem => vendorAssortmentItem.VendorProduct.VendorID)) { TraceInformation("Importing assortment for vendor '{0}'...", vendorAssortmentGrouping.Key != VendorID ? Unit.Scope.Repository <Vendor>().GetSingle(vendor => vendor.VendorID == vendorAssortmentGrouping.Key).Name : VendorName); var bulkConfig = new VendorAssortmentBulkConfiguration { IsPartialAssortment = true }; using (var bulk = new VendorAssortmentBulk(vendorAssortmentGrouping, vendorAssortmentGrouping.Key, VendorID, bulkConfig)) { try { bulk.Init(Unit.Context); bulk.Sync(Unit.Context); } catch (Exception exception) { success = false; TraceCritical(exception); } } } fileInfo.CopyTo(fileInfo.FullName + (success ? ".processed" : ".failed"), true); fileInfo.Delete(); } } ImportProductConfiguration(PropertyStore.ColorCode, PropertyStore.SizeCode); ImportProductGroups(); } } _monitoring.Notify(Name, 1); }
protected override void SyncProducts() { var config = GetConfiguration(); XDocument products = new XDocument(); DataTable content = new DataTable(); DataTable statuses = new DataTable(); DataTable taxTable = new DataTable(); try { FtpManager productDownloader = new FtpManager( config.AppSettings.Settings["CopacoProductFtpUrl"].Value, config.AppSettings.Settings["CopacoProductPath"].Value, config.AppSettings.Settings["CopacoUserName"].Value, config.AppSettings.Settings["CopacoPassword"].Value, false, true, log); FtpManager contentDownloader = new FtpManager( config.AppSettings.Settings["CopacoFtpUrl"].Value, config.AppSettings.Settings["CopacoContentPath"].Value, config.AppSettings.Settings["CopacoContentUserName"].Value, config.AppSettings.Settings["CopacoContentPassword"].Value, false, true, log); log.AuditInfo("Getting data.."); using (var file = productDownloader.OpenFile("Copaco_prijslijst_73546.xml")) { try { XmlReaderSettings settings = new XmlReaderSettings(); settings.XmlResolver = null; settings.ProhibitDtd = false; using (var reader = XmlReader.Create(file.Data, settings)) { reader.MoveToContent(); products = XDocument.Load(reader); } } catch (Exception ex) { log.AuditFatal("Failed to download product file"); return; } } try { SimpleFtp ftp = new SimpleFtp( config.AppSettings.Settings["CopacoFtpUrl"].Value, config.AppSettings.Settings["CopacoContentUserName"].Value, config.AppSettings.Settings["CopacoContentPassword"].Value, log, true); using (Stream contentFileStream = ftp.GetFtpFileStream(config.AppSettings.Settings["CopacoContentPath"].Value, "COPACO_PRODUCTHIERARCHIE.CSV")) { content = CreateDataTable(contentFileStream, false, ','); contentFileStream.Close(); } using (Stream contentFileStream = ftp.GetFtpFileStream(config.AppSettings.Settings["CopacoContentPath"].Value, "COPACO_ATP_KWALIFICATIES.csv")) { statuses = CreateDataTable(contentFileStream, false, ','); contentFileStream.Close(); } using (Stream contentFileStream = ftp.GetFtpFileStream(config.AppSettings.Settings["CopacoContentPath"].Value, "Country_tax_NL.csv")) { taxTable = CreateDataTable(contentFileStream, false, ','); contentFileStream.Close(); } log.AuditInfo("Finished getting data"); } catch (Exception ex) { log.AuditFatal("Failed to download catalog file", ex); return; } } catch (Exception ex) { log.AuditError("Error get copaco files from ftp", ex); } int count = 0; try { using (var unit = GetUnitOfWork()) { if (products != null && content != null && statuses != null) { #region Parse Data log.AuditInfo("Parse data"); var taxList = (from tax in taxTable.AsEnumerable() select new { ID = tax[1].ToString(), Tax = tax[2].ToString() }).ToList(); var vendorStatuses = (from status in statuses.AsEnumerable() select new { Code = status[0].ToString(), Name = status[1].ToString() }); var itemContent = (from cont in content.AsEnumerable() select new { Code = cont[0].ToString(), Name = cont[2].ToString(), Level = cont[1].ToString() }).ToList(); var itemProducts = (from itemproduct in products.Element("XMLOUT_pricelist_01").Elements("item") let cont = itemContent select new { VendorName = itemproduct.Element("vendor").Value, CustomItemNr = itemproduct.Element("item_id").Value, VendorItemNr = itemproduct.Element("vendor_id").Value, Longdescription = itemproduct.Element("long_desc").Value, Price = itemproduct.Element("price").Value, Tax = taxList.FirstOrDefault(x => x.ID == itemproduct.Element("item_id").Value), Status = vendorStatuses.FirstOrDefault(x => x.Code == itemproduct.Element("status").Value), QuantityOnHand = itemproduct.Element("stock").Value, VendorProductGroupCode1 = cont.FirstOrDefault(x => x.Code.StartsWith(itemproduct.Element("item_group").Value.Substring(0, 2)) && Int32.Parse(x.Level) == 1), VendorProductGroupCode2 = cont.FirstOrDefault(x => x.Code.StartsWith(itemproduct.Element("item_group").Value.Substring(0, 2)) && Int32.Parse(x.Level) == 2), VendorProductGroupCode3 = cont.FirstOrDefault(x => x.Code.StartsWith(itemproduct.Element("item_group").Value.Substring(0, 2)) && Int32.Parse(x.Level) == 3), VendorProductGroupCode4 = cont.FirstOrDefault(x => x.Code.StartsWith(itemproduct.Element("item_group").Value.Substring(0, 2)) && Int32.Parse(x.Level) == 4), VendorProductGroupCode5 = cont.FirstOrDefault(x => x.Code.StartsWith(itemproduct.Element("item_group").Value.Substring(0, 2)) && Int32.Parse(x.Level) == 5), Barcode = itemproduct.Element("EAN_code").Value, ShortContentDescription = "" }).ToList(); log.AuditInfo("Finished parsing data"); #endregion List <Concentrator.Objects.Vendors.Bulk.VendorAssortmentBulk.VendorAssortmentItem> assortmentList = new List <Concentrator.Objects.Vendors.Bulk.VendorAssortmentBulk.VendorAssortmentItem>(); // Loops through all the rowss foreach (var product in itemProducts) { var assortment = new Concentrator.Objects.Vendors.Bulk.VendorAssortmentBulk.VendorAssortmentItem { #region BrandVendor BrandVendors = new List <VendorAssortmentBulk.VendorImportBrand>() { new VendorAssortmentBulk.VendorImportBrand() { VendorID = DefaultVendorID, VendorBrandCode = product.VendorProductGroupCode1 != null?product.VendorProductGroupCode1.Code.Trim() : "Unknown", //UITGEVER_ID ParentBrandCode = null, Name = product.VendorName != null?product.VendorName.Trim() : "Unknown" //UITGEVER_NM } }, #endregion #region GeneralProductInfo VendorProduct = new VendorAssortmentBulk.VendorProduct { VendorItemNumber = product.VendorItemNr != null?product.VendorItemNr.Trim() : "Unknown", //EAN CustomItemNumber = product.CustomItemNr != null?product.CustomItemNr.Trim() : "Unknown", //EAN ShortDescription = product.Longdescription != null ? product.Longdescription.Length > 150 ? product.Longdescription.Substring(0, 150) : product.Longdescription : string.Empty, //Subtitel LongDescription = product.Longdescription != null?product.Longdescription.Trim() : string.Empty, LineType = null, LedgerClass = null, ProductDesk = null, ExtendedCatalog = null, VendorID = VendorID, DefaultVendorID = DefaultVendorID, VendorBrandCode = product.VendorProductGroupCode1 != null?product.VendorProductGroupCode1.Code.Trim() : "Unknown", Barcode = String.IsNullOrEmpty(product.Barcode) ? product.Barcode.Trim() : string.Empty, //EAN VendorProductGroupCode1 = product.VendorProductGroupCode1 != null ? product.VendorProductGroupCode1.Code : string.Empty, VendorProductGroupCodeName1 = product.VendorProductGroupCode1 != null ? product.VendorProductGroupCode1.Name : string.Empty, VendorProductGroupCode2 = product.VendorProductGroupCode2 != null ? product.VendorProductGroupCode2.Code : string.Empty, VendorProductGroupCodeName2 = product.VendorProductGroupCode2 != null ? product.VendorProductGroupCode2.Name : string.Empty, VendorProductGroupCode3 = product.VendorProductGroupCode3 != null ? product.VendorProductGroupCode3.Code : string.Empty, VendorProductGroupCodeName3 = product.VendorProductGroupCode3 != null ? product.VendorProductGroupCode3.Name : string.Empty, VendorProductGroupCode4 = product.VendorProductGroupCode4 != null ? product.VendorProductGroupCode4.Code : string.Empty, VendorProductGroupCodeName4 = product.VendorProductGroupCode4 != null ? product.VendorProductGroupCode4.Name : string.Empty, VendorProductGroupCode5 = product.VendorProductGroupCode5 != null ? product.VendorProductGroupCode5.Code : string.Empty, VendorProductGroupCodeName5 = product.VendorProductGroupCode5 != null ? product.VendorProductGroupCode5.Name : string.Empty }, #endregion #region RelatedProducts not needed RelatedProducts = new List <VendorAssortmentBulk.VendorImportRelatedProduct>() { }, #endregion #region Attributes not needed VendorImportAttributeValues = new List <VendorAssortmentBulk.VendorImportAttributeValue>() { }, #endregion #region Prices VendorImportPrices = new List <Concentrator.Objects.Vendors.Bulk.VendorAssortmentBulk.VendorImportPrice>() { new Concentrator.Objects.Vendors.Bulk.VendorAssortmentBulk.VendorImportPrice() { VendorID = VendorID, DefaultVendorID = DefaultVendorID, CustomItemNumber = product.CustomItemNr.Trim(), //EAN Price = product.Price != null && product.Price != "" ? Decimal.Parse(product.Price).ToString("0.00", CultureInfo.InvariantCulture) : null, //ADVIESPRIJS CostPrice = null, //NETTOPRIJS TaxRate = product.Tax != null ? (Decimal.Parse(product.Tax.Tax) / Decimal.Parse(product.Price)).ToString("0.00", CultureInfo.InvariantCulture): null, //TODO: Calculate this! MinimumQuantity = 0, CommercialStatus = product.Status == null?Int32.Parse(product.QuantityOnHand) > 0 ? "InStock" : "OutOfStock" : product.Status.Name //STADIUM_LEVENSCYCLUS_KD } }, #endregion #region Stock VendorImportStocks = new List <Concentrator.Objects.Vendors.Bulk.VendorAssortmentBulk.VendorImportStock>() { new Concentrator.Objects.Vendors.Bulk.VendorAssortmentBulk.VendorImportStock() { VendorID = VendorID, DefaultVendorID = DefaultVendorID, CustomItemNumber = product.CustomItemNr.Trim(), //EAN QuantityOnHand = product.QuantityOnHand != null?Int32.Parse(product.QuantityOnHand) : 0, StockType = "Assortment", StockStatus = product.Status == null?Int32.Parse(product.QuantityOnHand) > 0 ? "InStock" : "OutOfStock" : product.Status.Name//STADIUM_LEVENSCYCLUS_KD } }, #endregion }; // assortment will be added to the list defined outside of this loop assortmentList.Add(assortment); count++; } using (var vendorAssortmentBulk = new VendorAssortmentBulk(assortmentList, VendorID, DefaultVendorID)) { vendorAssortmentBulk.Init(unit.Context); vendorAssortmentBulk.Sync(unit.Context); } } } } catch (Exception ex) { log.AuditError("Error import products", ex); } }
private void ProcessCsv(CsvParser parser) { using (var unit = GetUnitOfWork()) { RelatedProductTypes relatedProductTypes = new RelatedProductTypes(unit.Scope.Repository <RelatedProductType>()); var relatedProductType = relatedProductTypes.SyncRelatedProductTypes("CompatibleProducts"); //there are products with repeating vendoritemnumbers List <string> vendorItemNumbers = unit.Scope.Repository <Product>().GetAll(p => p.SourceVendorID == VendorID).Select(c => c.VendorItemNumber).ToList(); var vendor = unit.Scope.Repository <Vendor>().GetSingle(x => x.VendorID == VendorID); int couterProduct = 0; int logCount = 0; var importedproducts = parser.ToList(); int totalProducts = importedproducts.Count(); ProductStatusVendorMapper mapper = new ProductStatusVendorMapper(unit.Scope.Repository <VendorProductStatus>(), VendorID); List <Concentrator.Objects.Vendors.Bulk.VendorAssortmentBulk.VendorAssortmentItem> assortmentList = new List <Concentrator.Objects.Vendors.Bulk.VendorAssortmentBulk.VendorAssortmentItem>(); //Used for VendorImportAttributeValues var productAttributes = unit.Scope.Repository <ProductAttributeMetaData>().GetAll(c => c.VendorID == VendorID).ToList(); var attributeList = productAttributes.ToDictionary(x => x.AttributeCode, y => y.AttributeID); foreach (Dictionary <string, string> record in importedproducts) { couterProduct++; logCount++; if (logCount == 250) { log.DebugFormat("Products Processed : {0}/{1} for Vendor {2}", couterProduct, totalProducts, vendor.Name); logCount = 0; } int concentratorStatusID = -1; DateTime backorderDate = DateTime.Now; if (!string.IsNullOrEmpty(record.Get(TechDataColumnDefs.BackorderDate.ToString())) && DateTime.TryParseExact(record.Get(TechDataColumnDefs.BackorderDate.ToString()), "dd/MM/yyyy", null, DateTimeStyles.None, out backorderDate) && DateTime.Compare(backorderDate, DateTime.Now) > 0) { concentratorStatusID = mapper.SyncVendorStatus("BackOrder", -1); } else { concentratorStatusID = mapper.SyncVendorStatus("InStock", -1); } string vendorItemNumber = record.Get(TechDataColumnDefs.VendorItemNumber.ToString()).Trim(); //if already an item with this vendor item number exists --> do nothing if (vendorItemNumbers.Contains(vendorItemNumber.Trim())) { continue; } Decimal price = decimal.Parse(record.Get(TechDataColumnDefs.Price.ToString())); string customItemNumber = record.Get(TechDataColumnDefs.CustomItemNumber.ToString()).Trim(); string productGroupCode = record.Get(TechDataColumnDefs.GrandChildVendorProductGroupCode.ToString()); string parentProductGroupCode = record.Get(TechDataColumnDefs.ChildVendorProductGroupCode.ToString()); string grandParentProductGroupCode = record.Get(TechDataColumnDefs.ParentVendorProductGroupCode.ToString()); var assortment = new Concentrator.Objects.Vendors.Bulk.VendorAssortmentBulk.VendorAssortmentItem { #region BrandVendor BrandVendors = new List <VendorAssortmentBulk.VendorImportBrand>() { new VendorAssortmentBulk.VendorImportBrand() { VendorID = VendorID, VendorBrandCode = record.Get(TechDataColumnDefs.Brand.ToString()).Trim().ToLower(), ParentBrandCode = null, Name = record.Get(TechDataColumnDefs.Brand.ToString()).Trim().ToLower(), } }, #endregion #region GeneralProductInfo VendorProduct = new VendorAssortmentBulk.VendorProduct { VendorItemNumber = vendorItemNumber, CustomItemNumber = customItemNumber, ShortDescription = record.Get(TechDataColumnDefs.Description.ToString()), LongDescription = record.Get(TechDataColumnDefs.Description.ToString()), LineType = null, LedgerClass = null, ProductDesk = null, ExtendedCatalog = null, VendorID = VendorID, DefaultVendorID = DefaultVendorID, VendorBrandCode = record.Get(TechDataColumnDefs.Brand.ToString()).Trim().ToLower(), Barcode = record.Get(TechDataColumnDefs.EanCode.ToString()), VendorProductGroupCode1 = grandParentProductGroupCode, VendorProductGroupCodeName1 = null, VendorProductGroupCode2 = parentProductGroupCode, VendorProductGroupCodeName2 = null, VendorProductGroupCode3 = productGroupCode, VendorProductGroupCodeName3 = null }, #endregion #region RelatedProducts RelatedProducts = new List <VendorAssortmentBulk.VendorImportRelatedProduct>() { new Concentrator.Objects.Vendors.Bulk.VendorAssortmentBulk.VendorImportRelatedProduct { VendorID = VendorID, DefaultVendorID = DefaultVendorID, CustomItemNumber = customItemNumber, RelatedProductType = relatedProductType.Type, RelatedCustomItemNumber = vendorItemNumber } }, #endregion #region Attributes VendorImportAttributeValues = new List <VendorAssortmentBulk.VendorImportAttributeValue>(), //VendorImportAttributeValues = (from attr in enumValList // let prop = record.Equals(attr) // let attributeID = attributeList.ContainsKey(attr) ? attributeList[attr] : 2 //TODO set as -1 // let value = prop.ToString() // where !string.IsNullOrEmpty(value) // select new Concentrator.Objects.Vendors.Bulk.VendorAssortmentBulk.VendorImportAttributeValue // { // VendorID = VendorID, // DefaultVendorID = DefaultVendorID, // CustomItemNumber = customItemNumber, // AttributeID = attributeID, // Value = value, // LanguageID = "1", // AttributeCode = attr, // }).ToList(), #endregion #region Prices VendorImportPrices = new List <Concentrator.Objects.Vendors.Bulk.VendorAssortmentBulk.VendorImportPrice>() { new Concentrator.Objects.Vendors.Bulk.VendorAssortmentBulk.VendorImportPrice() { VendorID = VendorID, DefaultVendorID = DefaultVendorID, CustomItemNumber = customItemNumber, Price = price.ToString("0.00", CultureInfo.InvariantCulture), CostPrice = price.ToString("0.00", CultureInfo.InvariantCulture), TaxRate = "19", MinimumQuantity = 0, CommercialStatus = "SR" } }, #endregion #region Stock VendorImportStocks = new List <Concentrator.Objects.Vendors.Bulk.VendorAssortmentBulk.VendorImportStock>() { new Concentrator.Objects.Vendors.Bulk.VendorAssortmentBulk.VendorImportStock() { VendorID = VendorID, DefaultVendorID = DefaultVendorID, CustomItemNumber = customItemNumber, QuantityOnHand = 0, StockType = "Assortment", StockStatus = "S" } }, #endregion }; assortmentList.Add(assortment); } using (var vendorAssortmentBulk = new VendorAssortmentBulk(assortmentList, VendorID, VendorID)) { vendorAssortmentBulk.Init(unit.Context); vendorAssortmentBulk.Sync(unit.Context); } } }
private void Parseproducts(DataTable content) { try { using (var unit = GetUnitOfWork()) { // VendorID's retrieved from appsettings.config var config = GetConfiguration(); var itemProducts = (from line in content.AsEnumerable() select new { CustomItemNr = line[1].ToString().Trim(), ProductName = line[2].ToString().Trim(), SalesPrice = line[12].ToString().Trim(), EAN = line[4].ToString().Trim(), Brand = line[5].ToString().Trim(), ProductGroup = line[6].ToString().Trim(), VendorItemNr = line[7].ToString().Trim(), Stock = line[9].ToString().Trim(), StockIncl = line[10].ToString().Trim(), Date = line[14].ToString().Trim() }).ToList(); List <Concentrator.Objects.Vendors.Bulk.VendorAssortmentBulk.VendorAssortmentItem> assortmentList = new List <Concentrator.Objects.Vendors.Bulk.VendorAssortmentBulk.VendorAssortmentItem>(); int counter = 0; int total = itemProducts.Count(); int totalNumberOfProductsToProcess = total; log.InfoFormat("Start processing {0} products", total); // Loops through all the rowss foreach (var product in itemProducts) { DateTime RequestDate; DateTime.TryParseExact(product.Date, "yyyyMMdd", null, DateTimeStyles.None, out RequestDate); if (RequestDate != null && RequestDate > DateTime.Now) { continue; } var assortment = new Concentrator.Objects.Vendors.Bulk.VendorAssortmentBulk.VendorAssortmentItem { #region BrandVendor BrandVendors = new List <VendorAssortmentBulk.VendorImportBrand>() { new VendorAssortmentBulk.VendorImportBrand() { VendorID = VendorID, VendorBrandCode = product.Brand.Trim(), ParentBrandCode = null, Name = product.Brand.Trim() } }, #endregion #region GeneralProductInfo VendorProduct = new VendorAssortmentBulk.VendorProduct { VendorItemNumber = product.VendorItemNr.Trim(), //EAN CustomItemNumber = product.CustomItemNr.Trim(), //EAN ShortDescription = string.Empty, LongDescription = string.Empty, LineType = null, LedgerClass = null, ProductDesk = null, ExtendedCatalog = null, VendorID = VendorID, DefaultVendorID = DefaultVendorID, VendorBrandCode = product.Brand.Trim(), //UITGEVER_ID Barcode = string.IsNullOrEmpty(product.EAN) ? null : product.EAN.Trim(), //EAN VendorProductGroupCode1 = product.Try(x => x.ProductGroup, string.Empty), //REEKS_NR VendorProductGroupCodeName1 = product.Try(x => x.ProductGroup, string.Empty), //REEKS_NM }, #endregion #region RelatedProducts RelatedProducts = new List <VendorAssortmentBulk.VendorImportRelatedProduct>() { new Concentrator.Objects.Vendors.Bulk.VendorAssortmentBulk.VendorImportRelatedProduct { VendorID = VendorID, DefaultVendorID = DefaultVendorID, CustomItemNumber = product.CustomItemNr.Trim(), //EAN RelatedProductType = string.Empty, RelatedCustomItemNumber = string.Empty } }, #endregion #region Attributes VendorImportAttributeValues = new List <VendorAssortmentBulk.VendorImportAttributeValue>(), #endregion #region Prices VendorImportPrices = new List <Concentrator.Objects.Vendors.Bulk.VendorAssortmentBulk.VendorImportPrice>() { new Concentrator.Objects.Vendors.Bulk.VendorAssortmentBulk.VendorImportPrice() { VendorID = VendorID, DefaultVendorID = DefaultVendorID, CustomItemNumber = product.CustomItemNr.Trim(), //EAN Price = (Decimal.Parse(product.SalesPrice) / 100).ToString("0.00", CultureInfo.InvariantCulture), CostPrice = null, //NETTOPRIJS TaxRate = "19", //TODO: Calculate this! MinimumQuantity = 0, CommercialStatus = product.Stock != null || product.Stock != "" ? Int32.Parse(product.Stock) > 0 ? "InStock" : "OutOfStock" : "OutOfStock" } }, #endregion #region Stock VendorImportStocks = new List <Concentrator.Objects.Vendors.Bulk.VendorAssortmentBulk.VendorImportStock>() { new Concentrator.Objects.Vendors.Bulk.VendorAssortmentBulk.VendorImportStock() { VendorID = VendorID, DefaultVendorID = DefaultVendorID, CustomItemNumber = product.CustomItemNr.Trim(), //EAN QuantityOnHand = product.Stock != null || product.Stock != "" ? Int32.Parse(product.Stock) : 0, StockType = "Assortment", StockStatus = product.Stock != null || product.Stock != "" ? Int32.Parse(product.Stock) > 0 ? "InStock" : "OutOfStock" : "OutOfStock" } }, #endregion }; // assortment will be added to the list defined outside of this loop assortmentList.Add(assortment); } // Creates a new instance of VendorAssortmentBulk(Passes in the AssortmentList defined above, vendorID and DefaultVendorID) using (var vendorAssortmentBulk = new VendorAssortmentBulk(assortmentList, VendorID, DefaultVendorID)) { vendorAssortmentBulk.Init(unit.Context); vendorAssortmentBulk.Sync(unit.Context); } } } catch (Exception ex) { log.AuditFatal(string.Format("Something went wrong: {0}", ex)); } }
protected void ProcessProductsTable(DataTable table, int vendorBrandID, IEnumerable <ProductAttributeMetaData> productAttributes, ProductGroupSyncer syncer, ProductStatusVendorMapper mapper, Dictionary <int, VendorAssortment> inactiveAss) { var products = (from r in table.Rows.Cast <DataRow>() where !String.IsNullOrEmpty(r.Field <string>("EANNumber")) group r by r.Field <string>("EANNumber") into grp let r = grp.First() select new { ProductID = r.Field <string>("ProductCode"), EAN = r.Field <string>("EANNumber"), EAN_Alt = r.Field <string>("EANNumberAlternative"), Description = r.Field <string>("ProductName"), TagLine = r.Field <string>("TagLine"), Title = r.Field <string>("Title"), ProductionYear = r.Field <int?>("ProductionYear"), RunningTime = r.Field <int?>("RunningTime"), CountryName = r.Field <string>("CountryName"), UsrReleaseDate = r.Field <string>("UsrReleaseDate"), ProductStatusID = r.Field <long?>("ProductStatusID"), ProductStatus = r.Field <string>("ProductStatus").Trim(), SalesPrice = r.Field <decimal?>("SalesPrice"), RetailPrice = ((r.Field <decimal?>("RetailPrice") ?? 0) / (decimal)1.19), ListRetailPrice = r.Field <decimal?>("ListRetailPrice"), ListSalesPrice = r.Field <decimal?>("ListSalesPrice"), InStock = r.Field <int?>("InStock"), GenreID = r.Field <long?>("GenreID"), GenreName = r.Field <string>("GenreName"), ProductGroupCode = r.Field <string>("ProductGroupCode"), ProductGroup = r.Field <string>("ProductGroup"), SubProductGroupCode = r.Field <string>("SubProductGroupCode"), SubProductGroup = r.Field <string>("SubProductGroup"), SubGenreID = r.Field <long?>("SubGenreID"), SubGenreName = r.Field <string>("SubGenreName"), RatingAge = r.Field <string>("RatingAge"), MediaType = r.Field <string>("MediaType"), MediaTypeID = r.Field <long?>("MediaTypeID"), Artist = r.Field <string>("Artist"), MediaDescription = r.Field <string>("MediaDescription") }).ToList(); 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); //ctx.LoadOptions = options; List <Concentrator.Objects.Vendors.Bulk.VendorAssortmentBulk.VendorAssortmentItem> assortmentList = new List <Concentrator.Objects.Vendors.Bulk.VendorAssortmentBulk.VendorAssortmentItem>(); RelatedProductTypes relatedProductTypes = new RelatedProductTypes(unit.Scope.Repository <RelatedProductType>()); var relatedProductType = relatedProductTypes.SyncRelatedProductTypes("CompatibleProducts"); var productGroupVendorRepo = unit.Scope.Repository <ProductGroupVendor>().Include(c => c.VendorAssortments); var assortmentRepo = unit.Scope.Repository <VendorAssortment>().Include(c => c.VendorPrices); var stockRepo = unit.Scope.Repository <VendorStock>(); var productRepo = unit.Scope.Repository <Product>().Include(c => c.ProductBarcodes); var priceRepo = unit.Scope.Repository <VendorPrice>(); var productGroupVendorRecords = productGroupVendorRepo.GetAll(c => c.VendorID == VendorID).ToList(); int step = 1000; int todo = products.Count(); int done = 0; var languages = new[] { (int)LanguageTypes.English, (int)LanguageTypes.Netherlands }; var vendorAssortment = assortmentRepo.GetAll(x => x.VendorID == VendorID).ToDictionary(x => x.ProductID, y => y); var attributeList = productAttributes.ToDictionary(x => x.AttributeCode, y => y.AttributeID); var vendorStock = stockRepo.GetAll(x => x.VendorID == VendorID).ToDictionary(x => x.ProductID, y => y); var prodType = products.First().GetType(); var currentProductGroupVendors = productGroupVendorRepo.GetAll(v => v.VendorID == VendorID).ToList(); log.InfoFormat(todo + " products to be processed"); while (done < todo) { log.DebugFormat("{0} products to be processed", todo - done); var toProcess = products.OrderByDescending(x => x.UsrReleaseDate).Skip(done).Take(step); foreach (var product in toProcess) { try { if (product.ProductGroupCode != "GAMES" && product.ProductGroupCode != "HARDWARE") { continue; } //#if DEBUG // if (product.EAN != "8714025503775") // continue; //#endif //log.DebugFormat("{0} products to be processed in batch", toProcess.Count()); var assortment = new Concentrator.Objects.Vendors.Bulk.VendorAssortmentBulk.VendorAssortmentItem { #region BrandVendor BrandVendors = new List <VendorAssortmentBulk.VendorImportBrand>() { new VendorAssortmentBulk.VendorImportBrand() { VendorID = VendorID, VendorBrandCode = BrandVendorCode, ParentBrandCode = null, Name = product.GenreName } }, #endregion #region GeneralProductInfo VendorProduct = new VendorAssortmentBulk.VendorProduct { VendorItemNumber = product.EAN, CustomItemNumber = product.ProductID, ShortDescription = product.Description.Length > 150 ? product.Description.Substring(0, 150) : product.Description, LongDescription = product.Description, LineType = "S", LedgerClass = null, ProductDesk = null, ExtendedCatalog = null, VendorID = VendorID, DefaultVendorID = DefaultVendorID, VendorBrandCode = BrandVendorCode, Barcode = product.EAN, VendorProductGroupCode1 = product.ProductGroupCode, VendorProductGroupCodeName1 = product.ProductGroup, VendorProductGroupCode2 = product.SubProductGroupCode, VendorProductGroupCodeName2 = product.SubProductGroup, VendorProductGroupCode3 = product.GenreName //VendorProductGroupCodeName3 = product.SubProductGroup }, #endregion #region RelatedProducts RelatedProducts = new List <VendorAssortmentBulk.VendorImportRelatedProduct>() { new Concentrator.Objects.Vendors.Bulk.VendorAssortmentBulk.VendorImportRelatedProduct { VendorID = VendorID, DefaultVendorID = DefaultVendorID, CustomItemNumber = product.ProductID, RelatedProductType = relatedProductType.Type, RelatedCustomItemNumber = product.EAN } }, #endregion #region Attributes VendorImportAttributeValues = (from attr in AttributeMapping let prop = product.Equals(attr)//d.Field<object>(attr) let attributeID = attributeList.ContainsKey(attr) ? attributeList[attr] : -1 let value = prop.ToString() where !string.IsNullOrEmpty(value) select new Concentrator.Objects.Vendors.Bulk.VendorAssortmentBulk.VendorImportAttributeValue { VendorID = VendorID, DefaultVendorID = DefaultVendorID, CustomItemNumber = product.ProductID, AttributeID = attributeID, Value = value, LanguageID = "1", AttributeCode = attr, }).ToList(), #endregion #region Prices VendorImportPrices = new List <Concentrator.Objects.Vendors.Bulk.VendorAssortmentBulk.VendorImportPrice>() { new Concentrator.Objects.Vendors.Bulk.VendorAssortmentBulk.VendorImportPrice() { VendorID = VendorID, DefaultVendorID = DefaultVendorID, CustomItemNumber = product.ProductID, Price = decimal.Round(product.RetailPrice, 4).ToString("0.00", CultureInfo.InvariantCulture), CostPrice = decimal.Round(product.SalesPrice.Value, 4).ToString("0.00", CultureInfo.InvariantCulture), TaxRate = "19", //TODO: Calculate this! MinimumQuantity = 1, CommercialStatus = product.ProductStatus } }, #endregion #region Stock VendorImportStocks = new List <Concentrator.Objects.Vendors.Bulk.VendorAssortmentBulk.VendorImportStock>() { new Concentrator.Objects.Vendors.Bulk.VendorAssortmentBulk.VendorImportStock() { VendorID = VendorID, DefaultVendorID = DefaultVendorID, CustomItemNumber = product.ProductID, QuantityOnHand = 0, StockType = "Assortment", StockStatus = product.ProductStatus } }, #endregion }; assortmentList.Add(assortment); } catch (Exception ex) { log.WarnFormat("Batch update failed with message : {0}", ex.Message); } } done += toProcess.Count(); } #region delete unused foreach (var vProdVendor in currentProductGroupVendors) { if (vProdVendor.ProductGroupID == -1) { //productGroupVendorRepo.Delete(vProdVendor); } } #endregion // Creates a new instance of VendorAssortmentBulk(Passes in the AssortmentList defined above, vendorID and DefaultVendorID) using (var vendorAssortmentBulk = new VendorAssortmentBulk(assortmentList, VendorID, VendorID)) { vendorAssortmentBulk.Init(unit.Context); vendorAssortmentBulk.Sync(unit.Context); } log.AuditInfo("Products processing finished. Processed " + done + " products"); } }
protected override void Process() { _monitoring.Notify(Name, 0); var vendorOverridesSetting = GetConfiguration().AppSettings.Settings["VendorIDOverrides"].Try(c => c.Value, string.Empty); if (!string.IsNullOrEmpty(vendorOverridesSetting)) { _vendorIDs = (from p in vendorOverridesSetting.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries) select Convert.ToInt32(p)).ToList(); } var cultureInfoAmerican = CultureInfo.InvariantCulture; List <ProductAttributeMetaData> attributes = new List <ProductAttributeMetaData>(); string connectionString = string.Empty; string stockConnectionString = string.Empty; var pluginConfig = GetConfiguration(); var currentYear = DateTime.Now.Year; using (var unit = GetUnitOfWork()) { connectionString = VendorHelper.GetConnectionStringForPFA(1); //todo: fix vendorid CoolcatPFARepository repository = new CoolcatPFARepository(connectionString, stockConnectionString, log); AssortmentHelper helper = new AssortmentHelper(); try { SetupAttributes(unit, CCAttributeHelper.Attributes, out attributes); } catch (Exception e) { log.Debug(e.InnerException); } var shopWeekLookup = repository.GetShopWeekLookup(); var sizeCodeLookup = repository.GetSizeCodeLookup(); var validArtCodes = repository.GetValidItemNumbers(); var colorNameLookup = repository.GetColorLookup(); Dictionary <string, string> colorCodesDict = new Dictionary <string, string>(); foreach (var vendorID in _vendorIDs) { try { _monitoring.Notify(Name, vendorID); #if DEBUG if (vendorID != 15) { continue; } #endif Dictionary <string, int> justArrivedCounters = new Dictionary <string, int>(); var vendor = unit.Scope.Repository <Vendor>().GetSingle(c => c.VendorID == vendorID); var shouldNotCheckForSolden = vendor.VendorSettings.GetValueByKey <bool>("NonSoldenVendor", false); var vendorDoesNotImportDescription = vendor.VendorSettings.GetValueByKey <bool>("VendorDoesNotImportDescriptions", false); var countryCode = VendorHelper.GetCountryCode(vendorID); log.Info("Starting import for vendor " + vendor.Name); var connectorID = vendor.ContentProducts.Select(x => x.ConnectorID).FirstOrDefault(); bool isSolden; if (shouldNotCheckForSolden) { isSolden = true; } else if (connectorID == null || !GetSoldenPeriod(connectorID, out isSolden)) { throw new Exception("Solden period values are corrupt."); } var parentVendorID = vendor.ParentVendorID.HasValue ? vendor.ParentVendorID.Value : vendor.VendorID; var currencyCode = vendor.VendorSettings.FirstOrDefault(c => c.SettingKey == "PFACurrencyCode").Try(c => c.Value, string.Empty); currencyCode.ThrowIfNullOrEmpty(new InvalidOperationException("Missing PFA currency code")); List <Concentrator.Objects.Vendors.Bulk.VendorAssortmentBulk.VendorAssortmentItem> items = new List <Concentrator.Objects.Vendors.Bulk.VendorAssortmentBulk.VendorAssortmentItem>(); List <Concentrator.Objects.Vendors.Bulk.VendorBarcodeBulk.VendorImportBarcode> vendorBarcodes = new List <VendorBarcodeBulk.VendorImportBarcode>(); log.Info("Found products in total: " + validArtCodes.Count()); int counter = 0; foreach (var itemNumber in validArtCodes) { var productInfo = repository.GetGeneralProductInformation(itemNumber, countryCode); //productInfo.TaxRate = productInfo.TaxRate.Replace("%", string.Empty); var rate = helper.GetCurrentBTWRate(productInfo.TaxRatePercentage, productInfo.TaxRateDates, 21, productInfo.TaxCode); counter++; if (counter % 100 == 0) { log.Info("Found " + counter); } if (!justArrivedCounters.ContainsKey(productInfo.GroupName1)) { justArrivedCounters.Add(productInfo.GroupName1, 0); } var priceRules = repository.GetProductPriceRules(itemNumber, currencyCode); if (!string.IsNullOrEmpty(productInfo.override_tax_code)) { rate = helper.GetCurrentBTWRate(productInfo.override_tax_rates, productInfo.override_tax_dates, 21, productInfo.override_tax_code); } DateTime?weekShop = null; shopWeekLookup.TryGetValue(itemNumber, out weekShop); Concentrator.Objects.Vendors.Bulk.VendorAssortmentBulk.VendorAssortmentItem itemToAdd = null; if (itemNumber != PfaCoolcatConfiguration.Current.ShipmentCostsProduct && itemNumber != PfaCoolcatConfiguration.Current.ReturnCostsProduct && itemNumber != PfaCoolcatConfiguration.Current.KialaShipmentCostsProduct && itemNumber != PfaCoolcatConfiguration.Current.KialaReturnCostsProduct) { itemToAdd = new Concentrator.Objects.Vendors.Bulk.VendorAssortmentBulk.VendorAssortmentItem { BrandVendors = new List <VendorAssortmentBulk.VendorImportBrand>() { GetVendorBrand(vendorID) }, VendorProduct = GetVendorProduct(itemNumber, productInfo.ShortDescription, productInfo.Material, vendorID, parentVendorID, true, productInfo.GroupCode1, productInfo.GroupName1, productInfo.GroupCode2, productInfo.GroupName2, productInfo.GroupCode3, productInfo.GroupName3), VendorProductDescriptions = vendorDoesNotImportDescription ? new List <Concentrator.Objects.Vendors.Bulk.VendorAssortmentBulk.VendorProductDescription>() : GetProductDescriptions(itemNumber, vendorID, parentVendorID, productInfo, _languageIDs), VendorImportAttributeValues = GetAttributesOnConfigurableLevel(productInfo, itemNumber, attributes, CONCENTRATOR_VENDOR_ID, vendorID), RelatedProducts = new List <VendorAssortmentBulk.VendorImportRelatedProduct>(), VendorImportPrices = new List <Concentrator.Objects.Vendors.Bulk.VendorAssortmentBulk.VendorImportPrice>() { GetVendorPrice(vendorID, parentVendorID, itemNumber, "0", rate.ToString(cultureInfoAmerican), "0", LEVEL_NOT_EXPORTABLE_STATUS) }, VendorImportStocks = new List <Concentrator.Objects.Vendors.Bulk.VendorAssortmentBulk.VendorImportStock>() }; items.Add(itemToAdd); } int?shopWeekNumber = null; if (weekShop.HasValue) { Calendar cal = new CultureInfo("nl-NL").Calendar; shopWeekNumber = cal.GetWeekOfYear(weekShop.Value, CalendarWeekRule.FirstFourDayWeek, DayOfWeek.Sunday); } if (itemToAdd != null && shopWeekNumber.HasValue) { itemToAdd.VendorImportAttributeValues.Add(new Concentrator.Objects.Vendors.Bulk.VendorAssortmentBulk.VendorImportAttributeValue() { AttributeCode = SHOP_WEEK_ATTRIBUTE_CODE, Value = weekShop.Value.Year.ToString() + shopWeekNumber.ToString().PadLeft(2, '0'), AttributeID = attributes.FirstOrDefault(c => c.AttributeCode == SHOP_WEEK_ATTRIBUTE_CODE).AttributeID, CustomItemNumber = itemNumber, DefaultVendorID = vendorID, LanguageID = null, VendorID = CONCENTRATOR_VENDOR_ID }); } var skus = repository.GetValidSkus(itemNumber); var skuSpecs = repository.GetSkuSpecifications(itemNumber); //process color level foreach (var colorLevel in skus.GroupBy(c => c.ColorCode)) { var colorItemNumber = string.Format("{0} {1}", itemNumber, colorLevel.Key).Trim(); Concentrator.Objects.Vendors.Bulk.VendorAssortmentBulk.VendorAssortmentItem colorLevelProduct = null; if (itemNumber != PfaCoolcatConfiguration.Current.ShipmentCostsProduct && itemNumber != PfaCoolcatConfiguration.Current.ReturnCostsProduct && itemNumber != PfaCoolcatConfiguration.Current.KialaShipmentCostsProduct && itemNumber != PfaCoolcatConfiguration.Current.KialaReturnCostsProduct) { colorLevelProduct = new Concentrator.Objects.Vendors.Bulk.VendorAssortmentBulk.VendorAssortmentItem() { BrandVendors = new List <VendorAssortmentBulk.VendorImportBrand>() { GetVendorBrand(vendorID) }, VendorProduct = GetVendorProduct(colorItemNumber, productInfo.ShortDescription, productInfo.Material, vendorID, parentVendorID, true, productInfo.GroupCode1, productInfo.GroupName1, productInfo.GroupCode2, productInfo.GroupName2, productInfo.GroupCode3, productInfo.GroupName3, parentCustomItemNumber: itemNumber), VendorProductDescriptions = vendorDoesNotImportDescription ? new List <Concentrator.Objects.Vendors.Bulk.VendorAssortmentBulk.VendorProductDescription>() : GetProductDescriptions(colorItemNumber, vendorID, parentVendorID, productInfo, _languageIDs), VendorImportAttributeValues = GetAttributesOnConfigurableLevel(productInfo, colorItemNumber, attributes, CONCENTRATOR_VENDOR_ID, vendorID), RelatedProducts = new List <VendorAssortmentBulk.VendorImportRelatedProduct>( (from rp in skus.GroupBy(c => c.ColorCode) where rp.Key != colorLevel.Key select new Concentrator.Objects.Vendors.Bulk.VendorAssortmentBulk.VendorImportRelatedProduct() { CustomItemNumber = colorItemNumber, DefaultVendorID = vendorID, VendorID = vendorID, IsConfigured = 0, RelatedCustomItemNumber = string.Format("{0} {1}", itemNumber, rp.Key).Trim(), RelatedProductType = "Related Color Level" }).ToList() ), VendorImportPrices = new List <Concentrator.Objects.Vendors.Bulk.VendorAssortmentBulk.VendorImportPrice>() { GetVendorPrice(vendorID, parentVendorID, colorItemNumber, "0", rate.ToString(cultureInfoAmerican), "0") }, VendorImportStocks = new List <Concentrator.Objects.Vendors.Bulk.VendorAssortmentBulk.VendorImportStock>() }; if (colorLevelProduct != null && shopWeekNumber.HasValue) { colorLevelProduct.VendorImportAttributeValues.Add(new Concentrator.Objects.Vendors.Bulk.VendorAssortmentBulk.VendorImportAttributeValue() { AttributeCode = SHOP_WEEK_ATTRIBUTE_CODE, Value = weekShop.Value.Year.ToString() + shopWeekNumber.ToString().PadLeft(2, '0'), AttributeID = attributes.FirstOrDefault(c => c.AttributeCode == SHOP_WEEK_ATTRIBUTE_CODE).AttributeID, CustomItemNumber = colorItemNumber, DefaultVendorID = vendorID, LanguageID = null, VendorID = CONCENTRATOR_VENDOR_ID }); } items.Add(colorLevelProduct); if (itemToAdd != null) { itemToAdd.RelatedProducts.Add(new VendorAssortmentBulk.VendorImportRelatedProduct() { CustomItemNumber = itemNumber, RelatedCustomItemNumber = colorItemNumber, IsConfigured = 0, DefaultVendorID = parentVendorID, VendorID = vendorID, RelatedProductType = "Style" }); } } if (justArrivedCounters[productInfo.GroupName1] < 60) { if (weekShop.HasValue) { var daysInRange = (DateTime.Now - weekShop.Value).Days; if (daysInRange >= 0 && daysInRange <= 14) { if (colorLevelProduct != null) { colorLevelProduct.VendorProduct.VendorProductGroupCode4 = "Just arrived"; colorLevelProduct.VendorProduct.VendorProductGroupCodeName4 = "Just arrived"; justArrivedCounters[productInfo.GroupName1]++; } } } } foreach (var sku in colorLevel) { var skuBarcode = CompleteBarcode(sku.Barcode); int webshopStock = 0; int ceyenneStock = 0; int transferStock = 0; int wmsStock = 0; string sizeCodePfa = sku.SizeCode; foreach (var lookupT in new List <string>() { productInfo.MtbCode1, productInfo.MtbCode2, productInfo.MtbCode3, productInfo.MtbCode4 }) { var lookup = sizeCodeLookup.FirstOrDefault(c => c.SizeCode.ToLower() == sku.SizeCode.ToLower() && c.MtbCode.ToLower() == lookupT.ToLower()); if (lookup != null) { sizeCodePfa = lookup.PfaCode; break; } } var product = new Concentrator.Objects.Vendors.Bulk.VendorAssortmentBulk.VendorAssortmentItem(); string skuNew = string.Empty; if (itemNumber == PfaCoolcatConfiguration.Current.ShipmentCostsProduct || itemNumber == PfaCoolcatConfiguration.Current.ReturnCostsProduct || itemNumber == PfaCoolcatConfiguration.Current.KialaShipmentCostsProduct || itemNumber == PfaCoolcatConfiguration.Current.KialaReturnCostsProduct) { skuNew = itemNumber; } else { skuNew = string.Format("{0} {1} {2}", itemNumber, sku.ColorCode, sku.SizeCode); } Concentrator.Objects.Vendors.Bulk.VendorBarcodeBulk.VendorImportBarcode bc = new VendorBarcodeBulk.VendorImportBarcode() { CustomItemNumber = skuNew, Barcode = sizeCodePfa, Type = 4, VendorID = 1 }; vendorBarcodes.Add(bc); var price = helper.GetPrice(itemNumber, sku.ColorCode, sku.SizeCode, priceRules); var discount = helper.GetDiscount(itemNumber, sku.ColorCode, sku.SizeCode, priceRules); if (!isSolden) { if (discount.HasValue) { price = discount.Value; discount = null; } } var item = items.Where(c => c.VendorProduct.CustomItemNumber == itemNumber); if (item == null) { continue; } product = new Concentrator.Objects.Vendors.Bulk.VendorAssortmentBulk.VendorAssortmentItem() { VendorProduct = GetVendorProduct(skuNew, productInfo.ShortDescription, productInfo.LongDescription, vendorID, parentVendorID, false, productInfo.GroupCode1, productInfo.GroupName1, productInfo.GroupCode2, productInfo.GroupName2, productInfo.GroupCode3, productInfo.GroupName3, parentCustomItemNumber: colorItemNumber, barcode: skuBarcode), VendorProductDescriptions = vendorDoesNotImportDescription ? new List <Concentrator.Objects.Vendors.Bulk.VendorAssortmentBulk.VendorProductDescription>() : GetProductDescriptions(skuNew, vendorID, parentVendorID, productInfo, _languageIDs), BrandVendors = new List <VendorAssortmentBulk.VendorImportBrand>() { GetVendorBrand(vendorID) }, VendorImportAttributeValues = (from m in CCAttributeHelper.Attributes where m.Configurable let aM = attributes.FirstOrDefault(c => c.AttributeCode.ToLower() == m.Code.ToLower()) select new Concentrator.Objects.Vendors.Bulk.VendorAssortmentBulk.VendorImportAttributeValue { AttributeCode = aM.AttributeCode, AttributeID = aM.AttributeID, CustomItemNumber = skuNew, DefaultVendorID = vendorID, LanguageID = null, VendorID = CONCENTRATOR_VENDOR_ID, Value = (m.Code.ToLower() == "color" ? sku.ColorCode : sku.SizeCode) }).ToList(), RelatedProducts = new List <VendorAssortmentBulk.VendorImportRelatedProduct>(), VendorImportPrices = new List <Concentrator.Objects.Vendors.Bulk.VendorAssortmentBulk.VendorImportPrice>() { GetVendorPrice(vendorID, parentVendorID, skuNew, price.ToString(cultureInfoAmerican), rate.ToString(cultureInfoAmerican), (discount.HasValue && discount.Value < price)? discount.Value.ToString(cultureInfoAmerican) :null) }, VendorImportStocks = new List <Concentrator.Objects.Vendors.Bulk.VendorAssortmentBulk.VendorImportStock>() }; if ((discount.HasValue && discount.Value > 0) && (price != discount)) { if (itemToAdd != null) { //That is because code4 might be filled with just arrived if (string.IsNullOrEmpty(colorLevelProduct.VendorProduct.VendorProductGroupCode4)) { colorLevelProduct.VendorProduct.VendorProductGroupCode4 = "SALE"; colorLevelProduct.VendorProduct.VendorProductGroupCodeName4 = "SALE"; } else { colorLevelProduct.VendorProduct.VendorProductGroupCode5 = "SALE"; colorLevelProduct.VendorProduct.VendorProductGroupCodeName5 = "SALE"; } if (string.IsNullOrEmpty(itemToAdd.VendorProduct.VendorProductGroupCode4)) { itemToAdd.VendorProduct.VendorProductGroupCode4 = "SALE"; itemToAdd.VendorProduct.VendorProductGroupCodeName4 = "SALE"; } else { itemToAdd.VendorProduct.VendorProductGroupCode5 = "SALE"; itemToAdd.VendorProduct.VendorProductGroupCodeName5 = "SALE"; } if (string.IsNullOrEmpty(product.VendorProduct.VendorProductGroupCode4)) { product.VendorProduct.VendorProductGroupCode4 = "SALE"; product.VendorProduct.VendorProductGroupCodeName4 = "SALE"; } else { product.VendorProduct.VendorProductGroupCode5 = "SALE"; product.VendorProduct.VendorProductGroupCodeName5 = "SALE"; } } } var attributeColorRows = skuSpecs.Where(c => c.ColorCode == sku.ColorCode).ToList(); var mentality = GetAttributeValue(attributeColorRows, "Mentality"); var input = GetAttributeValue(attributeColorRows, "Input"); var Style = GetAttributeValue(attributeColorRows, "Style"); var Usermoment = GetAttributeValue(attributeColorRows, "Usermoment"); var Module = GetAttributeValue(attributeColorRows, "Module"); AddAttributeValue(itemToAdd, "Mentality", mentality, attributes, itemNumber, CONCENTRATOR_VENDOR_ID, vendorID); AddAttributeValue(itemToAdd, "Style", Style, attributes, itemNumber, CONCENTRATOR_VENDOR_ID, vendorID); AddAttributeValue(itemToAdd, "Usermoment", Usermoment, attributes, itemNumber, CONCENTRATOR_VENDOR_ID, vendorID); AddAttributeValue(product, "Module", Module, attributes, skuNew, CONCENTRATOR_VENDOR_ID, vendorID); AddAttributeValue(itemToAdd, "InputCode", input, attributes, itemNumber, CONCENTRATOR_VENDOR_ID, vendorID); AddAttributeValue(itemToAdd, "Gender", DetermineGenderByVendorItemNumber(itemNumber), attributes, itemNumber, CONCENTRATOR_VENDOR_ID, vendorID); items.Add(product); if (colorLevelProduct != null) { //relate to main product if (colorLevelProduct.RelatedProducts.Where(c => c.CustomItemNumber == colorItemNumber && c.RelatedCustomItemNumber == skuNew).FirstOrDefault() == null) { colorLevelProduct.RelatedProducts.Add(new VendorAssortmentBulk.VendorImportRelatedProduct() { CustomItemNumber = colorItemNumber, DefaultVendorID = parentVendorID, IsConfigured = 1, RelatedCustomItemNumber = skuNew, RelatedProductType = "Configured product", VendorID = vendorID }); } } } } } var bulkConfig = new VendorAssortmentBulkConfiguration(); using (var vendorAssortmentBulk = new VendorAssortmentBulk(items, vendorID, parentVendorID, bulkConfig)) { vendorAssortmentBulk.Init(unit.Context); vendorAssortmentBulk.Sync(unit.Context); } using (var barcodeBulk = new VendorBarcodeBulk(vendorBarcodes, vendorID, 4)) { barcodeBulk.Init(unit.Context); barcodeBulk.Sync(unit.Context); } } catch (Exception e) { log.AuditCritical("Import failed for vendor " + vendorID, e); _monitoring.Notify(Name, -vendorID); } } AddValueLabels(unit, colorCodesDict); ConfigureProductAttributes(_vendorIDs, unit); } _monitoring.Notify(Name, 1); }
protected override void SyncProducts() { var UserName = Config.AppSettings.Settings["Username"].Value; var Password = Config.AppSettings.Settings["Password"].Value; SessionService.SessionServiceClient session = new SessionService.SessionServiceClient(); var key = session.Try(x => x.GetSessionKey(UserName, Password), string.Empty); //If session failed if (!key.Equals(string.Empty)) { log.AuditFatal("Failed to create session"); return; } ProductInfoService.ProductInfoServiceClient client = new ProductInfoService.ProductInfoServiceClient(); var prodsList = client.GetFullProductListExtended(key).ItemInfos; var prodsNames = client.GetFullDeviceList(key); var itemProducts = (from p in prodsList join prod in prodsNames on p.ItemReference equals prod.ItemReference select new { ProductName = prod.Name, ShortDescription = p.Description, //OtherDescription = p.DescriptionFR, LongDescription = p.DescriptionFR, //checken of dit klopt!! Brand = p.Category2, VendorProductGroupCodeName3 = p.Category1, VendorProductGroupCodeName2 = p.Category3, VendorProductGroupCodeName1 = p.Category4, VendorProductGroupCode3 = p.CategoryCode.Substring(0, 3), VendorProductGroupCode2 = p.CategoryCode.Substring(6, 3), VendorProductGroupCode1 = p.CategoryCode.Substring(9, 3), Currency = p.Currency, RelatedProduct = p.Devices, p.Images, p.InStock, CostPrice = p.Price1Piece, Price = p.PriceEndUser, CustomItemNumber = p.ItemReference.OurItemNo, EAN = p.ItemReference.EANCode, VendorItemNumber = p.ItemReference.VendorItemNo }); List <Concentrator.Objects.Vendors.Bulk.VendorAssortmentBulk.VendorAssortmentItem> assortmentList = new List <Concentrator.Objects.Vendors.Bulk.VendorAssortmentBulk.VendorAssortmentItem>(); int counter = 0; int total = itemProducts.Count(); int totalNumberOfProductsToProcess = total; log.InfoFormat("Start processing {0} products", total); using (var unit = GetUnitOfWork()) { foreach (var product in itemProducts) { var languageID = 2; //switch (product.Language) //{ // case "nl-NL": // languageID = 2; // break; // case "en-GB": // languageID = 1; // break; // default: // continue; //} if (counter == 50) { counter = 0; log.InfoFormat("Still need to process {0} of {1}; {2} done;", totalNumberOfProductsToProcess, total, total - totalNumberOfProductsToProcess); } totalNumberOfProductsToProcess--; counter++; var assortment = new Concentrator.Objects.Vendors.Bulk.VendorAssortmentBulk.VendorAssortmentItem { #region BrandVendor BrandVendors = new List <VendorAssortmentBulk.VendorImportBrand>() { new VendorAssortmentBulk.VendorImportBrand() { VendorID = VendorID, VendorBrandCode = product.Brand.Trim(), ParentBrandCode = null, Name = product.Brand.Trim() } }, #endregion #region GeneralProductInfo VendorProduct = new VendorAssortmentBulk.VendorProduct { VendorItemNumber = product.VendorItemNumber.Trim(), //EAN CustomItemNumber = product.CustomItemNumber.Trim(), //EAN ShortDescription = product.ShortDescription != null ? product.ShortDescription.Length > 150 ? product.ShortDescription.Substring(0, 150) : product.ShortDescription : string.Empty, LongDescription = product.ShortDescription != null ? product.ShortDescription.Length > 1000 ? product.ShortDescription.Substring(0, 1000) : product.ShortDescription : string.Empty, LineType = null, LedgerClass = null, ProductDesk = null, ExtendedCatalog = null, VendorID = VendorID, DefaultVendorID = DefaultVendorID, VendorBrandCode = product.Brand.Trim(), //UITGEVER_ID Barcode = product.Try(x => x.EAN, string.Empty), //EAN VendorProductGroupCode1 = product.Try(x => x.VendorProductGroupCode1, string.Empty), VendorProductGroupCodeName1 = product.Try(x => x.VendorProductGroupCodeName1, string.Empty), VendorProductGroupCode2 = product.Try(x => x.VendorProductGroupCode2, string.Empty), VendorProductGroupCodeName2 = product.Try(x => x.VendorProductGroupCodeName2, string.Empty), VendorProductGroupCode3 = product.Try(x => x.VendorProductGroupCode3, string.Empty), VendorProductGroupCodeName3 = product.Try(x => x.VendorProductGroupCodeName3, string.Empty), }, #endregion #region RelatedProducts RelatedProducts = new List <VendorAssortmentBulk.VendorImportRelatedProduct>() { //new Concentrator.Objects.Vendors.Bulk.VendorAssortmentBulk.VendorImportRelatedProduct //{ // VendorID = VendorID, // DefaultVendorID = DefaultVendorID, // CustomItemNumber = product.ProductID.Trim(), //EAN // RelatedProductType = string.Empty, // RelatedCustomItemNumber = string.Empty //} }, #endregion #region Attributes VendorImportAttributeValues = new List <VendorAssortmentBulk.VendorImportAttributeValue>(), #endregion #region Prices VendorImportPrices = new List <Concentrator.Objects.Vendors.Bulk.VendorAssortmentBulk.VendorImportPrice>() { new Concentrator.Objects.Vendors.Bulk.VendorAssortmentBulk.VendorImportPrice() { VendorID = VendorID, DefaultVendorID = DefaultVendorID, CustomItemNumber = product.CustomItemNumber.Trim(), //EAN Price = product.Price.ToString(), //.ToString("0.00", CultureInfo.InvariantCulture) , CostPrice = product.CostPrice.ToString(), //.ToString("0.00", CultureInfo.InvariantCulture), //NETTOPRIJS TaxRate = "19", //TODO: Calculate this! MinimumQuantity = 0, CommercialStatus = product.InStock > 0 ? "InStock" : "OutOfStock" } }, #endregion #region Stock VendorImportStocks = new List <Concentrator.Objects.Vendors.Bulk.VendorAssortmentBulk.VendorImportStock>() { new Concentrator.Objects.Vendors.Bulk.VendorAssortmentBulk.VendorImportStock() { VendorID = VendorID, DefaultVendorID = DefaultVendorID, CustomItemNumber = product.CustomItemNumber.Trim(), //EAN QuantityOnHand = product.InStock, StockType = "Assortment", StockStatus = product.InStock > 0 ? "InStock" : "OutOfStock" } }, #endregion #region Descriptions VendorProductDescriptions = new List <VendorAssortmentBulk.VendorProductDescription>() { new VendorAssortmentBulk.VendorProductDescription() { VendorID = VendorID, LanguageID = languageID, DefaultVendorID = VendorID, CustomItemNumber = product.CustomItemNumber.Trim(), //EAN LongContentDescription = product.LongDescription, ShortContentDescription = product.LongDescription != string.Empty ? product.LongDescription.Length > 1000 ? product.LongDescription.Substring(0, 1000) : product.LongDescription : product.ShortDescription, ProductName = product.ProductName } } #endregion }; // assortment will be added to the list defined outside of this loop assortmentList.Add(assortment); } // Creates a new instance of VendorAssortmentBulk(Passes in the AssortmentList defined above, vendorID and DefaultVendorID) using (var vendorAssortmentBulk = new VendorAssortmentBulk(assortmentList, VendorID, DefaultVendorID)) { //vendorAssortmentBulk.IncludeBrandMapping = true; vendorAssortmentBulk.Init(unit.Context); vendorAssortmentBulk.Sync(unit.Context); } } throw new NotImplementedException(); }
protected override void SyncProducts() { var CustNo = Config.AppSettings.Settings["BrightPointCustomerNo"].Value; var Pass = Config.AppSettings.Settings["BrightPointPassword"].Value; var Instance = Config.AppSettings.Settings["BrightPointInstance"].Value; var Site = Config.AppSettings.Settings["BrightPointSite"].Value; var WorkingDirectory = Config.AppSettings.Settings["WorkingDirectory"].Value; int VendorID = Int32.Parse(Config.AppSettings.Settings["vendorID"].Value); int DefaultVendorID = Int32.Parse(Config.AppSettings.Settings["vendorID"].Value); if (!Directory.Exists(WorkingDirectory)) { Directory.CreateDirectory(WorkingDirectory); } BrightPointService.AuthHeaderUser authHeader = new BrightPointService.AuthHeaderUser(); authHeader.sCustomerNo = CustNo; authHeader.sInstance = Instance; authHeader.sPassword = Pass; authHeader.sSite = Site; #region Get Data BrightPointService.Category[] brandsList = null; BrightPointService.Category[] categories_LOB = null; BrightPointService.Category[] categories_Types = null; //BrightPointService.Language[] languages = null; //BrightPointService.InventoryInStock[] inventory; //BrightPointService.SalesPart_ProjectStockItems[] pstock; BrightPointService.SalesPart[] catalog = null; using (BrightPointService.PartcatalogSoapClient client = new BrightPointService.PartcatalogSoapClient("Part catalogSoap")) { try { #region salesPart var salesFile = Path.Combine(WorkingDirectory, "SalesPart.xml"); if (!File.Exists(salesFile) || new FileInfo(salesFile).LastWriteTime.AddHours(1) < DateTime.Now) { catalog = client.getSalesPartCatalog(authHeader); XmlSerializer seri = new XmlSerializer(typeof(SalesPart[])); using (TextWriter writer = new StreamWriter(salesFile)) { seri.Serialize(writer, catalog); } } //catalog from file XmlSerializer ser = new XmlSerializer(typeof(SalesPart[])); using (StreamReader reader = new StreamReader(salesFile)) { catalog = (SalesPart[])ser.Deserialize(reader); } #endregion #region Brandlist var brandFile = Path.Combine(WorkingDirectory, "Brand.xml"); if (!File.Exists(brandFile) || new FileInfo(brandFile).LastWriteTime.AddHours(1) < DateTime.Now) { brandsList = client.getCategory_Brand(authHeader); XmlSerializer serBrand = new XmlSerializer(typeof(Category[])); using (TextWriter writer = new StreamWriter(brandFile)) { serBrand.Serialize(writer, brandsList); } } //brandslist from file XmlSerializer ser2 = new XmlSerializer(typeof(Category[])); using (StreamReader reader = new StreamReader(brandFile)) { brandsList = (Category[])ser2.Deserialize(reader); } #endregion #region Catalog var categoryFile = Path.Combine(WorkingDirectory, "Category.xml"); if (!File.Exists(categoryFile) || new FileInfo(categoryFile).LastWriteTime.AddHours(1) < DateTime.Now) { categories_LOB = client.getCategory_LineOfBusiness(authHeader, "NED"); XmlSerializer serCat = new XmlSerializer(typeof(Category[])); using (TextWriter writer = new StreamWriter(categoryFile)) { serCat.Serialize(writer, categories_LOB); } } //LOB list from file XmlSerializer ser3 = new XmlSerializer(typeof(Category[])); using (StreamReader reader = new StreamReader(categoryFile)) { categories_LOB = (Category[])ser3.Deserialize(reader); } #endregion #region Catalog_types var categoryFileType = Path.Combine(WorkingDirectory, "Category_types.xml"); if (!File.Exists(categoryFileType) || new FileInfo(categoryFileType).LastWriteTime.AddHours(1) < DateTime.Now) { //Types list from file categories_Types = client.getCategory_Types(authHeader, "NED"); XmlSerializer serCatType = new XmlSerializer(typeof(Category[])); using (TextWriter writer = new StreamWriter(categoryFileType)) { serCatType.Serialize(writer, categories_Types); } } XmlSerializer ser4 = new XmlSerializer(typeof(Category[])); using (StreamReader reader = new StreamReader(categoryFileType)) { categories_Types = (Category[])ser4.Deserialize(reader); } #endregion // XmlSerializer ser = new XmlSerializer(typeof(SalesPart[])); // //using (TextWriter writer = new StreamWriter(@"C:\test.xml")) // //{ // // ser.Serialize(writer, a); // //} // using (StreamReader reader = new StreamReader(@"C:\test.xml")) // { // catalog = (SalesPart[])ser.Deserialize(reader); // } } catch (Exception ex) { log.AuditError("Error Brightpoint", ex); } #endregion using (var unit = GetUnitOfWork()) { List <ProductAttributeMetaData> attributes; //SetupAttributes(unit, AttributeMapping, out attributes, null); //Used for VendorImportAttributeValues var productAttributes = unit.Scope.Repository <ProductAttributeMetaData>().GetAll(c => c.VendorID == DefaultVendorID).ToList(); var attributeList = productAttributes.ToDictionary(x => x.AttributeCode, y => y.AttributeID); List <VendorAssortmentBulk.VendorAssortmentItem> assortmentList = new List <Concentrator.Objects.Vendors.Bulk.VendorAssortmentBulk.VendorAssortmentItem>(); // Create new stopwatch Stopwatch stopwatch = new Stopwatch(); // Loops through all the rowss foreach (var product in catalog) { BrightPointService.SalesPart_Attributes[] atts = null; //get product attributes try { if (stopwatch.Elapsed.Seconds > 0) { while (stopwatch.Elapsed.Seconds < 15) { log.Info("Wainting for download"); } stopwatch.Reset(); } atts = client.getSalesPartCatalog_Attributes(authHeader, product.SalesPartID, "NED"); // Begin timing stopwatch.Start(); } catch (Exception ex) { log.AuditWarning("Error while retreiving product attributes"); } if (atts == null) { atts = new SalesPart_Attributes[1]; } // Line is a row of data seperated by semicolons. The values will be split and added to the column array var br = product.CatalogGroup.Substring(0, 2); var lob = product.CatalogGroup.Substring(2, 2); var type = product.CatalogGroup.Substring(4, 2); var assortment = new Concentrator.Objects.Vendors.Bulk.VendorAssortmentBulk.VendorAssortmentItem { #region BrandVendor BrandVendors = new List <VendorAssortmentBulk.VendorImportBrand>() { new VendorAssortmentBulk.VendorImportBrand() { VendorID = DefaultVendorID, VendorBrandCode = brandsList.FirstOrDefault(x => x.Code == br) != null?brandsList.FirstOrDefault(x => x.Code == br).Code.Trim() : br.Trim(), //UITGEVER_ID ParentBrandCode = null, Name = brandsList.FirstOrDefault(x => x.Code == br) != null?brandsList.First(x => x.Code == br).Value.Trim() : br.Trim() //UITGEVER_NM } }, #endregion #region GeneralProductInfo VendorProduct = new VendorAssortmentBulk.VendorProduct { VendorItemNumber = product.InventoryManufacturerPartNo.ToString().Trim(), //EAN CustomItemNumber = product.SalesPartID.ToString(), //EAN ShortDescription = product.Description.Length > 150 ? product.Description.Substring(0, 150).Trim() : product.Description.Trim(), //Subtitel LongDescription = product.Description.Trim(), LineType = null, LedgerClass = null, ProductDesk = null, ExtendedCatalog = null, VendorID = VendorID, DefaultVendorID = DefaultVendorID, VendorBrandCode = brandsList.FirstOrDefault(x => x.Code == br) != null?brandsList.FirstOrDefault(x => x.Code == br).Code.Trim() : br.Trim(), //UITGEVER_ID Barcode = product.EANCode.Trim(), //EAN VendorProductGroupCode1 = lob.Trim(), //REEKS_NR VendorProductGroupCodeName1 = categories_LOB.First(x => x.Code == lob) != null?categories_LOB.First(x => x.Code == lob).Value.Trim() : null, //REEKS_NM VendorProductGroupCode2 = type.Trim(), //BOEKSOORT_KD VendorProductGroupCodeName2 = categories_Types.First(x => x.Code == type) != null?categories_Types.First(x => x.Code == type).Value.Trim() : null //GEEN NAAM }, #endregion #region RelatedProducts RelatedProducts = new List <VendorAssortmentBulk.VendorImportRelatedProduct>() { //new Concentrator.Objects.Vendors.Bulk.VendorAssortmentBulk.VendorImportRelatedProduct //{ // VendorID = VendorID, // DefaultVendorID = DefaultVendorID, // CustomItemNumber = column[0].Trim(), //EAN // RelatedProductType = column[19].Trim(), //ISBN_FYSIEK_BOEK // RelatedCustomItemNumber = column[19].Trim(), //ISBN_FYSIEK_BOEK //} }, #endregion #region Attributes VendorImportAttributeValues = (from attr in atts let attributeID = GetAttributeID(attr.AttributeName, unit) //d.Field<object>(attr) //let attributeID = attributeList.ContainsKey(attr.AttributeName) ? attributeList[attr] : 2//-1 //let value = prop.ToString() where !string.IsNullOrEmpty(attr.AttributeName) select new Concentrator.Objects.Vendors.Bulk.VendorAssortmentBulk.VendorImportAttributeValue { VendorID = VendorID, DefaultVendorID = DefaultVendorID, CustomItemNumber = product.SalesPartID.ToString(), //EAN AttributeID = attributeID, Value = attr.Value, LanguageID = "1", AttributeCode = attr.AttributeName, }).ToList(), #endregion #region Prices VendorImportPrices = new List <Concentrator.Objects.Vendors.Bulk.VendorAssortmentBulk.VendorImportPrice>() { new Concentrator.Objects.Vendors.Bulk.VendorAssortmentBulk.VendorImportPrice() { VendorID = VendorID, DefaultVendorID = DefaultVendorID, CustomItemNumber = product.SalesPartID.ToString().Trim(), //EAN Price = product.UnitPrice.ToString("0.00", CultureInfo.InvariantCulture), //ADVIESPRIJS CostPrice = product.UnitCostPrice.ToString("0.00", CultureInfo.InvariantCulture), //NETTOPRIJS TaxRate = "19", //TODO: Calculate this! MinimumQuantity = 0, CommercialStatus = String.IsNullOrEmpty(product.Flag.ToString()) ? null : product.Flag.ToString().Trim() //STADIUM_LEVENSCYCLUS_KD } }, #endregion #region Stock VendorImportStocks = new List <Concentrator.Objects.Vendors.Bulk.VendorAssortmentBulk.VendorImportStock>() { new Concentrator.Objects.Vendors.Bulk.VendorAssortmentBulk.VendorImportStock() { VendorID = VendorID, DefaultVendorID = DefaultVendorID, CustomItemNumber = product.SalesPartID.ToString().Trim(), //EAN QuantityOnHand = 0, StockType = "Assortment", StockStatus = Enum.GetName(typeof(BrightPointStockStatus), product.Flag)//STADIUM_LEVENSCYCLUS_KD } } //VendorImportImages = new List<Concentrator.Objects.Vendors.Bulk.VendorAssortmentBulk.VendorImportImage>() //{ //} #endregion }; // assortment will be added to the list defined outside of this loop assortmentList.Add(assortment); } // Creates a new instance of VendorAssortmentBulk(Passes in the AssortmentList defined above, vendorID and DefaultVendorID) using (var vendorAssortmentBulk = new VendorAssortmentBulk(assortmentList, VendorID, DefaultVendorID)) { vendorAssortmentBulk.Init(unit.Context); vendorAssortmentBulk.Sync(unit.Context); } bool success = true; } } }
/* * <Products version="1.0"issuedate=20100323"> * <Product id="0011B006AA"> * <Content lang="nl"> * <Description>Printer Inktjet PIXMA iP6220D Kleur</Description> * <Brand id="CAN">Canon</Brand> * <UNSPSC id="43212104">Inkjetprinters</UNSPSC> * <Specifications> * <Specification id="000027"> * <Description>printerfunctionaliteit</Description> * <Value>Printer</Value> * </Specification> * <Specification id="000029"> * <Description>type printer</Description> * <Value>Inktjet</Value> * </Specification> * <Specification id="000026"> * <Description>printernaam</Description> * <Value>PIXMA iP6220D</Value> * </Specification> * <Specification id="000028"> * <Description>type output</Description> * <Value>Kleur</Value> * </Specification> * </Specifications> * </Content> * <Content lang="uk"> * <Description>Printer Inktjet PIXMA iP6220D Colour</Description> * <Brand id="CAN">Canon</Brand> * <UNSPSC id="43212104">Inkjet printers</UNSPSC> * <Specifications> * <Specification id="000027"> * <Description>printer functionality</Description> * <Value>Printer</Value> * </Specification> * <Specification id="000029"> * <Description>printer type</Description> * <Value>Inktjet</Value> * </Specification> * <Specification id="000026"> * <Description>printer name</Description> * <Value>PIXMA iP6220D</Value> * </Specification> * <Specification id="000028"> * <Description>Output type</Description> * <Value>Colour</Value> * </Specification> * </Specifications> * </Content> * <Identifiers> * <OEM>0011B006AA</OEM> * <CustomerID>0011B006AA</CustomerID> * <EANProduct>4960999258423</EANProduct> * <EANMasterCarton></EANMasterCarton> * <OnetrailPDI></OnetrailPDI> * </Identifiers> * <Purchase> * <Stock>0</Stock> * <MOQ>1</MOQ> * <Status>O</Status> * <ReplacedBy></ReplacedBy> * </Purchase> * <Images> * <Product>http://images.alpha-international.eu/products/originals/0011B006AA.JPG</Product> * <Brand>http://images.alpha-international.eu/brands/originals/CAN.GIF</Brand> * </Images> * <Logistics> * <ProductsPerOuterCarton></ProductsPerOuterCarton> * <ProductsPerLayer></ProductsPerLayer> * <ProductsPerPallet></ProductsPerPallet> * <OuterCartonPerPallet></OuterCartonPerPallet> * <Weights unit="gr"> * <ProductWeight>5600</ProductWeight> * <OuterCartonWeight></OuterCartonWeight> * </Weights> * <Measures unit="cm"> * <ProductLength>50.5</ProductLength> * <ProductWidth>37.5</ProductWidth> * <ProductHeight>24.5</ProductHeight> * <OuterCartonLength></OuterCartonLength> * <OuterCartonWidth></OuterCartonWidth> * <OuterCartonHeight></OuterCartonHeight> * </Measures> * </Logistics> * <Compatibility> * <Product>CAN22165</Product> * <Product>CAN22167</Product> * <Product>CAN22166</Product> * <Product>CAN22168</Product> * </Compatibility> * <CrossSell> * </CrossSell> * </Product> * <Product ... > * .... * </Product> * </Products> */ #endregion private bool ProcessXml(XDocument doc, Dictionary <string, ProductIdentifier> relations) { try { var products = from pr in doc.Element("Products").Elements("Product") group pr by new { pr.Element("Identifiers").Element("OEM").Value, ID = pr.Attribute("id").Value } into pro let p = pro.First() let identifiers = p.Element("Identifiers") let purchase = p.Element("Purchase") let oemCode = identifiers.Element("OEM").Value let images = p.Element("Images") let compat = p.Element("Compatibility") select new { VenderItemNumber = p.Attribute("id").Value, Content = from c in p.Elements("Content") let brand = c.Element("Brand") let cat = c.Element("UNSPSC") select new { Language = c.Attribute("lang").Value, Description = c.Element("Description").Value, Brand = new { ID = brand.Attribute("id").Value, Name = brand.Value }, Category = new { ID = cat.Attribute("id").Value, Name = cat.Value } , Specs = c.Element("Specifications") == null ? null : from s in c.Element("Specifications").Elements("Specification") select new { ID = s.Attribute("id").Value, Desc = s.Element("Description").Value, s.Element("Value").Value } }, Identifiers = new { OEM = ((oemCode == "ONBEKEND" || string.IsNullOrEmpty(oemCode)) ? p.Attribute("id").Value : oemCode), CustomerID = identifiers.Element("CustomerID").Value, EAN = identifiers.Element("EANProduct").Value }, InStock = purchase.Element("Stock") != null ? (int)purchase.Element("Stock") : 0, MinQuantity = purchase.Element("MOQ") != null ? (int)purchase.Element("MOQ") : 1, Status = purchase.Element("Status").Value, Price = purchase.Element("Price") != null ? (decimal?)purchase.Element("Price") : null, ProductImages = from i in images.Elements("Product") select i.Value, CompatibleProducts = new ProductIdentifier { productID = p.Attribute("id").Value, compatibleProducts = (compat != null ? (from cp in compat.Elements("Product") select cp.Value).ToList() : new List <string>()) } }; using (var unit = GetUnitOfWork()) { int counter = 0; int total = products.Count(); int totalNumberOfProductsToProcess = total; log.InfoFormat("Start import {0} products", total); var productAttributes = unit.Scope.Repository <ProductAttributeMetaData>().GetAll(c => c.VendorID == VendorID).ToList(); var attributeList = productAttributes.ToDictionary(x => x.AttributeCode, y => y.AttributeID); List <Concentrator.Objects.Vendors.Bulk.VendorAssortmentBulk.VendorAssortmentItem> assortmentList = new List <Concentrator.Objects.Vendors.Bulk.VendorAssortmentBulk.VendorAssortmentItem>(); RelatedProductTypes relatedProductTypes = new RelatedProductTypes(unit.Scope.Repository <RelatedProductType>()); var relatedProductType = relatedProductTypes.SyncRelatedProductTypes("CompatibleProducts"); var AttributeMapping = (from p in products where p.Content != null && p.Content.Count() > 0 from a in p.Content.Where(x => x.Specs != null).SelectMany(x => x.Specs) select a.Desc).Distinct().ToArray(); List <ProductAttributeMetaData> attributes; SetupAttributes(unit, AttributeMapping, out attributes, null); foreach (var product in products) { if (counter == 100) { counter = 0; log.InfoFormat("Still need to process {0} of {1}; {2} done;", totalNumberOfProductsToProcess, total, total - totalNumberOfProductsToProcess); } totalNumberOfProductsToProcess--; counter++; //use english content for all non-language specifics var enContent = product.Content.FirstOrDefault(c => c.Language.ToUpper() == "UK"); if (enContent == null) { enContent = product.Content.FirstOrDefault(c => c.Language.ToUpper() == "NL"); } var assortment = new Concentrator.Objects.Vendors.Bulk.VendorAssortmentBulk.VendorAssortmentItem { #region BrandVendor BrandVendors = new List <VendorAssortmentBulk.VendorImportBrand>() { new VendorAssortmentBulk.VendorImportBrand() { VendorID = VendorID, VendorBrandCode = enContent.Brand.ID, ParentBrandCode = null, Name = enContent.Brand.Name } }, #endregion #region GeneralProductInfo VendorProduct = new VendorAssortmentBulk.VendorProduct { VendorItemNumber = product.Identifiers.OEM, CustomItemNumber = product.VenderItemNumber, ShortDescription = enContent.Description.Length > 150 ? enContent.Description.Substring(0, 150) : enContent.Description, LongDescription = enContent.Description, LineType = null, LedgerClass = null, ProductDesk = null, ExtendedCatalog = null, VendorID = VendorID, DefaultVendorID = DefaultVendorID, VendorBrandCode = enContent.Brand.ID, Barcode = product.Identifiers.EAN, VendorProductGroupCode1 = enContent.Category.ID, VendorProductGroupCodeName1 = enContent.Category.Name }, #endregion #region RelatedProducts RelatedProducts = new List <VendorAssortmentBulk.VendorImportRelatedProduct>() { new Concentrator.Objects.Vendors.Bulk.VendorAssortmentBulk.VendorImportRelatedProduct { VendorID = VendorID, DefaultVendorID = DefaultVendorID, CustomItemNumber = product.VenderItemNumber, RelatedProductType = relatedProductType.Type, RelatedCustomItemNumber = product.VenderItemNumber } }, #endregion #region Attributes VendorImportAttributeValues = (from att in product.Content.Where(x => x.Specs != null).SelectMany(x => x.Specs) let attributeID = attributeList.ContainsKey(att.Desc) ? attributeList[att.Desc] : -1 where !string.IsNullOrEmpty(att.Value) select new Concentrator.Objects.Vendors.Bulk.VendorAssortmentBulk.VendorImportAttributeValue { VendorID = VendorID, DefaultVendorID = DefaultVendorID, CustomItemNumber = product.VenderItemNumber, AttributeID = attributeID, Value = att.Value, LanguageID = 1.ToString(), AttributeCode = att.Desc, }).ToList(), #endregion #region Prices VendorImportPrices = new List <Concentrator.Objects.Vendors.Bulk.VendorAssortmentBulk.VendorImportPrice>() { new Concentrator.Objects.Vendors.Bulk.VendorAssortmentBulk.VendorImportPrice() { VendorID = VendorID, DefaultVendorID = DefaultVendorID, CustomItemNumber = product.VenderItemNumber, Price = product.Price.HasValue ? product.Price.Value.ToString("0.00", CultureInfo.InvariantCulture) : null, CostPrice = null, TaxRate = "19", MinimumQuantity = product.MinQuantity, CommercialStatus = product.Status } }, #endregion #region Stock VendorImportStocks = new List <Concentrator.Objects.Vendors.Bulk.VendorAssortmentBulk.VendorImportStock>() { new Concentrator.Objects.Vendors.Bulk.VendorAssortmentBulk.VendorImportStock() { VendorID = VendorID, DefaultVendorID = DefaultVendorID, CustomItemNumber = product.VenderItemNumber, QuantityOnHand = 0, StockType = "Assortment", StockStatus = product.Status } }, #endregion }; assortmentList.Add(assortment); } using (var vendorAssortmentBulk = new VendorAssortmentBulk(assortmentList, VendorID, VendorID)) { vendorAssortmentBulk.Init(unit.Context); vendorAssortmentBulk.Sync(unit.Context); } return(true); } } catch (Exception ex) { log.AuditFatal(String.Format("Failed to process file"), ex); return(false); } }