Пример #1
0
        private void ParseDocuments(IUnitOfWork unit, XDocument[] products, XDocument cont)
        {
            #region Xml Data

            //products = new XDocument[1];
            //products[0] = XDocument.Load(@"C:\Lenmar\test.xml");

            var itemContent = (from content in cont.Root.Elements("item")
                               let attributes = 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 = attributes
            }).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();

            #endregion

            var _brandVendorRepo       = unit.Scope.Repository <BrandVendor>();
            var _productRepo           = unit.Scope.Repository <Product>();
            var _assortmentRepo        = unit.Scope.Repository <VendorAssortment>();
            var productGroupVendorRepo = unit.Scope.Repository <ProductGroupVendor>();
            var _prodDescriptionRepo   = unit.Scope.Repository <ProductDescription>();
            var _attrGroupRepo         = unit.Scope.Repository <ProductAttributeGroupMetaData>();
            var _attrGroupName         = unit.Scope.Repository <ProductAttributeGroupName>();
            var _attrRepo      = unit.Scope.Repository <ProductAttributeMetaData>();
            var _attrNameRepo  = unit.Scope.Repository <ProductAttributeName>();
            var _attrValueRepo = unit.Scope.Repository <ProductAttributeValue>();
            var _mediaRepo     = unit.Scope.Repository <ProductMedia>();
            var _priceRepo     = unit.Scope.Repository <VendorPrice>();
            var _stockRepo     = unit.Scope.Repository <VendorStock>();
            var _barcodeRepo   = unit.Scope.Repository <ProductBarcode>();

            var brands                     = _brandVendorRepo.GetAll(bv => bv.VendorID == VendorID).ToList();
            var productGroups              = productGroupVendorRepo.GetAll(g => g.VendorID == VendorID).ToList();
            var productAttributes          = _attrRepo.GetAll(g => g.VendorID == VendorID).ToList();
            var productAttributeGroups     = _attrGroupRepo.GetAll().ToList();
            var currentProductGroupVendors = productGroupVendorRepo.GetAll(g => g.VendorID == VendorID).ToList();

            ProductStatusVendorMapper mapper = new ProductStatusVendorMapper(unit.Scope.Repository <VendorProductStatus>(), VendorID);

            var unusedVendorAssortmentItems = _assortmentRepo.GetAll(x => x.VendorID == VendorID && x.IsActive == true).ToList();

            int counter = 0;
            int total   = itemProducts.Count();
            int totalNumberOfProductsToProcess = total;
            log.InfoFormat("Start import {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++;

                try
                {
                    #region BrandVendor

                    Product prod = null;
                    //check if brandvendor exists in db
                    var brandVendor = brands.FirstOrDefault(vb => vb.VendorBrandCode == product.VendorBrandCode);

                    if (brandVendor == null) //if brandvendor does not exist
                    {
                        //create new brandVendor
                        brandVendor = new BrandVendor
                        {
                            BrandID         = unmappedID,
                            VendorID        = VendorID,
                            VendorBrandCode = product.VendorBrandCode,
                            Name            = product.VendorBrandCode
                        };
                        _brandVendorRepo.Add(brandVendor);
                        brands.Add(brandVendor);
                    }

                    //use BrandID to create product and retreive ProductID

                    var BrandID = brandVendor.BrandID;

                    var prods = _productRepo.GetAll(p => p.VendorItemNumber == product.SupplierSKU && (p.BrandID == BrandID || p.BrandID < 0)).ToList();
                    prod = prods.OrderByDescending(x => x.BrandID).FirstOrDefault();

                    if (prods.Count() > 1)
                    {
                        try
                        {
                            _stockRepo.Delete(prods.Where(x => x.BrandID < 0).SelectMany(x => x.VendorStocks));
                            unit.Save();
                            _productRepo.Delete(prods.Where(x => x.BrandID < 0));
                            unit.Save();
                        }
                        catch (Exception ex)
                        {
                        }
                    }

                    //if product does not exist (usually true)
                    if (prod == null)
                    {
                        prod = new Product
                        {
                            VendorItemNumber = product.SupplierSKU,
                            SourceVendorID   = VendorID
                        };
                        _productRepo.Add(prod);
                    }
                    prod.BrandID = BrandID;
                    unit.Save();

                    #endregion

                    #region VendorAssortMent

                    var productID = prod.ProductID;

                    if (prod.VendorAssortments == null)
                    {
                        prod.VendorAssortments = new List <VendorAssortment>();
                    }
                    var vendorAssortment = prod.VendorAssortments.FirstOrDefault(va => va.VendorID == VendorID);

                    //if vendorAssortMent does not exist
                    if (vendorAssortment == null)
                    {
                        //create vendorAssortMent with productID
                        vendorAssortment = new VendorAssortment
                        {
                            Product          = prod,
                            CustomItemNumber = product.CustomItemNr,
                            VendorID         = VendorID
                        };
                        _assortmentRepo.Add(vendorAssortment);
                    }
                    vendorAssortment.IsActive         = true;
                    vendorAssortment.ShortDescription =
                        product.ShortDescription.Length > 150
                                       ? product.ShortDescription.Substring(0, 150)
                                       : product.ShortDescription;
                    vendorAssortment.LongDescription = "";

                    unusedVendorAssortmentItems.Remove(vendorAssortment);

                    #endregion

                    #region VendorPrice

                    if (vendorAssortment.VendorPrices == null)
                    {
                        vendorAssortment.VendorPrices = new List <VendorPrice>();
                    }
                    var vendorPrice = vendorAssortment.VendorPrices.FirstOrDefault();
                    //create vendorPrice with vendorAssortmentID
                    if (vendorPrice == null)
                    {
                        vendorPrice = new VendorPrice
                        {
                            VendorAssortment = vendorAssortment
                        };
                        _priceRepo.Add(vendorPrice);
                    }

                    vendorPrice.Price                = Decimal.Parse(product.Price) / 119;
                    vendorPrice.TaxRate              = (Decimal)19.00;
                    vendorPrice.CommercialStatus     = product.Status;
                    vendorPrice.MinimumQuantity      = 0;
                    vendorPrice.CostPrice            = Decimal.Parse(product.CostPrice) / 100;
                    vendorPrice.ConcentratorStatusID = mapper.SyncVendorStatus(product.Status, -1);

                    #endregion

                    #region VendorStock

                    //var vendorStock = vendorAssortment.VendorStock.FirstOrDefault();
                    var vendorStock = _stockRepo.GetSingle(c => c.ProductID == vendorAssortment.ProductID && c.VendorID == vendorAssortment.VendorID);
                    //create vendorStock with productID
                    if (vendorStock == null)
                    {
                        vendorStock = new VendorStock
                        {
                            Product = prod
                        };
                        _stockRepo.Add(vendorStock);
                    }

                    vendorStock.StockStatus          = product.Status;
                    vendorStock.QuantityOnHand       = int.Parse(product.QuantityOnHand);
                    vendorStock.VendorID             = VendorID;
                    vendorStock.VendorStockTypeID    = 1;
                    vendorStock.VendorStatus         = product.Status;
                    vendorStock.ConcentratorStatusID = mapper.SyncVendorStatus(product.Status, -1);

                    #endregion

                    #region ProductGroupVendor

                    //var vendorProductGroupAssortments = (from c in context.VendorProductGroupAssortments
                    //                                     where
                    //                                       c.VendorAssortment == vendorAssortment
                    //                                     select c).ToList();

                    //create vendorGroup five times, each time with a different VendorProductGroupCode on a different level if not exist
                    string vendorProductGroupCode1 = string.IsNullOrEmpty(product.VendorProductGroupCode1) ? "Battery" : product.VendorProductGroupCode1;

                    var productGroupVendor1 =
                        productGroups.FirstOrDefault(pg => pg.VendorProductGroupCode1 == vendorProductGroupCode1);

                    if (productGroupVendor1 == null)
                    {
                        productGroupVendor1 = new ProductGroupVendor
                        {
                            ProductGroupID          = unmappedID,
                            VendorID                = VendorID,
                            VendorName              = product.VendorName,
                            VendorProductGroupCode1 = vendorProductGroupCode1,

                            VendorAssortments = new List <VendorAssortment>()
                        };
                        productGroupVendorRepo.Add(productGroupVendor1);
                        productGroups.Add(productGroupVendor1);
                    }


                    #region sync

                    if (currentProductGroupVendors.Contains(productGroupVendor1))
                    {
                        currentProductGroupVendors.Remove(productGroupVendor1);
                    }
                    #endregion



                    if (!productGroupVendor1.VendorAssortments.Any(c => c == vendorAssortment))
                    {
                        productGroupVendor1.VendorAssortments.Add(vendorAssortment);
                    }

                    if (!string.IsNullOrEmpty(product.VendorProductGroupCode2))
                    {
                        var productGroupVendor2 =
                            productGroups.FirstOrDefault(pg => pg.VendorProductGroupCode2 == product.VendorProductGroupCode2);

                        if (productGroupVendor2 == null)
                        {
                            productGroupVendor2 = new ProductGroupVendor
                            {
                                ProductGroupID          = unmappedID,
                                VendorID                = VendorID,
                                VendorName              = product.VendorName,
                                VendorProductGroupCode2 = product.VendorProductGroupCode2,
                                VendorAssortments       = new List <VendorAssortment>()
                            };

                            productGroupVendorRepo.Add(productGroupVendor2);
                            productGroups.Add(productGroupVendor2);
                        }


                        #region sync

                        if (currentProductGroupVendors.Contains(productGroupVendor2))
                        {
                            currentProductGroupVendors.Remove(productGroupVendor2);
                        }
                        #endregion

                        var vendorProductGroupAssortment2 =
                            productGroupVendor2.VendorAssortments.FirstOrDefault(c => c.VendorAssortmentID == vendorAssortment.VendorAssortmentID);

                        if (vendorProductGroupAssortment2 == null)
                        {
                            productGroupVendor2.VendorAssortments.Add(vendorAssortment);
                        }
                    }

                    if (!string.IsNullOrEmpty(product.VendorProductGroupCode3))
                    {
                        var productGroupVendor3 =
                            productGroups.FirstOrDefault(pg => pg.VendorProductGroupCode3 == product.VendorProductGroupCode3);

                        if (productGroupVendor3 == null)
                        {
                            productGroupVendor3 = new ProductGroupVendor
                            {
                                ProductGroupID          = unmappedID,
                                VendorID                = VendorID,
                                VendorName              = product.VendorName,
                                VendorProductGroupCode3 = product.VendorProductGroupCode3,
                                VendorAssortments       = new List <VendorAssortment>()
                            };

                            productGroupVendorRepo.Add(productGroupVendor3);
                            productGroups.Add(productGroupVendor3);
                        }


                        #region sync

                        if (currentProductGroupVendors.Contains(productGroupVendor3))
                        {
                            currentProductGroupVendors.Remove(productGroupVendor3);
                        }
                        #endregion

                        var vendorProductGroupAssortment3 =
                            productGroupVendor3.VendorAssortments.FirstOrDefault(c => c.VendorAssortmentID == vendorAssortment.VendorAssortmentID);

                        if (vendorProductGroupAssortment3 == null)
                        {
                            productGroupVendor3.VendorAssortments.Add(vendorAssortment);
                        }
                    }

                    if (!string.IsNullOrEmpty(product.VendorProductGroupCode4))
                    {
                        var productGroupVendor4 =
                            productGroups.FirstOrDefault(pg => pg.VendorProductGroupCode4 == product.VendorProductGroupCode4);

                        if (productGroupVendor4 == null)
                        {
                            productGroupVendor4 = new ProductGroupVendor
                            {
                                ProductGroupID          = unmappedID,
                                VendorID                = VendorID,
                                VendorName              = product.VendorName,
                                VendorProductGroupCode4 = product.VendorProductGroupCode4,
                                VendorAssortments       = new List <VendorAssortment>()
                            };

                            productGroupVendorRepo.Add(productGroupVendor4);
                            productGroups.Add(productGroupVendor4);
                        }


                        #region sync

                        if (currentProductGroupVendors.Contains(productGroupVendor4))
                        {
                            currentProductGroupVendors.Remove(productGroupVendor4);
                        }
                        #endregion

                        var vendorProductGroupAssortment4 =
                            productGroupVendor4.VendorAssortments.FirstOrDefault(c => c.VendorAssortmentID == vendorAssortment.VendorAssortmentID);

                        if (vendorProductGroupAssortment4 == null)
                        {
                            productGroupVendor4.VendorAssortments.Add(vendorAssortment);
                        }
                    }

                    if (!string.IsNullOrEmpty(product.VendorProductGroupCode5))
                    {
                        var productGroupVendor5 =
                            productGroups.FirstOrDefault(pg => pg.VendorProductGroupCode5 == product.VendorProductGroupCode5);

                        if (productGroupVendor5 == null)
                        {
                            productGroupVendor5 = new ProductGroupVendor
                            {
                                ProductGroupID          = unmappedID,
                                VendorID                = VendorID,
                                VendorName              = product.VendorName,
                                VendorProductGroupCode5 = product.VendorProductGroupCode5,
                                VendorAssortments       = new List <VendorAssortment>()
                            };

                            productGroupVendorRepo.Add(productGroupVendor5);
                            productGroups.Add(productGroupVendor5);
                        }


                        #region sync

                        if (currentProductGroupVendors.Contains(productGroupVendor5))
                        {
                            currentProductGroupVendors.Remove(productGroupVendor5);
                        }

                        #endregion
                        var vendorProductGroupAssortment5 =
                            productGroupVendor5.VendorAssortments.FirstOrDefault(c => c.VendorAssortmentID == vendorAssortment.VendorAssortmentID);

                        if (vendorProductGroupAssortment5 == null)
                        {
                            productGroupVendor5.VendorAssortments.Add(vendorAssortment);
                        }
                    }

                    if (!string.IsNullOrEmpty(product.VendorBrandCode))
                    {
                        var brandProductGroupvendor =
                            productGroups.FirstOrDefault(pg => pg.BrandCode == product.VendorBrandCode && pg.VendorProductGroupCode1 == null && pg.VendorProductGroupCode2 == null && pg.VendorProductGroupCode3 == null && pg.VendorProductGroupCode4 == null && pg.VendorProductGroupCode5 == null);

                        if (brandProductGroupvendor == null)
                        {
                            brandProductGroupvendor = new ProductGroupVendor
                            {
                                ProductGroupID = unmappedID,
                                VendorID       = VendorID,
                                VendorName     = product.VendorName,
                                BrandCode      = product.VendorBrandCode
                            };

                            productGroupVendorRepo.Add(brandProductGroupvendor);
                            productGroups.Add(brandProductGroupvendor);
                        }


                        #region sync

                        if (currentProductGroupVendors.Contains(brandProductGroupvendor))
                        {
                            currentProductGroupVendors.Remove(brandProductGroupvendor);
                        }

                        #endregion
                        var brandProductGroupAssortment =
                            brandProductGroupvendor.VendorAssortments.FirstOrDefault(c => c.VendorAssortmentID == vendorAssortment.VendorAssortmentID);

                        if (brandProductGroupAssortment == null)
                        {
                            brandProductGroupvendor.VendorAssortments.Add(vendorAssortment);
                        }
                    }

                    #endregion

                    #region ProductBarcode
                    if (prod.ProductBarcodes == null)
                    {
                        prod.ProductBarcodes = new List <ProductBarcode>();
                    }
                    if (!prod.ProductBarcodes.Any(pb => pb.Barcode.Trim() == product.Barcode))
                    {
                        //create ProductBarcode if not exists
                        _barcodeRepo.Add(new ProductBarcode
                        {
                            Product     = prod,
                            Barcode     = product.Barcode,
                            VendorID    = VendorID,
                            BarcodeType = (int)BarcodeTypes.Default
                        });
                    }

                    #endregion

                    #region ProductDescription
                    if (prod.ProductDescriptions == null)
                    {
                        prod.ProductDescriptions = new List <ProductDescription>();
                    }
                    var productDescription =
                        prod.ProductDescriptions.FirstOrDefault(pd => pd.LanguageID == languageID && pd.VendorID == VendorID);

                    if (productDescription == null)
                    {
                        //create ProductDescription
                        productDescription = new ProductDescription
                        {
                            Product    = prod,
                            LanguageID = languageID,
                            VendorID   = VendorID
                        };

                        _prodDescriptionRepo.Add(productDescription);
                    }
                    productDescription.ShortContentDescription = product.ShortContentDescription;

                    #endregion

                    foreach (var content in itemContent.Where(x => x.LenmarSKU == product.SupplierSKU))
                    {
                        #region ProductAttributeGroupMetaData

                        var productAttributeGroupMetaData =
                            productAttributeGroups.FirstOrDefault(c => c.GroupCode == content.GroupCode);
                        //create ProductAttributeGroupMetaData if not exists
                        if (productAttributeGroupMetaData == null)
                        {
                            productAttributeGroupMetaData = new ProductAttributeGroupMetaData
                            {
                                Index     = 0,
                                GroupCode = content.GroupCode,
                                VendorID  = VendorID
                            };
                            _attrGroupRepo.Add(productAttributeGroupMetaData);
                            productAttributeGroups.Add(productAttributeGroupMetaData);
                        }
                        #endregion

                        #region ProductAttributeGroupName
                        if (productAttributeGroupMetaData.ProductAttributeGroupNames == null)
                        {
                            productAttributeGroupMetaData.ProductAttributeGroupNames = new List <ProductAttributeGroupName>();
                        }
                        var productAttributeGroupName =
                            productAttributeGroupMetaData.ProductAttributeGroupNames.FirstOrDefault(c => c.LanguageID == languageID);
                        //create ProductAttributeGroupName if not exists
                        if (productAttributeGroupName == null)
                        {
                            productAttributeGroupName = new ProductAttributeGroupName
                            {
                                Name = "General",
                                ProductAttributeGroupMetaData = productAttributeGroupMetaData,
                                LanguageID = languageID
                            };
                            _attrGroupName.Add(productAttributeGroupName);
                        }

                        #endregion

                        #region ProductAttributeMetaData

                        //create ProductAttributeMetaData as many times that there are entrys in content.dynamic
                        foreach (var element in content.dynamic)
                        {
                            var productAttributeMetaData =
                                productAttributes.FirstOrDefault(c => c.AttributeCode == element.Name.ToString());
                            //create ProductAttributeMetaData if not exists
                            if (productAttributeMetaData == null)
                            {
                                productAttributeMetaData = new ProductAttributeMetaData
                                {
                                    ProductAttributeGroupMetaData = productAttributeGroupMetaData,
                                    AttributeCode = element.Name.ToString(),
                                    Index         = 0,
                                    IsVisible     = true,
                                    NeedsUpdate   = true,
                                    VendorID      = VendorID,
                                    IsSearchable  = false
                                };
                                _attrRepo.Add(productAttributeMetaData);
                                productAttributes.Add(productAttributeMetaData);
                            }

                            #endregion

                            #region ProductAttributeName
                            if (productAttributeMetaData.ProductAttributeNames == null)
                            {
                                productAttributeMetaData.ProductAttributeNames = new List <ProductAttributeName>();
                            }
                            var productAttributeName =
                                productAttributeMetaData.ProductAttributeNames.FirstOrDefault(c => c.LanguageID == languageID);
                            //create ProductAttributeName with generated productAttributeMetaData.AttributeID if not exists
                            if (productAttributeName == null)
                            {
                                productAttributeName = new ProductAttributeName
                                {
                                    ProductAttributeMetaData = productAttributeMetaData,
                                    LanguageID = languageID,
                                    Name       = element.Name.ToString()
                                };
                                _attrNameRepo.Add(productAttributeName);
                            }

                            #endregion

                            #region ProductAttributeValue

                            if (productAttributeMetaData.ProductAttributeValues == null)
                            {
                                productAttributeMetaData.ProductAttributeValues = new List <ProductAttributeValue>();
                            }
                            var productAttributeValue =
                                productAttributeMetaData.ProductAttributeValues.FirstOrDefault(c => c.ProductID == prod.ProductID);
                            //create ProductAttributeValue with generated productAttributeMetaData.AttributeID
                            if (productAttributeValue == null)
                            {
                                productAttributeValue = new ProductAttributeValue
                                {
                                    ProductAttributeMetaData = productAttributeMetaData,
                                    Product    = prod,
                                    Value      = element.Value,
                                    LanguageID = languageID
                                };
                                _attrValueRepo.Add(productAttributeValue);
                            }

                            #endregion
                        }
                    }
                    unit.Save();
                }
                catch (Exception ex)
                {
                    log.ErrorFormat("product: {0} error: {1}", product.SupplierSKU, ex.StackTrace);
                }
            }
            #region delete unused vendorProductGroups
            foreach (var vProdVendor in currentProductGroupVendors)
            {
                if (vProdVendor.ProductGroupID == -1)
                {
                    productGroupVendorRepo.Add(vProdVendor);
                }
            }
            unit.Save();

            unusedVendorAssortmentItems.ForEach(x => x.IsActive = false);
            unit.Save();

            #endregion
        }
