Example #1
0
        public void SendItemUpdates()
        {
            _log.Info("Begin ItemUpdates");
            using (var db = _dbFactory.GetRWDb())
            {
                var toDate  = _time.GetAppNowTime().AddHours(-30);
                var dbItems = db.Items.GetAll()
                              .Where(i => (i.ItemPublishedStatus == (int)PublishedStatuses.None ||
                                           i.ItemPublishedStatus == (int)PublishedStatuses.New ||
                                           i.ItemPublishedStatus == (int)PublishedStatuses.PublishingErrors ||
                                           i.ItemPublishedStatus == (int)PublishedStatuses.HasChanges ||
                                           i.ItemPublishedStatus == (int)PublishedStatuses.HasChangesWithProductId ||
                                           i.ItemPublishedStatus == (int)PublishedStatuses.HasChangesWithSKU ||
                                           ((i.ItemPublishedStatus == (int)PublishedStatuses.PublishedInProgress ||
                                             i.ItemPublishedStatus == (int)PublishedStatuses.ChangesSubmited) &&
                                            i.ItemPublishedStatusDate < toDate)) && //NOTE: Added in-progress statuses if items in it more then one day
                                     i.Market == (int)_api.Market &&
                                     !String.IsNullOrEmpty(i.Barcode) &&
                                     i.StyleItemId.HasValue)
                              .ToList();

                //NOTE: Need to submit items with group, otherwise we have incorrect color variations calculation, and sometimes image calculation
                var parentASINList = dbItems.Select(i => i.ParentASIN).Distinct().ToList();
                _log.Info("Parent ASIN Count to submit=" + parentASINList.Count + ", item count=" + dbItems.Count);

                var allItemList = db.Items.GetAllActualExAsDto()
                                  .Where(i => parentASINList.Contains(i.ParentASIN) &&
                                         i.Market == (int)_api.Market &&
                                         !String.IsNullOrEmpty(i.Barcode)).ToList();

                //var parentASINList = dbItems.Select(i => i.ParentASIN).Distinct().ToList();
                var allParentItemList = db.ParentItems.GetAllAsDto().Where(p => parentASINList.Contains(p.ASIN) &&
                                                                           p.Market == (int)_api.Market)
                                        .ToList();

                var styleIdList       = allItemList.Where(i => i.StyleId.HasValue).Select(i => i.StyleId.Value).ToList();
                var allStyleList      = db.Styles.GetAllAsDtoEx().Where(s => styleIdList.Contains(s.Id)).ToList();
                var allStyleImageList = db.StyleImages.GetAllAsDto().Where(sim => styleIdList.Contains(sim.StyleId)).ToList();
                var allFeatures       = db.FeatureValues.GetValuesByStyleIds(styleIdList);

                foreach (var item in allItemList)
                {
                    var parent = allParentItemList.FirstOrDefault(p => p.ASIN == item.ParentASIN);
                    if (parent != null)
                    {
                        item.OnHold = parent.OnHold;
                    }

                    var itemStyle = allStyleList.FirstOrDefault(s => s.Id == item.StyleId);

                    if (String.IsNullOrEmpty(itemStyle.BulletPoint1))
                    {
                        var features = allFeatures.Where(f => f.StyleId == item.StyleId).ToList();

                        var subLiscense =
                            StyleFeatureHelper.GetFeatureValue(
                                features.FirstOrDefault(f => f.FeatureId == StyleFeatureHelper.SUB_LICENSE1));
                        var mainLicense =
                            StyleFeatureHelper.PrepareMainLicense(
                                StyleFeatureHelper.GetFeatureValue(
                                    features.FirstOrDefault(f => f.FeatureId == StyleFeatureHelper.MAIN_LICENSE)),
                                subLiscense);
                        var material =
                            StyleFeatureHelper.GetFeatureValue(
                                features.FirstOrDefault(f => f.FeatureId == StyleFeatureHelper.MATERIAL));
                        var gender =
                            StyleFeatureHelper.GetFeatureValue(
                                features.FirstOrDefault(f => f.FeatureId == StyleFeatureHelper.GENDER));
                        var bulletPoints = ExportDataHelper.BuildKeyFeatures(mainLicense,
                                                                             subLiscense,
                                                                             material,
                                                                             gender);

                        item.Features = String.Join(";", bulletPoints);
                    }
                    else
                    {
                        item.Features = String.Join(";", new string[]
                        {
                            itemStyle.BulletPoint1,
                            itemStyle.BulletPoint2,
                            itemStyle.BulletPoint3,
                            itemStyle.BulletPoint4,
                            itemStyle.BulletPoint5,
                        });
                    }
                }

                //Exclude OnHold (after ParentItem onHold was applied)
                allItemList = allItemList.Where(i => !i.OnHold).ToList();

                foreach (var styleImage in allStyleImageList)
                {
                    try
                    {
                        var filepath = ImageHelper.BuildJetImage(_jetImageDirectory, styleImage.Image);
                        var filename = Path.GetFileName(filepath);
                        styleImage.Image = _jetImageBaseUrl + filename;
                    }
                    catch (Exception ex)
                    {
                        _log.Info("BuildWalmartImage error, image=" + styleImage.Image, ex);
                    }
                }

                //foreach (var style in allStyleList)
                //{
                //    try
                //    {
                //        var filepath = ImageHelper.BuildSwatchImage(_swatchImageDirectory, style.Image);
                //        var filename = Path.GetFileName(filepath);
                //        style.SwatchImage = _swatchImageBaseUrl + filename;
                //    }
                //    catch (Exception ex)
                //    {
                //        _log.Info("BuildSwatchImage error, image=" + style.Image, ex);
                //    }
                //}

                if (allItemList.Any())
                {
                    _log.Info("Items to update=" + String.Join(", ", allItemList.Select(i => i.SKU).ToList()));

                    foreach (var item in allItemList)
                    {
                        var style       = allStyleList.FirstOrDefault(s => s.Id == item.StyleId);
                        var styleImages = new List <StyleImageDTO>();

                        var styleFeatures = allFeatures.Where(f => f.StyleId == item.StyleId).ToList();
                        var parentItem    = allParentItemList.FirstOrDefault(p => p.ASIN == item.ASIN);
                        var groupItems    = allItemList.Where(i => i.ParentASIN == item.ParentASIN).ToList();

                        var enableColorVariation = (parentItem != null && parentItem.ForceEnableColorVariations) ||
                                                   groupItems.GroupBy(i => i.Size)
                                                   .Select(g => new
                        {
                            Count = g.Count(),
                            Size  = g.Key,
                        })
                                                   .Count(g => g.Count > 1) > 0;

                        if (!enableColorVariation)
                        {
                            //NOTE: get images from all styles from group
                            var groupStyleIds = groupItems.Select(i => i.StyleId).Distinct().ToList();
                            styleImages = allStyleImageList
                                          .Where(im => groupStyleIds.Contains(im.StyleId) && !im.IsSystem)
                                          .OrderByDescending(im => im.IsDefault)
                                          .ThenBy(im => im.Id)
                                          .ToList();
                        }
                        else
                        {
                            //NOTE: when color variation, get images only from current style, other images were present other color variations
                            styleImages = allStyleImageList
                                          .Where(im => im.StyleId == item.StyleId && !im.IsSystem)
                                          .OrderByDescending(im => im.IsDefault)
                                          .ThenBy(im => im.Id)
                                          .ToList();
                        }

                        var result = _api.SendProduct(item,
                                                      style,
                                                      styleImages.Select(im => im.Image).ToList(),
                                                      styleFeatures);

                        var dbItem = db.Items.GetAll().FirstOrDefault(i => i.Id == item.Id);
                        if (dbItem != null)
                        {
                            if (result.IsSuccess)
                            {
                                dbItem.ItemPublishedStatus     = (int)PublishedStatuses.Published;
                                dbItem.ItemPublishedStatusDate = _time.GetAppNowTime();
                            }
                            else
                            {
                                dbItem.ItemPublishedStatus     = (int)PublishedStatuses.PublishingErrors;
                                dbItem.ItemPublishedStatusDate = _time.GetAppNowTime();
                            }
                        }
                        else
                        {
                            _log.Error("Can't find Item record in DB to update, id=" + item.Id + ", SKU=" + item.SKU);
                        }
                    }
                    db.Commit();

                    foreach (var parentItem in allParentItemList)
                    {
                        var childItems = allItemList.Where(i => i.ParentASIN == parentItem.ASIN).ToList();

                        var enableColorVariation = (parentItem != null && parentItem.ForceEnableColorVariations) ||
                                                   childItems.GroupBy(i => i.Size)
                                                   .Select(g => new
                        {
                            Count = g.Count(),
                            Size  = g.Key,
                        })
                                                   .Count(g => g.Count > 1) > 0;

                        _api.SendVariations(childItems[0].SKU,
                                            childItems.Skip(1).Select(i => i.SKU).ToArray(),
                                            enableColorVariation);
                    }
                }
                _log.Info("End ItemUpdates");
            }
        }
        public void SubmitFeed(IList <string> asinList, PublishedStatuses overrideStatus)
        {
            using (var db = _dbFactory.GetRWDb())
            {
                var             toDate = _time.GetAppNowTime().AddHours(-2);
                IList <ItemDTO> itemsToSubmit;

                if (asinList == null || !asinList.Any())
                {
                    itemsToSubmit = (from i in db.Items.GetAll()
                                     join l in db.Listings.GetAll() on i.Id equals l.ItemId
                                     where (i.ItemPublishedStatus == (int)PublishedStatuses.None ||
                                            i.ItemPublishedStatus == (int)PublishedStatuses.New ||
                                            i.ItemPublishedStatus == (int)PublishedStatuses.PublishingErrors ||
                                            i.ItemPublishedStatus == (int)PublishedStatuses.HasChanges ||
                                            i.ItemPublishedStatus == (int)PublishedStatuses.HasChangesWithProductId ||
                                            i.ItemPublishedStatus == (int)PublishedStatuses.HasChangesWithSKU ||
                                            ((i.ItemPublishedStatus == (int)PublishedStatuses.PublishedInProgress ||
                                              i.ItemPublishedStatus == (int)PublishedStatuses.ChangesSubmited) &&
                                             (i.ItemPublishedStatusDate < toDate ||
                                              !i.ItemPublishedStatusDate.HasValue)))
                                     //NOTE: Added in-progress statuses if items in it more then one day
                                     && i.Market == (int)_api.Market
                                     //&& !String.IsNullOrEmpty(i.Barcode)
                                     && i.StyleItemId.HasValue &&
                                     !l.IsRemoved &&
                                     !String.IsNullOrEmpty(i.Barcode)
                                     select new ItemDTO()
                    {
                        Id = i.Id,
                        PuclishedStatusDate = i.ItemPublishedStatusDate,
                        CreateDate = i.CreateDate,
                        ParentASIN = i.ParentASIN,
                    })
                                    .ToList();
                }
                else
                {
                    itemsToSubmit = (from i in db.Items.GetAll()
                                     join l in db.Listings.GetAll() on i.Id equals l.ItemId
                                     where i.Market == (int)_api.Market &&
                                     !l.IsRemoved
                                     //&& !String.IsNullOrEmpty(i.Barcode)
                                     && i.StyleItemId.HasValue &&
                                     asinList.Contains(l.SKU)
                                     select new ItemDTO()
                    {
                        Id = i.Id,
                        PuclishedStatusDate = i.ItemPublishedStatusDate,
                        CreateDate = i.CreateDate,
                        ParentASIN = i.ParentASIN,
                    })
                                    .ToList();
                }

                //NOTE: Need to submit items with group, otherwise we have incorrect color variations calculation, and sometimes image calculation
                var parentInfoQuery = from i in itemsToSubmit
                                      group i by i.ParentASIN into byParent
                                      select new
                {
                    ParentASIN = byParent.Key,
                    ItemPublishedStatusDate = byParent.Min(i => i.PuclishedStatusDate ?? i.CreateDate)
                };

                var parentASINList = parentInfoQuery
                                     .OrderBy(pi => pi.ItemPublishedStatusDate)
                                     .Select(pi => pi.ParentASIN) //NOTE: Walmart has issue with large request ("(413) Request Entity Too Large.")
                                     .ToList();

                var itemDtoList = db.Items.GetAllActualExAsDto()
                                  .Where(i => parentASINList.Contains(i.ParentASIN) &&
                                         i.Market == (int)_api.Market &&
                                         !String.IsNullOrEmpty(i.Barcode)).ToList();

                _log.Info("Parent ASIN Count to submit=" + parentASINList.Count + ", item actually submitted=" + itemDtoList.Count + " (items in queue to submit: " + itemsToSubmit.Count + ")");
                _log.Info("SKUs to submit: " + String.Join(", ", itemDtoList.Select(i => i.SKU)));

                if (overrideStatus != PublishedStatuses.None)
                {
                    var toOverrideItems = itemDtoList.Where(i => asinList.Contains(i.SKU)).ToList();
                    toOverrideItems.ForEach(i => i.PublishedStatus = (int)overrideStatus);
                }

                //var parentASINList = dbItems.Select(i => i.ParentASIN).Distinct().ToList();
                var parentItemDtoList = db.ParentItems.GetAllAsDto().Where(p => parentASINList.Contains(p.ASIN) &&
                                                                           p.Market == (int)_api.Market)
                                        .ToList();

                var styleIdList       = itemDtoList.Where(i => i.StyleId.HasValue).Select(i => i.StyleId.Value).ToList();
                var styleList         = db.Styles.GetAllAsDtoEx().Where(s => styleIdList.Contains(s.Id)).ToList();
                var allStyleImageList = db.StyleImages.GetAllAsDto().Where(sim => styleIdList.Contains(sim.StyleId) &&
                                                                           sim.Category != (int)StyleImageCategories.Deleted).ToList();
                var allFeatures = db.FeatureValues.GetValuesByStyleIds(styleIdList);

                var allBrandMappings = db.WalmartBrandInfoes.GetAllAsDto().ToList();

                foreach (var item in itemDtoList)
                {
                    var parent = parentItemDtoList.FirstOrDefault(p => p.ASIN == item.ParentASIN);
                    if (parent != null && parent.OnHold)
                    {
                        item.OnHold = parent.OnHold;
                    }

                    var styleForItem = styleList.FirstOrDefault(s => s.Id == item.StyleId);

                    var features    = allFeatures.Where(f => f.StyleId == item.StyleId).ToList();
                    var subLiscense =
                        StyleFeatureHelper.GetFeatureValue(
                            features.FirstOrDefault(f => f.FeatureId == StyleFeatureHelper.SUB_LICENSE1));
                    var mainLicense =
                        StyleFeatureHelper.PrepareMainLicense(
                            StyleFeatureHelper.GetFeatureValue(
                                features.FirstOrDefault(f => f.FeatureId == StyleFeatureHelper.MAIN_LICENSE)),
                            subLiscense);

                    var brand        = StringHelper.GetFirstNotEmpty(mainLicense, styleForItem.Manufacturer);
                    var brandMapping = allBrandMappings.FirstOrDefault(b => b.GlobalBrandLicense == brand && StringHelper.ContainsNoCase(b.Character, subLiscense));
                    if (brandMapping == null)
                    {
                        var brandMappingCandidates = allBrandMappings.Where(b => b.GlobalBrandLicense == brand).ToList();
                        if (brandMappingCandidates.Count == 1)
                        {
                            brandMapping = brandMappingCandidates.FirstOrDefault();
                        }
                    }

                    var character = StringHelper.GetFirstNotEmpty(brandMapping?.Character,
                                                                  StyleFeatureHelper.GetFeatureValueByName(features, StyleFeatureHelper.MAIN_CHARACTER_KEY));
                    StyleFeatureHelper.AddOrUpdateFeatureValueByName(allFeatures, styleForItem.Id, StyleFeatureHelper.MAIN_CHARACTER_KEY, character);

                    var globalLicense = StringHelper.GetFirstNotEmpty(brandMapping?.GlobalBrandLicense,
                                                                      brand);
                    StyleFeatureHelper.AddOrUpdateFeatureValueByName(allFeatures, styleForItem.Id, StyleFeatureHelper.GLOBAL_LICENSE_KEY, globalLicense);

                    brand = StringHelper.GetFirstNotEmpty(brandMapping?.Brand, brand);
                    StyleFeatureHelper.AddOrUpdateFeatureValueByName(allFeatures, styleForItem.Id, StyleFeatureHelper.BRAND_KEY, brand);

                    if (String.IsNullOrEmpty(styleForItem.BulletPoint1))
                    {
                        var material =
                            StyleFeatureHelper.GetFeatureValue(
                                features.FirstOrDefault(f => f.FeatureId == StyleFeatureHelper.MATERIAL));
                        var gender =
                            StyleFeatureHelper.GetFeatureValue(
                                features.FirstOrDefault(f => f.FeatureId == StyleFeatureHelper.GENDER));

                        var bulletPoints = ExportDataHelper.BuildKeyFeatures(mainLicense,
                                                                             subLiscense,
                                                                             material,
                                                                             gender);

                        styleForItem.BulletPoint1 = bulletPoints.Count > 0 ? bulletPoints[0] : null;
                        styleForItem.BulletPoint2 = bulletPoints.Count > 1 ? bulletPoints[1] : null;
                        styleForItem.BulletPoint3 = bulletPoints.Count > 2 ? bulletPoints[2] : null;
                        styleForItem.BulletPoint4 = bulletPoints.Count > 3 ? bulletPoints[3] : null;
                        styleForItem.BulletPoint5 = bulletPoints.Count > 4 ? bulletPoints[4] : null;

                        item.Features = String.Join(";", bulletPoints);
                    }
                    else
                    {
                        //var itemStyleValue = WalmartUtils.GetFeatureValue(allFeatures.Where(f => f.StyleId == itemStyle.Id).ToList(), StyleFeatureHelper.ITEMSTYLE);

                        item.Features = String.Join(";", StyleFeatureHelper.PrepareBulletPoints(new string[]
                        {
                            styleForItem.BulletPoint1,
                            styleForItem.BulletPoint2,
                            styleForItem.BulletPoint3,
                            styleForItem.BulletPoint4,
                            styleForItem.BulletPoint5,
                        }));
                    }
                }

                //Exclude OnHold (after ParentItem onHold was applied)
                //itemDtoList = itemDtoList.Where(i => !i.OnHold).ToList();

                foreach (var styleImage in allStyleImageList)
                {
                    try
                    {
                        var styleString = styleList.FirstOrDefault(s => s.Id == styleImage.StyleId)?.StyleID;

                        var filepath = ImageHelper.BuildWalmartImage(_walmartImageDirectory,
                                                                     styleImage.Image,
                                                                     styleString + "_" + MD5Utils.GetMD5HashAsString(styleImage.Image));
                        var filename = Path.GetFileName(filepath);
                        styleImage.Image = UrlUtils.CombinePath(_walmartImageBaseUrl, filename);
                    }
                    catch (Exception ex)
                    {
                        _log.Info("BuildWalmartImage error, image=" + styleImage.Image, ex);
                    }
                }

                foreach (var style in styleList)
                {
                    //var styleImages = allStyleImageList.Where(sim => sim.StyleId == style.Id).ToList();

                    //var styleImage = styleImages.Where(si => si.Type == (int) StyleImageType.LoRes
                    //                                            || si.Type == (int) StyleImageType.HiRes)
                    //    .OrderByDescending(si => si.Type) //First Hi-res
                    //    .ThenBy(si => si.IsSystem) //First not system
                    //    .ThenByDescending(si => si.IsDefault) //First isDefault
                    //    .FirstOrDefault();

                    //if (styleImage != null)
                    //    style.Image = styleImage.Image; //Set to Hi-res

                    try
                    {
                        var swatchImage    = style.Image;
                        var swatchImageObj = allStyleImageList.FirstOrDefault(st => st.Id == style.Id &&
                                                                              st.Category == (int)StyleImageCategories.Swatch);
                        if (swatchImageObj != null)
                        {
                            swatchImage = swatchImageObj.Image;
                        }

                        var filepath = ImageHelper.BuildSwatchImage(_swatchImageDirectory, swatchImage);
                        var filename = Path.GetFileName(filepath);
                        style.SwatchImage = UrlUtils.CombinePath(_swatchImageBaseUrl, filename);
                    }
                    catch (Exception ex)
                    {
                        _log.Info("BuildSwatchImage error, image=" + style.Image, ex);
                    }
                }



                if (itemDtoList.Any())
                {
                    _log.Info("Items to submit=" + String.Join(", ", itemDtoList.Select(i => i.SKU).ToList()));

                    var newFeed = new Feed()
                    {
                        Market        = (int)Market,
                        MarketplaceId = MarketplaceId,
                        Type          = (int)FeedType,
                        Status        = (int)FeedStatus.Submitted,
                        MessageCount  = itemDtoList.Count,
                        SubmitDate    = _time.GetAppNowTime()
                    };
                    db.Feeds.Add(newFeed);
                    db.Commit();

                    _log.Info("Feed id=" + newFeed.Id);

                    IList <FeedMessageDTO> messages;

                    var submitResult = _api.SubmitItemsFeed(newFeed.Id.ToString(),
                                                            itemDtoList,
                                                            parentItemDtoList,
                                                            styleList,
                                                            allStyleImageList,
                                                            allFeatures,
                                                            _feedBaseDirectory,
                                                            out messages);

                    #region Update item errors
                    var itemIds = itemDtoList.Select(i => i.Id).ToList();
                    //Remove all exist errors
                    var dbExistErrors = db.ItemAdditions.GetAll().Where(i => itemIds.Contains(i.ItemId) &&
                                                                        (i.Field == ItemAdditionFields.PrePublishError)).ToList();
                    foreach (var dbExistError in dbExistErrors)
                    {
                        db.ItemAdditions.Remove(dbExistError);
                    }
                    foreach (var message in messages)
                    {
                        db.ItemAdditions.Add(new Core.Entities.Listings.ItemAddition()
                        {
                            ItemId     = (int)message.ItemId.Value,
                            Field      = ItemAdditionFields.PrePublishError,
                            Value      = message.Message,
                            Source     = newFeed.Id.ToString(),
                            CreateDate = _time.GetAppNowTime(),
                        });
                    }
                    db.Commit();
                    #endregion

                    if (submitResult.IsSuccess)
                    {
                        _log.Info("Walmart feed id=" + submitResult.Data);

                        newFeed.AmazonIdentifier = submitResult.Data.AmazonIdentifier;
                        newFeed.RequestFilename  = submitResult.Data.RequestFilename;
                        db.Commit();

                        var dbItems = db.Items.GetAll().Where(i => itemIds.Contains(i.Id)).ToList();
                        foreach (var item in dbItems)
                        {
                            _log.Info("Mark item as in-progress, id=" + item.Id);

                            item.ItemPublishedStatusBeforeRepublishing = item.ItemPublishedStatus;
                            item.ItemPublishedStatus     = (int)PublishedStatuses.ChangesSubmited;
                            item.ItemPublishedStatusDate = _time.GetAppNowTime();
                        }
                        db.Commit();

                        foreach (var item in itemDtoList)
                        {
                            db.FeedItems.Add(new Core.Entities.Feeds.FeedItem()
                            {
                                FeedId = newFeed.Id,
                                ItemId = item.Id,
                            });
                            db.Commit();
                        }

                        _log.Info("Feed submitted, feedId=" + newFeed.AmazonIdentifier);
                    }
                    else
                    {
                        _log.Fatal("Feed DIDN'T submitted, mark feed as deleted");

                        newFeed.Status = (int)FeedStatus.SubmissionFail;
                        db.Commit();

                        throw new Exception("Unable to submit feed, submission status failed. Details: " + submitResult.Message);
                    }
                }
            }
        }
        private IList <GrouponGoodLine> BuildProductLines(IList <ItemExDTO> allItems,
                                                          IList <ParentItemDTO> allParentItems,
                                                          IList <StyleEntireDto> allStyles,
                                                          IList <StyleImageDTO> allStyleImages,
                                                          IList <StyleItemDTO> allStyleItems,
                                                          IList <FeatureValueDTO> allFeatures)
        {
            var results = new List <GrouponGoodLine>();

            foreach (var parentItem in allParentItems)
            {
                var items = allItems.Where(i => i.ParentASIN == parentItem.ASIN).ToList();

                foreach (var item in items)
                {
                    var style         = allStyles.FirstOrDefault(s => s.Id == item.StyleId);
                    var styleItem     = allStyleItems.FirstOrDefault(si => si.StyleItemId == item.StyleItemId);
                    var styleImages   = allStyleImages.Where(si => si.StyleId == style.Id && !si.IsSystem).ToList();
                    var styleFeatures = allFeatures.Where(f => f.StyleId == item.StyleId).ToList();

                    var gender              = styleFeatures.FirstOrDefault(f => f.FeatureId == StyleFeatureHelper.GENDER)?.Value;
                    var subLicense          = styleFeatures.FirstOrDefault(f => f.FeatureId == StyleFeatureHelper.SUB_LICENSE1)?.Value;
                    var mainLicense         = StyleFeatureHelper.PrepareMainLicense(styleFeatures.FirstOrDefault(f => f.FeatureId == StyleFeatureHelper.MAIN_LICENSE)?.Value, subLicense);
                    var material            = styleFeatures.FirstOrDefault(f => f.FeatureId == StyleFeatureHelper.MATERIAL)?.Value;
                    var sleeve              = styleFeatures.FirstOrDefault(f => f.FeatureId == StyleFeatureHelper.SLEEVE)?.Value;
                    var itemStyleValue      = styleFeatures.FirstOrDefault(f => f.FeatureId == StyleFeatureHelper.ITEMSTYLE)?.Value;
                    var color1              = styleFeatures.FirstOrDefault(f => f.FeatureId == StyleFeatureHelper.COLOR1)?.Value;
                    var shippingSize        = styleFeatures.FirstOrDefault(f => f.FeatureId == StyleFeatureHelper.SHIPPING_SIZE)?.Value;
                    var isSmallShippingSize = shippingSize == "XS" || shippingSize == "S";

                    var searchTerms = style != null ? style.SearchTerms : null;
                    var isToddler   = items.All(i => SizeHelper.IsToddlers(i.StyleSize));
                    var description = style != null ? style.Description : null;
                    description = StringHelper.TrimTags(description);

                    var category = GrouponUtils.GetCategories(gender, itemStyleValue);

                    if (category == null || !category.Any())
                    {
                        _log.Info("No category info");
                        continue;
                    }
                    if (!style.MSRP.HasValue)
                    {
                        _log.Info("No MSRP");
                        //continue;
                    }

                    var packageSize = GrouponUtils.GetSizes(shippingSize);

                    var attributes = FillAttributesByCategory(category,
                                                              styleFeatures,
                                                              description,
                                                              style.Name,
                                                              item.Color,
                                                              styleItem.Size ?? item.Size);

                    if (attributes == null || !attributes.Any())
                    {
                        _log.Info("No attributes, category=" + category);
                        continue;
                    }

                    var model = new GrouponGoodLine()
                    {
                        CategoryID            = category,
                        VendorSKU             = item.SKU,
                        Title                 = GrouponUtils.PrepareText(StringHelper.Substring(style.Name, 80)),
                        Description           = GrouponUtils.PrepareText(StringHelper.GetFirstNotEmpty(description, style.Name)),
                        Manufacturer          = mainLicense,
                        ModelNumber           = style.StyleID,
                        Brand                 = mainLicense,
                        IsBundle              = "No",
                        ProductIdentifierType = "UPC",
                        ProductIdentifier     = item.Barcode,
                        VariationGroupingID   = StringHelper.GetFirstNotEmpty(parentItem.GroupId, parentItem.ASIN),

                        UnitPrice         = PriceHelper.RoundRoundToTwoPrecision(item.CurrentPrice).ToString(),
                        ShippingCost      = PriceHelper.RoundRoundToTwoPrecision(0).ToString(), //NOTE: Free
                        ReferencePrice    = style.MSRP.HasValue ? PriceHelper.RoundRoundToTwoPrecision(style.MSRP.Value).ToString() : "",
                        ReferencePriceURL = item.SourceMarketUrl,

                        ProductWeight         = (decimal)(item.Weight ?? 1.0),
                        ProductWeightUnit     = "Ounces",
                        ProductHeight         = packageSize[0],
                        ProductLength         = packageSize[1],
                        ProductWidth          = packageSize[2],
                        ProductDimensionsUnit = "Inches",
                        IsLTLShippingRequired = "No",
                        PackageWeight         = (decimal)(item.Weight ?? 1.0),
                        PackageWeightUnit     = "Ounces",
                        PackageHeight         = packageSize[0],
                        PackageLength         = packageSize[1],
                        PackageWidth          = packageSize[2],
                        PackageDimensionsUnit = "Inches",
                        CountryofOrigin       = "US",

                        Quantity = Math.Min(5, item.RealQuantity),

                        MainImage       = styleImages.Count > 0 ? styleImages[0]?.Image : "",
                        AlternateImage1 = styleImages.Count > 1 ? styleImages[1]?.Image : "",
                        AlternateImage2 = styleImages.Count > 2 ? styleImages[2]?.Image : "",
                        AlternateImage3 = styleImages.Count > 3 ? styleImages[3]?.Image : "",

                        Bullet1Description = GrouponUtils.PrepareText(StringHelper.Substring(StringHelper.TrimTags(style.BulletPoint1), 128)),
                        Bullet2Description = GrouponUtils.PrepareText(StringHelper.Substring(StringHelper.TrimTags(style.BulletPoint2), 128)),
                        Bullet3Description = GrouponUtils.PrepareText(StringHelper.Substring(StringHelper.TrimTags(style.BulletPoint3), 128)),
                        Bullet4Description = GrouponUtils.PrepareText(StringHelper.Substring(StringHelper.TrimTags(style.BulletPoint4), 128)),
                        Bullet5Description = GrouponUtils.PrepareText(StringHelper.Substring(StringHelper.TrimTags(style.BulletPoint5), 128)),

                        Attributes = attributes,
                    };

                    results.Add(model);
                }

                //Extract attributes
                var attributeNames = new Dictionary <string, int>();
                var lastIndex      = 1;
                foreach (var model in results)
                {
                    foreach (var attribte in model.Attributes)
                    {
                        if (!attributeNames.ContainsKey(attribte.Name))
                        {
                            attributeNames.Add(attribte.Name, lastIndex++);
                        }
                    }
                }

                foreach (var model in results)
                {
                    foreach (var attribute in model.Attributes)
                    {
                        var index = attributeNames[attribute.Name];
                        SetAttribute(model, index, attribute);
                    }
                }
            }

            return(results);
        }
