public virtual async Task CreateTemplateFromProxy(CommerceContext commerceContext, ProxyComposer.ComposerTemplate proxyComposerTemplate)
        {
            ComposerCommander composerCommander = this;

            Condition.Requires(commerceContext).IsNotNull("CommerceContext");
            Condition.Requires(proxyComposerTemplate).IsNotNull("composerTemplate");
            using (CommandActivity.Start(commerceContext, composerCommander))
            {
                KnownResultCodes errorCodes           = commerceContext.GetPolicy <KnownResultCodes>();
                string           composerTemplateName = proxyComposerTemplate.Name;
                if (string.IsNullOrEmpty(composerTemplateName))
                {
                    string composerTemplatePropertyName = "Name";
                    string str2 = await commerceContext.AddMessage(errorCodes.ValidationError, "InvalidOrMissingPropertyValue", new object[1]
                    {
                        composerTemplatePropertyName
                    }, "Invalid or missing value for property '" + composerTemplatePropertyName + "'.").ConfigureAwait(false);

                    return;
                }
                string templateId = proxyComposerTemplate.Id;
                if (await composerCommander.GetEntity <ComposerTemplate>(commerceContext, templateId, false).ConfigureAwait(false) != null)
                {
                    string str = await commerceContext.AddMessage(errorCodes.ValidationError, "NameAlreadyInUse", new object[1]
                    {
                        proxyComposerTemplate.Name
                    }, "Name '" + proxyComposerTemplate.Name + "' is already in use.").ConfigureAwait(false);

                    return;
                }

                ComposerTemplate engineComposerTemplate = new ComposerTemplate(templateId);
                engineComposerTemplate.Name           = proxyComposerTemplate.Name;
                engineComposerTemplate.DisplayName    = proxyComposerTemplate.DisplayName;
                engineComposerTemplate.FriendlyId     = proxyComposerTemplate.Name;
                engineComposerTemplate.LinkedEntities = proxyComposerTemplate.LinkedEntities;

                this.AddTagsFromProxy(engineComposerTemplate, proxyComposerTemplate);
                this.AddComposerTemplateListMembershipsFromProxy(engineComposerTemplate, proxyComposerTemplate);
                await this.AddComposerTemplateEntityViewFromProxy(commerceContext, engineComposerTemplate, proxyComposerTemplate);

                this.AddItemDefinitionsFromProxy(engineComposerTemplate, proxyComposerTemplate);

                int num = await composerCommander.PersistEntity(commerceContext, engineComposerTemplate).ConfigureAwait(false) ? 1 : 0;

                errorCodes = null;
                templateId = null;
            }
        }
Exemple #2
0
        public async Task <JsonResponse> Process(CommerceContext commerceContext, string uri)
        {
            using (CommandActivity.Start(commerceContext, this))
            {
                var response = new JsonResponse {
                    Uri = uri
                };

                try
                {
                    using (var httpClient = new HttpClient())
                    {
                        response.Json = await httpClient.GetStringAsync(response.Uri);
                    }

                    var reader = new StringReader(response.Json);

                    response.Reader = new JsonTextReader(reader);
                }
                catch (Exception ex)
                {
                    await commerceContext.AddMessage(
                        commerceContext.GetPolicy <KnownResultCodes>().Error,
                        $"JsonCommand.Get.Exception: Message={ex.Message}",
                        new object[] { ex },
                        $"JsonCommand.Get.Exception: Message={ex.Message}|Stack={ex.StackTrace}");

                    response = null;
                }
                return(response);
            }
        }
        /// <summary>
        /// Processes the specified commerce context.
        /// </summary>
        /// <param name="commerceContext">The commerce context.</param>
        /// <returns>User site terms</returns>
        public virtual async Task <IEnumerable <Customer> > Process(CommerceContext commerceContext)
        {
            using (CommandActivity.Start(commerceContext, this))
            {
                var sqlContext = ConnectionHelper.GetProfilesSqlContext(commerceContext);
                var rows       = await sqlContext.GetAllProfiles();

                var migratedCustomers = new List <Customer>();

                foreach (DataRow row in rows)
                {
                    try
                    {
                        var contextOptions = commerceContext.GetPipelineContextOptions();

                        var csCustomer = await this._migrateCustomerPipeline.Run(row, contextOptions);

                        if (csCustomer != null)
                        {
                            migratedCustomers.Add(csCustomer);
                        }
                    }
                    catch (Exception ex)
                    {
                        await commerceContext.AddMessage(
                            commerceContext.GetPolicy <KnownResultCodes>().Error,
                            "EntityNotFound",
                            new object[] { row["u_user_id"] as string, ex },
                            $"Customer {row["u_user_id"] as string} was not migrated.");
                    }
                }

                return(migratedCustomers);
            }
        }
Exemple #4
0
        public override async Task <bool> Run(bool arg, CommercePipelineExecutionContext context)
        {
            if (arg)
            {
                return(true);
            }

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

            if (argument == null)
            {
                return(true);
            }

            var result = await _initIndexPipeline.Run(argument, context);

            if (result != null)
            {
                return(true);
            }

            CommercePipelineExecutionContext executionContext = context;
            CommerceContext commerceContext = context.CommerceContext;
            string          error           = context.GetPolicy <KnownResultCodes>().Error;
            string          commerceTermKey = "CreateIndexError";

            object[] args           = { argument.IndexName };
            string   defaultMessage = $"Search index '{argument.IndexName as object}' was not created.";

            executionContext.Abort(await commerceContext.AddMessage(error, commerceTermKey, args, defaultMessage), context);
            return(false);
        }
        /// <summary>
        /// The process of the command
        /// </summary>
        /// <param name="commerceContext">
        /// The commerce context
        /// </param>
        /// <returns>
        /// The <see cref="Task"/>.
        /// </returns>
        public async Task <DateTime> GetEbayTime(CommerceContext commerceContext)
        {
            using (var activity = CommandActivity.Start(commerceContext, this))
            {
                //Instantiate the call wrapper class
                GeteBayOfficialTimeCall apiCall = new GeteBayOfficialTimeCall(await GetEbayContext(commerceContext).ConfigureAwait(false));

                //Send the call to eBay and get the results
                try
                {
                    var ebayConfig = await this._commerceCommander.GetEntity <EbayConfigEntity>(commerceContext, "Entity-EbayConfigEntity-Global", true).ConfigureAwait(false);

                    if (ebayConfig.HasComponent <EbayBusinessUserComponent>())
                    {
                        var ebayConfigComponent = ebayConfig.GetComponent <EbayBusinessUserComponent>();
                        if (!string.IsNullOrEmpty(ebayConfigComponent.EbayToken))
                        {
                            DateTime officialTime = apiCall.GeteBayOfficialTime();
                            return(officialTime);
                        }
                    }
                }
                catch (Exception ex)
                {
                    commerceContext.Logger.LogError($"Ebay.GetEbayTime.Exception: Message={ex.Message}");
                    await commerceContext.AddMessage("Error", "Ebay.GetEbayTime.Exception", new Object[] { ex }, ex.Message).ConfigureAwait(false);
                }

                //Handle the result returned
                //Console.WriteLine("eBay official Time: " + officialTime);

                return(new DateTime());
            }
        }
        public override async Task <PriceCard> Run(PriceCard arg, CommercePipelineExecutionContext context)
        {
            Condition.Requires(arg).IsNotNull(Name + ": The price card can not be null");
            PriceCard card = arg;
            var       snapshotTierArgument = context.CommerceContext.GetObject <PriceCardSnapshotCustomTierArgument>();
            CommercePipelineExecutionContext executionContext;

            if (snapshotTierArgument == null)
            {
                executionContext = context;
                CommerceContext commerceContext = context.CommerceContext;
                string          error           = context.GetPolicy <KnownResultCodes>().Error;
                string          defaultMessage  = "Argument of type " + typeof(PriceCardSnapshotCustomTierArgument).Name + " was not found in context.";
                executionContext.Abort(await commerceContext.AddMessage(error, "ArgumentNotFound", new object[] { typeof(PriceCardSnapshotCustomTierArgument).Name }, defaultMessage).ConfigureAwait(false), context);
                executionContext = null;

                return(card);
            }

            Condition.Requires(snapshotTierArgument.PriceSnapshot).IsNotNull(Name + ": The price snapshot can not be null");
            Condition.Requires(snapshotTierArgument.PriceSnapshot.Id).IsNotNullOrEmpty(Name + ": The price snapshot id can not be null or empty");
            Condition.Requires(snapshotTierArgument.PriceTier).IsNotNull(Name + ": The price tier can not be null");
            Condition.Requires(snapshotTierArgument.PriceTier.Id).IsNotNullOrEmpty(Name + ": The price tier id can not be null or empty");
            Condition.Requires(snapshotTierArgument.PriceTier.Currency).IsNotNullOrEmpty(Name + ": The price tier currency can not be null or empty");

            PriceSnapshotComponent snapshot = snapshotTierArgument.PriceSnapshot;
            var tier = snapshotTierArgument.PriceTier;
            PriceSnapshotComponent existingSnapshot = card.Snapshots.FirstOrDefault(n => n.Id.Equals(snapshot.Id, StringComparison.OrdinalIgnoreCase));

            if (existingSnapshot == null)
            {
                return(card);
            }

            var membershipTiersComponent = existingSnapshot.GetComponent <MembershipTiersComponent>();
            var existingTier             = membershipTiersComponent.Tiers.FirstOrDefault(t => t.Id.Equals(tier.Id, StringComparison.OrdinalIgnoreCase));

            if (existingTier == null)
            {
                executionContext = context;
                CommerceContext commerceContext = context.CommerceContext;
                string          validationError = context.GetPolicy <KnownResultCodes>().ValidationError;
                string          defaultMessage  = "Price tier " + tier.Id + " was not found in snapshot " + snapshot.Id + " for card " + card.FriendlyId + ".";
                executionContext.Abort(await commerceContext.AddMessage(validationError, "PriceTierNotFound", new object[] { tier.Id, snapshot.Id, card.FriendlyId }, defaultMessage).ConfigureAwait(false), context);
                executionContext = null;

                return(card);
            }

            await context.CommerceContext.AddMessage(context.GetPolicy <KnownResultCodes>().Information, null, null, "Removed price tier " + tier.Id + " from price snapshot " + snapshot.Id)
            .ConfigureAwait(false);

            membershipTiersComponent.Tiers.Remove(existingTier);

            return(card);
        }
 /// <summary>
 /// Copies messages from one context into another.
 /// </summary>
 /// <param name="targetContext">The context that will recieve the messages.</param>
 /// <param name="sourceContext">The context that is the source of the messages.</param>
 protected void MergeMessages(CommerceContext targetContext, CommerceContext sourceContext)
 {
     Condition.Requires(targetContext, nameof(targetContext)).IsNotNull();
     if (sourceContext != null)
     {
         foreach (var message in sourceContext.GetMessages())
         {
             targetContext.AddMessage(message);
         }
     }
 }
