Ejemplo n.º 1
0
        public virtual async Task Run(SearchProductResponse parameter, Func <SearchProductResponse, Task> next)
        {
            if (parameter == null)
            {
                throw new ArgumentNullException(nameof(parameter));
            }

            var query = parameter.Query;

            if (query == null)
            {
                throw new OperationCanceledException("Query must be set");
            }

            var productIds    = parameter.Results.Select(x => x.Id).ToArray();
            var responseGroup = EnumUtility.SafeParse(query.GetResponseGroup(), ExpProductResponseGroup.None);

            // If products availabilities requested
            if (responseGroup.HasFlag(ExpProductResponseGroup.LoadInventories))
            {
                var inventories = new List <InventoryInfo>();

                var countResult = await _inventorySearchService.SearchInventoriesAsync(new InventorySearchCriteria
                {
                    ProductIds = productIds,
                });

                var pageSize = 10;

                for (var i = 0; i < countResult.TotalCount; i += pageSize)
                {
                    var searchResult = await _inventorySearchService.SearchInventoriesAsync(new InventorySearchCriteria
                    {
                        ProductIds = productIds,
                        Skip       = i,
                        Take       = pageSize,
                    });

                    inventories.AddRange(searchResult.Results);
                }

                if (inventories.Any())
                {
                    parameter.Results.Apply(x => x.ApplyStoreInventories(inventories, parameter.Store));
                }
            }

            await next(parameter);
        }
        public async Task DoExportAsync(Stream outStream, Action <ExportImportProgressInfo> progressCallback, ICancellationToken cancellationToken)
        {
            cancellationToken.ThrowIfCancellationRequested();

            var progressInfo = new ExportImportProgressInfo {
                Description = "The fulfilmentCenters are loading"
            };

            progressCallback(progressInfo);

            using (var sw = new StreamWriter(outStream, Encoding.UTF8))
                using (var writer = new JsonTextWriter(sw))
                {
                    await writer.WriteStartObjectAsync();

                    await writer.WritePropertyNameAsync("FulfillmentCenters");

                    await writer.SerializeJsonArrayWithPagingAsync(_jsonSerializer, BatchSize, async (skip, take) =>
                    {
                        var searchCriteria  = AbstractTypeFactory <FulfillmentCenterSearchCriteria> .TryCreateInstance();
                        searchCriteria.Take = take;
                        searchCriteria.Skip = skip;
                        var searchResult    = await _fulfillmentCenterSearchService.SearchCentersAsync(searchCriteria);
                        return((GenericSearchResult <FulfillmentCenter>)searchResult);
                    }, (processedCount, totalCount) =>
                    {
                        progressInfo.Description = $"{processedCount} of {totalCount} FulfillmentCenters have been exported";
                        progressCallback(progressInfo);
                    }, cancellationToken);

                    progressInfo.Description = "The Inventories are loading";
                    progressCallback(progressInfo);

                    await writer.WritePropertyNameAsync("Inventories");

                    await writer.SerializeJsonArrayWithPagingAsync(_jsonSerializer, BatchSize, async (skip, take) =>
                    {
                        var searchCriteria  = AbstractTypeFactory <InventorySearchCriteria> .TryCreateInstance();
                        searchCriteria.Take = take;
                        searchCriteria.Skip = skip;
                        var searchResult    = await _inventorySearchService.SearchInventoriesAsync(searchCriteria);
                        return((GenericSearchResult <InventoryInfo>)searchResult);
                    }, (processedCount, totalCount) =>
                    {
                        progressInfo.Description = $"{processedCount} of {totalCount} inventories have been exported";
                        progressCallback(progressInfo);
                    }, cancellationToken);

                    await writer.WriteEndObjectAsync();

                    await writer.FlushAsync();
                }
        }
Ejemplo n.º 3
0
        /// <summary>
        /// Load inventories and apply them to <see cref="CartProduct"/>s
        /// </summary>
        /// <param name="aggregate">Cart aggregate</param>
        /// <param name="products">List of <see cref="CartProduct"/>s</param>
        protected virtual async Task ApplyInventoriesToCartProductAsync(CartAggregate aggregate, List <CartProduct> products)
        {
            if (products.IsNullOrEmpty())
            {
                return;
            }

            var ids = products.Select(x => x.Id).ToArray();

            var countResult = await _inventorySearchService.SearchInventoriesAsync(new InventorySearchCriteria
            {
                ProductIds = ids,
                Skip       = 0,
                Take       = DefaultPageSize
            });

            var allLoadInventories = countResult.Results.ToList();

            if (countResult.TotalCount > DefaultPageSize)
            {
                for (var i = DefaultPageSize; i < countResult.TotalCount; i += DefaultPageSize)
                {
                    var loadInventoriesTask = await _inventorySearchService.SearchInventoriesAsync(new InventorySearchCriteria
                    {
                        ProductIds = ids,
                        Skip       = i,
                        Take       = DefaultPageSize
                    });

                    allLoadInventories.AddRange(loadInventoriesTask.Results);
                }
            }

            foreach (var cartProduct in products)
            {
                cartProduct.ApplyInventories(allLoadInventories, aggregate.Store);
            }
        }