Example #4
0
        private XmlDocument ComposeDocument(IUnitOfWork db,
                                            MarketType market,
                                            string marketplaceId,
                                            IList <string> skuList,
                                            string merchantId,
                                            string type,
                                            out int nodesCount,
                                            out IList <FeedItemDTO> feedItems,
                                            out IList <FeedMessageDTO> messages)
        {
            var toDate = Time.GetAppNowTime().Subtract(IntervalBetweenAttempts);

            IList <int>             itemIds;
            IList <SystemActionDTO> requestInfoes = null;

            if (skuList == null || !skuList.Any())
            {
                requestInfoes = db.SystemActions.GetAllAsDto()
                                .Where(a => a.Type == (int)SystemActionType.UpdateOnMarketProductData &&
                                       a.Status == (int)SystemActionStatus.None &&
                                       (!a.AttemptDate.HasValue || a.AttemptDate < toDate))
                                .OrderByDescending(a => a.CreateDate)
                                .ToList();

                var tags = requestInfoes.Select(i => i.Tag).ToList();
                itemIds = tags.Select(i => StringHelper.TryGetInt(i)).ToList().Where(i => i.HasValue).Select(i => i.Value).ToList();
            }
            else
            {
                itemIds = (from i in db.Items.GetAll()
                           join l in db.Listings.GetAll() on i.Id equals l.ItemId
                           where i.Market == (int)market &&
                           (i.MarketplaceId == marketplaceId || String.IsNullOrEmpty(marketplaceId)) &&
                           (!String.IsNullOrEmpty(i.Barcode) ||
                            i.IsExistOnAmazon == true) &&
                           i.StyleItemId.HasValue &&
                           skuList.Contains(l.SKU) &&
                           !l.IsFBA
                           select i.Id).ToList();
            }

            //NOTE: No need to sumbit all childs
            Log.Info("Items to submit=" + itemIds.Count);

            var dtoItems = db.Items.GetAllActualExAsDto()
                           .Where(i => itemIds.Contains(i.Id) &&
                                  i.Market == (int)market &&
                                  (i.MarketplaceId == marketplaceId || String.IsNullOrEmpty(marketplaceId)) &&
                                  (!String.IsNullOrEmpty(i.Barcode) ||
                                   i.IsExistOnAmazon == true) &&
                                  !i.IsFBA) //NOTE: Exclude FBA listings
                           .ToList();

            if (skuList == null)
            {
                dtoItems.ForEach(i => i.Id = 0);
            }
            else
            {
                foreach (var dtoItem in dtoItems)
                {
                    var requestInfo = requestInfoes.FirstOrDefault(i => i.Tag == dtoItem.Id.ToString());
                    dtoItem.Id = (int)(requestInfo?.Id ?? 0);
                }
            }

            var parentASINList = dtoItems.Select(i => i.ParentASIN).Distinct().ToList();

            //TEMP: Exclude updates for already published items
            //itemDtoList = itemDtoList.Where(i => i.PublishedStatus != (int)PublishedStatuses.Published).ToList();

            //var parentASINList = dbItems.Select(i => i.ParentASIN).Distinct().ToList();
            var parentItemDtoList = db.ParentItems.GetAllAsDto().Where(p => parentASINList.Contains(p.ASIN) &&
                                                                       p.Market == (int)market &&
                                                                       p.MarketplaceId == marketplaceId)
                                    .ToList();

            #region Detect Variation Type
            var allChildItems = db.Items.GetAll().Where(i => parentASINList.Contains(i.ParentASIN))
                                .Select(i => new ItemDTO()
            {
                ParentASIN = i.ParentASIN,
                Size       = i.Size,
                Color      = i.Color,
            }).ToList();
            var colorVariations = allChildItems.GroupBy(i => i.ParentASIN).Select(i => new ParentItemDTO()
            {
                ASIN = i.Key,
                ForceEnableColorVariations = i.Select(c => c.Color).Distinct().Count() > 1,
            }).ToList();

            foreach (var parentItem in parentItemDtoList)
            {
                var colorVariation = colorVariations.FirstOrDefault(c => c.ASIN == parentItem.ASIN);
                if (colorVariation != null)
                {
                    parentItem.ForceEnableColorVariations = parentItem.ForceEnableColorVariations || colorVariation.ForceEnableColorVariations;
                }
            }
            #endregion

            //var lockedParentASINs = parentItemDtoList
            //    .Where(pi => pi.LockMarketUpdate)
            //    .Select(pi => pi.ASIN)
            //    .ToList();

            //parentItemDtoList = parentItemDtoList.Where(pi => !pi.LockMarketUpdate).ToList();
            //itemDtoList = itemDtoList.Where(i => !lockedParentASINs.Contains(i.ParentASIN)).ToList();

            var styleIdList       = dtoItems.Where(i => i.StyleId.HasValue).Select(i => i.StyleId.Value).ToList();
            var styleList         = db.Styles.GetAllAsDtoEx().Where(s => styleIdList.Contains(s.Id)).ToList();
            var allStyleImageList =
                db.StyleImages.GetAllAsDto().Where(sim => styleIdList.Contains(sim.StyleId)).ToList();
            var allFeatures = db.FeatureValues.GetValuesByStyleIds(styleIdList);

            nodesCount = dtoItems.Count;

            foreach (var item in dtoItems)
            {
                var parent = parentItemDtoList.FirstOrDefault(p => p.ASIN == item.ParentASIN);
                if (parent != null)
                {
                    item.OnHold = parent.OnHold;
                }

                var itemStyle = styleList.FirstOrDefault(s => s.Id == item.StyleId);

                if (String.IsNullOrEmpty(itemStyle.BulletPoint1))
                {
                    var features = allFeatures.Where(f => f.StyleId == item.StyleId).ToList();

                    var subLiscense =
                        StyleFeatureHelper.GetFeatureValue(
                            features.FirstOrDefault(f => f.FeatureId == StyleFeatureHelper.SUB_LICENSE1));
                    var mainLicense =
                        StyleFeatureHelper.PrepareMainLicense(
                            StyleFeatureHelper.GetFeatureValue(
                                features.FirstOrDefault(f => f.FeatureId == StyleFeatureHelper.MAIN_LICENSE)),
                            subLiscense);
                    var material =
                        StyleFeatureHelper.GetFeatureValue(
                            features.FirstOrDefault(f => f.FeatureId == StyleFeatureHelper.MATERIAL));
                    var gender =
                        StyleFeatureHelper.GetFeatureValue(
                            features.FirstOrDefault(f => f.FeatureId == StyleFeatureHelper.GENDER));
                    var bulletPoints = ExportDataHelper.BuildKeyFeatures(mainLicense,
                                                                         subLiscense,
                                                                         material,
                                                                         gender);

                    item.Features = String.Join(";", bulletPoints);
                }
                else
                {
                    item.Features = String.Join(";", new string[]
                    {
                        itemStyle.BulletPoint1,
                        itemStyle.BulletPoint2,
                        itemStyle.BulletPoint3,
                        itemStyle.BulletPoint4,
                        itemStyle.BulletPoint5,
                    });
                }
            }

            //Exclude OnHold (after ParentItem onHold was applied)
            //itemDtoList = itemDtoList.Where(i => !i.OnHold).ToList();

            if (dtoItems.Any())
            {
                Log.Info("Items to submit=" + String.Join(", ", dtoItems.Select(i => i.SKU).ToList()));

                var newFeed = new Feed()
                {
                    Market        = (int)market,
                    MarketplaceId = marketplaceId,
                    Type          = (int)Type,
                    Status        = (int)FeedStatus.Submitted,
                    SubmitDate    = Time.GetAppNowTime()
                };
                db.Feeds.Add(newFeed);
                db.Commit();

                Log.Info("Feed id=" + newFeed.Id);

                var builder = new ProductFeedBuilder(Log, Time, _categoryService, ChooseTemplate);
                IList <WithMessages <AmazonProductExportDto> > items = new List <WithMessages <AmazonProductExportDto> >();
                items = builder.Build(
                    dtoItems,
                    parentItemDtoList,
                    styleList,
                    allStyleImageList,
                    allFeatures,
                    UseStyleImageModes.StyleImage,
                    market,
                    marketplaceId);

                feedItems = items
                            .Where(i => i.Value.Parentage != ExcelHelper.ParentageParent.ToLower() && //TODO: why Perentage != ParentageParent ????
                                   i.IsSucess)
                            .Select(i => new FeedItemDTO()
                {
                    FeedId    = newFeed.Id,
                    MessageId = i.Value.MessageID,
                    ItemId    = i.Value.Id ?? 0
                }).ToList();

                messages = items.SelectMany(i => i.Messages.Select(m => new FeedMessageDTO()
                {
                    Id      = i.Value?.Id ?? 0,
                    Message = m.Message
                }).ToList())
                           .ToList();

                UpdatePrePublishErrors(db, itemIds, messages, ItemAdditionFields.PublishError);

                var xml = builder.ToXmlFeed(items.Select(i => i.Value).ToList(),
                                            merchantId,
                                            Type.ToString());

                var doc = new XmlDocument();
                doc.LoadXml(xml);
                return(doc);
            }

            feedItems = new List <FeedItemDTO>();
            messages  = new List <FeedMessageDTO>();
            return(null);
        }