Example #1
0
            private IList <ProductPrice> CalculateProductPrices(RequestContext requestContext, IEnumerable <Product> products)
            {
                // use truncated date for comparison and price search
                DateTimeOffset today = requestContext.GetNowInChannelTimeZone();

                // create sales lines for calculation
                var salesLines = new List <SalesLine>();

                foreach (var product in products)
                {
                    SalesLine salesLine = new SalesLine
                    {
                        ItemId = product.ItemId,
                        InventoryDimensionId = string.Empty,
                        LineId = System.Guid.NewGuid().ToString("N"),
                        SalesOrderUnitOfMeasure = product.Rules.DefaultUnitOfMeasure,
                        Quantity  = 1,
                        ProductId = product.RecordId,
                        SalesDate = today,
                    };

                    salesLines.Add(salesLine);

                    if (product.IsMasterProduct)
                    {
                        foreach (var variant in product.GetVariants())
                        {
                            salesLine = new SalesLine
                            {
                                ItemId = product.ItemId,
                                InventoryDimensionId = variant.InventoryDimensionId,
                                LineId = System.Guid.NewGuid().ToString("N"),
                                SalesOrderUnitOfMeasure = product.Rules.DefaultUnitOfMeasure,
                                Quantity  = 1,
                                ProductId = variant.DistinctProductVariantId,
                                SalesDate = today,
                            };

                            salesLines.Add(salesLine);
                        }
                    }
                }

                // set the catalogIds on the sales lines
                var productCatalogAssociationRequest = new GetProductCatalogAssociationsDataRequest(salesLines.Select(p => p.ProductId));

                productCatalogAssociationRequest.QueryResultSettings = QueryResultSettings.AllRecords;
                var productCatalogs = requestContext.Runtime.Execute <GetProductCatalogAssociationsDataResponse>(
                    productCatalogAssociationRequest,
                    requestContext).CatalogAssociations;

                foreach (var sl in salesLines)
                {
                    sl.CatalogIds.UnionWith(productCatalogs.Where(pc => pc.ProductRecordId == sl.ProductId).Select(pc => pc.CatalogRecordId));
                }

                // create price context for calculation
                ISet <string> itemIds            = PE.PriceContextHelper.GetItemIds(salesLines);
                var           pricingDataManager = new PricingDataServiceManager(requestContext);
                var           priceContext       = PE.PriceContextHelper.CreatePriceContext(requestContext, pricingDataManager, this.priceParameters, new ChannelCurrencyOperations(requestContext), itemIds, PE.PriceContextHelper.GetCatalogIds(salesLines), today, PricingCalculationMode.Independent, DiscountCalculationMode.None);

                // calculate product prices
                PE.PricingEngine.CalculatePricesForSalesLines(salesLines, priceContext, pricingDataManager);

                IList <ProductPrice> prices = new List <ProductPrice>(salesLines.Count);

                foreach (var salesLine in salesLines)
                {
                    prices.Add(new ProductPrice
                    {
                        ItemId = salesLine.ItemId,
                        InventoryDimensionId = salesLine.InventoryDimensionId,
                        ProductId            = salesLine.ProductId,
                        BasePrice            = salesLine.BasePrice,
                        AdjustedPrice        = salesLine.AdjustedPrice,
                        TradeAgreementPrice  = salesLine.AgreementPrice
                    });
                }

                // return updated product prices
                return(prices);
            }
 private static GetProductCatalogAssociationsDataResponse GetProductCatalogAssociations(GetProductCatalogAssociationsDataRequest request)
 {
     return(new GetProductCatalogAssociationsDataResponse(new ReadOnlyCollection <ProductCatalogAssociation>(new List <ProductCatalogAssociation>())));
 }