Exemple #8
0
        public override async Task <PriceCard> Run(PriceCardSnapshotArgument arg, CommercePipelineExecutionContext context)
        {
            Condition.Requires(arg).IsNotNull(Name + ": The argument can not be null");
            Condition.Requires(arg.PriceSnapshot).IsNotNull(Name + ": The price snapshot can not be null");
            Condition.Requires(arg.PriceSnapshot.BeginDate).IsNotNull(Name + ": The price snapshot begin date can not be null");
            Condition.Requires(arg.PriceCard).IsNotNull(Name + ": The price card can not be null");
            context.CommerceContext.AddUniqueObjectByType(arg);

            PriceCard card = arg.PriceCard;
            PriceSnapshotComponent snapshot = arg.PriceSnapshot;

            snapshot.SetComponent(new ApprovalComponent(context.GetPolicy <ApprovalStatusPolicy>().Draft, ""));
            PriceSnapshotComponent           snapshotComponent = card.Snapshots.OrderByDescending(s => s.BeginDate).FirstOrDefault(s => s.IsApproved(context.CommerceContext));
            CommercePipelineExecutionContext executionContext;

            if (snapshotComponent != null && snapshotComponent.BeginDate.CompareTo(snapshot.BeginDate) >= 0)
            {
                executionContext = context;
                CommerceContext commerceContext = context.CommerceContext;
                string          validationError = context.GetPolicy <KnownResultCodes>().ValidationError;
                string          commerceTermKey = "PriceSnapshotCannotBeAddedOrEdited";
                object[]        args            = new object[1]
                {
                    card.FriendlyId
                };
                string defaultMessage = "Price snapshot can not be added to/modified in price card " + card.FriendlyId + " because its begin date is not greater than existing snapshots.";
                executionContext.Abort(await commerceContext.AddMessage(validationError, commerceTermKey, args, defaultMessage), context);
                executionContext = null;
                return(card);
            }
            if (card.Snapshots.Any(s => DateTimeOffset.Compare(s.BeginDate, snapshot.BeginDate) == 0))
            {
                executionContext = context;
                CommerceContext commerceContext = context.CommerceContext;
                string          validationError = context.GetPolicy <KnownResultCodes>().ValidationError;
                string          commerceTermKey = "PriceSnapshotAlreadyExists";
                object[]        args            = new object[1]
                {
                    card.FriendlyId
                };
                string defaultMessage = "Price snapshot with specified date already exists for price card '" + card.FriendlyId + "'.";
                executionContext.Abort(await commerceContext.AddMessage(validationError, commerceTermKey, args, defaultMessage), context);
                executionContext = null;
                return(card);
            }

            snapshot.Id = Guid.NewGuid().ToString("N");
            card.Snapshots.Add(snapshot);
            PriceSnapshotAdded priceSnapshotAdded = new PriceSnapshotAdded(snapshot.Id);

            priceSnapshotAdded.Name = snapshot.Name;
            context.CommerceContext.AddModel(priceSnapshotAdded);
            return(card);
        }
        private async Task TransformD365Category(CommerceContext commerceContext, List <SellableItem> importItems, List <TransientImportSellableItemDataPolicy> transientDataList)
        {
            var d365Response = await commerceContext.GetPolicy <ConnectionPolicy>().GetCategories();

            var d365CategoriesLookup = (d365Response).ToLookup(c => c[CategoryDisplayNameIndex].ToString());
            var d365ProductCategoryAssignmentsLookup = (await commerceContext.GetPolicy <ConnectionPolicy>().GetProductCategoryAssignments()).ToLookup(a => a[ProductNumberIndex].ToString());

            var defaultCatalogName = d365Response.First()[CategoryCatalogName].ToString();

            foreach (var item in importItems)
            {
                var data = item.GetPolicy <TransientImportSellableItemDataPolicy>();

                var assignmentList = d365ProductCategoryAssignmentsLookup[item.ProductId];
                if (assignmentList != null && !assignmentList.Count().Equals(0))
                {
                    foreach (var assignment in assignmentList)
                    {
                        var categoryDisplayName = assignment[ProductCategoryDisplayNameIndex].ToString();
                        var d365CategoryList    = d365CategoriesLookup[categoryDisplayName];
                        if (d365CategoryList == null || d365CategoryList.Count().Equals(0))
                        {
                            throw new Exception($"Error, product with ID '{item.ProductId}' is a assigned to a category '{categoryDisplayName}' that can't be found.");
                        }

                        data.CategoryAssociationList.Add(new CategoryAssociationModel
                        {
                            CatalogName  = assignment[ProductCatalogNameIndex].ToString(),
                            CategoryName = d365CategoryList.First()[CategoryNameIndex].ToString()
                        });

                        Console.WriteLine($"Product Id '{item.ProductId}' associating to '{categoryDisplayName}'.");
                        await commerceContext.AddMessage(commerceContext.GetPolicy <KnownResultCodes>().Information, null, null, $"Product Id '{item.ProductId}' associating to '{categoryDisplayName}'.");
                    }

                    foreach (var catalogName in data.CategoryAssociationList.Select(a => a.CatalogName).Distinct())
                    {
                        data.CatalogAssociationList.Add(new CatalogAssociationModel {
                            Name = catalogName
                        });
                    }
                }
                else
                {
                    data.CatalogAssociationList.Add(new CatalogAssociationModel {
                        Name = defaultCatalogName
                    });
                }

                transientDataList.Add(data);
            }
        }
Exemple #10
0
        /// <summary>
        /// The execute.
        /// </summary>
        /// <param name="arg">
        /// The AddJobConnectionArgument argument.
        /// </param>
        /// <param name="context">
        /// The context.
        /// </param>
        /// <returns>
        /// The <see cref="JobConnection"/>.
        /// </returns>
        public override async Task <JobConnection> Run(AddJobConnectionArgument arg, CommercePipelineExecutionContext context)
        {
            Condition.Requires <AddJobConnectionArgument>(arg).IsNotNull <AddJobConnectionArgument>("AddJobConnectionArgument The argument cannot be null.");
            Condition.Requires <string>(arg.Name).IsNotNullOrEmpty("The Job Connection name cannot be null or empty.");
            Condition.Requires <string>(arg.Type).IsNotNullOrEmpty("The Job Connection type cannot be null or empty.");
            TaskAwaiter <bool> awaiter = _findEntityPipeline.Run(new FindEntityArgument(typeof(JobConnection),
                                                                                        $"{(object) CommerceEntity.IdPrefix<JobConnection>()}{ arg.Name}"), context).GetAwaiter();

            if (awaiter.GetResult())
            {
                CommerceContext commerceContext = context.CommerceContext;
                string          validationError = context.GetPolicy <KnownResultCodes>().ValidationError;
                string          commerceTermKey = "JobConnectionNameAlreadyInUse";
                object[]        args            = new object[1] {
                    (object)arg.Name
                };
                string defaultMessage = $"Job Connection name {(object) arg.Name} is already in use.";
                context.Abort("Ok|" + await commerceContext.AddMessage(validationError, commerceTermKey, args, defaultMessage), context);
                context = null;
                return(null);
            }
            JobConnection jobConnection = new JobConnection(arg.Name, arg.Type);

            jobConnection.Id          = $"{ CommerceEntity.IdPrefix<JobConnection>()}{ arg.Name}";
            jobConnection.FriendlyId  = $"{arg.Name}";;
            jobConnection.Description = arg.Description;;
            jobConnection.DisplayName = arg.DisplayName;
            var jobConnectionPolicy = context.GetPolicy <JobConnectionPolicy>();

            jobConnectionPolicy.DbConnectionString = arg.DbConnectionString;
            jobConnectionPolicy.WebServiceUrl      = arg.WebServiceUrl;
            jobConnectionPolicy.Username           = arg.Username;
            jobConnectionPolicy.Password           = arg.Password;
            jobConnection.SetPolicy(jobConnectionPolicy);
            jobConnection.SetComponent(new ListMembershipsComponent()
            {
                Memberships = new List <string>()
                {
                    CommerceEntity.ListName <JobConnection>()
                }
            });
            JobConnectionAdded jobConnectionAdded = new JobConnectionAdded(jobConnection.FriendlyId);

            jobConnectionAdded.Name = jobConnection.Name;
            context.CommerceContext.AddModel(jobConnectionAdded);
            return(jobConnection);
        }
        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);
        }
        /// <summary>
        /// Processes the specified commerce context.
        /// </summary>
        /// <param name="commerceContext">The commerce context.</param>
        /// <returns>
        /// Number of migrated customers
        /// </returns>
        public virtual async Task <int> Process(CommerceContext commerceContext)
        {
            using (CommandActivity.Start(commerceContext, this))
            {
                var context  = commerceContext.GetPipelineContextOptions();
                var listName = CommerceEntity.ListName <Customer>();

                var result = await this.Command <GetListMetadataCommand>().Process(commerceContext, listName);

                if (result == null)
                {
                    await commerceContext.AddMessage(
                        commerceContext.GetPolicy <KnownResultCodes>().Error,
                        "EntityNotFound",
                        new object[] { listName },
                        $"There is no customers in the list {listName}.");

                    return(0);
                }

                if (result.Count == 0)
                {
                    await context.CommerceContext.AddMessage(
                        context.CommerceContext.GetPolicy <KnownResultCodes>().Error,
                        "EntityNotFound",
                        new object[] { listName },
                        $"There is no customers in the list {listName}.");

                    return(0);
                }

                int customersCount = 0;
                int skip           = 0;
                int take           = 20;

                while (customersCount < result.Count)
                {
                    customersCount += await this.UpgradeCustomersInList(context, listName, skip, take);

                    skip += take;
                }

                return(customersCount);
            }
        }
        public async Task <ItemType> GetItem(CommerceContext commerceContext, string itemId)
        {
            using (var activity = CommandActivity.Start(commerceContext, this))
            {
                //Instantiate the call wrapper class
                var apiCall = new GetItemCall(await GetEbayContext(commerceContext).ConfigureAwait(false));

                try
                {
                    var result = apiCall.GetItem(itemId);
                    return(result);
                }
                catch (Exception ex)
                {
                    await commerceContext.AddMessage("Warn", "Ebay.GetItem.Exception", new Object[] { ex }, ex.Message).ConfigureAwait(false);
                }
                return(new ItemType());
            }
        }
        /// <summary>
        /// Returns true if ... is valid.
        /// </summary>
        /// <param name="commerceContext">The commerce context.</param>
        /// <returns>Returns true if ... is valid.</returns>
        public async Task <bool> IsValid(CommerceContext commerceContext)
        {
            if (!string.IsNullOrEmpty(this.Environment) &&
                !string.IsNullOrEmpty(this.MerchantId) &&
                !string.IsNullOrEmpty(this.PublicKey) &&
                !string.IsNullOrEmpty(this.PrivateKey))
            {
                return(true);
            }

            await commerceContext.AddMessage(
                commerceContext.GetPolicy <KnownResultCodes>().Error,
                "InvalidClientPolicy",
                null,
                "Invalid Braintree Client Policy")
            .ConfigureAwait(false);

            return(false);
        }
