示例#1
0
        private async Task <MoneyDTO> GetShippingResponseRatesAsync(RateShipmentResponse shipmentResponse, string shippingMethod, CommercePipelineExecutionContext context)
        {
            // Func<Rate, bool> shippingMethodMatchDelegate = rate => rate.ServiceCode?.IndexOf(shippingMethod, StringComparison.InvariantCultureIgnoreCase) >= 0;

            var shipmentDetail =
                shipmentResponse
                .RateResponse
                .Rates
                .FirstOrDefault(r => r.ServiceCode?.IndexOf(shippingMethod, StringComparison.InvariantCultureIgnoreCase) >= 0);

            if (shipmentDetail == null)
            {
                if (shipmentResponse.RateResponse.Errors.Count > 0)
                {
                    for (int i = 0; i < shipmentResponse.RateResponse.Errors.Count; i++)
                    {
                        context.Abort(await context.CommerceContext.AddMessage(
                                          context.GetPolicy <KnownResultCodes>().Error,
                                          "UnavailableServiceType",
                                          new object[1] {
                            shipmentResponse.RateResponse.Errors[i].Message
                        }
                                          ).ConfigureAwait(continueOnCapturedContext: false), context);
                    }
                }

                return(null);
            }


            return(shipmentDetail.ShippingAmount);
        }
示例#2
0
        public override async Task <RuleSet> Run(
            IEnumerable <RuleModel> arg,
            CommercePipelineExecutionContext context)
        {
            List <RuleModel> source = arg as List <RuleModel> ?? arg.ToList();

            // ISSUE: explicit non-virtual call
            Condition.Requires(source).IsNotNull($"{Name}: The argument cannot be null");

            if (!source.Any())
            {
                CommercePipelineExecutionContext executionContext = context;
                string error = context.GetPolicy <KnownResultCodes>().Error;
                executionContext.Abort(await context.CommerceContext
                                       .AddMessage(error, "RulesCannotBeNullOrEmpty", null,
                                                   "Rules cannot be null or empty.")
                                       .ConfigureAwait(false), context);
                return(null);
            }

            _ruleBuilder = _services.GetService <IRuleBuilderInit>();
            var ruleSet1 = new RuleSet
            {
                Id = $"{CommerceEntity.IdPrefix<RuleSet>() as object}{Guid.NewGuid() as object:N}"
            };
            RuleSet ruleSet2 = ruleSet1;

            foreach (RuleModel model in source.Where(rm => rm != null))
            {
                try
                {
                    ruleSet2.Rules.Add(BuildRule(model));
                }
                catch (Exception ex)
                {
                    CommercePipelineExecutionContext executionContext = context;
                    string error = context.GetPolicy <KnownResultCodes>().Error;
                    var    args  = new object[] { model.Name, ex };
                    executionContext.Abort(await context.CommerceContext
                                           .AddMessage(error, "RuleNotBuilt", args,
                                                       $"Rule '{model.Name}' cannot be built.")
                                           .ConfigureAwait(false), context);
                    return(null);
                }
            }

            return(ruleSet2);
        }
        public override async Task <RuleSet> Run(IEnumerable <RuleModel> arg, CommercePipelineExecutionContext context)
        {
            BuildRuleSetBlock buildRuleSetBlock = this;
            List <RuleModel>  ruleModels        = arg as List <RuleModel> ?? arg.ToList <RuleModel>();

            // ISSUE: explicit non-virtual call
            Condition.Requires <List <RuleModel> >(ruleModels).IsNotNull <List <RuleModel> >(string.Format("{0}: The argument cannot be null", (object)(buildRuleSetBlock.Name)));
            CommercePipelineExecutionContext executionContext;

            if (!ruleModels.Any <RuleModel>())
            {
                executionContext = context;
                executionContext.Abort(await context.CommerceContext.AddMessage(context.GetPolicy <KnownResultCodes>().Error, "RulesCannotBeNullOrEmpty", (object[])null, "Rules cannot be null or empty."), (object)context);
                executionContext = (CommercePipelineExecutionContext)null;
                return((RuleSet)null);
            }
            buildRuleSetBlock._ruleBuilder = buildRuleSetBlock._services.GetService <IRuleBuilderInit>();
            RuleSet ruleSet1 = new RuleSet();

            ruleSet1.Id = string.Format("{0}{1:N}", (object)CommerceEntity.IdPrefix <RuleSet>(), (object)Guid.NewGuid());
            RuleSet ruleSet = ruleSet1;

            foreach (RuleModel model in ruleModels.Where <RuleModel>((Func <RuleModel, bool>)(rm => rm != null)))
            {
                try
                {
                    ruleSet.Rules.Add(buildRuleSetBlock.BuildRule(model));
                }
                catch (Exception ex)
                {
                    executionContext = context;
                    CommerceContext commerceContext = context.CommerceContext;
                    string          error           = context.GetPolicy <KnownResultCodes>().Error;
                    string          commerceTermKey = "RuleNotBuilt";
                    object[]        args            = new object[2]
                    {
                        (object)model.Name,
                        (object)ex
                    };
                    string defaultMessage = string.Format("Rule '{0}' cannot be built.", (object)model.Name);
                    executionContext.Abort(await commerceContext.AddMessage(error, commerceTermKey, args, defaultMessage), (object)context);
                    executionContext = (CommercePipelineExecutionContext)null;
                    return((RuleSet)null);
                }
            }
            return(ruleSet);
        }
