public async void GetAll_WhenNotFound()
        {
            // arrange
            var errorCodeConverter = new ErrorCodeConverter();

            var skuServiceMoq = new Mock<ISkuService>();
            skuServiceMoq.Setup(x => x.GetAll())
                .ReturnsAsync(() => new Result<IEnumerable<Sku>>(ResultCode.NotFound));

            var dataStructureConverterMoq = new Mock<IDataStructureConverter>();
            dataStructureConverterMoq.Setup(x => x.Convert(It.IsAny<string>(), It.IsAny<object>()))
                .Returns(new Dictionary<string, object>
                        {
                            { "skus", SkuHelper.GetMany() }
                        });

            var sut = new SkusController(skuServiceMoq.Object, errorCodeConverter, dataStructureConverterMoq.Object)
            {
                ControllerContext = DefaultControllerContext()
            };

            // act
            var result = await sut.GetAll();
            var notFoundResult = result as NotFoundResult;

            // assert
            Assert.NotNull(notFoundResult);
        }
        public async void GetAll_WhenFound()
        {
            // arrange
            var errorCodeConverter = new ErrorCodeConverter();

            var skuServiceMoq = new Mock<ISkuService>();
            skuServiceMoq.Setup(x => x.GetAll())
                .ReturnsAsync(() => new Result<IEnumerable<Sku>>(ResultCode.Success, TestSkus()));

            var dataStructureConverterMoq = new Mock<IDataStructureConverter>();
            dataStructureConverterMoq.Setup(x => x.Convert(It.IsAny<string>(), It.IsAny<object>()))
                .Returns(new Dictionary<string, object>
                        {
                            { "skus", SkuHelper.GetMany() }
                        });

            var sut = new SkusController(skuServiceMoq.Object, errorCodeConverter, dataStructureConverterMoq.Object)
            {
                ControllerContext = DefaultControllerContext()
            };

            // act
            var result = await sut.GetAll();
            var okResult = result as OkObjectResult;
            var response = okResult.Value as Dictionary<string, object>;

            // assert
            Assert.Equal(200, okResult.StatusCode);
        }
Beispiel #3
0
        public void Case3()
        {
            var items = new List <char>
            {
                'A', 'A', 'A', 'B', 'B', 'B', 'B', 'B', 'C', 'D'
            };
            var cart = new Cart()
            {
                Items = SkuHelper.GetSkuList(items)
            };
            int actualOrderValue = handler.Handle(ref cart);

            Assert.AreEqual(280, actualOrderValue);
        }