Ejemplo n.º 4
0
        public async Task <IEnumerable <CartProduct> > GetCartProductsByIdsAsync(CartAggregate cartAggr, string[] ids)
        {
            if (cartAggr == null)
            {
                throw new ArgumentNullException(nameof(cartAggr));
            }
            if (ids == null)
            {
                throw new ArgumentNullException(nameof(ids));
            }

            var result   = new List <CartProduct>();
            var products = await _productService.GetByIdsAsync(ids, (ItemResponseGroup.ItemAssets | ItemResponseGroup.ItemInfo | ItemResponseGroup.Outlines | ItemResponseGroup.Seo).ToString());

            if (!products.IsNullOrEmpty())
            {
                var loadInventoriesTask = _inventorySearchService.SearchInventoriesAsync(new InventorySearchCriteria
                {
                    ProductIds = ids,
                    //Do not use int.MaxValue use only 10 items per requested product
                    //TODO: Replace to pagination load
                    Take = Math.Min(ids.Length * 10, 500)
                });

                var pricesEvalContext = _mapper.Map <PriceEvaluationContext>(cartAggr);
                pricesEvalContext.ProductIds = ids;
                var evalPricesTask = _pricingService.EvaluateProductPricesAsync(pricesEvalContext);

                await Task.WhenAll(loadInventoriesTask, evalPricesTask);

                foreach (var product in products)
                {
                    var cartProduct = new CartProduct(product);
                    //Apply inventories
                    cartProduct.ApplyInventories(loadInventoriesTask.Result.Results, cartAggr.Store);

                    //Apply prices
                    cartProduct.ApplyPrices(evalPricesTask.Result, cartAggr.Currency);
                    result.Add(cartProduct);
                }
            }
            return(result);
        }
        public virtual async Task Run(SearchProductResponse parameter, Func <SearchProductResponse, Task> next)
        {
            if (parameter == null)
            {
                throw new ArgumentNullException(nameof(parameter));
            }

            var query = parameter.Query;

            if (query == null)
            {
                throw new OperationCanceledException("Query must be set");
            }

            var productIds    = parameter.Results.Select(x => x.Id).ToArray();
            var responseGroup = EnumUtility.SafeParse(query.GetResponseGroup(), ExpProductResponseGroup.None);

            // If products availabilities requested
            if (responseGroup.HasFlag(ExpProductResponseGroup.LoadInventories))
            {
                var inventories = await _inventorySearchService.SearchInventoriesAsync(new InventorySearchCriteria
                {
                    ProductIds = productIds,
                    //Do not use int.MaxValue use only 10 items per requested product
                    //TODO: Replace to pagination load
                    Take = Math.Min(productIds.Length * 10, 500)
                });

                if (inventories.Results.Any())
                {
                    parameter.Results.Apply(x => x.ApplyStoreInventories(inventories.Results, parameter.Store));
                }
            }


            await next(parameter);
        }
        public async Task ExportAsync(Stream outStream, ExportImportOptions options, Action <ExportImportProgressInfo> progressCallback, ICancellationToken cancellationToken)
        {
            cancellationToken.ThrowIfCancellationRequested();

            var progressInfo = new ExportImportProgressInfo {
                Description = "The fulfilmentCenters are loading"
            };

            progressCallback(progressInfo);

            //var backupObject = await GetBackupObject(progressCallback);
            using (var sw = new StreamWriter(outStream, Encoding.UTF8))
                using (var writer = new JsonTextWriter(sw))
                {
                    writer.WriteStartObject();

                    var centers = await _fulfillmentCenterSearchService.SearchCentersAsync(new FulfillmentCenterSearchCriteria { Take = int.MaxValue });

                    writer.WritePropertyName("FulfillmentCenterTotalCount");
                    writer.WriteValue(centers.TotalCount);

                    writer.WritePropertyName("FulfillmentCenters");
                    writer.WriteStartArray();

                    foreach (var fulfillmentCenter in centers.Results)
                    {
                        _serializer.Serialize(writer, fulfillmentCenter);
                    }

                    writer.WriteEndArray();

                    progressInfo.Description = "Evaluation the number of inventory records";
                    progressCallback(progressInfo);

                    var searchResult = await _inventorySearchService.SearchInventoriesAsync(new InventorySearchCriteria { Take = BatchSize });

                    var totalCount = searchResult.TotalCount;
                    writer.WritePropertyName("InventoriesTotalCount");
                    writer.WriteValue(totalCount);

                    writer.WritePropertyName("Inventories");
                    writer.WriteStartArray();

                    for (int i = BatchSize; i < totalCount; i += BatchSize)
                    {
                        progressInfo.Description = $"{i} of {totalCount} inventories have been loaded";
                        progressCallback(progressInfo);

                        searchResult = await _inventorySearchService.SearchInventoriesAsync(new InventorySearchCriteria { Skip = i, Take = BatchSize });

                        foreach (var inventory in searchResult.Results)
                        {
                            _serializer.Serialize(writer, inventory);
                        }
                        writer.Flush();
                        progressInfo.Description = $"{ Math.Min(totalCount, i + BatchSize) } of { totalCount } inventories exported";
                        progressCallback(progressInfo);
                    }

                    writer.WriteEndArray();

                    writer.WriteEndObject();
                    writer.Flush();
                }
        }