Exemple #15
0
        public override async Task <CartLineArgument> Run(CartLineArgument arg, CommercePipelineExecutionContext context)
        {
            string fulfillmentLocationCart = string.Empty;

            Condition.Requires(arg).IsNotNull("GetCartLineArticleInfoBlock: Cart can not be null");
            var currentSellableItem = context.CommerceContext.GetEntity <SellableItem>();
            var currentCartLineArg  = context.CommerceContext.GetObject <CartLineArgument>();

            Condition.Requires(currentSellableItem).IsNotNull("GetCartLineArticleInfoBlock: Sellable item can not be null");
            SellableItemService sellableItemService = new SellableItemService(_getSellableItemPipeline);
            string fulfillmentLocationItem          = sellableItemService.GetFulFilmmentLocationForItem(currentSellableItem);

            //get the current cart
            if (!string.IsNullOrEmpty(context.CommerceContext?.Headers["CustomerId"]))
            {
                string cartId = "Default" + context.CommerceContext?.Headers["CustomerId"] + context.CommerceContext.CurrentShopName();
                var    resolveCartArgument = new ResolveCartArgument(context.CommerceContext.CurrentShopName(),
                                                                     cartId,
                                                                     context.CommerceContext.CurrentShopperId());
                Cart cart = await this._getCartPipeline.Run(resolveCartArgument, context.CommerceContext.PipelineContextOptions);

                if (cart != null && cart.Lines != null && cart.Lines.Count > 0)
                {
                    fulfillmentLocationCart = await sellableItemService.GetFulFilmmentLocationForCartLines(cart.Lines, context);
                }

                CommercePipelineExecutionContext executionContext;
                if (cart.Lines.Count > 0 && fulfillmentLocationCart != fulfillmentLocationItem)
                {
                    executionContext = context;
                    CommerceContext commerceContext = context.CommerceContext;
                    string          error           = context.GetPolicy <KnownResultCodes>().Error;
                    object[]        args            = new object[1]
                    {
                        (object)currentSellableItem.DisplayName
                    };
                    string defaultMessage = "Item '" + currentSellableItem.DisplayName + "' is not purchasable.";
                    executionContext.Abort(await commerceContext.AddMessage(error, "AddCartFulfillmentErrorMessage", args, defaultMessage).ConfigureAwait(false), (object)context);
                    return((CartLineArgument)null);
                }
            }
            return(arg);
        }
        public override async Task <CommerceEnvironment> Run(string arg, CommercePipelineExecutionContext context)
        {
            CustomValidateEnvironmentJsonBlock environmentJsonBlock = this;

            Condition.Requires <string>(arg).IsNotNullOrEmpty(environmentJsonBlock.Name + ": The raw environment cannot be null or empty.");
            int num = 0;
            CommerceEnvironment commerceEnvironment = null;
            Exception           exception           = null;

            try
            {
                commerceEnvironment = JsonConvert.DeserializeObject <CommerceEnvironment>(arg, new JsonSerializerSettings()
                {
                    TypeNameHandling  = TypeNameHandling.Auto,
                    NullValueHandling = NullValueHandling.Ignore
                });
            }
            catch (Exception ex)
            {
                num       = 1;
                exception = ex;
            }
            if (num != 1)
            {
                return(commerceEnvironment);
            }

            CommercePipelineExecutionContext executionContext = context;
            CommerceContext commerceContext = context.CommerceContext;
            string          error           = context.GetPolicy <KnownResultCodes>().Error;
            string          commerceTermKey = "InvalidEnvironmentJson";

            object[] args = new object[1] {
                (object)exception
            };
            string defaultMessage = "Environment json is not valid.";

            executionContext.Abort(await commerceContext.AddMessage(error, commerceTermKey, args, defaultMessage).ConfigureAwait(false), (object)context);
            executionContext = null;
            return(null);
        }
        protected virtual async Task <CustomPriceTier> GetCustomPriceTier(CommerceContext context, PriceCard priceCard, PriceSnapshotComponent priceSnapshot, string priceTierId)
        {
            if (priceCard == null ||
                priceSnapshot == null ||
                string.IsNullOrEmpty(priceTierId))
            {
                return(null);
            }

            var membershipTiersComponent = priceSnapshot.GetComponent <MembershipTiersComponent>();
            var existingPriceTier        = membershipTiersComponent.Tiers.FirstOrDefault(t => t.Id.Equals(priceTierId, StringComparison.OrdinalIgnoreCase));

            if (existingPriceTier != null)
            {
                return(existingPriceTier);
            }

            await context.AddMessage(context.GetPolicy <KnownResultCodes>().ValidationError, "PriceTierNotFound",
                                     new object[] { priceTierId, priceSnapshot.Id, priceCard.FriendlyId }, "Price tier " + priceTierId + " was not found in snapshot " + priceSnapshot.Id + " for card " + priceCard.FriendlyId + ".")
            .ConfigureAwait(false);

            return(existingPriceTier);
        }
        public override async Task <SearchIndexArgument> Run(SearchIndexArgument arg, CommercePipelineExecutionContext context)
        {
            // ISSUE: explicit non-virtual call
            Condition.Requires(arg).IsNotNull($"{nameof(Name)}: argument cannot be null.");
            Index searchIndex = _command.GetSearchIndex(arg.IndexName, context.CommerceContext);

            context.CommerceContext.AddObject(CreateIndexView(searchIndex, arg.IndexName, context));

            if (searchIndex != null)
            {
                return(arg);
            }

            CommercePipelineExecutionContext executionContext = context;
            CommerceContext commerceContext = context.CommerceContext;

            string error           = context.GetPolicy <KnownResultCodes>().Error;
            string commerceTermKey = "EntityNotFound";
            string defaultMessage  = $"Entity '{arg.IndexName}' was not found.";

            executionContext.Abort(await commerceContext.AddMessage(error, commerceTermKey, new object[] { arg.IndexName }, defaultMessage), context);
            return(arg);
        }
        /// <summary>
        /// Migrates the entity.
        /// </summary>
        /// <param name="entity">The entity.</param>
        /// <param name="context">The context.</param>
        /// <returns>Upgraded entity json</returns>
        private async Task <string> MigrateEntity(string entity, CommerceContext context)
        {
            try
            {
                JObject jObject = null;
                using (var reader = new StringReader(entity))
                {
                    using (var jsonReader = new JsonTextReader(reader)
                    {
                        DateParseHandling = DateParseHandling.DateTimeOffset
                    })
                    {
                        while (jsonReader.Read())
                        {
                            if (jsonReader.TokenType == JsonToken.StartObject)
                            {
                                jObject = JObject.Load(jsonReader);
                                UpgradeObsoleteTokens(jObject, context);
                            }
                        }
                    }
                }

                return(JsonConvert.SerializeObject(jObject));
            }
            catch (Exception ex)
            {
                var mes = ex.Message;
                await context.AddMessage(
                    context.GetPolicy <KnownResultCodes>().Error,
                    "FailedToMigrateEnvironment",
                    new object[] { entity, ex },
                    $"Failed to migrate environment.");

                return(entity);
            }
        }
