コード例 #1
0
        public ActionResult Export(string fileName, string selectedColumns)
        {
            //取得原始資料
            var exportData = db.Customers.OrderBy(x => x.CustomerID).ToList();

            //使用 AutoMapper 建立斷映轉換設定
            Mapper.CreateMap <Customer, CustomerViewModel>();

            //使用 AutoMapper 將 Customer 型別的原始資料對映轉換為 CustomerViewModel 型別.
            var result = Mapper.Map <List <CustomerViewModel> >(exportData);

            //使用轉換後的匯出資料與使用者所選的匯出欄位,產生作為匯出 Excel 的 DataTable.
            var dt = ExportDataHelper.GetExportDataTable(result, selectedColumns);

            //決定匯出 Excel 檔案的檔名
            var exportFileName = string.IsNullOrWhiteSpace(fileName)
                ? string.Concat(
                "CustomerData_",
                DateTime.Now.ToString("yyyyMMddHHmmss"),
                ".xlsx")
                : string.Concat(fileName, ".xlsx");

            return(new ExportExcelResult
            {
                SheetName = "客戶資料",
                FileName = exportFileName,
                ExportData = dt
            });
        }
コード例 #2
0
        public ActionResult Export(string fileName, string selectedColumns)
        {
            //取得原始資料
            var exportData = db.Products.OrderBy(x => x.ProductID).ToList();

            //使用 AutoMapper 建立斷映轉換設定
            Mapper.CreateMap <Product, ProductViewModel>()
            .ForMember(d => d.SupplierName, o => o.MapFrom(s => s.Supplier.CompanyName))
            .ForMember(d => d.CategoryName, o => o.MapFrom(s => s.Category.CategoryName))
            .ForMember(d => d.Discontinued, o => o.MapFrom(s => s.Discontinued ? "已停止" : "--"));

            //使用 AutoMapper 將 Product 型別的原始資料對映轉換為 ProductViewModel 型別.
            var result = Mapper.Map <List <ProductViewModel> >(exportData);

            //使用轉換後的匯出資料與使用者所選的匯出欄位,產生作為匯出 Excel 的 DataTable.
            var dt = ExportDataHelper.GetExportDataTable(result, selectedColumns);

            //決定匯出 Excel 檔案的檔名
            var exportFileName = string.IsNullOrWhiteSpace(fileName)
                ? string.Concat(
                "ProductData_",
                DateTime.Now.ToString("yyyyMMddHHmmss"),
                ".xlsx")
                : string.Concat(fileName, ".xlsx");

            return(new ExportExcelResult
            {
                SheetName = "產品資料",
                FileName = exportFileName,
                ExportData = dt
            });
        }
コード例 #3
0
        public void GetAllDataGroup()
        {
            GetAllDataGroupResponse response = _groupService.GetAllDataGroup();

            ExportDataHelper.ExportToExcel <Group>("Test.xlsx", "Sheet1", response.GroupList);
            Assert.IsTrue(response.Messages.Count == 0, "Failed get all data");
        }
コード例 #4
0
        public void ExportDataToExcel_Valid( )
        {
            var            table      = CreateSampleData( );
            ExportDataInfo exportInfo = ExportDataHelper.ExportToExcelDocument(table);

            byte[] byteStrem = exportInfo.FileStream;
            string path      = CreateExportDirectory( );
            string filePath  = Path.Combine(path, "Test.xlsx");

            var file = new FileStream(filePath, FileMode.Create);

            file.Write(byteStrem, 0, byteStrem.Length);
            file.Close( );
        }
コード例 #5
0
        //取出屬性名稱對照的中文
        public Dictionary <string, string> EntityPropertyName()
        {
            Type t = typeof(TEntity);

            Dictionary <string, string> listTableName = new Dictionary <string, string>();

            foreach (var pro in t.GetProperties())
            {
                var proKeyName = ExportDataHelper.CustomerExportColumns()
                                 .FirstOrDefault(p => p.Key == pro.Name);
                listTableName.Add(proKeyName.Key, proKeyName.Value);
            }


            return(listTableName);
        }
コード例 #6
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");
            }
        }
コード例 #7
0
        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);
                    }
                }
            }
        }
コード例 #8
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);
        }