Beispiel #4
0
        public ProductDisplay PutProductWithResetSkus(Guid productKey)
        {
            var merchProduct = _productService.GetByKey(productKey);

            if (!merchProduct.ProductVariants.Any())
            {
                return(merchProduct.ToProductDisplay(DetachedValuesConversionType.Editor));
            }

            foreach (var variant in merchProduct.ProductVariants)
            {
                variant.Sku = SkuHelper.GenerateSkuForVariant(merchProduct, variant);
            }

            _productService.Save(merchProduct);

            return(merchProduct.ToProductDisplay(DetachedValuesConversionType.Editor));
        }
 private IEnumerable<Sku> TestSkus()
 {
     return SkuHelper.GetMany();
 }
 private Sku TestSku()
 {
     return SkuHelper.Get();
 }
        public static IList <ItemVariationExportViewModel> CreateStyleVariations(IUnitOfWork db,
                                                                                 string styleString,
                                                                                 IList <ItemSizeMapping> existSizeMapping,
                                                                                 MarketType market,
                                                                                 string marketplaceId)
        {
            var results = new List <ItemVariationExportViewModel>();

            var style = db.Styles.GetActiveByStyleIdAsDto(styleString);

            if (style == null)
            {
                return(results);
            }

            var styleMainLicenseDto = db.StyleFeatureValues.GetFeatureValueByStyleIdByFeatureId(style.Id,
                                                                                                StyleFeatureHelper.MAIN_LICENSE);
            var styleSubLicenseDto = db.StyleFeatureValues.GetFeatureValueByStyleIdByFeatureId(style.Id,
                                                                                               StyleFeatureHelper.SUB_LICENSE1);
            var styleMainLicense = styleMainLicenseDto != null ? styleMainLicenseDto.Value : null;
            var styleSubLicense  = styleSubLicenseDto != null ? styleSubLicenseDto.Value : null;

            var styleItems = db.StyleItems
                             .GetByStyleIdWithBarcodesAsDto(style.Id)
                             .OrderBy(o => SizeHelper.GetSizeIndex(o.Size))
                             .ToList();

            var forceReplace = styleItems.Any(s => (s.Size ?? "").Contains("/"));

            foreach (var styleItem in styleItems)
            {
                var newItem = new ItemVariationExportViewModel();

                var index   = 0;
                var baseSKU = style.StyleID + "-" + SizeHelper.PrepareSizeForSKU(styleItem.Size, forceReplace);

                while (db.Listings.CheckForExistenceSKU(SkuHelper.SetSKUMiddleIndex(baseSKU, index),
                                                        (MarketType)market,
                                                        marketplaceId))
                {
                    index++;
                }

                newItem.IsSelected  = true;
                newItem.SKU         = SkuHelper.SetSKUMiddleIndex(baseSKU, index);
                newItem.StyleId     = styleItem.StyleId;
                newItem.StyleString = style.StyleID;
                newItem.StyleItemId = styleItem.StyleItemId;
                newItem.StyleColor  = styleItem.Color;
                newItem.StyleSize   = styleItem.Size;

                newItem.BrandName = ItemExportHelper.GetBrandName(styleMainLicense, styleSubLicense);
                newItem.Size      = SizeHelper.PrepareSizeForExport(db, newItem.StyleSize, existSizeMapping);

                if (styleItem.Barcodes != null)
                {
                    foreach (var barcode in styleItem.Barcodes)
                    {
                        if (!String.IsNullOrEmpty(barcode.Barcode) &&
                            !db.Items.CheckForExistenceBarcode(barcode.Barcode, market, marketplaceId))
                        {
                            newItem.Barcode = barcode.Barcode;
                            break;
                        }
                    }
                }
                if (String.IsNullOrEmpty(newItem.Barcode))
                {
                    newItem.AutoGeneratedBarcode = true;
                }

                results.Add(newItem);
            }

            return(results);
        }
        public void ProcessNewListingsWithItems(IUnitOfWork db, IMarketApi api, ITime time, IList <ItemDTO> items)
        {
            _log.Debug("Begin process new items");

            foreach (var dtoItem in items)
            {
                try
                {
                    if (dtoItem.IsExistOnAmazon == true)
                    {
                        _syncInfo.AddSuccess(dtoItem.ASIN, "New listing item was filled by Amazon");

                        if (String.IsNullOrEmpty(dtoItem.ParentASIN))
                        {
                            _syncInfo.AddWarning(dtoItem.ASIN, "Empty ParentASIN");
                        }

                        dtoItem.IsAmazonParentASIN   = !String.IsNullOrEmpty(dtoItem.ParentASIN);
                        dtoItem.LastUpdateFromAmazon = time.GetUtcTime();
                        //Add new item, no need to additional check
                        dtoItem.StyleString = SkuHelper.RetrieveStyleIdFromSKU(db,
                                                                               dtoItem.SKU,
                                                                               dtoItem.Name);


                        var dbItem = db.Items.StoreItemIfNotExist(_itemHistoryService,
                                                                  "ListingLineProcessing",
                                                                  dtoItem,
                                                                  api.Market,
                                                                  api.MarketplaceId,
                                                                  _companyId,
                                                                  time.GetAppNowTime());

                        //NOTE: fresh size (for some reason can start came emtpy)
                        dtoItem.Size = dbItem.Size;

                        if (!dbItem.StyleItemId.HasValue)
                        {
                            //Keep exists styleId
                            dtoItem.StyleId = dbItem.StyleId;

                            var styleItem = FindOrCreateStyleItem(db, dtoItem);
                            if (styleItem != null)
                            {
                                if (styleItem.StyleItemId > 0)
                                {
                                    dbItem.StyleId     = styleItem.StyleId;
                                    dbItem.StyleItemId = styleItem.StyleItemId;
                                }
                                else
                                {
                                    if (!dbItem.StyleId.HasValue)
                                    {
                                        dbItem.StyleId = styleItem.StyleId;
                                    }
                                }
                                _log.Debug(String.Format("Set for ASIN={0}, styleId={1}, styleItemId={2}",
                                                         dtoItem.ASIN,
                                                         styleItem.StyleId,
                                                         styleItem.StyleItemId));
                            }
                            db.Commit();
                        }

                        if (!String.IsNullOrEmpty(dtoItem.Barcode) &&
                            dbItem.StyleItemId.HasValue)
                        {
                            _styleManager.StoreOrUpdateBarcode(db,
                                                               dbItem.StyleItemId.Value,
                                                               dtoItem.Barcode);
                        }

                        var dbListing = db.Listings.StoreOrUpdate(dtoItem,
                                                                  dbItem,
                                                                  api.Market,
                                                                  api.MarketplaceId,
                                                                  time.GetAppNowTime());

                        dtoItem.IsDefault = dbListing.IsDefault;

                        _syncInfo.AddSuccess(dtoItem.ASIN, "New listing item was stored");
                        _log.Debug("Store item:" + dbItem.ASIN + ", parentASIN=" + dbItem.ParentASIN + ", SKU=" + dtoItem.SKU + ", StyleString=" + dbItem.StyleString + ", quantity=" + dtoItem.RealQuantity);
                    }
                    else
                    {
                        _syncInfo.AddWarning(dtoItem.ASIN, "Item is not filled by Amazon (new listing item)");
                        _log.Warn("Item is not filled by Amazon (new listing item), item=" + dtoItem.ASIN);
                    }
                }
                catch (Exception ex)
                {
                    _syncInfo.AddError(dtoItem.ASIN, "Error while creating item", ex);
                    _log.Error(string.Format("Error while creating item, asin={0}", dtoItem.ASIN), ex);
                }
            }
            _log.Debug("End process new items");
        }
        private void SetItemFieldsIfExistOnAmazon(IUnitOfWork db, ItemDTO dtoItem, Item dbItem)
        {
            //NOTE: Skip any ParentASIN updates
            //NOTE: updates for childs only when we change ParentItem objects
            //NOTE: to keep source relationships
            //if (!String.IsNullOrEmpty(dtoItem.ParentASIN))
            //{
            //    dbItem.ParentASIN = dtoItem.ParentASIN;
            //}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

            if (!String.IsNullOrEmpty(dtoItem.Barcode) &&
                dbItem.StyleItemId.HasValue)
            {
                _styleManager.StoreOrUpdateBarcode(db,
                                                   dbItem.StyleItemId.Value,
                                                   dtoItem.Barcode);
            }
        }