Exemple #20
0
        public async Task <JsonResponse> Put(CommerceContext commerceContext, string uri, JsonAction body)
        {
            var response = new JsonResponse {
                Uri = uri
            };

            using (CommandActivity.Start(commerceContext, this))
            {
                try
                {
                    using (var httpClient = new HttpClient())
                    {
                        var postResponse = await httpClient.PutAsJsonAsync(response.Uri, body);

                        response.Json = await postResponse.Content.ReadAsStringAsync();
                    }

                    var reader = new StringReader(response.Json);

                    response.Reader = new JsonTextReader(reader);
                }
                catch (Exception ex)
                {
                    await commerceContext.AddMessage(
                        commerceContext.GetPolicy <KnownResultCodes>().Error,
                        "FailedToDeserialize",
                        new object[] { ex },
                        $"GetProdPadCommand.Exception: Message={ex.Message}|Stack={ex.StackTrace}");

                    commerceContext.Logger.LogWarning($"Exception: {ex.Message}");

                    response = null;
                }
                return(response);
            }
        }
        /// <summary>
        /// Processes the specified commerce context.
        /// </summary>
        /// <param name="commerceContext">The commerce context.</param>
        /// <param name="sourceEnvironmentName">Name of the source environment.</param>
        /// <param name="newEnvironmentName">New name of the environment.</param>
        /// <param name="newArtifactStoreId">The new artifact store identifier.</param>
        /// <returns>
        /// User site terms
        /// </returns>
        public virtual async Task <bool> Process(CommerceContext commerceContext, string sourceEnvironmentName, string newEnvironmentName, Guid newArtifactStoreId)
        {
            using (CommandActivity.Start(commerceContext, this))
            {
                var migrationSqlPolicy = commerceContext.GetPolicy <MigrationSqlPolicy>();
                if (migrationSqlPolicy == null)
                {
                    await commerceContext.AddMessage(
                        commerceContext.GetPolicy <KnownResultCodes>().Error,
                        "InvalidOrMissingPropertyValue",
                        new object[] { "MigrationSqlPolicy" },
                        $"{this.GetType()}. Missing MigrationSqlPolicy");

                    return(false);
                }

                if (string.IsNullOrEmpty(migrationSqlPolicy.SourceStoreSqlPolicy.Server))
                {
                    await commerceContext.AddMessage(
                        commerceContext.GetPolicy <KnownResultCodes>().Error,
                        "InvalidOrMissingPropertyValue",
                        new object[] { "MigrationSqlPolicy" },
                        $"{this.GetType()}. Empty server name in the MigrationSqlPolicy");

                    return(false);
                }

                var migrationPolicy = commerceContext.GetPolicy <MigrationPolicy>();
                if (migrationPolicy == null)
                {
                    await commerceContext.AddMessage(
                        commerceContext.GetPolicy <KnownResultCodes>().Error,
                        "InvalidOrMissingPropertyValue",
                        new object[] { "MigrationPolicy" },
                        $"{this.GetType()}. Missing MigrationPolicy");

                    return(false);
                }

                Guid id;
                if (!Guid.TryParse(migrationSqlPolicy.ArtifactStoreId, out id))
                {
                    await commerceContext.AddMessage(
                        commerceContext.GetPolicy <KnownResultCodes>().Error,
                        "InvalidOrMissingPropertyValue",
                        new object[] { "MigrationSqlPolicy.ArtifactStoreId" },
                        "MigrationSqlPolicy. Invalid ArtifactStoreId");

                    return(false);
                }

                var context = commerceContext.GetPipelineContextOptions();

                var findArg    = new FindEntityArgument(typeof(CommerceEnvironment), $"{CommerceEntity.IdPrefix<CommerceEnvironment>()}{newEnvironmentName}");
                var findResult = await this._findEntityPipeline.Run(findArg, context);

                var newEnvironment = findResult as CommerceEnvironment;
                if (newEnvironment != null)
                {
                    await commerceContext.AddMessage(
                        commerceContext.GetPolicy <KnownResultCodes>().Error,
                        "InvalidOrMissingPropertyValue",
                        new object[] { newEnvironmentName },
                        $"Environment {newEnvironmentName} already exists.");

                    return(false);
                }

                findArg    = new FindEntityArgument(typeof(CommerceEnvironment), $"{CommerceEntity.IdPrefix<CommerceEnvironment>()}{migrationPolicy.DefaultEnvironmentName}");
                findResult = await this._findEntityPipeline.Run(findArg, context);

                var sourceEnvironment = findResult as CommerceEnvironment;
                if (sourceEnvironment == null)
                {
                    await commerceContext.AddMessage(
                        commerceContext.GetPolicy <KnownResultCodes>().Error,
                        "EntityNotFound",
                        new object[] { migrationPolicy.DefaultEnvironmentName },
                        $"Entity {migrationPolicy.DefaultEnvironmentName} was not found.");

                    return(false);
                }

                if (sourceEnvironment.HasPolicy <EntityShardingPolicy>())
                {
                    commerceContext.AddUniqueObjectByType(sourceEnvironment.GetPolicy <EntityShardingPolicy>());
                    sourceEnvironment.RemovePolicy(typeof(EntityShardingPolicy));
                }

                // set sql policies
                var sqlPoliciesCollection = new List <KeyValuePair <string, EntityStoreSqlPolicy> >
                {
                    new KeyValuePair <string, EntityStoreSqlPolicy>("SourceGlobal", migrationSqlPolicy.SourceStoreSqlPolicy)
                };

                // Get sql Policy set
                var ps = await this._findEntityPipeline.Run(new FindEntityArgument(typeof(PolicySet), $"{CommerceEntity.IdPrefix<PolicySet>()}{migrationPolicy.SqlPolicySetName}"), context);

                if (ps == null)
                {
                    context.CommerceContext.Logger.LogError($"PolicySet {migrationPolicy.SqlPolicySetName} was not found.");
                }
                else
                {
                    sqlPoliciesCollection.Add(new KeyValuePair <string, EntityStoreSqlPolicy>("DestinationShared", ps.GetPolicy <EntityStoreSqlPolicy>()));
                }

                commerceContext.AddUniqueObjectByType(sqlPoliciesCollection);

                sourceEnvironment.Name            = sourceEnvironmentName;
                sourceEnvironment.ArtifactStoreId = id;
                sourceEnvironment.Id = $"{CommerceEntity.IdPrefix<CommerceEnvironment>()}{sourceEnvironmentName}";
                sourceEnvironment.SetPolicy(migrationSqlPolicy.SourceStoreSqlPolicy);

                var migrateEnvironmentArgument = new MigrateEnvironmentArgument(sourceEnvironment, newArtifactStoreId, newEnvironmentName);

                var result = await this._migrateEnvironmentPipeline.Run(migrateEnvironmentArgument, context);

                return(result);
            }
        }
        public override async Task <EntityView> Run(EntityView arg, CommercePipelineExecutionContext context)
        {
            if (string.IsNullOrEmpty(arg?.Action) ||
                !arg.Action.Equals(context.GetPolicy <KnownCustomPricingActionsPolicy>().SelectMembershipCurrency, StringComparison.OrdinalIgnoreCase) ||
                !arg.Name.Equals(context.GetPolicy <KnownCustomPricingViewsPolicy>().PriceCustomRow, StringComparison.OrdinalIgnoreCase))
            {
                return(arg);
            }

            var card = context.CommerceContext.GetObjects <PriceCard>().FirstOrDefault(p => p.Id.Equals(arg.EntityId, StringComparison.OrdinalIgnoreCase));

            if (card == null)
            {
                return(arg);
            }

            KnownResultCodes policy = context.GetPolicy <KnownResultCodes>();

            if (string.IsNullOrEmpty(arg.ItemId))
            {
                await context.CommerceContext.AddMessage(policy.ValidationError, "InvalidOrMissingPropertyValue",
                                                         new object[] { "ItemId" }, "Invalid or missing value for property 'ItemId'.")
                .ConfigureAwait(false);

                return(arg);
            }

            PriceSnapshotComponent snapshot = card.Snapshots.FirstOrDefault(s => s.Id.Equals(arg.ItemId, StringComparison.OrdinalIgnoreCase));

            if (snapshot == null)
            {
                await context.CommerceContext.AddMessage(policy.ValidationError, "PriceSnapshotNotFound",
                                                         new object[] { arg.ItemId, card.FriendlyId }, "Price snapshot " + arg.ItemId + " on price card " + card.FriendlyId + " was not found.")
                .ConfigureAwait(false);

                return(arg);
            }

            var currencyProperty = arg.Properties.FirstOrDefault(p => p.Name.Equals("Currency", StringComparison.OrdinalIgnoreCase));

            string currency = currencyProperty?.Value;

            if (string.IsNullOrEmpty(currency))
            {
                await context.CommerceContext.AddMessage(policy.ValidationError, "InvalidOrMissingPropertyValue",
                                                         new object[] { currencyProperty == null ? "Currency" : currencyProperty.DisplayName }, "Invalid or missing value for property 'Currency'.")
                .ConfigureAwait(false);

                return(arg);
            }

            if (snapshot.Tiers.Any(t => t.Currency.Equals(currency, StringComparison.OrdinalIgnoreCase)))
            {
                await context.CommerceContext.AddMessage(policy.ValidationError, "CurrencyAlreadyExists",
                                                         new object[] { currency, snapshot.Id, card.FriendlyId }, "Currency " + currency + " already exists for snapshot " + snapshot.Id + " on price card " + card.FriendlyId + ".")
                .ConfigureAwait(false);

                return(arg);
            }

            CurrencySet currencySet  = null;
            string      entityTarget = (await _findEntityCommand.Process(context.CommerceContext, typeof(PriceBook), card.Book.EntityTarget, false).ConfigureAwait(false) as PriceBook)?.CurrencySet.EntityTarget;

            if (!string.IsNullOrEmpty(entityTarget))
            {
                currencySet = await _getCurrencySetCommand.Process(context.CommerceContext, entityTarget).ConfigureAwait(false);

                if (currencySet != null)
                {
                    var    currencies = currencySet.GetComponent <CurrenciesComponent>().Currencies;
                    string str        = string.Join(", ", currencies.Select(c => c.Code));

                    if (!currencies.Any(c => c.Code.Equals(currency, StringComparison.OrdinalIgnoreCase)))
                    {
                        CommercePipelineExecutionContext executionContext = context;
                        CommerceContext commerceContext = context.CommerceContext;
                        string          validationError = context.GetPolicy <KnownResultCodes>().ValidationError;
                        string          commerceTermKey = "InvalidCurrency";
                        var             args            = new object[] { currency, str };
                        string          defaultMessage  = "Invalid currency '" + currency + "'. Valid currencies are '" + str + "'.";
                        executionContext.Abort(await commerceContext.AddMessage(validationError, commerceTermKey, args, defaultMessage).ConfigureAwait(false), context);
                        executionContext = null;

                        return(arg);
                    }
                }
            }

            currencyProperty.IsReadOnly = true;
            currencyProperty.Policies   = new List <Policy>()
            {
                new AvailableSelectionsPolicy(currencySet == null ||
                                              !currencySet.HasComponent <CurrenciesComponent>() ?  new List <Selection>() :  currencySet.GetComponent <CurrenciesComponent>()
                                              .Currencies.Select(c =>
                {
                    return(new Selection()
                    {
                        DisplayName = c.Code,
                        Name = c.Code
                    });
                }).ToList(), false)
            };

            EntityView priceCustomCellEntityView = new EntityView
            {
                Name     = context.GetPolicy <KnownCustomPricingViewsPolicy>().PriceCustomCell,
                EntityId = card.Id,
                ItemId   = snapshot.Id
            };

            var membershipLevels        = context.GetPolicy <MembershipLevelPolicy>().MembershipLevels;
            List <Selection> selections = currencySet == null || !currencySet.HasComponent <CurrenciesComponent>() ? new List <Selection>() : membershipLevels.Select(c =>
            {
                return(new Selection()
                {
                    DisplayName = c.MemerbshipLevelName,
                    Name = c.MemerbshipLevelName
                });
            }).ToList();

            AvailableSelectionsPolicy availableSelectionsPolicy = new AvailableSelectionsPolicy(selections, false);

            List <Policy> commercePolicies = new List <Policy>()
            {
                availableSelectionsPolicy
            };

            ViewProperty membershipLevelViewProperty = new ViewProperty()
            {
                Name         = "MembershipLevel",
                OriginalType = typeof(string).FullName,
                Policies     = commercePolicies
            };

            priceCustomCellEntityView.Properties.Add(membershipLevelViewProperty);

            ViewProperty quantityViewProperty = new ViewProperty();

            quantityViewProperty.Name         = "Quantity";
            quantityViewProperty.OriginalType = typeof(decimal).FullName;
            priceCustomCellEntityView.Properties.Add(quantityViewProperty);

            ViewProperty priceViewProperty = new ViewProperty
            {
                Name         = "Price",
                RawValue     = null,
                OriginalType = typeof(decimal).FullName
            };

            priceCustomCellEntityView.Properties.Add(priceViewProperty);
            arg.ChildViews.Add(priceCustomCellEntityView);
            arg.UiHint = "Grid";
            context.CommerceContext.AddModel(new MultiStepActionModel(context.GetPolicy <KnownCustomPricingActionsPolicy>().AddMembershipCurrency));

            return(arg);
        }
Exemple #23
0
        public override async Task <bool> Run(bool arg, CommercePipelineExecutionContext context)
        {
            SetApprovalStatusArgument argument = context.CommerceContext.GetObject <SetApprovalStatusArgument>();

            if (!(argument?.Entity is PriceCard) || string.IsNullOrEmpty(argument.Status) || string.IsNullOrEmpty(argument.ItemId))
            {
                return(arg);
            }

            PriceCard entity = (PriceCard)argument.Entity;
            PriceSnapshotComponent           snapshot = entity.Snapshots.FirstOrDefault(s => s.Id.Equals(argument.ItemId, StringComparison.OrdinalIgnoreCase));
            CommercePipelineExecutionContext executionContext;

            if (snapshot == null)
            {
                executionContext = context;
                CommerceContext commerceContext = context.CommerceContext;
                string          validationError = context.GetPolicy <KnownResultCodes>().ValidationError;
                string          commerceTermKey = "PriceSnapshotNotFound";
                object[]        args            = new object[2]
                {
                    argument.ItemId,
                    entity.FriendlyId
                };
                string defaultMessage = "Price snapshot '" + argument.ItemId + "' on price card '" + entity.FriendlyId + "' was not found.";
                executionContext.Abort(await commerceContext.AddMessage(validationError, commerceTermKey, args, defaultMessage), context);
                executionContext = null;

                return(false);
            }

            var membershipTiersComponent = snapshot.GetComponent <MembershipTiersComponent>();

            if (!snapshot.Tiers.Any() && !membershipTiersComponent.Tiers.Any())
            {
                executionContext = context;
                CommerceContext commerceContext = context.CommerceContext;
                string          validationError = context.GetPolicy <KnownResultCodes>().ValidationError;
                string          commerceTermKey = "InvalidPriceSnapshot";
                object[]        args            = new object[2]
                {
                    argument.ItemId,
                    entity.FriendlyId
                };
                string defaultMessage = "Price snapshot '" + argument.ItemId + "' on price card '" + entity.FriendlyId + "' has not pricing.";
                executionContext.Abort(await commerceContext.AddMessage(validationError, commerceTermKey, args, defaultMessage), context);
                executionContext = null;
                return(false);
            }

            string currentStatus         = snapshot.GetComponent <ApprovalComponent>().Status;
            IEnumerable <string> strings = await _getPossibleStatusesPipeline.Run(new GetPossibleApprovalStatusesArgument(snapshot), context);

            if (strings == null || !strings.Any())
            {
                return(false);
            }

            if (!strings.Any(s => s.Equals(argument.Status, StringComparison.OrdinalIgnoreCase)))
            {
                string str = string.Join(",", strings);
                executionContext = context;
                CommerceContext commerceContext = context.CommerceContext;
                string          error           = context.GetPolicy <KnownResultCodes>().Error;
                string          commerceTermKey = "SetStatusFailed";
                object[]        args            = new object[4]
                {
                    snapshot.Id,
                    argument.Status,
                    str,
                    currentStatus
                };
                string defaultMessage = "Attempted to change status for '" + snapshot.Id + "' to '" + argument.Status + "'. Allowed status are '" + str + "' when current status is '" + currentStatus + "'.";
                executionContext.Abort(await commerceContext.AddMessage(error, commerceTermKey, args, defaultMessage), context);
                executionContext = null;
                return(false);
            }

            snapshot.GetComponent <ApprovalComponent>().ModifyStatus(argument.Status, argument.Comment);
            await context.CommerceContext.AddMessage(context.GetPolicy <KnownResultCodes>().Information, null, null, "Price snapshot '" + snapshot.Id + "' approval status has been updated.");

            return(true);
        }