示例#4
0
        /// <summary>
        /// The execute.
        /// </summary>
        /// <param name="arg">
        /// The argument.
        /// </param>
        /// <param name="context">
        /// The context.
        /// </param>
        /// <returns>
        /// A list of <see cref="Entitlement"/>.
        /// </returns>
        public override async Task <IEnumerable <Entitlement> > Run(IEnumerable <Entitlement> arg, CommercePipelineExecutionContext context)
        {
            var entitlements = arg as List <Entitlement> ?? arg.ToList();

            Condition.Requires(entitlements).IsNotNull($"{this.Name}: The entitlements can not be null");

            var argument = context.CommerceContext.GetObjects <ProvisionEntitlementsArgument>().FirstOrDefault();

            if (argument == null)
            {
                return(entitlements.AsEnumerable());
            }

            var customer = argument.Customer;
            var order    = argument.Order;

            if (order == null)
            {
                return(entitlements.AsEnumerable());
            }

            var digitalTags          = context.GetPolicy <KnownEntitlementsTags>().DigitalProductTags;
            var lineWithDigitalGoods = order.Lines.Where(line => line != null &&
                                                         line.GetComponent <CartProductComponent>().HasPolicy <AvailabilityAlwaysPolicy>() &&
                                                         line.GetComponent <CartProductComponent>().Tags.Select(t => t.Name).Intersect(digitalTags, StringComparer.OrdinalIgnoreCase).Any()).ToList();

            if (!lineWithDigitalGoods.Any())
            {
                return(entitlements.AsEnumerable());
            }

            var hasErrors = false;

            foreach (var line in lineWithDigitalGoods)
            {
                foreach (var index in Enumerable.Range(1, (int)line.Quantity))
                {
                    try
                    {
                        var entitlement = new DigitalProduct();
                        var id          = Guid.NewGuid().ToString("N");
                        entitlement.Id         = $"{CommerceEntity.IdPrefix<DigitalProduct>()}{id}";
                        entitlement.FriendlyId = id;
                        entitlement.SetComponent(
                            new ListMembershipsComponent
                        {
                            Memberships =
                                new List <string>
                            {
                                $"{CommerceEntity.ListName<DigitalProduct>()}",
                                $"{CommerceEntity.ListName<Entitlement>()}"
                            }
                        });
                        entitlement.Order = new EntityReference(order.Id, order.Name);
                        if (customer != null)
                        {
                            entitlement.Customer = new EntityReference(customer.Id, customer.Name);
                        }

                        await this._persistEntityPipeline.Run(new PersistEntityArgument(entitlement), context);

                        entitlements.Add(entitlement);
                        context.Logger.LogInformation(
                            $"DigitalProduct Entitlement Created - Order={order.Id}, LineId={line.Id}, EntitlementId={entitlement.Id}");
                    }
                    catch
                    {
                        hasErrors = true;
                        context.Logger.LogError(
                            $"DigitalProduct Entitlement NOT Created - Order={order.Id}, LineId={line.Id}");
                        break;
                    }
                }

                if (hasErrors)
                {
                    break;
                }
            }

            if (!hasErrors)
            {
                return(entitlements.AsEnumerable());
            }

            context.Abort(
                context.CommerceContext.AddMessage(
                    context.GetPolicy <KnownResultCodes>().Error,
                    "ProvisioningEntitlementErrors",
                    new object[] { order.Id },
                    $"Error(s) occurred provisioning entitlements for order '{order.Id}'"),
                context);
            return(null);
        }