Beispiel #10
0
        public void ReadItemsInfo(SupplieroasisApi api)
        {
            _log.Info("Begin ReadItemsInfo");
            var itemsWithError = new List <string>();
            var items          = api.GetItems(_log,
                                              _time,
                                              null,
                                              ItemFillMode.Defualt,
                                              out itemsWithError);

            using (var db = _dbFactory.GetRWDb())
            {
                _log.Info("Total items=" + items.Count());
                //Create
                var allItems = db.Items.GetAllViewAsDto().Where(m => m.Market == (int)api.Market &&
                                                                (m.MarketplaceId == api.MarketplaceId ||
                                                                 String.IsNullOrEmpty(api.MarketplaceId))).ToList();
                foreach (var item in items)
                {
                    foreach (var variation in item.Variations)
                    {
                        var existItem = allItems.FirstOrDefault(i => StringHelper.IsEqualNoCase(i.SKU, variation.SKU));

                        if (existItem == null)
                        {
                            _log.Info("Add new item, MarketItemId=" + variation.SourceMarketId);

                            var exampleItem = db.Items.GetAllViewAsDto().FirstOrDefault(i => i.Market == (int)MarketType.Amazon &&
                                                                                        i.MarketplaceId == MarketplaceKeeper.AmazonComMarketplaceId &&
                                                                                        i.SKU == variation.SKU);
                            if (exampleItem == null)
                            {
                                exampleItem = db.Items.GetAllViewAsDto().OrderByDescending(i => i.CreateDate).FirstOrDefault(i => i.SKU == variation.SKU);
                            }

                            var styleString = SkuHelper.RetrieveStyleIdFromSKU(db, variation.SKU, null);
                            if (String.IsNullOrEmpty(styleString))
                            {
                                styleString = variation.SKU;
                            }

                            if (String.IsNullOrEmpty(styleString))
                            {
                                _log.Info("StyleString is empty for: " + variation.SKU + ", itemSKU=" + item.SKU);
                                continue;
                            }

                            var parentItem = db.ParentItems.GetAll().FirstOrDefault(pi => pi.ASIN == styleString &&
                                                                                    pi.Market == (int)MarketType.OverStock);
                            if (parentItem == null)
                            {
                                parentItem = new ParentItem()
                                {
                                    ASIN           = styleString,
                                    SourceMarketId = styleString,
                                    Market         = item.Market,
                                    MarketplaceId  = item.MarketplaceId,

                                    CreateDate = _time.GetAmazonNowTime()
                                };

                                db.ParentItems.Add(parentItem);
                                db.Commit();
                            }

                            if (exampleItem == null)
                            {
                                exampleItem = new DTO.ItemDTO();
                                var style = db.Styles.GetAll().FirstOrDefault(st => st.StyleID == styleString);
                                if (style != null)
                                {
                                    exampleItem.StyleId = style.Id;
                                }
                                var size = SkuHelper.RetrieveSizeFromSKU(variation.SKU);

                                if (style != null)
                                {
                                    var styleItem = db.StyleItems.GetAll().FirstOrDefault(si => si.StyleId == style.Id &&
                                                                                          si.Size == size);
                                    if (styleItem != null)
                                    {
                                        exampleItem.StyleItemId = styleItem.Id;
                                    }
                                }
                            }

                            var newItem = new Item()
                            {
                                ASIN          = item.ASIN,
                                ParentASIN    = parentItem.ASIN,
                                Market        = item.Market,
                                MarketplaceId = item.MarketplaceId,

                                Barcode = variation.Barcode,

                                SourceMarketId      = item.SourceMarketId,
                                ItemPublishedStatus = variation.PublishedStatus,

                                StyleId     = exampleItem?.StyleId,
                                StyleItemId = exampleItem?.StyleItemId,

                                CreateDate = _time.GetAmazonNowTime()
                            };
                            db.Items.Add(newItem);
                            db.Commit();

                            var newListing = new Listing()
                            {
                                ItemId        = newItem.Id,
                                SKU           = variation.SKU,
                                ListingId     = variation.SKU,
                                Market        = variation.Market,
                                MarketplaceId = variation.MarketplaceId,

                                CreateDate         = _time.GetAmazonNowTime(),
                                AmazonRealQuantity = variation.AmazonRealQuantity,
                            };
                            db.Listings.Add(newListing);
                            db.Commit();
                        }
                    }
                }


                //Update
                var updatedItemIds = new List <long>();
                foreach (var item in items)
                {
                    foreach (var variation in item.Variations)
                    {
                        _log.Info("Read info for SKU=" + variation.SKU);
                        var dbListing = db.Listings.GetAll().FirstOrDefault(m => m.Market == (int)api.Market &&
                                                                            (m.MarketplaceId == api.MarketplaceId ||
                                                                             String.IsNullOrEmpty(api.MarketplaceId)) &&
                                                                            m.SKU == variation.SKU);
                        if (dbListing == null)
                        {
                            _log.Info("Unable to find item for, SKU=" + variation.SKU);
                            continue;
                        }

                        var dbItem = db.Items.GetAll().FirstOrDefault(i => i.Id == dbListing.ItemId);
                        if (dbItem == null)
                        {
                            _log.Info("Unable to find item for itemId=" + dbListing.ItemId);
                            continue;
                        }

                        updatedItemIds.Add(dbItem.Id);

                        if (dbItem.ItemPublishedStatus != variation.PublishedStatus)
                        {
                            dbItem.ItemPublishedStatus       = variation.PublishedStatus;
                            dbItem.ItemPublishedStatusDate   = _time.GetAppNowTime();
                            dbItem.ItemPublishedStatusReason = "Derived from market";
                        }

                        dbItem.Barcode = variation.Barcode;

                        //dbListing.AmazonCurrentPrice = variation.AmazonCurrentPrice;
                        //dbListing.AmazonCurrentPriceUpdateDate = _time.GetAppNowTime();

                        dbListing.AmazonRealQuantity           = variation.AmazonRealQuantity;
                        dbListing.AmazonRealQuantityUpdateDate = _time.GetAppNowTime();
                    }
                }
                db.Commit();

                //Remove not exists
                var toRemoveItems = db.Items.GetAll().Where(i => i.Market == (int)api.Market &&
                                                            (i.MarketplaceId == api.MarketplaceId ||
                                                             String.IsNullOrEmpty(api.MarketplaceId)) &&
                                                            !updatedItemIds.Contains(i.Id) &&
                                                            i.ItemPublishedStatus == (int)PublishedStatuses.Published);
                _log.Info("Items to unpublish, count=" + toRemoveItems.Count());
                foreach (var toRemoveItem in toRemoveItems)
                {
                    toRemoveItem.ItemPublishedStatusBeforeRepublishing = toRemoveItem.ItemPublishedStatus;
                    toRemoveItem.ItemPublishedStatus     = (int)PublishedStatuses.Unpublished;
                    toRemoveItem.ItemPublishedStatusDate = _time.GetUtcTime();
                }
                db.Commit();
            }
            _log.Info("End ReadItemsInfo");
        }