Exemple #24
0
        public override async Task <PriceCard> Run(PriceCard arg, CommercePipelineExecutionContext context)
        {
            Condition.Requires(arg).IsNotNull(Name + ": The price card can not be null");
            PriceCard card = arg;
            PriceCardSnapshotCustomTierArgument argument = context.CommerceContext.GetObjects <PriceCardSnapshotCustomTierArgument>().FirstOrDefault();
            CommercePipelineExecutionContext    executionContext;

            if (argument == null)
            {
                executionContext = context;
                var    commerceContext = context.CommerceContext;
                string error           = context.GetPolicy <KnownResultCodes>().Error;
                string defaultMessage  = "Argument of type " + typeof(PriceCardSnapshotCustomTierArgument).Name + " was not found in context.";
                executionContext.Abort(await commerceContext.AddMessage(error, "ArgumentNotFound", new object[] { typeof(PriceCardSnapshotCustomTierArgument).Name }, defaultMessage)
                                       .ConfigureAwait(false), context);
                executionContext = null;

                return(card);
            }

            Condition.Requires(argument.PriceSnapshot).IsNotNull(Name + ": The price snapshot cannot be null.");
            Condition.Requires(argument.PriceSnapshot.Id).IsNotNullOrEmpty(Name + ": The price snapshot id cannot be null or empty.");
            Condition.Requires(argument.PriceTier).IsNotNull(Name + ": The price tier cannot be null.");
            Condition.Requires(argument.PriceTier.Currency).IsNotNullOrEmpty(Name + ": The price tier currency cannot be null or empty.");
            Condition.Requires(argument.PriceTier.Quantity).IsNotNull(Name + ": The price tier quantity cannot be null.");
            Condition.Requires(argument.PriceTier.Price).IsNotNull(Name + ": The price tier price cannot be null.");

            var snapshot = argument.PriceSnapshot;
            var tier     = argument.PriceTier;
            var membershipTiersComponent = snapshot.GetComponent <MembershipTiersComponent>();

            if (membershipTiersComponent.Tiers.Any(x => x.Currency == tier.Currency && x.MembershipLevel == tier.MembershipLevel && x.Quantity == tier.Quantity))
            {
                executionContext = context;
                CommerceContext commerceContext = context.CommerceContext;
                string          validationError = context.GetPolicy <KnownResultCodes>().ValidationError;
                string          defaultMessage  = "A tier for specified Currency, Membership Level and Quantity already exists for price snapshot '" + snapshot.Id + "' in price card '" + card.FriendlyId + "'.";
                executionContext.Abort(await commerceContext.AddMessage(validationError, "PriceTierAlreadyExists", new object[] { snapshot.Id, card.FriendlyId }, defaultMessage)
                                       .ConfigureAwait(false), context);
                executionContext = null;

                return(card);
            }

            GlobalPricingPolicy policy = context.GetPolicy <GlobalPricingPolicy>();

            if (argument.PriceTier.Quantity <= policy.MinimumPricingQuantity)
            {
                executionContext = context;
                CommerceContext commerceContext = context.CommerceContext;
                string          error           = context.GetPolicy <KnownResultCodes>().Error;
                string          defaultMessage  = string.Format("Invalid quantity. Quantity must be greater than '{0}'.", policy.MinimumPricingQuantity);
                executionContext.Abort(await commerceContext.AddMessage(error, "InvalidQuantity", new object[] { policy.MinimumPricingQuantity }, defaultMessage)
                                       .ConfigureAwait(false), context);
                executionContext = null;

                return(card);
            }

            if (argument.PriceTier.Price < policy.MinimumPrice)
            {
                executionContext = context;
                CommerceContext commerceContext = context.CommerceContext;
                string          error           = context.GetPolicy <KnownResultCodes>().Error;
                string          defaultMessage  = string.Format("Invalid price. Minimum price allowed is '{0}'.", policy.MinimumPrice);
                executionContext.Abort(await commerceContext.AddMessage(error, "InvalidPrice", new object[] { policy.MinimumPrice }, defaultMessage)
                                       .ConfigureAwait(false), context);
                executionContext = null;

                return(card);
            }

            PriceBook priceBook = await _findEntityPipeline.Run(new FindEntityArgument(typeof(PriceBook), card.Book.EntityTarget, false), context)
                                  .ConfigureAwait(false) as PriceBook;

            CurrencySet currencySet = await _getCurrencySetPipeline.Run(priceBook?.CurrencySet?.EntityTarget, context)
                                      .ConfigureAwait(false);

            bool   flag = false;
            string str  = string.Empty;

            if (currencySet != null && currencySet.HasComponent <CurrenciesComponent>())
            {
                CurrenciesComponent component = currencySet.GetComponent <CurrenciesComponent>();
                str = string.Join(", ", component.Currencies.Select(c => c.Code));
                if (component.Currencies.Any(c => c.Code.Equals(argument.PriceTier.Currency, StringComparison.OrdinalIgnoreCase)))
                {
                    flag = true;
                }
            }

            if (!flag)
            {
                executionContext = context;
                CommerceContext commerceContext = context.CommerceContext;
                string          validationError = context.GetPolicy <KnownResultCodes>().ValidationError;
                string          defaultMessage  = "Invalid currency '" + argument.PriceTier.Currency + "'. Valid currencies are '" + str + "'.";
                executionContext.Abort(await commerceContext.AddMessage(validationError, "InvalidCurrency", new object[] { argument.PriceTier.Currency, str }, defaultMessage)
                                       .ConfigureAwait(false), context);
                executionContext = null;

                return(card);
            }

            tier.Id = Guid.NewGuid().ToString("N", CultureInfo.InvariantCulture);
            PriceSnapshotComponent snapshotComponent = card.Snapshots.FirstOrDefault(n => n.Id.Equals(snapshot.Id, StringComparison.OrdinalIgnoreCase));

            if (snapshotComponent != null)
            {
                var component = snapshotComponent.GetComponent <MembershipTiersComponent>();
                if (component != null)
                {
                    component.Tiers.Add(tier);
                }
            }

            PriceTierAdded priceTierAdded = new PriceTierAdded(tier.Id)
            {
                Name = tier.Name
            };

            context.CommerceContext.AddModel(priceTierAdded);

            return(card);
        }