Пример #2
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);
                }
            }
        }
Пример #3
0
        private void ParseDocuments(IUnitOfWork unit, XDocument prods, DataTable cont, DataTable statuses, DataTable taxTable)
        {
            #region Xml 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 content in cont.AsEnumerable()
                               select new
            {
                Code = content[0].ToString(),
                Name = content[2].ToString(),
                Level = content[1].ToString()
            }).ToList();

            var itemProducts = (from itemproduct in prods.Element("XMLOUT_pricelist_01").Elements("item")
                                let content = 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 = content.FirstOrDefault(x => x.Code.StartsWith(itemproduct.Element("item_group").Value.Substring(0, 2)) && Int32.Parse(x.Level) == 1),
                VendorProductGroupCode2 = content.FirstOrDefault(x => x.Code.StartsWith(itemproduct.Element("item_group").Value.Substring(0, 2)) && Int32.Parse(x.Level) == 2),
                VendorProductGroupCode3 = content.FirstOrDefault(x => x.Code.StartsWith(itemproduct.Element("item_group").Value.Substring(0, 2)) && Int32.Parse(x.Level) == 3),
                VendorProductGroupCode4 = content.FirstOrDefault(x => x.Code.StartsWith(itemproduct.Element("item_group").Value.Substring(0, 2)) && Int32.Parse(x.Level) == 4),
                VendorProductGroupCode5 = content.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();

            #endregion

            var repoBrandVendor = unit.Scope.Repository <BrandVendor>();

            var prodRepo = unit.Scope.Repository <Product>().Include(c => c.ProductMedias, c => c.ProductBarcodes, c => c.ProductDescriptions);
            var productAttributeGroups = unit.Scope.Repository <ProductAttributeGroupMetaData>().GetAll(g => g.VendorID == VendorID).ToList();
            var repoAssortment         = unit.Scope.Repository <VendorAssortment>().Include(c => c.VendorPrices);
            var stockRepo              = unit.Scope.Repository <VendorStock>();
            var repoAttributeGroup     = unit.Scope.Repository <ProductAttributeGroupMetaData>();
            var repoAttributeGroupName = unit.Scope.Repository <ProductAttributeGroupName>();
            var repoAttribute          = unit.Scope.Repository <ProductAttributeMetaData>().Include(c => c.ProductAttributeNames, c => c.ProductAttributeValues);
            var repoVendor             = unit.Scope.Repository <ProductGroupVendor>();
            var prodDescriptionRepo    = unit.Scope.Repository <ProductDescription>();

            var products                   = prodRepo.GetAll(x => x.SourceVendorID == VendorID).ToList();
            var vendorassortments          = repoAssortment.GetAll(x => x.VendorID == VendorID).ToList();
            var productAttributes          = repoAttribute.GetAll(g => g.VendorID == VendorID).ToList();
            var currentProductGroupVendors = repoVendor.GetAll(v => v.Vendor.VendorID == VendorID).ToList();
            var productGroupVendorRecords  = repoVendor.GetAll(pc => pc.VendorID == VendorID).ToList();
            var brands = repoBrandVendor.GetAll(bv => bv.VendorID == VendorID).ToList();

            var vendorStock      = stockRepo.GetAll(x => x.VendorID == VendorID).ToList();
            var prodDescriptions = prodDescriptionRepo.GetAll().ToList();

            var prodAttributeGroups = repoAttributeGroup.GetAll(g => g.VendorID == VendorID).ToList();

            ProductStatusVendorMapper mapper = new ProductStatusVendorMapper(unit.Scope.Repository <VendorProductStatus>(), VendorID);

            int counter = 0;
            int total   = itemProducts.Count();
            int totalNumberOfProductsToProcess = total;
            log.InfoFormat("Start import {0} products", total);

            foreach (var product in itemProducts)
            {
                try
                {
                    if (counter == 100)
                    {
                        counter = 0;
                        log.InfoFormat("Still need to process {0} of {1}; {2} done;", totalNumberOfProductsToProcess, total, total - totalNumberOfProductsToProcess);
                    }

                    totalNumberOfProductsToProcess--;
                    counter++;

                    #region Brand

                    var vbrand = brands.FirstOrDefault(vb => vb.VendorBrandCode == product.VendorProductGroupCode1.Code);

                    if (vbrand == null)
                    {
                        vbrand = new BrandVendor
                        {
                            VendorID        = VendorID,
                            VendorBrandCode = product.VendorProductGroupCode1.Code,
                            BrandID         = UnMappedID
                        };

                        brands.Add(vbrand);

                        repoBrandVendor.Add(vbrand);
                    }

                    vbrand.Name = product.VendorName;

                    #endregion Brand

                    #region Product

                    var item = products.FirstOrDefault(p => p.VendorItemNumber == product.VendorItemNr && p.BrandID == vbrand.BrandID);
                    if (item == null)
                    {
                        item = new Product
                        {
                            VendorItemNumber = product.VendorItemNr,
                            BrandID          = vbrand.BrandID,
                            SourceVendorID   = VendorID
                        };
                        prodRepo.Add(item);
                        products.Add(item);
                        unit.Save();
                    }
                    else
                    {
                        if (item.BrandID < 0)
                        {
                            item.BrandID = vbrand.BrandID;
                        }
                    }

                    #endregion Product

                    #region Vendor assortment


                    //if (item.VendorAssortments == null) item.VendorAssortments = new List<VendorAssortment>();

                    var assortment = vendorassortments.FirstOrDefault(x => x.ProductID == item.ProductID);
                    if (assortment == null)
                    {
                        assortment = new VendorAssortment
                        {
                            VendorID = VendorID,
                            Product  = item
                        };
                        vendorassortments.Add(assortment);
                        repoAssortment.Add(assortment);
                    }

                    assortment.ShortDescription = product.Longdescription.Length > 150 ? product.Longdescription.Substring(0, 150) : product.Longdescription;
                    assortment.CustomItemNumber = product.CustomItemNr;
                    assortment.IsActive         = true;
                    assortment.LongDescription  = product.Longdescription;


                    #region Product group
                    try
                    {
                        var brndCode = product.Try(x => x.VendorProductGroupCode1, null);

                        if (brndCode != null)
                        {
                            var productGroupVendor = productGroupVendorRecords.Where(pg => pg.GetType().GetProperty("BrandCode").GetValue(pg, null) != null &&
                                                                                     pg.GetType().GetProperty("BrandCode").GetValue(pg, null).ToString() == brndCode.Code.Trim()).FirstOrDefault();

                            if (productGroupVendor == null)
                            {
                                productGroupVendor = new ProductGroupVendor
                                {
                                    ProductGroupID = UnMappedID,
                                    VendorID       = VendorID,
                                    VendorName     = brndCode.Name.Trim()
                                };

                                productGroupVendor.GetType().GetProperty("BrandCode").SetValue(productGroupVendor, brndCode.Code.Trim(), null);

                                repoVendor.Add(productGroupVendor);
                                productGroupVendorRecords.Add(productGroupVendor);
                            }

                            #region sync
                            if (currentProductGroupVendors.Contains(productGroupVendor))
                            {
                                currentProductGroupVendors.Remove(productGroupVendor);
                            }
                            #endregion
                        }
                        for (int i = 2; i <= 4; i++)
                        {
                            var category = i == 2 ? product.Try(x => x.VendorProductGroupCode2, null) : i == 3 ? product.Try(x => x.VendorProductGroupCode3, null) : i == 4 ? product.Try(x => x.VendorProductGroupCode4, null) : null;

                            if (category != null)
                            {
                                var productGroupVendor = productGroupVendorRecords.Where(pg => pg.GetType().GetProperty("VendorProductGroupCode" + i).GetValue(pg, null) != null &&
                                                                                         pg.GetType().GetProperty("VendorProductGroupCode" + i).GetValue(pg, null).ToString() == category.Code.Trim()).FirstOrDefault();

                                if (productGroupVendor == null)
                                {
                                    productGroupVendor = new ProductGroupVendor
                                    {
                                        ProductGroupID = UnMappedID,
                                        VendorID       = VendorID,
                                        VendorName     = category.Name.Trim()
                                    };

                                    productGroupVendor.GetType().GetProperty("VendorProductGroupCode" + i).SetValue(productGroupVendor, category.Code.Trim(), null);

                                    repoVendor.Add(productGroupVendor);
                                    productGroupVendorRecords.Add(productGroupVendor);
                                }

                                #region sync
                                if (currentProductGroupVendors.Contains(productGroupVendor))
                                {
                                    currentProductGroupVendors.Remove(productGroupVendor);
                                }
                                #endregion
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        log.Error("Failed productgroups", ex);
                    }
                    #endregion

                    #region Vendor Product Group Assortment

                    string brandCode = product.VendorProductGroupCode1.Code;
                    /// string groupCode1 = product.VendorProductGroupCode1.Code;
                    string groupCode1 = product.VendorProductGroupCode2.Code;
                    string groupCode2 = product.VendorProductGroupCode3.Code;
                    string groupCode3 = product.VendorProductGroupCode4.Code;

                    var records = (from l in productGroupVendorRecords
                                   where
                                   ((brandCode != null && l.BrandCode.Trim() == brandCode) || l.BrandCode == null)
                                   &&
                                   ((groupCode1 != null && l.VendorProductGroupCode1 != null &&
                                     l.VendorProductGroupCode1.Trim() == groupCode1) || l.VendorProductGroupCode1 == null)
                                   &&
                                   ((groupCode2 != null && l.VendorProductGroupCode2 != null &&
                                     l.VendorProductGroupCode2.Trim() == groupCode2) || l.VendorProductGroupCode2 == null)
                                   &&
                                   ((groupCode3 != null && l.VendorProductGroupCode3 != null &&
                                     l.VendorProductGroupCode3.Trim() == groupCode3) || l.VendorProductGroupCode3 == null)
                                   select l).ToList();


                    List <int> existingProductGroupVendors = new List <int>();

                    foreach (ProductGroupVendor prodGroupVendor in records)
                    {
                        existingProductGroupVendors.Add(prodGroupVendor.ProductGroupVendorID);

                        if (prodGroupVendor.VendorAssortments == null)
                        {
                            prodGroupVendor.VendorAssortments = new List <VendorAssortment>();
                        }
                        if (prodGroupVendor.VendorAssortments.Any(x => x.VendorAssortmentID == assortment.VendorAssortmentID))
                        { // only add new rows
                            continue;
                        }
                        prodGroupVendor.VendorAssortments.Add(assortment);
                    }

                    var unusedPGV = new List <ProductGroupVendor>();
                    assortment.ProductGroupVendors.ForEach((pgv, id) =>
                    {
                        if (!existingProductGroupVendors.Contains(pgv.ProductGroupVendorID))
                        {
                            unusedPGV.Add(pgv);
                        }
                    });

                    unusedPGV.ForEach((pg) => { assortment.ProductGroupVendors.Remove(pg); });

                    #endregion

                    #endregion Vendor assortment

                    #region Stock

                    var stock = vendorStock.FirstOrDefault(c => c.ProductID == assortment.ProductID && c.VendorID == assortment.VendorID);

                    if (stock == null)
                    {
                        stock = new VendorStock
                        {
                            VendorID          = VendorID,
                            Product           = item,
                            VendorStockTypeID = 1
                        };
                        vendorStock.Add(stock);
                        stockRepo.Add(stock);
                    }
                    stock.QuantityOnHand = Int32.Parse(product.QuantityOnHand);
                    stock.StockStatus    = product.Status == null ? null : product.Status.Name;
                    if (product.Status != null)
                    {
                        stock.ConcentratorStatusID = mapper.SyncVendorStatus(product.Status.Name, -1);
                    }

                    #endregion Stock

                    #region Price

                    if (assortment.VendorPrices == null)
                    {
                        assortment.VendorPrices = new List <VendorPrice>();
                    }
                    var price = assortment.VendorPrices.FirstOrDefault();
                    if (price == null)
                    {
                        price = new VendorPrice
                        {
                            VendorAssortment = assortment,
                            MinimumQuantity  = 0
                        };

                        unit.Scope.Repository <VendorPrice>().Add(price);
                    }
                    price.CommercialStatus = product.Status == null ? null : product.Status.Name;
                    price.BasePrice        = Decimal.Parse(product.Price);
                    if (product.Tax != null)
                    {
                        price.TaxRate = Decimal.Parse(product.Tax.Tax) / Decimal.Parse(product.Price);
                    }
                    price.ConcentratorStatusID = stock.ConcentratorStatusID;

                    #endregion Price

                    #region Barcode

                    if (!String.IsNullOrEmpty(product.Barcode))
                    {
                        if (item.ProductBarcodes == null)
                        {
                            item.ProductBarcodes = new List <ProductBarcode>();
                        }
                        if (!item.ProductBarcodes.Any(pb => pb.Barcode.Trim() == product.Barcode.Trim()))
                        {
                            unit.Scope.Repository <ProductBarcode>().Add(new ProductBarcode
                            {
                                Product     = item,
                                Barcode     = product.Barcode.Trim(),
                                BarcodeType = (int)BarcodeTypes.Default,
                                VendorID    = VendorID
                            });
                        }
                    }

                    #endregion Barcode
                    unit.Save();
                }
                catch (Exception ex)
                {
                    log.Error("Error import products for Copaco", ex);
                }
            }
            #region delete unused productgroupvendor records
            foreach (var vProdGroup in currentProductGroupVendors)
            {
                if (vProdGroup.ProductGroupID == -1)
                {
                    unit.Scope.Repository <ProductGroupVendor>().Delete(vProdGroup);
                }
            }
            #endregion
        }