Beispiel #11
0
        public void ExportSetupByMatch()
        {
            using (var db = _dbFactory.GetRWDb())
            {
                var allAmazonItems = db.Items.GetAllViewActual()
                                     .Where(i => i.Market == (int)MarketType.Amazon &&
                                            i.MarketplaceId == MarketplaceKeeper.AmazonComMarketplaceId)
                                     .Select(i => new ItemDTO()
                {
                    SKU          = i.SKU,
                    Barcode      = i.Barcode,
                    CurrentPrice = i.CurrentPrice,
                    StyleId      = i.StyleId,
                })
                                     .ToList();

                var allWalmartItems = db.Items.GetAllViewActual()
                                      .Where(i => i.Market == (int)MarketType.Walmart)
                                      .Select(i => new ItemDTO()
                {
                    SKU     = i.SKU,
                    Barcode = i.Barcode
                })
                                      .ToList();

                var results = new List <SetupByMatchProduct>(allAmazonItems.Count);
                foreach (var amzItem in allAmazonItems)
                {
                    var genderValue = amzItem.StyleId.HasValue
                           ? db.StyleFeatureValues.GetFeatureValueByStyleIdByFeatureId(amzItem.StyleId.Value, StyleFeatureHelper.GENDER)?.Value
                           : null;

                    if (allWalmartItems.All(i => i.Barcode != amzItem.Barcode))
                    {
                        var sku   = amzItem.SKU;
                        var index = 0;
                        while (allWalmartItems.Any(i => i.SKU == sku))
                        {
                            sku = SkuHelper.SetSKUMiddleIndex(sku, index);
                            index++;
                        }
                        results.Add(new SetupByMatchProduct()
                        {
                            ProductIdType1 = "UPC",
                            ProductId1     = amzItem.Barcode,

                            ProductTaxCode = WalmartUtils.GetProductTaxCode(genderValue, null)?.ToString(),

                            SKU      = sku,
                            Currency = "USD",
                            Price    = amzItem.CurrentPrice,

                            Weight     = PriceHelper.RoundToTwoPrecision((decimal)((amzItem.Weight == null || amzItem.Weight == 0) ? 5 : amzItem.Weight.Value) / (decimal)16),
                            WeightUnit = "lb",

                            Category    = "Clothing",
                            SubCategory = "Clothing"
                        });
                    }
                }

                var b       = new ExportColumnBuilder <SetupByMatchProduct>();
                var columns = new List <ExcelColumnInfo>()
                {
                    b.Build(p => p.ProductIdType1, "Product Identifier-Product Id Type (#1) *", 15),
                    b.Build(p => p.ProductId1, "Product Identifier-Product Id (#1) *", 15),
                    b.Build(p => p.ProductTaxCode, "Product Tax Code *", 15),
                    b.Build(p => p.ProductIdType2, "Additional Product Attribute-Product Attribute Name (#1) (Optional)", 15),
                    b.Build(p => p.ProductId2, "Additional Product Attribute-Product Attribute Value (#1) (Optional)", 15),
                    b.Build(p => p.SKU, "Sku *", 15),
                    b.Build(p => p.ASIN, "ASIN (Optional)", 15),
                    b.Build(p => p.Currency, "Price-Currency *", 15),
                    b.Build(p => p.Price, "Price-Amount *", 15),
                    b.Build(p => p.Weight, "Shipping Weight-Value *", 15),
                    b.Build(p => p.WeightUnit, "Shipping Weight-Unit *", 15),
                    b.Build(p => p.Category, "Category *", 15),
                    b.Build(p => p.SubCategory, "Sub-category *", 15),
                };

                var outputFilepath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "WMSetupByMatch-" + DateTime.Now.ToString("yyyyddMMHHmmss") + ".xls");
                using (var stream = ExcelHelper.Export(results,
                                                       columns,
                                                       null))
                {
                    stream.Seek(0, SeekOrigin.Begin);
                    using (var fileStream = File.Create(outputFilepath))
                    {
                        stream.CopyTo(fileStream);
                    }
                }
            }
        }
        public void CreateListings()
        {
            var now = _time.GetAppNowTime();

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

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

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

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

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

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

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

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

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

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

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

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

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

                        var newSKU = SkuHelper.AddPrimePostFix(dbListingToCopy.SKU);
                        var price  = salePrice ?? dbListingToCopy.CurrentPrice;
                        dbListingToCopy.ItemId                       = dbItemToCopy.Id;
                        dbListingToCopy.Id                           = 0;
                        dbListingToCopy.ListingId                    = newSKU;
                        dbListingToCopy.IsPrime                      = true;
                        dbListingToCopy.CurrentPrice                 = PriceHelper.RoundToFloor99(isOversizeTemplate ? (price + 9.49M) : (price + 7.49M));
                        dbListingToCopy.ListingPriceFromMarket       = null;
                        dbListingToCopy.AmazonCurrentPrice           = null;
                        dbListingToCopy.AmazonCurrentPriceUpdateDate = null;
                        dbListingToCopy.AmazonRealQuantity           = null;
                        dbListingToCopy.AmazonRealQuantityUpdateDate = null;
                        dbListingToCopy.PriceFromMarketUpdatedDate   = null;
                        dbListingToCopy.SKU                          = newSKU;
                        dbListingToCopy.OpenDate                     = _time.GetAppNowTime();
                        dbListingToCopy.CreateDate                   = _time.GetAppNowTime();
                        dbListingToCopy.UpdateDate                   = _time.GetAppNowTime();
                        dbListingToCopy.CreatedBy                    = null;
                        dbListingToCopy.UpdatedBy                    = null;
                        db.Listings.Add(dbListingToCopy);
                        db.Commit();
                        _log.Info("Copyied to SKU=" + dbListingToCopy.SKU + ", newPrice=" + dbListingToCopy.CurrentPrice);
                    }
                }
            }
        }