Exemple #25
0
        public override async Task <bool> Run(SellableItemInventorySetsArgument argument, CommercePipelineExecutionContext context)
        {
            AssociateStoreInventoryToSellablteItemBlock associateStoreInventoryToSellablteItemBlock = this;

            Condition.Requires(argument).IsNotNull(string.Format("{0}: The argument can not be null", argument));

            string         sellableItemId = argument.SellableItemId;
            CommerceEntity entity         = await associateStoreInventoryToSellablteItemBlock._findEntityPipeline.Run(new FindEntityArgument(typeof(SellableItem), sellableItemId, false), context).ConfigureAwait(false);

            CommercePipelineExecutionContext executionContext;

            if (!(entity is SellableItem))
            {
                executionContext = context;
                CommerceContext commerceContext = context.CommerceContext;
                string          validationError = context.GetPolicy <KnownResultCodes>().ValidationError;
                string          commerceTermKey = "EntityNotFound";
                object[]        args            = new object[1]
                {
                    argument.SellableItemId
                };
                string defaultMessage = string.Format("Entity {0} was not found.", argument.SellableItemId);
                executionContext.Abort(await commerceContext.AddMessage(validationError, commerceTermKey, args, defaultMessage).ConfigureAwait(false), context);
                executionContext = null;
                return(false);
            }

            SellableItem sellableItem = entity as SellableItem;

            if ((string.IsNullOrEmpty(argument.VariationId)) & sellableItem.HasComponent <ItemVariationsComponent>())
            {
                executionContext = context;
                executionContext.Abort(await context.CommerceContext.AddMessage(context.GetPolicy <KnownResultCodes>().ValidationError, "AssociateInventoryWithVariant", new object[0], "Can not associate inventory to the base sellable item. Use one of the variants instead.").ConfigureAwait(false), context);
                executionContext = null;
                return(false);
            }

            ItemVariationComponent sellableItemVariation = null;

            if (argument.VariationId != null)
            {
                sellableItemVariation = sellableItem.GetVariation(argument.VariationId);
                if (!string.IsNullOrEmpty(argument.VariationId) && sellableItemVariation == null)
                {
                    executionContext = context;
                    CommerceContext commerceContext = context.CommerceContext;
                    string          validationError = context.GetPolicy <KnownResultCodes>().ValidationError;
                    string          commerceTermKey = "ItemNotFound";
                    object[]        args            = new object[1]
                    {
                        argument.VariationId
                    };
                    string defaultMessage = string.Format("Item '{0}' was not found.", argument.VariationId);
                    executionContext.Abort(await commerceContext.AddMessage(validationError, commerceTermKey, args, defaultMessage).ConfigureAwait(false), context);
                    executionContext = null;
                    return(false);
                }
            }

            List <InventoryAssociation> inventoryAssociations = new List <InventoryAssociation>();

            foreach (var inventorySetId in argument.InventorySetIds)
            {
                bool   isUpdate = false;
                Random rnd      = new Random();
                InventoryInformation inventoryInformation = await associateStoreInventoryToSellablteItemBlock._getInventoryInformationCommand
                                                            .Process(context.CommerceContext, inventorySetId, argument.SellableItemId, argument.VariationId, false)
                                                            .ConfigureAwait(false);

                IFindEntitiesInListPipeline entitiesInListPipeline  = associateStoreInventoryToSellablteItemBlock._findEntitiesInListPipeline;
                FindEntitiesInListArgument  entitiesInListArgument1 = new FindEntitiesInListArgument(typeof(SellableItem), string.Format("{0}-{1}", "InventorySetToInventoryInformation", inventorySetId.SimplifyEntityName()), 0, int.MaxValue);
                entitiesInListArgument1.LoadEntities = false;
                CommercePipelineExecutionContext context1 = context;
                FindEntitiesInListArgument       entitiesInListArgument2 = await entitiesInListPipeline.Run(entitiesInListArgument1, context1).ConfigureAwait(false);

                if (inventoryInformation != null && entitiesInListArgument2 != null)
                {
                    List <ListEntityReference> entityReferences = entitiesInListArgument2.EntityReferences.ToList();
                    string id = inventoryInformation.Id;

                    if (entityReferences != null && entityReferences.Any(er => er.EntityId == id))
                    {
                        inventoryInformation.Quantity = rnd.Next(50);
                        isUpdate = true;
                    }
                }

                if (!isUpdate)
                {
                    string inventorySetName = string.Format("{0}-{1}", inventorySetId.SimplifyEntityName(), sellableItem.ProductId);
                    if (!string.IsNullOrEmpty(argument.VariationId))
                    {
                        inventorySetName += string.Format("-{0}", argument.VariationId);
                    }

                    InventoryInformation inventoryInformation1 = new InventoryInformation();
                    inventoryInformation1.Id = string.Format("{0}{1}", CommerceEntity.IdPrefix <InventoryInformation>(), inventorySetName);

                    inventoryInformation1.FriendlyId = inventorySetName;
                    EntityReference entityReference1 = new EntityReference(inventorySetId, "");
                    inventoryInformation1.InventorySet = entityReference1;
                    EntityReference entityReference2 = new EntityReference(argument.SellableItemId, "");
                    inventoryInformation1.SellableItem = entityReference2;
                    string variationId = argument.VariationId;
                    inventoryInformation1.VariationId = variationId;
                    inventoryInformation1.Quantity    = rnd.Next(50);
                    inventoryInformation = inventoryInformation1;
                }

                inventoryInformation.GetComponent <TransientListMembershipsComponent>().Memberships.Add(CommerceEntity.ListName <InventoryInformation>());
                PersistEntityArgument persistEntityArgument1 = await associateStoreInventoryToSellablteItemBlock._persistEntityPipeline.Run(new PersistEntityArgument((CommerceEntity)inventoryInformation), context).ConfigureAwait(false);

                RelationshipArgument relationshipArgument = await associateStoreInventoryToSellablteItemBlock._createRelationshipPipeline.Run(new RelationshipArgument(inventorySetId, inventoryInformation.Id, "InventorySetToInventoryInformation"), context).ConfigureAwait(false);

                InventoryAssociation inventoryAssociation = new InventoryAssociation()
                {
                    InventoryInformation = new EntityReference(inventoryInformation.Id, ""),
                    InventorySet         = new EntityReference(inventorySetId, "")
                };

                inventoryAssociations.Add(inventoryAssociation);
            }

            (sellableItemVariation != null ? sellableItemVariation.GetComponent <InventoryComponent>() : sellableItem.GetComponent <InventoryComponent>()).InventoryAssociations.AddRange(inventoryAssociations);

            PersistEntityArgument persistEntityArgument2 = await associateStoreInventoryToSellablteItemBlock._persistEntityPipeline.Run(new PersistEntityArgument(sellableItem), context).ConfigureAwait(false);

            return(true);
        }
        public async Task <bool> EndItemListing(CommerceContext commerceContext, SellableItem sellableItem, string reason)
        {
            using (var activity = CommandActivity.Start(commerceContext, this))
            {
                //Instantiate the call wrapper class

                try
                {
                    var apiCall = new EndItemCall(await GetEbayContext(commerceContext));

                    if (sellableItem.HasComponent <EbayItemComponent>())
                    {
                        var ebayItemComponent = sellableItem.GetComponent <EbayItemComponent>();

                        var reasonCodeType = EndReasonCodeType.NotAvailable;

                        switch (reason)
                        {
                        case "NotAvailable":
                            reasonCodeType = EndReasonCodeType.NotAvailable;
                            break;

                        case "CustomCode":
                            reasonCodeType = EndReasonCodeType.CustomCode;
                            break;

                        case "Incorrect":
                            reasonCodeType = EndReasonCodeType.Incorrect;
                            break;

                        case "LostOrBroken":
                            reasonCodeType = EndReasonCodeType.LostOrBroken;
                            break;

                        case "OtherListingError":
                            reasonCodeType = EndReasonCodeType.OtherListingError;
                            break;

                        case "SellToHighBidder":
                            reasonCodeType = EndReasonCodeType.SellToHighBidder;
                            break;

                        case "Sold":
                            reasonCodeType = EndReasonCodeType.Sold;
                            break;

                        default:
                            reasonCodeType = EndReasonCodeType.CustomCode;
                            break;
                        }

                        if (string.IsNullOrEmpty(ebayItemComponent.EbayId))
                        {
                            ebayItemComponent.Status = "LostSync";
                        }
                        else
                        {
                            if (ebayItemComponent.Status != "Ended")
                            {
                                //Call Ebay and End the Item Listing
                                try
                                {
                                    apiCall.EndItem(ebayItemComponent.EbayId, reasonCodeType);
                                    ebayItemComponent.Status = "Ended";
                                }
                                catch (Exception ex)
                                {
                                    if (ex.Message == "The auction has already been closed.")
                                    {
                                        //Capture a case where the listing has expired naturally and it can now no longer be ended.
                                        reason = "Expired";
                                        ebayItemComponent.Status = "Ended";
                                    }
                                    else
                                    {
                                        commerceContext.Logger.LogError(ex, $"EbayCommand.EndItemListing.Exception: Message={ex.Message}");
                                        await commerceContext.AddMessage("Error", "EbayCommand.EndItemListing", new [] { ex }, ex.Message).ConfigureAwait(false);
                                    }
                                }
                            }
                        }

                        ebayItemComponent.ReasonEnded = reason;

                        ebayItemComponent.History.Add(new HistoryEntryModel {
                            EventMessage = "Listing Ended", EventUser = commerceContext.CurrentCsrId()
                        });

                        sellableItem.GetComponent <TransientListMembershipsComponent>().Memberships.Add("Ebay_Ended");

                        var persistResult = await this._commerceCommander.PersistEntity(commerceContext, sellableItem).ConfigureAwait(false);

                        var listRemoveResult = await this._commerceCommander.Command <ListCommander>()
                                               .RemoveItemsFromList(commerceContext, "Ebay_Listed", new List <String>()
                        {
                            sellableItem.Id
                        }).ConfigureAwait(false);
                    }
                }
                catch (Exception ex)
                {
                    commerceContext.Logger.LogError($"Ebay.EndItemListing.Exception: Message={ex.Message}");
                    await commerceContext.AddMessage("Error", "Ebay.EndItemListing.Exception", new Object[] { ex }, ex.Message).ConfigureAwait(false);
                }

                return(true);
            }
        }
        public override async Task <Order> Run(OfflineStoreOrderArgument arg, CommercePipelineExecutionContext context)
        {
            CreateOfflineOrderBlock createOrderBlock = this;

            Condition.Requires(arg).IsNotNull($"{createOrderBlock.Name}: arg can not be null");

            CommercePipelineExecutionContext executionContext;

            if (string.IsNullOrEmpty(arg.Email))
            {
                executionContext = context;
                executionContext.Abort(await context.CommerceContext.AddMessage(context.GetPolicy <KnownResultCodes>().Error, "EmailIsRequired", new object[1], "Can not create order, email address is required.").ConfigureAwait(false), context);
                executionContext = null;
                return(null);
            }

            if (!arg.Lines.Any())
            {
                executionContext = context;
                CommerceContext commerceContext = context.CommerceContext;
                string          error           = context.GetPolicy <KnownResultCodes>().Error;
                string          commerceTermKey = "OrderHasNoLines";
                string          defaultMessage  = "Can not create order, cart  has no lines";
                executionContext.Abort(await commerceContext.AddMessage(error, commerceTermKey, null, defaultMessage).ConfigureAwait(false), context);
                executionContext = null;
                return(null);
            }

            // Find contact using email
            string           email            = arg.Email;
            ContactComponent contactComponent = new ContactComponent();
            EntityIndex      entityIndex      = await createOrderBlock._findEntityPipeline
                                                .Run(new FindEntityArgument(typeof(EntityIndex), string.Format("{0}{1}\\{2}", EntityIndex.IndexPrefix <Customer>("Id"), arg.Domain, arg.Email)), context)
                                                .ConfigureAwait(false)
                                                as EntityIndex;

            if (entityIndex != null)
            {
                var      customerEntityId = entityIndex.EntityId;
                Customer entityCustomer   = await createOrderBlock._findEntityPipeline
                                            .Run(new FindEntityArgument(typeof(Customer), customerEntityId), context)
                                            .ConfigureAwait(false)
                                            as Customer;

                if (entityCustomer != null)
                {
                    contactComponent.IsRegistered = true;
                    contactComponent.CustomerId   = entityCustomer.Id;
                    contactComponent.ShopperId    = entityCustomer.Id;
                    contactComponent.Name         = entityCustomer.Name;
                }
            }

            contactComponent.Email = email;
            KnownOrderListsPolicy policy1 = context.GetPolicy <KnownOrderListsPolicy>();
            string orderId    = string.Format("{0}{1:N}", CommerceEntity.IdPrefix <Order>(), Guid.NewGuid());
            Order  storeOrder = new Order();

            storeOrder.Components = new List <Component>();
            storeOrder.Id         = orderId;

            Totals totals = new Totals()
            {
                GrandTotal       = new Money(arg.CurrencyCode, arg.GrandTotal),
                SubTotal         = new Money(arg.CurrencyCode, arg.SubTotal),
                AdjustmentsTotal = new Money(arg.CurrencyCode, arg.Discount),
                PaymentsTotal    = new Money(arg.CurrencyCode, arg.GrandTotal)
            };

            storeOrder.Totals = totals;
            IList <CartLineComponent> lines = new List <CartLineComponent>();

            foreach (var line in arg.Lines)
            {
                var            items  = line.ItemId.Split('|');
                CommerceEntity entity = await createOrderBlock._findEntityPipeline
                                        .Run(new FindEntityArgument(typeof(SellableItem), "Entity-SellableItem-" + (items.Count() > 2 ? items[1] : line.ItemId), false), context)
                                        .ConfigureAwait(false);

                CartLineComponent lineComponent = new CartLineComponent
                {
                    ItemId   = line.ItemId,
                    Quantity = line.Quantity,
                    Totals   = new Totals()
                    {
                        SubTotal = new Money(arg.CurrencyCode, line.SubTotal), GrandTotal = new Money(arg.CurrencyCode, line.SubTotal)
                    },
                    UnitListPrice = new Money()
                    {
                        CurrencyCode = arg.CurrencyCode, Amount = line.UnitListPrice
                    },
                    Id = Guid.NewGuid().ToString("N"),
                    //Policies = new List<Policy>() //todo: determine if this is required
                };
                lineComponent.Policies.Add(new PurchaseOptionMoneyPolicy()
                {
                    PolicyId = "c24f0ed4f2f1449b8a488403b6bf368a", SellPrice = new Money()
                    {
                        CurrencyCode = arg.CurrencyCode, Amount = line.SubTotal
                    }
                });

                if (entity is SellableItem)
                {
                    SellableItem sellableItem = entity as SellableItem;
                    lineComponent.ChildComponents.Add(new CartProductComponent()
                    {
                        DisplayName = line.ProductName,
                        Id          = items.Count() > 2 ? items[1] : line.ItemId,
                        Image       = new Image()
                        {
                            ImageName  = line.ProductName,
                            AltText    = line.ProductName,
                            Height     = 50, Width = 50,
                            SitecoreId = sellableItem.GetComponent <ImagesComponent>().Images.FirstOrDefault()
                        }
                    });
                }
                // if it has a variant

                if (items.Count() > 2)
                {
                    // Set VariantionId
                    lineComponent.ChildComponents.Add(new ItemVariationSelectedComponent()
                    {
                        VariationId = items[2]
                    });
                }

                lines.Add(lineComponent);
            }

            storeOrder.Lines = lines;


            IList <AwardedAdjustment> adjustments = new List <AwardedAdjustment>();

            if (arg.Discount > 0)
            {
                var discountAdjustment = new CartLevelAwardedAdjustment
                {
                    AdjustmentType      = "Discount",
                    Adjustment          = new Money(arg.CurrencyCode, -arg.Discount),
                    IsTaxable           = false,
                    IncludeInGrandTotal = true,
                    Name          = "Discount",
                    AwardingBlock = "In Store Discount"
                };
                adjustments.Add(discountAdjustment);
            }

            if (arg.TaxTotal > 0)
            {
                var taxAdjustment = new CartLevelAwardedAdjustment
                {
                    AdjustmentType      = "Tax",
                    Adjustment          = new Money(arg.CurrencyCode, arg.TaxTotal),
                    IsTaxable           = false,
                    IncludeInGrandTotal = true,
                    Name          = "TaxFee",
                    AwardingBlock = "Tax:block:calculatecarttax"
                };
                adjustments.Add(taxAdjustment);
            }

            storeOrder.Adjustments = adjustments;

            // Payment
            FederatedPaymentComponent paymentComponent = new FederatedPaymentComponent(new Money(arg.CurrencyCode, arg.GrandTotal))
            {
                PaymentInstrumentType = arg.PaymentInstrumentType,
                CardType          = arg.CardType,
                ExpiresMonth      = arg.ExpiresMonth,
                ExpiresYear       = arg.ExpiresYear,
                TransactionId     = arg.TransactionId,
                TransactionStatus = arg.TransactionStatus,
                MaskedNumber      = arg.MaskedNumber,
                Amount            = new Money(arg.CurrencyCode, arg.GrandTotal),
                Comments          = "Store Payment",
                PaymentMethod     = new EntityReference("Card", new Guid().ToString()),
                BillingParty      = new Party(),
                Name = "Store Payment"
            };

            storeOrder.Components.Add(paymentComponent);


            // Fulfillment
            PhysicalFulfillmentComponent physicalFulfillmentComponent = new PhysicalFulfillmentComponent
            {
                //ShippingParty = new Party() { AddressName = arg.StoreDetails.Name, Address1 = arg.StoreDetails.Address, City = arg.StoreDetails.City, State = arg.StoreDetails.State,
                //                              StateCode = arg.StoreDetails.State, Country =arg.StoreDetails.Country, CountryCode = arg.StoreDetails.Country, ZipPostalCode = arg.StoreDetails.ZipCode.ToString(), ExternalId = "0" },
                FulfillmentMethod = new EntityReference()
                {
                    Name = "Offline Store Order By Customer", EntityTarget = "b146622d-dc86-48a3-b72a-05ee8ffd187a"
                }
            };


            var shippingParty = new FakeParty()
            {
                AddressName   = arg.StoreDetails.Name,
                Address1      = arg.StoreDetails.Address,
                City          = arg.StoreDetails.City,
                State         = arg.StoreDetails.State,
                StateCode     = arg.StoreDetails.State,
                Country       = arg.StoreDetails.Country,
                CountryCode   = arg.StoreDetails.Country,
                ZipPostalCode = arg.StoreDetails.ZipCode.ToString(),
                ExternalId    = "0"
            };

            // Have to do the following because we cannot set external id on party directly
            var   tempStorage = JsonConvert.SerializeObject(shippingParty);
            Party party       = JsonConvert.DeserializeObject <Party>(tempStorage);

            physicalFulfillmentComponent.ShippingParty = party;

            storeOrder.Components.Add(physicalFulfillmentComponent);


            storeOrder.Components.Add(contactComponent);
            storeOrder.Name = "InStoreOrder";

            storeOrder.ShopName            = arg.ShopName;
            storeOrder.FriendlyId          = orderId;
            storeOrder.OrderConfirmationId = arg.OrderConfirmationId;
            storeOrder.OrderPlacedDate     = Convert.ToDateTime(arg.OrderPlacedDate);
            //string createdOrderStatus = policy2.CreatedOrderStatus;
            storeOrder.Status = arg.Status;
            Order  order = storeOrder;
            string str3  = contactComponent.IsRegistered ? policy1.AuthenticatedOrders : policy1.AnonymousOrders;
            ListMembershipsComponent membershipsComponent1 = new ListMembershipsComponent()
            {
                Memberships = new List <string>()
                {
                    CommerceEntity.ListName <Order>(),
                    str3
                }
            };


            if (contactComponent.IsRegistered && !string.IsNullOrEmpty(contactComponent.CustomerId))
            {
                membershipsComponent1.Memberships.Add(string.Format(context.GetPolicy <KnownOrderListsPolicy>().CustomerOrders, contactComponent.CustomerId));
            }
            order.SetComponent(membershipsComponent1);


            Order order2 = order;
            TransientListMembershipsComponent membershipsComponent2 = new TransientListMembershipsComponent();

            membershipsComponent2.Memberships = new List <string>()
            {
                policy1.PendingOrders
            };


            context.Logger.LogInformation(string.Format("Offline Orders.ImportOrder: OrderId={0}|GrandTotal={1} {2}", orderId, order.Totals.GrandTotal.CurrencyCode, order.Totals.GrandTotal.Amount), Array.Empty <object>());
            context.CommerceContext.AddModel(new CreatedOrder()
            {
                OrderId = orderId
            });


            Dictionary <string, double> dictionary = new Dictionary <string, double>()
            {
                {
                    "GrandTotal",
                    Convert.ToDouble(order.Totals.GrandTotal.Amount, System.Globalization.CultureInfo.InvariantCulture)
                }
            };

            createOrderBlock._telemetryClient.TrackEvent("OrderCreated", null, dictionary);
            int orderTotal = Convert.ToInt32(Math.Round(order.Totals.GrandTotal.Amount, 0), System.Globalization.CultureInfo.InvariantCulture);

            if (context.GetPolicy <PerformancePolicy>().WriteCounters)
            {
                int num1 = await createOrderBlock._performanceCounterCommand.IncrementBy("SitecoreCommerceMetrics", "MetricCount", string.Format("Orders.GrandTotal.{0}", order.Totals.GrandTotal.CurrencyCode), orderTotal, context.CommerceContext).ConfigureAwait(false) ? 1 : 0;

                int num2 = await createOrderBlock._performanceCounterCommand.Increment("SitecoreCommerceMetrics", "MetricCount", "Orders.Count", context.CommerceContext).ConfigureAwait(false) ? 1 : 0;
            }
            return(order);
        }
