示例#1
0
        public void AddAttributeValue(Concentrator.Objects.Vendors.Bulk.VendorAssortmentBulk.VendorAssortmentItem item, string key, string value, List <ProductAttributeMetaData> items, string customItemNumber, int vendorID, int defaultVendorID)
        {
            if (item == null)
            {
                return;
            }



            if (!string.IsNullOrEmpty(value))
            {
                //prevent null refs
                if (item.VendorImportAttributeValues == null)
                {
                    item.VendorImportAttributeValues = new List <VendorAssortmentBulk.VendorImportAttributeValue>();
                }

                if (item.VendorImportAttributeValues.Any(c => c.AttributeCode == key))
                {
                    return;                                                            //if already set
                }
                item.VendorImportAttributeValues.Add(new VendorAssortmentBulk.VendorImportAttributeValue()
                {
                    AttributeCode    = key,
                    AttributeID      = items.First(c => c.AttributeCode.ToLower() == key.ToLower()).AttributeID,
                    CustomItemNumber = customItemNumber,
                    DefaultVendorID  = defaultVendorID,
                    LanguageID       = null,
                    Value            = value,
                    VendorID         = vendorID
                });
            }
        }
示例#2
0
        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;
                }
            }
        }
示例#3
0
        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);
        }
示例#4
0
        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();
        }
示例#5
0
        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 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);
            }
        }
示例#7
0
        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);
                }
            }
        }
示例#8
0
        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));
            }
        }
示例#10
0
        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");
            }
        }
示例#11
0
        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);
                }
            }
        }
示例#12
0
        /*
         * <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);
            }
        }