Beispiel #13
0
        public static void CopyToMarketplaces(IUnitOfWork db,
                                              ICacheService cache,
                                              IBarcodeService barcodeService,
                                              ISystemActionService actionService,
                                              IAutoCreateListingService autoCreateListingService,
                                              IItemHistoryService itemHistoryService,
                                              int id,
                                              DateTime when,
                                              long?by,
                                              IList <ItemMarketViewModel> toMarketplaces,
                                              out IList <MessageString> messages)
        {
            var parent = db.ParentItems.GetAsDTO(id);

            messages = new List <MessageString>();

            foreach (var toMarketplace in toMarketplaces)
            {
                var model = ItemEditViewModel.CreateFromParentASIN(db,
                                                                   autoCreateListingService,
                                                                   parent.ASIN,
                                                                   parent.Market,
                                                                   parent.MarketplaceId,
                                                                   false, //NOTE: false - ex.: exclude to copy FBP to Walmart
                                                                   out messages);

                model.Id            = null;
                model.Market        = toMarketplace.Market;
                model.MarketplaceId = toMarketplace.MarketplaceId;
                //model.OnHold = true;

                var parentBaseASIN = SkuHelper.RemoveSKULastIndex(model.ASIN);
                var parentIndex    = 0;
                while (db.ParentItems.GetAsDTO(parentBaseASIN + ((parentIndex == 0) ? "" : "-" + parentIndex), (MarketType)toMarketplace.Market, toMarketplace.MarketplaceId) != null)
                {
                    parentIndex++;
                }
                var parentSKU = parentBaseASIN + ((parentIndex == 0) ? "" : "-" + parentIndex);

                var forceReplace = model.VariationList.Any(s => (s.Size ?? "").Contains("/"));

                model.ASIN = parentSKU;

                foreach (var item in model.VariationList)
                {
                    item.Id = null;

                    if (model.Market == (int)MarketType.Walmart ||
                        model.Market == (int)MarketType.WalmartCA)
                    {
                        item.Barcode = null;
                        item.AutoGeneratedBarcode = true;
                    }

                    if (item.StyleItemId.HasValue)
                    {
                        var sourceUSDPrice = item.Price;
                        var fromCurrency   = PriceHelper.GetCurrencyAbbr((MarketType)parent.Market, parent.MarketplaceId);
                        if (fromCurrency != PriceHelper.USDSymbol)
                        {
                            sourceUSDPrice = PriceHelper.ConvertToUSD(item.Price, fromCurrency);
                        }

                        var rateForMarketplace = RateHelper.GetRatesByStyleItemId(db, item.StyleItemId.Value);
                        var newPrice           = RateHelper.CalculateForMarket((MarketType)toMarketplace.Market,
                                                                               toMarketplace.MarketplaceId,

                                                                               sourceUSDPrice,
                                                                               rateForMarketplace[MarketplaceKeeper.AmazonComMarketplaceId],
                                                                               rateForMarketplace[MarketplaceKeeper.AmazonCaMarketplaceId],
                                                                               rateForMarketplace[MarketplaceKeeper.AmazonUkMarketplaceId],
                                                                               rateForMarketplace[MarketplaceKeeper.AmazonAuMarketplaceId],
                                                                               RateService.GetMarketShippingAmount(MarketType.Amazon, MarketplaceKeeper.AmazonComMarketplaceId),
                                                                               RateService.GetMarketShippingAmount((MarketType)toMarketplace.Market, toMarketplace.MarketplaceId),
                                                                               RateService.GetMarketExtraAmount((MarketType)toMarketplace.Market, toMarketplace.MarketplaceId));

                        if (newPrice.HasValue)
                        {
                            item.Price = newPrice.Value;
                        }
                    }

                    if (db.Listings.CheckForExistenceSKU(item.SKU,
                                                         (MarketType)toMarketplace.Market,
                                                         toMarketplace.MarketplaceId))
                    {
                        var baseSKU = item.StyleString + "-" + SizeHelper.PrepareSizeForSKU(item.StyleSize, forceReplace);
                        var index   = parentIndex;

                        while (db.Listings.CheckForExistenceSKU(SkuHelper.SetSKUMiddleIndex(baseSKU, index),
                                                                (MarketType)toMarketplace.Market,
                                                                toMarketplace.MarketplaceId))
                        {
                            index++;
                        }

                        item.SKU = SkuHelper.SetSKUMiddleIndex(baseSKU, index);
                    }
                }

                model.Save(db,
                           cache,
                           barcodeService,
                           actionService,
                           itemHistoryService,
                           when,
                           by);
            }
        }