Exemple #28
0
        public override async Task <Cart> Run(CartLineArgument arg, CommercePipelineExecutionContext context)
        {
            AddWishListLineBlock addCartLineBlock = this;

            Condition.Requires <CartLineArgument>(arg).IsNotNull <CartLineArgument>(string.Format("{0}: The argument cannot be null.", addCartLineBlock.Name));
            Condition.Requires <Cart>(arg.Cart).IsNotNull <Cart>(string.Format("{0}: The cart cannot be null.", addCartLineBlock.Name));
            Condition.Requires <CartLineComponent>(arg.Line).IsNotNull <CartLineComponent>(string.Format("{0}: The line to add cannot be null.", addCartLineBlock.Name));
            context.CommerceContext.AddObject((object)arg);
            Cart cart = arg.Cart;

            var cartComponent = cart.GetComponent <CartTypeComponent>();

            if (cartComponent == null)
            {
                var cartTypeComponent = new CartTypeComponent();
                cartTypeComponent.CartType = CartTypeEnum.Wishlist.ToString();
                cart.SetComponent(cartTypeComponent);
            }
            cartComponent.CartType = CartTypeEnum.Wishlist.ToString();


            LineQuantityPolicy lineQuantityPolicy = context.GetPolicy <LineQuantityPolicy>();
            Decimal            quantity           = arg.Line.Quantity;
            CartLineComponent  existingLine       = cart.Lines.FirstOrDefault <CartLineComponent>((Func <CartLineComponent, bool>)(l => l.ItemId.Equals(arg.Line.ItemId, StringComparison.Ordinal)));
            bool flag1 = !await lineQuantityPolicy.IsValid(quantity, context.CommerceContext);

            if (!flag1)
            {
                bool flag2 = existingLine != null;
                if (flag2)
                {
                    flag2 = !await lineQuantityPolicy.IsValid(quantity + existingLine.Quantity, context.CommerceContext);
                }
                flag1 = flag2;
            }
            if (flag1)
            {
                context.Abort("Invalid or missing value for property 'Quantity'.", (object)context);
                return(cart);
            }
            if (!string.IsNullOrEmpty(arg.Line.ItemId))
            {
                if (arg.Line.ItemId.Split('|').Length >= 3)
                {
                    if (string.IsNullOrEmpty(arg.Line.Id))
                    {
                        arg.Line.Id = Guid.NewGuid().ToString("N");
                    }
                    List <CartLineComponent> list = cart.Lines.ToList <CartLineComponent>();
                    if (!context.CommerceContext.GetPolicy <RollupCartLinesPolicy>().Rollup)
                    {
                        list.Add(arg.Line);
                        context.CommerceContext.AddModel((Model) new LineAdded(arg.Line.Id, false));
                    }
                    else if (existingLine != null)
                    {
                        existingLine.Quantity += arg.Line.Quantity;
                        arg.Line.Id            = existingLine.Id;
                        context.CommerceContext.AddModel((Model) new LineUpdated(arg.Line.Id));
                    }
                    else
                    {
                        list.Add(arg.Line);
                        context.CommerceContext.AddModel((Model) new LineAdded(arg.Line.Id, false));
                    }
                    cart.Lines = (IList <CartLineComponent>)list;
                    return(cart);
                }
            }
            CommercePipelineExecutionContext executionContext = context;
            CommerceContext commerceContext = context.CommerceContext;
            string          error           = context.GetPolicy <KnownResultCodes>().Error;
            string          commerceTermKey = "ItemIdIncorrectFormat";

            object[] args = new object[1]
            {
                (object)arg.Line.ItemId
            };
            string defaultMessage = string.Format("Expecting a CatalogId and a ProductId in the ItemId: {0}.", (object)arg.Line.ItemId);

            executionContext.Abort(await commerceContext.AddMessage(error, commerceTermKey, args, defaultMessage), (object)context);
            executionContext = (CommercePipelineExecutionContext)null;
            return(cart);
        }
