public void ReadListingInventory()
        {
            if (_api.Market == MarketType.Walmart)
            {
                var markAllWFSListingInfos = ((WalmartApi)_api).GetWFSInventory(null);
                var markAllWFSSKUs         = markAllWFSListingInfos.Where(i => i.RealQuantity > 0 || i.AmazonRealQuantity > 0).Select(i => i.SKU).ToList();

                using (var db = _dbFactory.GetRWDb())
                {
                    var dbWFSListings = db.Listings.GetAll().Where(l => l.IsFBA &&
                                                                   l.Market == (int)MarketType.Walmart &&
                                                                   !l.IsRemoved)
                                        .ToList();
                    var dbExistWFSSKUs = dbWFSListings.Select(l => l.SKU).ToList();

                    var newWFSListingSKUs = markAllWFSSKUs.Where(i => !dbExistWFSSKUs.Contains(i)).ToList();
                    var dbNewWFSListings  = db.Listings.GetAll().Where(l => newWFSListingSKUs.Contains(l.SKU) &&
                                                                       l.Market == (int)MarketType.Walmart &&
                                                                       !l.IsRemoved).ToList();
                    foreach (var dbNewWFSListing in dbNewWFSListings)
                    {
                        _log.Info("Set IsFBA=true, for SKU=" + dbNewWFSListing.SKU);
                        _itemHistoryService.AddRecord(dbNewWFSListing.ItemId, ItemHistoryHelper.IsFBAKey, dbNewWFSListing.IsFBA, true, null);
                        dbNewWFSListing.IsFBA = true;
                        SystemActionHelper.RequestPriceRecalculation(db, _actionService, dbNewWFSListing.Id, null);
                    }

                    var dbRemoveWFSStatus = dbWFSListings.Where(i => !markAllWFSSKUs.Contains(i.SKU)).ToList();
                    foreach (var dbRemoveWFSListing in dbRemoveWFSStatus)
                    {
                        _log.Info("Rest IsFBA=false, for SKU=" + dbRemoveWFSListing.SKU);
                        _itemHistoryService.AddRecord(dbRemoveWFSListing.ItemId, ItemHistoryHelper.IsFBAKey, dbRemoveWFSListing.IsFBA, false, null);
                        dbRemoveWFSListing.IsFBA = false;
                        SystemActionHelper.RequestPriceRecalculation(db, _actionService, dbRemoveWFSListing.Id, null);
                    }
                }
            }
        }
        private void SetItemFieldsIfExistOnAmazon(IUnitOfWork db, ItemDTO dtoItem, Item dbItem)
        {
            //NOTE: Skip any ParentASIN updates
            //NOTE: updates for childs only when we change ParentItem objects
            //NOTE: to keep source relationships
            //if (!String.IsNullOrEmpty(dtoItem.ParentASIN))
            //{
            //    dbItem.ParentASIN = dtoItem.ParentASIN;
            //}

            //NOTE: only when no ParentASIN
            if (String.IsNullOrEmpty(dbItem.ParentASIN) &&
                !String.IsNullOrEmpty(dtoItem.ParentASIN))
            {
                dbItem.ParentASIN = dtoItem.ParentASIN;
            }

            if (dbItem.ASIN != dtoItem.ASIN)
            {
                _log.Info("For SKU=" + dtoItem.SKU + "(id: " + dbItem.Id + ")" + ", ASIN=" + dbItem.ASIN + "=>" + dtoItem.ASIN);
                dbItem.ASIN = dtoItem.ASIN;
            }

            if (dbItem.ItemPublishedStatus == (int)PublishedStatuses.New ||
                dbItem.ItemPublishedStatus == (int)PublishedStatuses.PublishedInactive ||
                dbItem.ItemPublishedStatus == (int)PublishedStatuses.PublishedInProgress ||
                dbItem.ItemPublishedStatus == (int)PublishedStatuses.PublishingErrors ||
                dbItem.ItemPublishedStatus == (int)PublishedStatuses.None ||
                dbItem.ItemPublishedStatus == (int)PublishedStatuses.HasPublishRequest)
            //NOTE: should be excluded HasUnpublishdRequest
            {
                dbItem.ItemPublishedStatus       = (int)PublishedStatuses.Published;
                dbItem.ItemPublishedStatusReason = "";
                dbItem.ItemPublishedStatusDate   = _time.GetAppNowTime();
            }

            dbItem.ItemPublishedStatusFromMarket     = (int)PublishedStatuses.Published;
            dbItem.ItemPublishedStatusFromMarketDate = _time.GetAppNowTime();

            dbItem.IsAmazonParentASIN = dtoItem.ParentASIN == dbItem.ParentASIN;
            dbItem.SourceMarketId     = dtoItem.SourceMarketId;
            dbItem.MarketParentASIN   = dtoItem.ParentASIN;

            if (dbItem.OnMarketTemplateName != dtoItem.OnMarketTemplateName)
            {
                _log.Debug("Template changed: " + dbItem.OnMarketTemplateName + "=>" + dtoItem.OnMarketTemplateName);
            }
            dbItem.OnMarketTemplateName = dtoItem.OnMarketTemplateName;

            //Updates size if came not null
            if (!String.IsNullOrEmpty(dtoItem.Size))
            {
                var newSize = StringHelper.Substring(dtoItem.Size, 50);
                if (dbItem.Size != newSize)
                {
                    if (_itemHistoryService != null)
                    {
                        _itemHistoryService.AddRecord(dbItem.Id,
                                                      ItemHistoryHelper.SizeKey,
                                                      dbItem.Size,
                                                      "ListingLineProcessing.SetItemFieldsIfExistOnAmazon",
                                                      newSize,
                                                      null,
                                                      null);
                    }
                    dbItem.Size = newSize;
                }
            }
            else
            {
                dtoItem.Size = dbItem.Size; //NOTE: item DTO size using in below code (should be actual)
            }

            dbItem.IsExistOnAmazon      = true;
            dbItem.LastUpdateFromAmazon = _time.GetUtcTime();

            //Set style string
            if (String.IsNullOrEmpty(dbItem.StyleString))
            {
                dtoItem.StyleString = SkuHelper.RetrieveStyleIdFromSKU(db,
                                                                       dtoItem.SKU,
                                                                       dtoItem.Name);

                _log.Debug(string.Format("StyleString updated from={0}, to={1}", dbItem.StyleString, dtoItem.StyleString));
                dbItem.StyleString = dtoItem.StyleString;
            }
            else
            {
                dtoItem.StyleString = dbItem.StyleString;
            }

            //Additional Fields
            dbItem.Title = dtoItem.Name;
            if (!String.IsNullOrEmpty(dtoItem.ImageUrl))
            {
                dbItem.PrimaryImage = dtoItem.ImageUrl;
            }
            dbItem.BrandName        = dtoItem.BrandName;
            dbItem.Type             = StringHelper.Substring(dtoItem.Type, 50);
            dbItem.ListPrice        = dtoItem.ListPrice;
            dbItem.Color            = StringHelper.Substring(dtoItem.Color, 50);
            dbItem.Department       = dtoItem.Department;
            dbItem.AdditionalImages = dtoItem.AdditionalImages;
            if (!String.IsNullOrEmpty(dtoItem.Features))
            {
                dbItem.Features = dtoItem.Features;
            }
            if (!String.IsNullOrEmpty(dtoItem.SearchKeywords))
            {
                dbItem.SearchKeywords = dtoItem.SearchKeywords;
            }
            if (!String.IsNullOrEmpty(dtoItem.Barcode))
            {
                dbItem.Barcode = dtoItem.Barcode;
            }

            //Setting styleId, create style, styleItem if not exist
            if (!dbItem.StyleItemId.HasValue)
            {
                //Kepp exists styleId
                dtoItem.StyleId = dbItem.StyleId;

                _log.Info("FindOrCreateStyleItem");
                var styleItem = FindOrCreateStyleItem(db, dtoItem);
                if (styleItem != null)
                {
                    if (styleItem.StyleItemId > 0)
                    {
                        _styleHistoryService.AddRecord(styleItem.StyleId,
                                                       StyleHistoryHelper.AttachListingKey,
                                                       dbItem.StyleItemId,
                                                       dbItem.Market + ":" + dbItem.MarketplaceId,
                                                       styleItem.StyleItemId,
                                                       dbItem.Id.ToString() + ":" + dbItem.ASIN,
                                                       null);

                        dbItem.StyleId     = styleItem.StyleId;
                        dbItem.StyleItemId = styleItem.StyleItemId;
                    }
                    else
                    {
                        if (!dbItem.StyleId.HasValue)
                        {
                            dbItem.StyleId = styleItem.StyleId;
                        }
                    }

                    _log.Debug(String.Format("Set for ASIN={0}, styleId={1}, styleItemId={2}",
                                             dtoItem.ASIN,
                                             styleItem.StyleId,
                                             styleItem.StyleItemId));
                }
                else
                {
                    _log.Info("Empty StyleItem");
                }
            }

            //Update style image
            if (dbItem.StyleId.HasValue &&
                !String.IsNullOrEmpty(dbItem.PrimaryImage))
            {
                _styleManager.UpdateStyleImageIfEmpty(db, dbItem.StyleId.Value, dbItem.PrimaryImage);
            }

            if (dtoItem.Weight.HasValue &&
                dbItem.StyleItemId.HasValue)
            {
                var dbStyleItem = db.StyleItems.Get(dbItem.StyleItemId.Value);
                if (!dbStyleItem.Weight.HasValue)
                {
                    dbStyleItem.Weight = dtoItem.Weight;
                }
            }

            if (!String.IsNullOrEmpty(dtoItem.Barcode) &&
                dbItem.StyleItemId.HasValue)
            {
                _styleManager.StoreOrUpdateBarcode(db,
                                                   dbItem.StyleItemId.Value,
                                                   dtoItem.Barcode);
            }
        }
        public void CreateListings()
        {
            var now = _time.GetAppNowTime();

            using (var db = _dbFactory.GetRWDb())
            {
                db.DisableValidation();
                db.DisableAutoDetectChanges();
                db.DisableProxyCreation();

                var existPrimeItems = (from i in db.Items.GetAll()
                                       join l in db.Listings.GetAll() on i.Id equals l.ItemId
                                       where i.MarketplaceId == MarketplaceKeeper.AmazonComMarketplaceId &&
                                       (l.IsPrime || l.SKU.Contains("-FBP")) &&
                                       !l.IsRemoved
                                       select new
                {
                    StyleItemId = i.StyleItemId,
                    ParentASIN = i.ParentASIN,
                    Quantity = l.RealQuantity
                }).ToList();

                var topStyles = (from sic in db.StyleItemCaches.GetAll()
                                 join st in db.Styles.GetAll() on sic.StyleId equals st.Id
                                 group sic by sic.StyleId into byStyle
                                 select new
                {
                    StyleId = byStyle.Key,
                    Quantity = byStyle.Sum(si => si.RemainingQuantity)
                }).ToList();

                //topStyles = topStyles.Where(st => st.Quantity > 100).ToList();

                topStyles = topStyles.OrderByDescending(st => st.Quantity)
                            .ToList();

                var styleIdToCopy = topStyles.Select(st => st.StyleId).ToList();

                var toCopyItems = (from i in db.Items.GetAll()
                                   join l in db.Listings.GetAll() on i.Id equals l.ItemId
                                   where i.MarketplaceId == MarketplaceKeeper.AmazonComMarketplaceId &&
                                   styleIdToCopy.Contains(i.StyleId) &&
                                   !l.IsRemoved &&
                                   !l.IsPrime &&
                                   !l.IsFBA &&
                                   !l.SKU.Contains("-FBP") &&
                                   !l.SKU.Contains("-FBA") &&
                                   l.RealQuantity > 5
                                   select new ItemDTO()
                {
                    Id = i.Id,
                    SKU = l.SKU,
                    StyleId = i.StyleId,
                    StyleItemId = i.StyleItemId,
                    ParentASIN = i.ParentASIN
                })
                                  .ToList();

                foreach (var itemToCopy in toCopyItems)
                {
                    var existPrime = existPrimeItems.FirstOrDefault(i => i.ParentASIN == itemToCopy.ParentASIN &&
                                                                    i.StyleItemId == itemToCopy.StyleItemId);
                    if (existPrime == null)
                    {
                        var dbItemToCopy    = db.Items.GetAll().FirstOrDefault(i => i.Id == itemToCopy.Id);
                        var dbListingToCopy = db.Listings.GetAll().FirstOrDefault(l => l.ItemId == itemToCopy.Id &&
                                                                                  !l.IsRemoved);

                        var salePrice = (from sl in db.StyleItemSaleToListings.GetAll()
                                         join sm in db.StyleItemSaleToMarkets.GetAll() on sl.SaleToMarketId equals sm.Id
                                         join s in db.StyleItemSales.GetAll() on sm.SaleId equals s.Id
                                         where sl.ListingId == dbListingToCopy.Id &&
                                         sm.MarketplaceId == MarketplaceKeeper.AmazonComMarketplaceId &&
                                         !s.IsDeleted &&
                                         (s.SaleStartDate.HasValue && s.SaleStartDate < now) &&
                                         sm.SalePrice.HasValue
                                         select sm.SalePrice).FirstOrDefault();

                        //var dbViewItem = db.Items.GetAllViewActual().FirstOrDefault(i => i.Id == dbItemToCopy.Id);
                        //if (dbViewItem == null)
                        //{
                        //    _log.Info("dbViewItem = null");
                        //    continue;
                        //}
                        _log.Info("Copy listing, SKU=" + itemToCopy.SKU + ", price=" + dbListingToCopy.CurrentPrice + ", salePrice=" + salePrice);

                        var isOversizeTemplate = dbItemToCopy.OnMarketTemplateName == AmazonTemplateHelper.OversizeTemplate;

                        dbItemToCopy.Id = 0;
                        dbItemToCopy.ItemPublishedStatus     = (int)PublishedStatuses.New;
                        dbItemToCopy.ItemPublishedStatusDate = null;
                        dbItemToCopy.ItemPublishedStatusBeforeRepublishing = null;
                        dbItemToCopy.ItemPublishedStatusFromMarket         = null;
                        dbItemToCopy.ItemPublishedStatusFromMarketDate     = null;
                        dbItemToCopy.ItemPublishedStatusReason             = null;
                        dbItemToCopy.OnMarketTemplateName = AmazonTemplateHelper.PrimeTemplate;
                        dbItemToCopy.CreateDate           = _time.GetAppNowTime();
                        dbItemToCopy.UpdateDate           = _time.GetAppNowTime();
                        dbItemToCopy.CreatedBy            = null;
                        dbItemToCopy.UpdatedBy            = null;
                        db.Items.Add(dbItemToCopy);
                        db.Commit();

                        _itemHistoryService.AddRecord(dbItemToCopy.Id,
                                                      ItemHistoryHelper.SizeKey,
                                                      null,
                                                      "AutoCreateAmazonUSPrimeListingService.CreateListing",
                                                      dbItemToCopy.Size,
                                                      null,
                                                      null);

                        var newSKU = SkuHelper.AddPrimePostFix(dbListingToCopy.SKU);
                        var price  = salePrice ?? dbListingToCopy.CurrentPrice;
                        dbListingToCopy.ItemId                       = dbItemToCopy.Id;
                        dbListingToCopy.Id                           = 0;
                        dbListingToCopy.ListingId                    = newSKU;
                        dbListingToCopy.IsPrime                      = true;
                        dbListingToCopy.CurrentPrice                 = PriceHelper.RoundToFloor99(isOversizeTemplate ? (price + 9.49M) : (price + 7.49M));
                        dbListingToCopy.ListingPriceFromMarket       = null;
                        dbListingToCopy.AmazonCurrentPrice           = null;
                        dbListingToCopy.AmazonCurrentPriceUpdateDate = null;
                        dbListingToCopy.AmazonRealQuantity           = null;
                        dbListingToCopy.AmazonRealQuantityUpdateDate = null;
                        dbListingToCopy.PriceFromMarketUpdatedDate   = null;
                        dbListingToCopy.SKU                          = newSKU;
                        dbListingToCopy.OpenDate                     = _time.GetAppNowTime();
                        dbListingToCopy.CreateDate                   = _time.GetAppNowTime();
                        dbListingToCopy.UpdateDate                   = _time.GetAppNowTime();
                        dbListingToCopy.CreatedBy                    = null;
                        dbListingToCopy.UpdatedBy                    = null;
                        db.Listings.Add(dbListingToCopy);
                        db.Commit();
                        _log.Info("Copyied to SKU=" + dbListingToCopy.SKU + ", newPrice=" + dbListingToCopy.CurrentPrice);
                    }
                }
            }
        }
        public void UpdateItemsForParentItem(
            IItemHistoryService itemChangeHistory,
            string calledFrom,
            string parentAsin,
            int market,
            string marketplaceId,
            IList <ItemDTO> items,
            DateTime when,
            long?by)
        {
            var dbExistItems = GetFiltered(l => l.ParentASIN == parentAsin &&
                                           l.Market == market &&
                                           l.MarketplaceId == marketplaceId).ToList();

            var existItemIdList = dbExistItems.Select(i => i.Id).ToList();
            var dbExistListings = unitOfWork.GetSet <Listing>()
                                  .Where(l => existItemIdList.Contains(l.ItemId))
                                  .ToList();

            var existListingIdList = dbExistListings.Select(l => l.Id).ToList();

            var newItems = items.Where(l => !l.ListingEntityId.HasValue || l.ListingEntityId == 0 || !existListingIdList.Contains(l.ListingEntityId.Value)).ToList();

            foreach (var dbListing in dbExistListings)
            {
                var existItem = items.FirstOrDefault(l => l.ListingEntityId == dbListing.Id);
                var dbItem    = dbExistItems.FirstOrDefault(l => l.Id == dbListing.ItemId);

                if (existItem != null)
                {
                    var hasChanges = dbItem.StyleItemId != existItem.StyleItemId ||
                                     dbItem.StyleId != existItem.StyleId ||
                                     dbItem.Size != existItem.Size ||
                                     dbItem.Color != existItem.Color ||
                                     dbItem.Title != existItem.Name ||
                                     dbItem.Barcode != existItem.Barcode ||
                                     dbItem.PrimaryImage != existItem.ImageUrl ||
                                     dbItem.ParentASIN != existItem.ParentASIN;

                    if (hasChanges)
                    {
                        dbItem.ParentASIN = existItem.ParentASIN;

                        dbItem.StyleString = existItem.StyleString;
                        dbItem.StyleId     = existItem.StyleId;
                        dbItem.StyleItemId = existItem.StyleItemId;

                        if (dbItem.Size != existItem.Size)
                        {
                            if (itemChangeHistory != null)
                            {
                                itemChangeHistory.AddRecord(dbItem.Id,
                                                            ItemHistoryHelper.SizeKey,
                                                            dbItem.Size,
                                                            calledFrom,
                                                            existItem.Size,
                                                            null,
                                                            by);
                            }
                        }

                        dbItem.Size  = existItem.Size;
                        dbItem.Color = existItem.Color;
                        dbItem.Title = existItem.Name;

                        if (!String.IsNullOrEmpty(existItem.Barcode)) //NOTE: may came empty when disable mode
                        {
                            if (dbItem.Barcode != existItem.Barcode)
                            {
                                if (itemChangeHistory != null)
                                {
                                    itemChangeHistory.AddRecord(dbItem.Id,
                                                                ItemHistoryHelper.BarcodeKey,
                                                                dbItem.Barcode,
                                                                calledFrom,
                                                                existItem.Barcode,
                                                                null,
                                                                by);
                                }

                                dbItem.Barcode = existItem.Barcode;
                            }
                        }

                        dbItem.PrimaryImage = existItem.ImageUrl;

                        dbItem.UpdateDate = when;
                        dbItem.UpdatedBy  = by;
                    }

                    if (dbItem.ItemPublishedStatus != (int)PublishedStatuses.None &&
                        dbItem.ItemPublishedStatus != (int)PublishedStatuses.New &&
                        dbItem.ItemPublishedStatus != (int)PublishedStatuses.Unpublished &&
                        dbItem.ItemPublishedStatus != (int)PublishedStatuses.HasUnpublishRequest)
                    {
                        dbItem.ItemPublishedStatus     = (int)PublishedStatuses.HasChanges;
                        dbItem.ItemPublishedStatusDate = when;
                    }
                    //NOTE: override with manuall if not empty
                    if (existItem.PublishedStatus != (int)PublishedStatuses.None)
                    {
                        dbItem.ItemPublishedStatus     = existItem.PublishedStatus;
                        dbItem.ItemPublishedStatusDate = when;
                    }

                    if (dbListing != null)
                    {
                        var hasListingChanges = dbListing.CurrentPrice != existItem.CurrentPrice ||
                                                dbListing.IsPrime != existItem.IsPrime ||
                                                dbListing.SKU != existItem.SKU ||
                                                dbListing.IsDefault != existItem.IsDefault;
                        if (hasListingChanges)
                        {
                            if (dbListing.CurrentPrice != existItem.CurrentPrice)
                            {
                                itemChangeHistory.LogListingPrice(PriceChangeSourceType.EnterNewPrice,
                                                                  dbListing.Id,
                                                                  dbListing.SKU,
                                                                  existItem.CurrentPrice,
                                                                  dbListing.CurrentPrice,
                                                                  when,
                                                                  by);

                                dbListing.CurrentPrice = existItem.CurrentPrice;
                            }

                            dbListing.IsPrime = existItem.IsPrime;

                            if (!String.IsNullOrEmpty(existItem.SKU)) //NOTE: may came empty when disable mode
                            {
                                if (dbListing.SKU != existItem.SKU)
                                {
                                    if (itemChangeHistory != null)
                                    {
                                        itemChangeHistory.AddRecord(dbItem.Id,
                                                                    ItemHistoryHelper.SKUKey,
                                                                    dbListing.SKU,
                                                                    calledFrom,
                                                                    existItem.SKU,
                                                                    null,
                                                                    by);
                                    }

                                    dbListing.SKU = existItem.SKU;
                                }
                            }
                            dbListing.IsDefault = existItem.IsDefault;

                            dbListing.UpdateDate = when;
                            dbListing.UpdatedBy  = by;
                        }

                        dbListing.QuantityUpdateRequested     = true;
                        dbListing.QuantityUpdateRequestedDate = when;
                        dbListing.PriceUpdateRequested        = true;
                        dbListing.PriceUpdateRequestedDate    = when;
                    }
                }
                else
                {
                    dbListing.IsRemoved = true;
                    unitOfWork.Commit();
                }
            }

            unitOfWork.Commit();

            foreach (var newItem in newItems)
            {
                var dbItem = new Item()
                {
                    ParentASIN    = newItem.ParentASIN,
                    Market        = market,
                    MarketplaceId = marketplaceId,

                    ASIN = StringHelper.Substring(newItem.ASIN, 50),

                    StyleString = newItem.StyleString,
                    StyleId     = newItem.StyleId,
                    StyleItemId = newItem.StyleItemId,
                    Size        = StringHelper.Substring(newItem.Size, 50),
                    Color       = StringHelper.Substring(newItem.Color, 50),

                    Barcode      = newItem.Barcode,
                    PrimaryImage = newItem.ImageUrl,

                    Title = newItem.Name,

                    ItemPublishedStatus     = (int)PublishedStatuses.New,
                    ItemPublishedStatusDate = when,

                    CreateDate = when,
                    CreatedBy  = by
                };
                Add(dbItem);
                unitOfWork.Commit();

                if (itemChangeHistory != null)
                {
                    itemChangeHistory.AddRecord(dbItem.Id,
                                                ItemHistoryHelper.SizeKey,
                                                null,
                                                calledFrom,
                                                dbItem.Size,
                                                null,
                                                by);
                }

                var dbListing = new Listing()
                {
                    ItemId        = dbItem.Id,
                    Market        = market,
                    MarketplaceId = marketplaceId,

                    ListingId = newItem.ListingId,
                    SKU       = StringHelper.Substring(newItem.SKU, 100),
                    IsDefault = newItem.IsDefault,

                    CurrentPrice = newItem.CurrentPrice,
                    RealQuantity = newItem.RealQuantity,

                    PriceUpdateRequested    = true,
                    QuantityUpdateRequested = true,

                    CreateDate = when,
                    CreatedBy  = by
                };

                unitOfWork.Listings.Add(dbListing);
                unitOfWork.Commit();

                newItem.ListingEntityId = dbListing.Id;
                newItem.Id = dbItem.Id;
            }
        }
        public Item StoreItemIfNotExist(IItemHistoryService itemHistory,
                                        string calledFrom,
                                        ItemDTO dto,
                                        MarketType market,
                                        string marketplaceId,
                                        long companyId,
                                        DateTime?when)
        {
            if (!ArgumentHelper.CheckMarket(market))
            {
                throw new ArgumentNullException("market");
            }
            if (!ArgumentHelper.CheckMarketplaceId(market, marketplaceId))
            {
                throw new ArgumentNullException("marketplaceId");
            }

            var item = GetByASIN(dto.ASIN, market, marketplaceId);

            if (item == null)
            {
                item = new Item
                {
                    ASIN          = dto.ASIN,
                    Market        = (int)market,
                    MarketplaceId = marketplaceId,

                    SourceMarketId = dto.SourceMarketId,

                    Title      = dto.Name,
                    ParentASIN = dto.ParentASIN ?? String.Empty,
                    Size       = StringHelper.Substring(dto.Size, 50),
                    Barcode    = dto.Barcode,

                    //SKU = dto.SKU,
                    StyleString = dto.StyleString,
                    StyleId     = dto.StyleId,
                    StyleItemId = dto.StyleItemId,

                    IsAmazonParentASIN   = dto.IsAmazonParentASIN,
                    LastUpdateFromAmazon = dto.LastUpdateFromAmazon,
                    IsExistOnAmazon      = dto.IsExistOnAmazon,

                    CreateDate  = when,
                    CompanyId   = companyId,
                    Description = dto.Description,

                    //Additional fields
                    PrimaryImage     = dto.ImageUrl,
                    BrandName        = dto.BrandName,
                    Type             = StringHelper.Substring(dto.Type, 50),
                    ListPrice        = dto.ListPrice,
                    Color            = StringHelper.Substring(dto.Color, 50),
                    Department       = dto.Department,
                    Features         = dto.Features,
                    AdditionalImages = dto.AdditionalImages,
                    SearchKeywords   = dto.SearchKeywords
                };
                Add(item);

                unitOfWork.Commit();

                if (itemHistory != null)
                {
                    itemHistory.AddRecord(item.Id,
                                          ItemHistoryHelper.SizeKey,
                                          null,
                                          calledFrom,
                                          item.Size,
                                          null,
                                          null);
                }
            }

            return(item);
        }