Beispiel #14
0
        //public static void UpdateSalePrices(IUnitOfWork db,
        //    long styleItemId,
        //    long saleId,
        //    decimal newSalePrice,
        //    decimal? newSFPSalePrice)
        //{
        //    var rateForMarketplace = RateHelper.GetRatesByStyleItemId(db, styleItemId);

        //    var marketPrices = db.StyleItemSaleToMarkets.GetAll().Where(s => s.SaleId == saleId).ToList();
        //    foreach (var marketPrice in marketPrices)
        //    {
        //        if (marketPrice.SalePrice.HasValue)
        //        {
        //            var marketListings = db.StyleItemSaleToListings.GetAll().Where(l => l.SaleToMarketId == )

        //            marketPrice.SalePrice = RateHelper.CalculateForMarket((MarketType) marketPrice.Market,
        //                marketPrice.MarketplaceId,
        //                newSalePrice,
        //                rateForMarketplace[MarketplaceKeeper.AmazonComMarketplaceId],
        //                rateForMarketplace[MarketplaceKeeper.AmazonCaMarketplaceId],
        //                rateForMarketplace[MarketplaceKeeper.AmazonUkMarketplaceId],
        //                rateForMarketplace[MarketplaceKeeper.AmazonAuMarketplaceId],
        //                RateService.GetMarketShippingAmount(MarketType.Amazon, MarketplaceKeeper.AmazonComMarketplaceId),
        //                RateService.GetMarketShippingAmount((MarketType)marketPrice.Market, marketPrice.MarketplaceId),
        //                RateService.GetMarketExtraAmount((MarketType)marketPrice.Market, marketPrice.MarketplaceId));


        //        }
        //    }

        //    db.Commit();
        //}

        public static IList <MarketPriceEditViewModel> GetForStyleItemId(IUnitOfWork db,
                                                                         IDbFactory dbFactory,
                                                                         long styleItemId,
                                                                         decimal?initSalePrice,
                                                                         decimal?initSFPSalePrice)
        {
            var priceService = new PriceService(dbFactory);

            var results         = new List <MarketPriceEditViewModel>();
            var allMarketplaces = UIMarketHelper.GetSalesMarketplaces();
            var allListings     = db.Listings.GetListingsAsListingDto()
                                  .Where(l => l.StyleItemId == styleItemId)
                                  .ToList()
                                  .Where(l => !l.IsFBA)
                                  .ToList();

            var rateForMarketplace = RateHelper.GetRatesByStyleItemId(db, styleItemId);

            var sale            = db.StyleItemSales.GetAllAsDto().FirstOrDefault(s => s.StyleItemId == styleItemId && !s.IsDeleted);
            var checkedListings = new List <StyleItemSaleToListingDTO>();

            if (sale != null)
            {
                checkedListings = db.StyleItemSaleToListings.GetAllAsDto().Where(s => s.SaleId == sale.Id).ToList();
            }

            var checkedMarkets = new List <StyleItemSaleToMarketDTO>();

            if (sale != null)
            {
                checkedMarkets = db.StyleItemSaleToMarkets.GetAllAsDto().Where(s => s.SaleId == sale.Id).ToList();
            }

            foreach (var market in allMarketplaces)
            {
                var checkedMarket = checkedMarkets.FirstOrDefault(l => l.Market == (int)market.Market &&
                                                                  (l.MarketplaceId == market.MarketplaceId || String.IsNullOrEmpty(market.MarketplaceId)));

                var marketListings = allListings
                                     .Where(l => l.Market == (int)market.Market &&
                                            (l.MarketplaceId == market.MarketplaceId ||
                                             String.IsNullOrEmpty(market.MarketplaceId)))
                                     .Select(l => new ListingPriceEditViewModel(l))
                                     .ToList();

                foreach (var listing in marketListings)
                {
                    listing.IsChecked = sale == null ?
                                        ((listing.IsPrime || SkuHelper.IsPrime(listing.SKU)) ? initSFPSalePrice.HasValue : initSalePrice.HasValue) :
                                        checkedListings.Any(l => l.ListingId == listing.ListingId);
                }

                var defaultPrice = //sale == null &&
                                   initSalePrice.HasValue &&
                                   marketListings.Any() ? priceService.GetMarketDefaultPrice(initSalePrice.Value,
                                                                                             market.Market,
                                                                                             market.MarketplaceId,
                                                                                             rateForMarketplace) : (decimal?)null;

                foreach (var marketListing in marketListings)
                {
                    var newDefaultPrice = priceService.ApplyMarketSpecified(defaultPrice,
                                                                            initSFPSalePrice,
                                                                            market.Market,
                                                                            market.MarketplaceId,
                                                                            marketListing.Weight,
                                                                            marketListing.IsPrime,
                                                                            marketListing.IsFBA);

                    if (newDefaultPrice != defaultPrice)
                    {
                        marketListing.OverrideSalePrice = newDefaultPrice;
                    }
                }

                var saleToMarket = new MarketPriceEditViewModel()
                {
                    Id = checkedMarket != null ? checkedMarket.Id : 0,

                    Market         = (MarketType)market.Market,
                    MarketplaceId  = market.MarketplaceId,
                    MarketName     = MarketHelper.GetMarketName((int)market.Market, market.MarketplaceId),
                    MarketCurrency = PriceHelper.GetCurrencySymbol(market.Market, market.MarketplaceId),

                    SalePrice          = checkedMarket != null ? checkedMarket.SalePrice : defaultPrice,
                    SFPSalePrice       = market.MarketplaceId == MarketplaceKeeper.AmazonComMarketplaceId ? initSFPSalePrice : null,
                    SalePercent        = checkedMarket != null ? checkedMarket.SalePercent : null,
                    ApplyToNewListings = checkedMarket != null ? checkedMarket.ApplyToNewListings : false,

                    Listings = marketListings
                };

                results.Add(saleToMarket);
            }

            return(results);
        }