Exemple #29
0
        private async Task <bool?> CalculateCartLinePrice(
            CartLineComponent arg,
            CommercePipelineExecutionContext context)
        {
            ProductArgument productArgument = ProductArgument.FromItemId(arg.ItemId);
            SellableItem    sellableItem    = null;

            if (productArgument.IsValid())
            {
                sellableItem = context.CommerceContext.GetEntity((Func <SellableItem, bool>)(s => s.ProductId.Equals(productArgument.ProductId, StringComparison.OrdinalIgnoreCase)));

                if (sellableItem == null)
                {
                    string simpleName = productArgument.ProductId.SimplifyEntityName();
                    sellableItem = context.CommerceContext.GetEntity((Func <SellableItem, bool>)(s => s.ProductId.Equals(simpleName, StringComparison.OrdinalIgnoreCase)));

                    if (sellableItem != null)
                    {
                        sellableItem.ProductId = simpleName;
                    }
                }
            }
            if (sellableItem == null)
            {
                CommercePipelineExecutionContext executionContext = context;
                CommerceContext commerceContext = context.CommerceContext;
                string          error           = context.GetPolicy <KnownResultCodes>().Error;
                object[]        args            = new object[] { arg.ItemId };
                string          defaultMessage  = "Item '" + arg.ItemId + "' is not purchasable.";
                executionContext.Abort(await commerceContext.AddMessage(error, "LineIsNotPurchasable", args, defaultMessage), context);
                executionContext = null;
                return(new bool?());
            }

            MessagesComponent messagesComponent = arg.GetComponent <MessagesComponent>();

            messagesComponent.Clear(context.GetPolicy <KnownMessageCodePolicy>().Pricing);

            if (sellableItem.HasComponent <MessagesComponent>())
            {
                List <MessageModel> messages = sellableItem.GetComponent <MessagesComponent>().GetMessages(context.GetPolicy <KnownMessageCodePolicy>().Pricing);
                messagesComponent.AddMessages(messages);
            }
            arg.UnitListPrice = sellableItem.ListPrice;
            string listPriceMessage = "CartItem.ListPrice<=SellableItem.ListPrice: Price=" + arg.UnitListPrice.AsCurrency(false, null);
            string sellPriceMessage = string.Empty;
            PurchaseOptionMoneyPolicy optionMoneyPolicy = new PurchaseOptionMoneyPolicy();

            if (sellableItem.HasPolicy <PurchaseOptionMoneyPolicy>())
            {
                optionMoneyPolicy.SellPrice = sellableItem.GetPolicy <PurchaseOptionMoneyPolicy>().SellPrice;
                sellPriceMessage            = "CartItem.SellPrice<=SellableItem.SellPrice: Price=" + optionMoneyPolicy.SellPrice.AsCurrency(false, null);
            }

            PriceSnapshotComponent snapshotComponent;

            if (sellableItem.HasComponent <ItemVariationsComponent>())
            {
                ItemVariationSelectedComponent lineVariant             = arg.ChildComponents.OfType <ItemVariationSelectedComponent>().FirstOrDefault();
                ItemVariationsComponent        itemVariationsComponent = sellableItem.GetComponent <ItemVariationsComponent>();
                ItemVariationComponent         itemVariationComponent;

                if (itemVariationsComponent == null)
                {
                    itemVariationComponent = null;
                }
                else
                {
                    IList <Component> childComponents = itemVariationsComponent.ChildComponents;
                    itemVariationComponent = childComponents?.OfType <ItemVariationComponent>().FirstOrDefault(v =>
                    {
                        return(!string.IsNullOrEmpty(v.Id) ? v.Id.Equals(lineVariant?.VariationId, StringComparison.OrdinalIgnoreCase) : false);
                    });
                }

                if (itemVariationComponent != null)
                {
                    if (itemVariationComponent.HasComponent <MessagesComponent>())
                    {
                        List <MessageModel> messages = itemVariationComponent.GetComponent <MessagesComponent>().GetMessages(context.GetPolicy <KnownMessageCodePolicy>().Pricing);
                        messagesComponent.AddMessages(messages);
                    }

                    arg.UnitListPrice = itemVariationComponent.ListPrice;
                    listPriceMessage  = "CartItem.ListPrice<=SellableItem.Variation.ListPrice: Price=" + arg.UnitListPrice.AsCurrency(false, null);

                    if (itemVariationComponent.HasPolicy <PurchaseOptionMoneyPolicy>())
                    {
                        optionMoneyPolicy.SellPrice = itemVariationComponent.GetPolicy <PurchaseOptionMoneyPolicy>().SellPrice;
                        sellPriceMessage            = "CartItem.SellPrice<=SellableItem.Variation.SellPrice: Price=" + optionMoneyPolicy.SellPrice.AsCurrency(false, null);
                    }
                }
                snapshotComponent = itemVariationComponent != null?itemVariationComponent.ChildComponents.OfType <PriceSnapshotComponent>().FirstOrDefault() : null;
            }
            else
            {
                snapshotComponent = sellableItem.Components.OfType <PriceSnapshotComponent>().FirstOrDefault();
            }

            string currentCurrency = context.CommerceContext.CurrentCurrency();

            PriceTier priceTier = snapshotComponent?.Tiers.OrderByDescending(t => t.Quantity).FirstOrDefault(t =>
            {
                return(t.Currency.Equals(currentCurrency, StringComparison.OrdinalIgnoreCase) ? t.Quantity <= arg.Quantity : false);
            });

            Customer customer = await _findEntityPipeline.Run(new FindEntityArgument(typeof(Customer), context.CommerceContext.CurrentCustomerId(), false), context) as Customer;

            bool isMembershipLevelPrice = false;

            if (customer != null && customer.HasComponent <MembershipSubscriptionComponent>())
            {
                var membershipSubscriptionComponent = customer.GetComponent <MembershipSubscriptionComponent>();
                var membershipLevel = membershipSubscriptionComponent.MemerbshipLevelName;

                if (snapshotComponent != null && snapshotComponent.HasComponent <MembershipTiersComponent>())
                {
                    var membershipTiersComponent = snapshotComponent.GetComponent <MembershipTiersComponent>();
                    var membershipPriceTier      = membershipTiersComponent.Tiers.FirstOrDefault(x => x.MembershipLevel == membershipLevel);

                    if (membershipPriceTier != null)
                    {
                        optionMoneyPolicy.SellPrice = new Money(membershipPriceTier.Currency, membershipPriceTier.Price);
                        isMembershipLevelPrice      = true;

                        sellPriceMessage = string.Format("CartItem.SellPrice<=PriceCard.ActiveSnapshot: MembershipLevel={0}|Price={1}|Qty={2}", membershipSubscriptionComponent.MemerbshipLevelName, optionMoneyPolicy.SellPrice.AsCurrency(false, null), membershipPriceTier.Quantity);
                    }
                }
            }

            if (!isMembershipLevelPrice && priceTier != null)
            {
                optionMoneyPolicy.SellPrice = new Money(priceTier.Currency, priceTier.Price);
                sellPriceMessage            = string.Format("CartItem.SellPrice<=PriceCard.ActiveSnapshot: Price={0}|Qty={1}", optionMoneyPolicy.SellPrice.AsCurrency(false, null), priceTier.Quantity);
            }

            arg.Policies.Remove(arg.Policies.OfType <PurchaseOptionMoneyPolicy>().FirstOrDefault());

            if (optionMoneyPolicy.SellPrice == null)
            {
                return(false);
            }

            arg.SetPolicy(optionMoneyPolicy);

            if (!string.IsNullOrEmpty(sellPriceMessage))
            {
                messagesComponent.AddMessage(context.GetPolicy <KnownMessageCodePolicy>().Pricing, sellPriceMessage);
            }

            if (!string.IsNullOrEmpty(listPriceMessage))
            {
                messagesComponent.AddMessage(context.GetPolicy <KnownMessageCodePolicy>().Pricing, listPriceMessage);
            }

            return(true);
        }
        public async Task <ItemType> AddItem(CommerceContext commerceContext, SellableItem sellableItem)
        {
            using (var activity = CommandActivity.Start(commerceContext, this))
            {
                var ebayItemComponent = sellableItem.GetComponent <EbayItemComponent>();

                try
                {
                    //Instantiate the call wrapper class
                    var apiCall = new AddFixedPriceItemCall(await GetEbayContext(commerceContext).ConfigureAwait(false));

                    var item = await PrepareItem(commerceContext, sellableItem).ConfigureAwait(false);

                    //Send the call to eBay and get the results
                    FeeTypeCollection feeTypeCollection = apiCall.AddFixedPriceItem(item);

                    foreach (var feeItem in feeTypeCollection)
                    {
                        var fee = feeItem as FeeType;
                        ebayItemComponent.Fees.Add(new AwardedAdjustment {
                            Adjustment = new Money(fee.Fee.currencyID.ToString(), System.Convert.ToDecimal(fee.Fee.Value)), AdjustmentType = "Fee", Name = fee.Name
                        });
                    }

                    ebayItemComponent.History.Add(new HistoryEntryModel {
                        EventMessage = "Listing Added", EventUser = commerceContext.CurrentCsrId()
                    });
                    ebayItemComponent.EbayId = item.ItemID;
                    ebayItemComponent.Status = "Listed";
                    sellableItem.GetComponent <TransientListMembershipsComponent>().Memberships.Add("Ebay_Listed");
                    await commerceContext.AddMessage("Info", "EbayCommand.AddItem", new [] { item.ItemID }, $"Item Listed:{item.ItemID}").ConfigureAwait(false);

                    return(item);
                }
                catch (Exception ex)
                {
                    if (ex.Message.Contains("It looks like this listing is for an item you already have on eBay"))
                    {
                        var existingId = ex.Message.Substring(ex.Message.IndexOf("(") + 1);
                        existingId = existingId.Substring(0, existingId.IndexOf(")"));
                        await commerceContext.AddMessage("Warn", "EbayCommand.AddItem", new [] { existingId }, $"ExistingId:{existingId}-ComponentId:{ebayItemComponent.EbayId}").ConfigureAwait(false);

                        ebayItemComponent.EbayId = existingId;
                        ebayItemComponent.Status = "Listed";
                        ebayItemComponent.History.Add(new HistoryEntryModel {
                            EventMessage = "Existing Listing Linked", EventUser = commerceContext.CurrentCsrId()
                        });
                        sellableItem.GetComponent <TransientListMembershipsComponent>().Memberships.Add("Ebay_Listed");
                    }
                    else
                    {
                        commerceContext.Logger.LogError($"Ebay.AddItem.Exception: Message={ex.Message}");
                        await commerceContext.AddMessage("Error", "Ebay.AddItem.Exception", new [] { ex }, ex.Message).ConfigureAwait(false);

                        ebayItemComponent.History.Add(new HistoryEntryModel {
                            EventMessage = $"Error-{ex.Message}", EventUser = commerceContext.CurrentCsrId()
                        });
                    }
                }
                return(new ItemType());
            }
        }