Ejemplo n.º 7
0
        public async Task DoExportAsync(Stream outStream, CsvExportInfo exportInfo, Action <ExportImportProgressInfo> progressCallback)
        {
            var prodgressInfo = new ExportImportProgressInfo
            {
                Description = "loading products..."
            };

            var streamWriter = new StreamWriter(outStream, Encoding.UTF8, 1024, true)
            {
                AutoFlush = true
            };

            using (var csvWriter = new CsvWriter(streamWriter))
            {
                //Notification
                progressCallback(prodgressInfo);

                //Load all products to export
                var products = await LoadProducts(exportInfo.CatalogId, exportInfo.CategoryIds, exportInfo.ProductIds);

                var allProductIds = products.Select(x => x.Id).ToArray();

                //Load prices for products
                prodgressInfo.Description = "loading prices...";
                progressCallback(prodgressInfo);

                var priceEvalContext = new PriceEvaluationContext
                {
                    ProductIds   = allProductIds,
                    PricelistIds = exportInfo.PriceListId == null ? null : new[] { exportInfo.PriceListId },
                    Currency     = exportInfo.Currency
                };
                var allProductPrices = (await _pricingService.EvaluateProductPricesAsync(priceEvalContext)).ToList();

                //Load inventories
                prodgressInfo.Description = "loading inventory information...";
                progressCallback(prodgressInfo);

                var inventorySearchCriteria = new InventorySearchCriteria()
                {
                    ProductIds           = allProductIds,
                    FulfillmentCenterIds = string.IsNullOrWhiteSpace(exportInfo.FulfilmentCenterId) ? Array.Empty <string>() : new[] { exportInfo.FulfilmentCenterId },
                    Take = int.MaxValue,
                };
                var allProductInventories = (await _inventorySearchService.SearchInventoriesAsync(inventorySearchCriteria)).Results.ToList();

                //Export configuration
                exportInfo.Configuration.PropertyCsvColumns = products.SelectMany(x => x.Properties).Select(x => x.Name).Distinct().ToArray();

                csvWriter.Configuration.Delimiter = exportInfo.Configuration.Delimiter;
                csvWriter.Configuration.RegisterClassMap(new CsvProductMap(exportInfo.Configuration));

                //Write header
                csvWriter.WriteHeader <CsvProduct>();
                csvWriter.NextRecord();

                prodgressInfo.TotalCount = products.Count;
                var notifyProductSizeLimit = 50;
                var counter = 0;

                //convert to dict for faster search
                var pricesDict      = allProductPrices.GroupBy(x => x.ProductId).ToDictionary(x => x.Key, x => x.First());
                var inventoriesDict = allProductInventories.GroupBy(x => x.ProductId).ToDictionary(x => x.Key, x => x.First());

                foreach (var product in products)
                {
                    try
                    {
                        var csvProducts = MakeMultipleExportProducts(product, pricesDict, inventoriesDict);

                        csvWriter.WriteRecords(csvProducts);
                    }
                    catch (Exception ex)
                    {
                        prodgressInfo.Errors.Add(ex.ToString());
                        progressCallback(prodgressInfo);
                    }

                    //Raise notification each notifyProductSizeLimit products
                    counter++;
                    prodgressInfo.ProcessedCount = counter;
                    prodgressInfo.Description    = string.Format("{0} of {1} products processed", prodgressInfo.ProcessedCount, prodgressInfo.TotalCount);
                    if (counter % notifyProductSizeLimit == 0 || counter == prodgressInfo.TotalCount)
                    {
                        progressCallback(prodgressInfo);
                    }
                }
            }
        }