示例#5
0
 public static async Task AbortWithError(this CommercePipelineExecutionContext context, string message, string key,
                                         string id)
 {
     context.Abort(await context.CommerceContext.AddMessage(context.GetPolicy <KnownResultCodes>().Error, key,
                                                            new object[] { id }, message), context);
 }
        public override async Task <IEnumerable <FulfillmentOption> > Run(
            CartArgument arg,
            CommercePipelineExecutionContext context)
        {
            Condition.Requires <CartArgument>(arg).IsNotNull <CartArgument>("The arg can not be null");
            Condition.Requires <Cart>(arg.Cart).IsNotNull <Cart>("The cart can not be null");
            Cart cart = arg.Cart;

            if (!cart.Lines.Any <CartLineComponent>())
            {
                CommercePipelineExecutionContext executionContext = context;
                CommerceContext commerceContext = context.CommerceContext;
                string          validationError = context.CommerceContext.GetPolicy <KnownResultCodes>().ValidationError;
                object[]        args            = new object[1] {
                    (object)cart.Id
                };
                string defaultMessage = "Cart '" + cart.Id + "' has no lines";
                executionContext.Abort(await commerceContext.AddMessage(validationError, "CartHasNoLines", args, defaultMessage), (object)context);
                executionContext = (CommercePipelineExecutionContext)null;
                return(new List <FulfillmentOption>().AsEnumerable <FulfillmentOption>());
            }
            List <FulfillmentOption> list = (await this._getOptions.Run(string.Empty, context)).ToList <FulfillmentOption>();

            if (list.Any <FulfillmentOption>() && cart.Lines.Count == 1)
            {
                FulfillmentOption fulfillmentOption = list.FirstOrDefault <FulfillmentOption>((Func <FulfillmentOption, bool>)(o => o.FulfillmentType.Equals("SplitShipping", StringComparison.OrdinalIgnoreCase)));
                if (fulfillmentOption != null)
                {
                    list.Remove(fulfillmentOption);
                }
            }
            bool cartHasDigitalProducts  = false;
            bool cartHasTangibleProducts = false;

            foreach (CartLineComponent withSubLine in (IEnumerable <CartLineComponent>)arg.Cart.Lines.WithSubLines())
            {
                if (!withSubLine.CartSubLineComponents.Any <CartLineComponent>())
                {
                    //if (withSubLine.GetComponent<CartProductComponent>().HasPolicy<AvailabilityAlwaysPolicy>())
                    if (withSubLine.GetComponent <CartProductComponent>().Tags.Any <Tag>((Func <Tag, bool>)(p => p.Name.Equals("digitalsubscription", StringComparison.OrdinalIgnoreCase))))
                    {
                        cartHasDigitalProducts = true;
                    }
                    else
                    {
                        cartHasTangibleProducts = true;
                    }
                }
            }
            //cart has digital products only
            if (cartHasDigitalProducts && !cartHasTangibleProducts)
            {
                //lets remove the shiptome option
                if (list.Any <FulfillmentOption>((Func <FulfillmentOption, bool>)(p => p.FulfillmentType.Equals("ShipToMe", StringComparison.OrdinalIgnoreCase))))
                {
                    list.Remove(list.First <FulfillmentOption>((Func <FulfillmentOption, bool>)(p => p.FulfillmentType.Equals("ShipToMe", StringComparison.OrdinalIgnoreCase))));
                }

                if (list.Any <FulfillmentOption>((Func <FulfillmentOption, bool>)(p => p.Name.ToLower().Equals("shiptome", StringComparison.OrdinalIgnoreCase))))
                {
                    list.Remove(list.First <FulfillmentOption>((Func <FulfillmentOption, bool>)(p => p.Name.ToLower().Equals("shiptome", StringComparison.OrdinalIgnoreCase))));
                }
            }
            if (!cartHasDigitalProducts && cartHasTangibleProducts)
            {
                //lets remove the digital products option
                if (list.Any <FulfillmentOption>((Func <FulfillmentOption, bool>)(p => p.FulfillmentType.Equals("Digital", StringComparison.OrdinalIgnoreCase))))
                {
                    list.Remove(list.First <FulfillmentOption>((Func <FulfillmentOption, bool>)(p => p.FulfillmentType.Equals("Digital", StringComparison.OrdinalIgnoreCase))));
                }

                if (list.Any <FulfillmentOption>((Func <FulfillmentOption, bool>)(p => p.Name.ToLower().Equals("digital", StringComparison.OrdinalIgnoreCase))))
                {
                    list.Remove(list.First <FulfillmentOption>((Func <FulfillmentOption, bool>)(p => p.Name.ToLower().Equals("digital", StringComparison.OrdinalIgnoreCase))));
                }
            }
            //if cart has digital products and tangible products, Do not remove them from list.
            return(list.AsEnumerable <FulfillmentOption>());
        }