Example #3
0
            /// <summary>
            /// Executes the workflow to retrieve the prices and calculated discount amount for the given product identifiers.
            /// </summary>
            /// <param name="request">The request.</param>
            /// <returns>The response.</returns>
            protected override GetIndependentProductPriceDiscountResponse Process(GetIndependentProductPriceDiscountRequest request)
            {
                ThrowIf.Null(request, "request");

                ProductSearchCriteria productSearchCriteria = new ProductSearchCriteria(
                    request.Context.ChannelId.GetValueOrDefault(),
                    request.Context.CatalogId.GetValueOrDefault())
                {
                    DataLevel = CommerceEntityDataLevel.Standard,
                    Ids       = request.ProductIds.ToList()
                };

                ProductSearchResultContainer productSearchResult = request.RequestContext.Runtime.Execute <ProductSearchServiceResponse>(
                    new ProductSearchServiceRequest(productSearchCriteria, request.QueryResultSettings), request.RequestContext).ProductSearchResult;

                List <ProductPrice> productPrices = new List <ProductPrice>(request.ProductIds.Count());

                // Create sales line for every product id there is in the request.
                List <SalesLine> salesLines = new List <SalesLine>(request.ProductIds.Count());

                foreach (var product in productSearchResult.Results)
                {
                    if (product.IsMasterProduct)
                    {
                        foreach (var variant in product.GetVariants())
                        {
                            if (request.ProductIds.Contains(variant.DistinctProductVariantId))
                            {
                                salesLines.Add(new SalesLine
                                {
                                    ItemId  = product.ItemId,
                                    Variant = variant,
                                    InventoryDimensionId    = variant.InventoryDimensionId,
                                    SalesOrderUnitOfMeasure = product.Rules.DefaultUnitOfMeasure,
                                    LineId    = System.Guid.NewGuid().ToString("N"),
                                    Quantity  = 1,
                                    ProductId = variant.DistinctProductVariantId,
                                    CatalogId = request.Context.CatalogId.GetValueOrDefault()
                                });
                            }
                        }
                    }
                    else
                    {
                        salesLines.Add(new SalesLine
                        {
                            ItemId = product.ItemId,
                            SalesOrderUnitOfMeasure = product.Rules.DefaultUnitOfMeasure,
                            LineId    = System.Guid.NewGuid().ToString("N"),
                            Quantity  = 1,
                            ProductId = product.RecordId,
                            CatalogId = request.Context.CatalogId.GetValueOrDefault()
                        });
                    }
                }

                // Set the catalog ids on the sales lines.
                if (request.Context.CatalogId != null)
                {
                    if (request.Context.CatalogId.Value > 0)
                    {
                        // If a specific catalogId is set on the context, add it to the catalogIds on the sales lines.
                        foreach (var sl in salesLines)
                        {
                            sl.CatalogIds.Add(request.Context.CatalogId.Value);
                        }
                    }
                    else
                    {
                        GetProductCatalogAssociationsDataRequest productCatalogAssociationRequest = new GetProductCatalogAssociationsDataRequest(salesLines.Select(p => p.ProductId))
                        {
                            QueryResultSettings = QueryResultSettings.AllRecords
                        };
                        ReadOnlyCollection <ProductCatalogAssociation> productCatalogs = request.RequestContext.Runtime.Execute <GetProductCatalogAssociationsDataResponse>(
                            productCatalogAssociationRequest,
                            request.RequestContext).CatalogAssociations;

                        // If catalogId is 0, add all independent catalogs to the catalogIds on the sales lines.
                        foreach (var sl in salesLines)
                        {
                            sl.CatalogIds.UnionWith(productCatalogs.Where(pc => pc.ProductRecordId == sl.ProductId).Select(pc => pc.CatalogRecordId));
                        }
                    }
                }

                Collection <SalesAffiliationLoyaltyTier> affiliations = null;

                if (request.AffiliationLoyaltyTiers != null)
                {
                    affiliations = new Collection <SalesAffiliationLoyaltyTier>((from alt in request.AffiliationLoyaltyTiers
                                                                                 select new SalesAffiliationLoyaltyTier
                    {
                        AffiliationId = alt.AffiliationId,
                        AffiliationType = alt.AffiliationType,
                        LoyaltyTierId = alt.LoyaltyTierId,
                        ReasonCodeLines = alt.ReasonCodeLines,
                        CustomerId = alt.CustomerId,
                        ChannelId = request.Context.ChannelId.GetValueOrDefault()
                    }).ToList());
                }

                SalesTransaction transaction = new SalesTransaction
                {
                    SalesLines = new Collection <SalesLine>(salesLines),
                    CustomerId = request.CustomerAccountNumber,
                    AffiliationLoyaltyTierLines = affiliations
                };

                // Calculate prices and discounts for sales lines
                GetIndependentPriceDiscountServiceRequest itemPriceDiscountServiceRequest = new GetIndependentPriceDiscountServiceRequest(transaction);
                GetPriceServiceResponse      itemPriceServiceResponse = this.Context.Execute <GetPriceServiceResponse>(itemPriceDiscountServiceRequest);
                Dictionary <long, SalesLine> salesLineDictionary      = itemPriceServiceResponse.Transaction.SalesLines.ToDictionary(sl => sl.ProductId);

                foreach (long productId in request.ProductIds)
                {
                    SalesLine salesLine;

                    if (!salesLineDictionary.TryGetValue(productId, out salesLine))
                    {
                        salesLine = new SalesLine();
                    }

                    ProductPrice productPrice = new ProductPrice
                    {
                        UnitOfMeasure        = salesLine.SalesOrderUnitOfMeasure,
                        ItemId               = salesLine.ItemId,
                        InventoryDimensionId = salesLine.InventoryDimensionId,
                        BasePrice            = salesLine.BasePrice,
                        TradeAgreementPrice  = salesLine.AgreementPrice,
                        AdjustedPrice        = salesLine.AdjustedPrice,
                        DiscountAmount       = salesLine.DiscountAmount,
                        ProductId            = productId,
                        ChannelId            = request.Context.ChannelId.GetValueOrDefault(),
                        CatalogId            = request.Context.CatalogId.GetValueOrDefault()
                    };

                    productPrices.Add(productPrice);
                }

                return(new GetIndependentProductPriceDiscountResponse(productPrices.AsPagedResult()));
            }
            /// <summary>
            /// Executes the workflow to retrieve active product prices for given product ids.
            /// </summary>
            /// <param name="request">The request.</param>
            /// <returns>The response.</returns>
            protected override GetActiveProductPriceResponse Process(GetActiveProductPriceRequest request)
            {
                ThrowIf.Null(request, "request");

                var validateCustomerAccountRequest  = new GetValidatedCustomerAccountNumberServiceRequest(request.CustomerAccountNumber, throwOnValidationFailure: true);
                var validateCustomerAccountResponse = this.Context.Execute <GetValidatedCustomerAccountNumberServiceResponse>(validateCustomerAccountRequest);

                if (validateCustomerAccountResponse.IsCustomerAccountNumberInContextDifferent)
                {
                    request.CustomerAccountNumber = validateCustomerAccountResponse.ValidatedAccountNumber;
                }

                bool downloadedProductsFilter = false;

                if (request.Context.ChannelId != this.Context.GetPrincipal().ChannelId)
                {
                    downloadedProductsFilter = true;
                }

                var settings        = new QueryResultSettings(PagingInfo.CreateWithExactCount(request.ProductIds.Count(), 0));
                var productsRequest = new GetProductsDataRequest(request.ProductIds, settings, downloadedProductsFilter);
                var products        = this.Context.Execute <EntityDataServiceResponse <SimpleProduct> >(productsRequest).PagedEntityCollection.Results;
                var activePrices    = new List <ProductPrice>(products.Count);

                // package sales lines to calculate
                var salesLines = new List <SalesLine>(products.Count);

                foreach (var product in products)
                {
                    salesLines.Add(new SalesLine
                    {
                        ItemId = product.ItemId,
                        InventoryDimensionId    = product.InventoryDimensionId,
                        SalesOrderUnitOfMeasure = product.DefaultUnitOfMeasure,
                        LineId    = System.Guid.NewGuid().ToString("N"),
                        Quantity  = 1,
                        ProductId = product.RecordId,
                        CatalogId = request.Context.CatalogId.GetValueOrDefault()
                    });
                }

                // set the catalogIds on the sales lines
                if (request.Context.CatalogId != null)
                {
                    if (request.Context.CatalogId.Value > 0)
                    {
                        // If a specific catalogId is set on the context, add it to the catalogIds on the sales lines.
                        foreach (var sl in salesLines)
                        {
                            sl.CatalogIds.Add(request.Context.CatalogId.Value);
                        }
                    }
                    else
                    {
                        // If catalogId is 0, add all active catalogs to the catalogIds on the sales lines.
                        foreach (var sl in salesLines)
                        {
                            var productCatalogAssociationRequest = new GetProductCatalogAssociationsDataRequest(salesLines.Select(p => p.ProductId))
                            {
                                QueryResultSettings = QueryResultSettings.AllRecords
                            };
                            var productCatalogs = request.RequestContext.Runtime.Execute <GetProductCatalogAssociationsDataResponse>(
                                productCatalogAssociationRequest,
                                request.RequestContext).CatalogAssociations;

                            sl.CatalogIds.UnionWith(productCatalogs.Where(pc => pc.ProductRecordId == sl.ProductId).Select(pc => pc.CatalogRecordId));
                        }
                    }
                }

                Customer customer = null;

                if (!string.IsNullOrWhiteSpace(request.CustomerAccountNumber))
                {
                    var getCustomerDataRequest = new GetCustomerDataRequest(request.CustomerAccountNumber);
                    SingleEntityDataServiceResponse <Customer> getCustomerDataResponse = this.Context.Runtime.Execute <SingleEntityDataServiceResponse <Customer> >(getCustomerDataRequest, this.Context);
                    customer = getCustomerDataResponse.Entity;
                }

                string priceGroup = customer != null ? customer.PriceGroup : string.Empty;

                // calculate prices for sales lines
                var itemPriceServiceRequest  = new GetPricesServiceRequest(salesLines, request.DateWhenActive, request.CustomerAccountNumber, priceGroup, PricingCalculationMode.Independent, request.AffiliationLoyaltyTiers);
                var itemPriceServiceResponse = this.Context.Execute <GetPricesServiceResponse>(itemPriceServiceRequest);
                var salesLineDictionary      = itemPriceServiceResponse.SalesLines.Results.ToDictionary(sl => sl.ProductId);

                foreach (var product in products)
                {
                    SalesLine salesLine;
                    if (!salesLineDictionary.TryGetValue(product.RecordId, out salesLine))
                    {
                        salesLine = new SalesLine();
                    }

                    ProductPrice activePrice = GetActiveProductPriceRequestHandler.ActivePriceFromSalesLine(product.RecordId, salesLine);
                    activePrice.ProductId    = product.RecordId;
                    activePrice.ValidFrom    = request.DateWhenActive;
                    activePrice.CurrencyCode = itemPriceServiceResponse.CurrencyCode;
                    activePrice.ChannelId    = request.Context.ChannelId.GetValueOrDefault();
                    activePrice.CatalogId    = request.Context.CatalogId.GetValueOrDefault();

                    activePrices.Add(activePrice);
                }

                return(new GetActiveProductPriceResponse(activePrices.AsPagedResult()));
            }