コード例 #9
0
        private void btnOK_Click(object sender, EventArgs e)
        {
            IName            internalObjectName;
            IFields          fields2;
            IEnumFieldError  error;
            string           fileNameWithoutExtension;
            string           str4;
            string           name;
            IField           field;
            int              num;
            IGeometryDefEdit geometryDef;
            Exception        exception;
            IFeatureDataset  dataset;

            if (this.txtOutName.Tag == null)
            {
                IGxFolder folder = new GxFolder();
                (folder as IGxFile).Path = Path.GetDirectoryName(this.txtOutName.Text);
                this.txtOutName.Tag      = folder;
            }
            if (this.txtOutName.Tag == null)
            {
                return;
            }
            IGxObject tag = this.txtOutName.Tag as IGxObject;

            if (tag is IGxFolder)
            {
                IWorkspaceName name2 = new WorkspaceName() as IWorkspaceName;


                name2.WorkspaceFactoryProgID = "esriDataSourcesFile.ShapefileWorkspaceFactory";
                name2.PathName = (tag.InternalObjectName as IFileName).Path;

                internalObjectName = name2 as IName;
                string text = this.txtOutName.Text;
                if (Path.GetExtension(this.txtOutName.Text) != ".shp")
                {
                    text = Path.GetFileNameWithoutExtension(this.txtOutName.Text) + ".shp";
                }
                if (File.Exists(text))
                {
                    MessageBox.Show("已经存在该shapefile文件,请重新输入文件名");
                    return;
                }
            }
            else
            {
                internalObjectName = tag.InternalObjectName;
            }
            IFields       inputField = this.m_pFeatureLayer.FeatureClass.Fields;
            IFieldChecker checker    = new FieldChecker();
            IFeatureClass class2     = null;

            if (internalObjectName is IWorkspaceName)
            {
                IFeatureWorkspace workspace = internalObjectName.Open() as IFeatureWorkspace;
                checker.ValidateWorkspace = workspace as IWorkspace;
                checker.Validate(inputField, out error, out fields2);
                fileNameWithoutExtension = Path.GetFileNameWithoutExtension(this.txtOutName.Text);
                checker.ValidateTableName(fileNameWithoutExtension, out str4);
                fileNameWithoutExtension = str4;
                ISpatialReference spatialReference = (this.m_pFeatureLayer.FeatureClass as IGeoDataset).SpatialReference;
                if (this.rdoSRType.SelectedIndex == 0)
                {
                    spatialReference = this.m_pMap.SpatialReference;
                }
                name = "";
                for (num = 0; num < fields2.FieldCount; num++)
                {
                    field = fields2.get_Field(num);
                    if (field.Type == esriFieldType.esriFieldTypeGeometry)
                    {
                        geometryDef = (field as IFieldEdit).GeometryDef as IGeometryDefEdit;
                        geometryDef.SpatialReference_2      = spatialReference;
                        (field as IFieldEdit).GeometryDef_2 = geometryDef;
                        name = field.Name;
                        break;
                    }
                }
                try
                {
                    if ((workspace is IWorkspace2) &&
                        (workspace as IWorkspace2).get_NameExists(esriDatasetType.esriDTFeatureClass,
                                                                  fileNameWithoutExtension))
                    {
                        MessageBox.Show("已经存在该要素类,请重新输入要素类名");
                        return;
                    }
                    class2 = workspace.CreateFeatureClass(fileNameWithoutExtension, fields2, null, null,
                                                          esriFeatureType.esriFTSimple, name, "");
                }
                catch (Exception exception1)
                {
                    exception = exception1;
                    MessageBox.Show("无法创建输出要素类!");
                    return;
                }
                goto Label_0400;
            }
            else
            {
                dataset = internalObjectName.Open() as IFeatureDataset;
                IWorkspace workspace2 = dataset.Workspace;
                checker.ValidateWorkspace = workspace2;
                checker.Validate(inputField, out error, out fields2);
                fileNameWithoutExtension = Path.GetFileNameWithoutExtension(this.txtOutName.Text);
                checker.ValidateTableName(fileNameWithoutExtension, out str4);
                fileNameWithoutExtension = str4;
                name = "";
                for (num = 0; num < fields2.FieldCount; num++)
                {
                    field = fields2.get_Field(num);
                    if (field.Type == esriFieldType.esriFieldTypeGeometry)
                    {
                        geometryDef = (field as IFieldEdit).GeometryDef as IGeometryDefEdit;
                        geometryDef.SpatialReference_2      = (dataset as IGeoDataset).SpatialReference;
                        (field as IFieldEdit).GeometryDef_2 = geometryDef;
                        name = field.Name;
                        break;
                    }
                }
            }
            try
            {
                class2 = dataset.CreateFeatureClass(fileNameWithoutExtension, fields2, null, null,
                                                    esriFeatureType.esriFTSimple, name, "");
            }
            catch (Exception exception2)
            {
                exception = exception2;
                MessageBox.Show("无法创建输出要素类!,原因:" + exception.Message);

                return;
            }
Label_0400:
            if (this.cboExportData.SelectedIndex == 0)
            {
                ExportDataHelper.ExportData(this.m_pFeatureLayer, class2, false);
            }
            else if (this.cboExportData.SelectedIndex == 1)
            {
                ISpatialFilter queryFilter = new SpatialFilter()
                {
                    Geometry = (this.m_pMap as IActiveView).Extent
                };
                IFeatureCursor cursor = this.m_pFeatureLayer.Search(queryFilter, false);
                ExportDataHelper.ExportData(cursor, class2);
                ComReleaser.ReleaseCOMObject(cursor);
            }
            else
            {
                ExportDataHelper.ExportData(this.m_pFeatureLayer, class2, true);
            }
            base.DialogResult = DialogResult.OK;
        }