Пример #1
0
        public static IComponentLocalizationMapper GetItemVariantComponentLocalizationMapper(this Mappings mappings, CommerceEntity targetEntity, Component component, ILanguageEntity languageEntity, object sourceVariant, CommerceCommander commerceCommander, CommercePipelineExecutionContext context)
        {
            var mapperType = mappings
                             .ItemVariationMappings
                             .FirstOrDefault();

            if (mapperType != null)
            {
                var t = Type.GetType(mapperType.LocalizationFullTypeName ?? mapperType.FullTypeName);

                if (t != null)
                {
                    if (Activator.CreateInstance(t, languageEntity.GetEntity(), sourceVariant, targetEntity, component, commerceCommander, context) is IComponentLocalizationMapper mapper)
                    {
                        return(mapper);
                    }
                }
            }

            return(null);
        }
Пример #2
0
        public static IComponentMapper GetEntityComponentMapper(this Mappings mappings, CommerceEntity targetEntity, ImportEntityArgument importEntityArgument, string componentMappingKey, CommerceCommander commerceCommander, CommercePipelineExecutionContext context)
        {
            var mapperType = mappings
                             .EntityComponentMappings
                             .FirstOrDefault(x => x.Key.Equals(componentMappingKey, StringComparison.OrdinalIgnoreCase));

            if (mapperType != null)
            {
                var t = Type.GetType(mapperType.FullTypeName);

                if (t != null)
                {
                    if (Activator.CreateInstance(t, importEntityArgument.SourceEntity, targetEntity, commerceCommander, context) is
                        IComponentMapper mapper)
                    {
                        return(mapper);
                    }
                }
            }

            return(null);
        }
 public ImportLocalizeContentArgument(CommerceEntity commerceEntity, ImportEntityArgument importEntityArgument)
 {
     CommerceEntity       = commerceEntity;
     ImportEntityArgument = importEntityArgument;
 }
Пример #4
0
        public override async Task <IEnumerable <Entitlement> > Run(IEnumerable <Entitlement> arg, CommercePipelineExecutionContext context)
        {
            var entitlements = arg as List <Entitlement> ?? arg.ToList();

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

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

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

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

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

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

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

            var hasErrors = false;

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

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

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

                if (hasErrors)
                {
                    break;
                }
            }

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

            context.Abort(
                context.CommerceContext.AddMessage(
                    context.GetPolicy <KnownResultCodes>().Error,
                    "ProvisioningEntitlementErrors",
                    new object[] { order.Id },
                    $"Error(s) occurred provisioning entitlements for order '{order.Id}'"),
                context);
            return(null);
        }
Пример #5
0
        public override Task <EntityView> Run(EntityView arg, CommercePipelineExecutionContext context)
        {
            if (string.IsNullOrEmpty(arg?.Name) ||
                !arg.Name.Equals(context.GetPolicy <KnownCustomPricingViewsPolicy>().CustomPricing, StringComparison.OrdinalIgnoreCase) ||
                !string.IsNullOrEmpty(arg.Action))
            {
                return(Task.FromResult(arg));
            }

            CommerceEntity entity = context.CommerceContext.GetObject <EntityViewArgument>()?.Entity;
            PriceCard      priceCard;

            if ((priceCard = entity as PriceCard) == null)
            {
                return(Task.FromResult(arg));
            }

            ActionsPolicy policy = arg.GetPolicy <ActionsPolicy>();

            bool isEnabled = priceCard.Snapshots.Any(s =>
            {
                if (s.Id.Equals(arg.ItemId, StringComparison.OrdinalIgnoreCase))
                {
                    return(s.IsDraft(context.CommerceContext));
                }

                return(false);
            });

            List <Policy>         commercePolicies = new List <Policy>();
            MultiStepActionPolicy stepActionPolicy = new MultiStepActionPolicy();

            EntityActionView selectMembershipCurrencyActionView = new EntityActionView
            {
                Name        = context.GetPolicy <KnownCustomPricingActionsPolicy>().SelectMembershipCurrency,
                DisplayName = "Select Membership Currency",
                Description = "Selects a Membership Currency",
                IsEnabled   = isEnabled,
                EntityView  = context.GetPolicy <KnownCustomPricingViewsPolicy>().PriceCustomRow
            };

            stepActionPolicy.FirstStep = selectMembershipCurrencyActionView;
            commercePolicies.Add(stepActionPolicy);

            policy.Actions.Add(new EntityActionView()
            {
                Name        = context.GetPolicy <KnownCustomPricingActionsPolicy>().AddMembershipCurrency,
                DisplayName = "Add membership currency",
                Description = "Adds a membership currency",
                IsEnabled   = isEnabled,
                EntityView  = string.Empty,
                Icon        = "add",
                Policies    = commercePolicies
            });

            bool isEnabledForEditAndRemove = !string.IsNullOrEmpty(arg.ItemId) && priceCard.Snapshots.Any(s =>
            {
                if (s.Id.Equals(arg.ItemId, StringComparison.OrdinalIgnoreCase))
                {
                    var membershipTiersComponent = s.GetComponent <MembershipTiersComponent>();

                    if (membershipTiersComponent != null && membershipTiersComponent.Tiers.Any())
                    {
                        return(s.IsDraft(context.CommerceContext));
                    }
                }

                return(false);
            });

            policy.Actions.Add(new EntityActionView
            {
                Name        = context.GetPolicy <KnownCustomPricingActionsPolicy>().EditMembershipCurrency,
                DisplayName = "Edit membership currency",
                Description = "Edits a membership currency",
                IsEnabled   = isEnabledForEditAndRemove,
                EntityView  = context.GetPolicy <KnownCustomPricingViewsPolicy>().PriceCustomRow,
                Icon        = "edit"
            });

            policy.Actions.Add(new EntityActionView
            {
                Name                 = context.GetPolicy <KnownCustomPricingActionsPolicy>().RemoveMembershipCurrency,
                DisplayName          = "Remove membership currency",
                Description          = "Removes a membership currency",
                IsEnabled            = isEnabledForEditAndRemove,
                EntityView           = string.Empty,
                RequiresConfirmation = true,
                Icon                 = "delete"
            });

            return(Task.FromResult(arg));
        }
Пример #6
0
 public abstract object MapTo(CommerceEntity entity);
Пример #7
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);
        }
Пример #8
0
        public override async Task <EntityView> Run(EntityView entityView, CommercePipelineExecutionContext context)
        {
            Contract.Requires(context != null);

            /* Adding the code to save a new Vat Tax configuration item */
            if (entityView == null ||
                !entityView.Action.Equals("VatTaxDashboard-AddDashboardEntity", StringComparison.OrdinalIgnoreCase))
            {
                return(entityView);
            }

            try
            {
                var taxTag      = entityView.Properties.First(p => p.Name == "TaxTag").Value ?? "";
                var countryCode = entityView.Properties.First(p => p.Name == "CountryCode").Value ?? "";
                var taxPct      = System.Convert.ToDecimal(entityView.Properties.First(p => p.Name == "TaxPct").Value ?? "0");

                var sampleDashboardEntity = new VatTaxEntity
                {
                    Id          = CommerceEntity.IdPrefix <VatTaxEntity>() + Guid.NewGuid().ToString("N"),
                    Name        = string.Empty,
                    TaxTag      = taxTag,
                    CountryCode = countryCode,
                    TaxPct      = taxPct
                };

                sampleDashboardEntity.GetComponent <ListMembershipsComponent>().Memberships.Add(CommerceEntity.ListName <VatTaxEntity>());

                await this._commerceCommander.PersistEntity(context.CommerceContext, sampleDashboardEntity);
            }
            catch (Exception ex)
            {
                context.Logger.LogError($"Catalog.DoActionAddDashboardEntity.Exception: Message={ex.Message}");
            }


            return(entityView);
        }
Пример #9
0
        public override void ExecuteQuery(CommerceQueryOperation queryOperation, OperationCacheDictionary operationCache, CommerceQueryOperationResponse response)
        {
            CommerceModelSearch searchCriteria = queryOperation.GetSearchCriteria <CommerceModelSearch>();

            ParameterChecker.CheckForNull(searchCriteria, "searchCriteria");

            if (searchCriteria.Model.Properties.Count == 1)
            {
                string sproc = string.Empty;

                if (searchCriteria.Model.Properties[0].Key == "OrganizationId")   // looking for users associated to org
                {
                    sproc = "[dbo].[sp_BEK_ReadUsersForOrg]";
                }
                else if (searchCriteria.Model.Properties[0].Key == "UserId")    // looking for orgs associated to user
                {
                    sproc = "[dbo].[sp_BEK_ReadOrgsForUser]";
                }

                CommerceResourceCollection csResources = SiteHelper.GetCsConfig();
                String connStr = csResources["Biz Data Service"]["s_BizDataStoreConnectionString"].ToString();
                //ProfileContext pContext = CommerceSiteContexts.Profile[GetSiteName()];

                using (OleDbConnection conn = new OleDbConnection(connStr)) {
                    conn.Open();

                    CommercePropertyItem item = searchCriteria.Model.Properties[0];

                    OleDbCommand cmd = new OleDbCommand(sproc, conn);

                    cmd.Parameters.Add(new OleDbParameter("@id", OleDbType.VarChar, 50));
                    cmd.Parameters[0].Value     = item.Value;
                    cmd.Parameters[0].Direction = ParameterDirection.Input;
                    cmd.CommandType             = CommandType.StoredProcedure;

                    using (OleDbDataAdapter adapter = new OleDbDataAdapter(cmd)) {
                        DataTable dt = new DataTable();
                        adapter.Fill(dt);

                        foreach (DataRow r in dt.Rows)
                        {
                            if (searchCriteria.Model.Properties[0].Key == "UserId")   // todo: use profile entity mapping to fill this in
                            //this.Metadata.ProfileMapping;
                            {
                                CommerceEntity org = new CommerceEntity("Organization");

                                org.Id = r.GetString("u_org_id");
                                org.SetPropertyValue("Name", r.GetString("u_name"));
                                org.SetPropertyValue("CustomerNumber", r.GetString("u_customer_number"));
                                org.SetPropertyValue("BranchNumber", r.GetString("u_branch_number"));
                                org.SetPropertyValue("DsrNumber", r.GetString("u_dsr_number"));
                                org.SetPropertyValue("ContractNumber", r.GetString("u_contract_number"));
                                org.SetPropertyValue("IsPoRequired", r.GetNullableBool("u_is_po_required"));
                                org.SetPropertyValue("IsPowerMenu", r.GetNullableBool("u_is_power_menu"));
                                org.SetPropertyValue("OrganizationType", r.GetString("u_organization_type"));
                                org.SetPropertyValue("NationalOrRegionalAccountNumber", r.GetString("u_national_or_regional_account_number"));
                                org.SetPropertyValue("ParentOrganizationId", r.GetString("u_parent_organization"));
                                org.SetPropertyValue("TermCode", r.GetString("u_term_code"));
                                org.SetPropertyValue("CurrentBalance", r.GetNullableDecimal("u_current_balance"));
                                org.SetPropertyValue("BalanceAge1", r.GetNullableDecimal("u_balance_age_1"));
                                org.SetPropertyValue("BalanceAge2", r.GetNullableDecimal("u_balance_age_2"));
                                org.SetPropertyValue("BalanceAge3", r.GetNullableDecimal("u_balance_age_3"));
                                org.SetPropertyValue("BalanceAge4", r.GetNullableDecimal("u_balance_age_4"));
                                org.SetPropertyValue("AmountDue", r.GetNullableDecimal("u_amount_due"));
                                org.SetPropertyValue("AchType", r.GetString("u_customer_ach_type"));
                                org.SetPropertyValue("GeneralInfo.preferred_address", r.GetString("u_preferred_address"));

                                response.CommerceEntities.Add(org);
                            }
                            else if (searchCriteria.Model.Properties[0].Key == "OrganizationId")
                            {
                                CommerceEntity org = new CommerceEntity("UserProfile");

                                org.Id = r.GetString("u_user_id");
                                org.SetPropertyValue("FirstName", r.GetString("u_first_name"));
                                org.SetPropertyValue("LastName", r.GetString("u_last_name"));
                                org.SetPropertyValue("Email", r.GetString("u_email_address"));

                                response.CommerceEntities.Add(org);
                            }
                        }
                    }

                    if (conn.State == ConnectionState.Open)
                    {
                        conn.Close();
                    }
                }
            }
            else
            {
                base.ExecuteQuery(queryOperation, operationCache, 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);
            }
        }
Пример #11
0
        public override async Task <List <string> > Run(string catalogName, CommercePipelineExecutionContext context)
        {
            List <InventorySet> inventorySets = new List <InventorySet>();

            GetProductsToUpdateInventoryBlock getProductsToUpdateInventoryBlock = this;

            // get the sitecoreid from catalog based on catalogname
            var catalogSitecoreId = "";
            FindEntitiesInListArgument entitiesInListArgumentCatalog = await getProductsToUpdateInventoryBlock._findEntitiesInListPipeline.Run(new FindEntitiesInListArgument(typeof(Catalog), string.Format("{0}", (object)CommerceEntity.ListName <Catalog>()), 0, int.MaxValue), context);

            foreach (CommerceEntity commerceEntity in (await getProductsToUpdateInventoryBlock._findEntitiesInListPipeline.Run(entitiesInListArgumentCatalog, (IPipelineExecutionContextOptions)context.ContextOptions)).List.Items)
            {
                var item = commerceEntity as Catalog;

                if (item.Name == catalogName)
                {
                    catalogSitecoreId = item.SitecoreId;
                    break;
                }
            }


            if (string.IsNullOrEmpty(catalogSitecoreId))
            {
                return(null);
            }

            List <string> productIds = new List <string>();


            string              cacheKey      = string.Format("{0}|{1}|{2}", context.CommerceContext.Environment.Name, context.CommerceContext.CurrentLanguage(), context.CommerceContext.CurrentShopName() ?? "");
            CatalogCachePolicy  cachePolicy   = context.GetPolicy <CatalogCachePolicy>();
            ICache              cache         = null;
            List <SellableItem> sellableItems = null;

            if (cachePolicy.AllowCaching)
            {
                IGetEnvironmentCachePipeline cachePipeline            = getProductsToUpdateInventoryBlock._cachePipeline;
                EnvironmentCacheArgument     environmentCacheArgument = new EnvironmentCacheArgument();
                environmentCacheArgument.CacheName = cachePolicy.CatalogsCacheName;
                CommercePipelineExecutionContext context1 = context;
                cache = await cachePipeline.Run(environmentCacheArgument, context1).ConfigureAwait(false);

                sellableItems = await cache.Get(cacheKey).ConfigureAwait(false) as List <SellableItem>;

                if (sellableItems != null)
                {
                    foreach (var item in sellableItems)
                    {
                        await GetProductId(context, getProductsToUpdateInventoryBlock, catalogSitecoreId, productIds, item);
                    }
                }
            }
            else
            {
                sellableItems = new List <SellableItem>();
                FindEntitiesInListArgument entitiesInListArgument = new FindEntitiesInListArgument(typeof(SellableItem), string.Format("{0}", (object)CommerceEntity.ListName <SellableItem>()), 0, int.MaxValue);
                foreach (CommerceEntity commerceEntity in (await getProductsToUpdateInventoryBlock._findEntitiesInListPipeline.Run(entitiesInListArgument, context.ContextOptions).ConfigureAwait(false)).List.Items)
                {
                    await GetProductId(context, getProductsToUpdateInventoryBlock, catalogSitecoreId, productIds, commerceEntity as SellableItem).ConfigureAwait(false);
                }

                if (cachePolicy.AllowCaching)
                {
                    if (cache != null)
                    {
                        await cache.Set(cacheKey, new Cachable <List <SellableItem> >(sellableItems, 1L), cachePolicy.GetCacheEntryOptions()).ConfigureAwait(false);
                    }
                }
            }

            return(productIds);
        }
Пример #12
0
        private static EntityViewComponent GetPopulatedEntityViewComponent(ImportSingleCsvLineArgument arg, CommerceEntity composerTemplate, string viewName)
        {
            var entityViewComponent = composerTemplate.GetComponent <EntityViewComponent>();

            if (!(entityViewComponent.View.ChildViews.FirstOrDefault(x => x.Name == viewName) is EntityView entityView))
            {
                return(null);
            }

            entityView.EntityId = arg.Line.ProductId.ToEntityId <SellableItem>();
            PopulatePropertyValue(entityView, "Waist", arg.Line.Waist);
            PopulatePropertyValue(entityView, "OutsideLeg", arg.Line.Leg);
            PopulatePropertyValue(entityView, "InsideLeg", arg.Line.InsideLeg);
            return(entityViewComponent);
        }
Пример #13
0
        public override async Task <EntityView> Run(EntityView entityView, CommercePipelineExecutionContext context)
        {
            Contract.Requires(entityView != null);
            Contract.Requires(context != null);
            Condition.Requires(entityView).IsNotNull($"{this.Name}: The argument cannot be null");

            if (entityView == null || !entityView.Action.Equals("VatTaxDashboard-AddDashboardEntity", StringComparison.OrdinalIgnoreCase))
            {
                return(entityView);
            }

            if (entityView != null && entityView.Action.Equals("VatTaxDashboard-AddDashboardEntity", StringComparison.OrdinalIgnoreCase))
            {
                var taxTag      = entityView.Properties.First(p => p.Name == "TaxTag").Value ?? "";
                var countryCode = entityView.Properties.First(p => p.Name == "CountryCode").Value ?? "";
                var taxPct      = Convert.ToDecimal(entityView.Properties.First(p => p.Name == "TaxPct").Value ?? "0");

                using (var sampleDashboardEntity = new VatTaxEntity())
                {
                    try
                    {
                        sampleDashboardEntity.Id          = CommerceEntity.IdPrefix <VatTaxEntity>() + Guid.NewGuid().ToString("N");
                        sampleDashboardEntity.Name        = string.Empty;
                        sampleDashboardEntity.TaxTag      = taxTag;
                        sampleDashboardEntity.CountryCode = countryCode;
                        sampleDashboardEntity.TaxPct      = taxPct;
                        sampleDashboardEntity.GetComponent <ListMembershipsComponent>().Memberships.Add(CommerceEntity.ListName <VatTaxEntity>());
                        await _commerceCommander.Pipeline <IPersistEntityPipeline>().Run(new PersistEntityArgument(sampleDashboardEntity), context).ConfigureAwait(false);
                    }
                    catch (ArgumentNullException ex)
                    {
                        context.Logger.LogError($"Catalog.DoActionAddDashboardEntity.Exception: Message={ex.Message}");
                    }
                }
            }
            else
            {
                System.Diagnostics.Debug.Write($"Error creating the View is", entityView.Name);
            }

            return(entityView);
        }
Пример #14
0
        /// <summary>
        /// You may customized what is returned here based on number od existing orders or date or get number from external system
        /// </summary>
        /// <param name="order"></param>
        /// <param name="context"></param>
        /// <param name="findEntitiesInListCommand"></param>
        /// <returns></returns>
        private string GetCustomOrderNumber(Order order, CommercePipelineExecutionContext context, FindEntitiesInListCommand findEntitiesInListCommand)
        {
            //Get Contact Component which contains customer information
            var contactComponent = order.GetComponent <ContactComponent>();

            try
            {
                int orderCounts = 0;
                // get all existing orders.
                IEnumerable <Order> orders = (IEnumerable <Order>)findEntitiesInListCommand.Process <Order>(context.CommerceContext, CommerceEntity.ListName <Order>(), 0, int.MaxValue).Result.Items;

                // use the info you have to generate an appropriate order number. You may also use the data you have to call an external system.
                // in this instance we will just return the number of existing orders incremented by 1
                // Return order count and increment by 1 as the new order number.
                if (orders.Any())
                {
                    // Total orders
                    orderCount = orders.Count();
                }
                return((orderCount + 1).ToString());
            }
            catch (Exception)
            {
                // return a random guid if ther was an isssue retriving existing orders or all else failed.
                return(Guid.NewGuid().ToString("B"));
            }
        }
Пример #15
0
 public void Add(CommerceEntity entity)
 {
     Entities.TryAdd(entity.Id, entity);
 }
 private static string GenerateFullCatalogName(string catalogName)
 {
     return($"{CommerceEntity.IdPrefix<Catalog>()}{catalogName}");
 }
Пример #17
0
        /// <summary>
        /// Interface to Create or Update Catalog
        /// </summary>
        /// <param name="context">context</param>
        /// <param name="parameter">parameter</param>
        /// <param name="updateExisting">Flag to determine if an existing catalog should be updated</param>
        /// <returns>Commerce Command</returns>
        public async Task <CommerceCommand> ExecuteImport(CommerceContext context, CreateOrUpdateCatalogParameter parameter, bool updateExisting = false)
        {
            // Try to create a new catalog
            Catalog catalog = await this._createCatalogCommand.Process(context, parameter.Name, parameter.DisplayName);

            // If the catalog already exist - check if it should be updated
            if (catalog == null && !updateExisting)
            {
                return(this._createCatalogCommand);
            }

            // If it does already exist - get it
            if (catalog == null)
            {
                catalog = await this._getCatalogCommand.Process(context, parameter.Name.ToEntityId <Catalog>());
            }

            // Association of Price Book
            CommerceEntity priceBookEntity = null;

            if (!string.IsNullOrEmpty(parameter.PriceBookName))
            {
                if (!string.IsNullOrEmpty(catalog.PriceBookName) && !catalog.PriceBookName.Equals(parameter.PriceBookName))
                {
                    bool success = await this._disassociateCatalogFromPriceBookCommand.Process(context, catalog.PriceBookName, catalog.Name);
                }

                priceBookEntity = await this._findEntityCommand.Process(context, typeof(PriceBook), parameter.PriceBookName.ToEntityId <PriceBook>(), false);

                if (priceBookEntity != null)
                {
                    bool priceBookAssociationResult = await this._associateCatalogToPriceBookCommand.Process(context, parameter.PriceBookName, parameter.Name);
                }
            }

            // Association of Promotion Book
            CommerceEntity promotionBookEntity = null;

            if (!string.IsNullOrEmpty(parameter.PromotionBookName))
            {
                if (string.IsNullOrEmpty(catalog.PromotionBookName) && !catalog.PromotionBookName.Equals(parameter.PromotionBookName))
                {
                    bool success = await this._disassociateCatalogFromPromotionBookCommand.Process(context, catalog.PromotionBookName, catalog.Name);
                }

                promotionBookEntity = await this._findEntityCommand.Process(context, typeof(PromotionBook), parameter.PromotionBookName.ToEntityId <PromotionBook>(), false);

                if (promotionBookEntity != null)
                {
                    bool promotionBookAssociationResult = await this._associateCatalogToPromotionBookCommand.Process(context, parameter.PromotionBookName, parameter.Name);
                }
            }

            // Association of Default Inventory Set Book
            CommerceEntity inventorySetEntity = null;

            if (!string.IsNullOrEmpty(parameter.DefaultInventorySetName))
            {
                if (string.IsNullOrEmpty(catalog.DefaultInventorySetName) && !catalog.DefaultInventorySetName.Equals(parameter.DefaultInventorySetName))
                {
                    bool success = await this._disassociateCatalogFromInventorySetCommand.Process(context, catalog.DefaultInventorySetName, catalog.Name);
                }

                inventorySetEntity = await this._findEntityCommand.Process(context, typeof(InventorySet), parameter.DefaultInventorySetName.ToEntityId <InventorySet>(), false);

                if (inventorySetEntity != null)
                {
                    bool inventorySetAssociationResult = await this._associateCatalogToInventorySetCommand.Process(context, parameter.DefaultInventorySetName, parameter.Name);
                }
            }

            // Edit existing catalog
            Catalog editedCatalog = await this._editCatalogCommand.Process(
                context,
                catalog,
                parameter.DisplayName,
                priceBookEntity != null?parameter.PriceBookName : catalog.PriceBookName,
                promotionBookEntity != null?parameter.PromotionBookName : catalog.PromotionBookName,
                inventorySetEntity != null?parameter.DefaultInventorySetName : catalog.DefaultInventorySetName);

            return(this._editCatalogCommand);
        }
        public override async Task <Cart> Run(Cart arg, CommercePipelineExecutionContext context)
        {
            Contract.Requires(arg != null);
            Contract.Requires(context != null);

            Condition.Requires(arg).IsNotNull($"{this.Name}: The cart can not be null");
            Condition.Requires(arg.Lines).IsNotNull($"{this.Name}: The cart lines can not be null");

            if (!arg.Lines.Any())
            {
                return(arg);
            }

            var currency = context.CommerceContext.CurrentCurrency();

            var globalTaxPolicy     = context.GetPolicy <GlobalTaxPolicy>();
            var globalPricingPolicy = context.GetPolicy <GlobalPricingPolicy>();

            context.Logger.LogDebug($"{this.Name} - Policy:{globalTaxPolicy.TaxCalculationEnabled}");

            /* STUDENT: Uncomment lines 47-98 after you have implemented the VatTax entity */

            var vatTaxTable = await this._commerceCommander.Command <ListCommander>()
                              .GetListItems <VatTaxEntity>(context.CommerceContext,
                                                           CommerceEntity.ListName <VatTaxEntity>(), 0, 99).ConfigureAwait(false);

            foreach (var line in arg.Lines)
            {
                var lineProductComponent = line.GetComponent <CartProductComponent>();
                var tags = lineProductComponent.Tags;

                foreach (var taxRateLine in vatTaxTable)
                {
                    if (tags.Any(p => p.Name == taxRateLine.TaxTag))
                    {
                        if (arg.HasComponent <PhysicalFulfillmentComponent>())
                        {
                            var physicalFulfillment = arg.GetComponent <PhysicalFulfillmentComponent>();
                            var party   = physicalFulfillment.ShippingParty;
                            var country = party.CountryCode;

                            if (taxRateLine.CountryCode == country)
                            {
                                var taxRate = taxRateLine.TaxPct / 100;
                                context.Logger.LogDebug($"{this.Name} - Item Tax Rate:{taxRate}");
                                var adjustmentTotal = line.Adjustments.Where(a => a.IsTaxable).Aggregate(0M, (current, adjustment) => current + adjustment.Adjustment.Amount);
                                context.Logger.LogDebug($"{this.Name} - SubTotal:{line.Totals.SubTotal.Amount}");
                                context.Logger.LogDebug($"{this.Name} - Adjustment Total:{adjustmentTotal}");
                                var tax = new Money(currency, (line.Totals.SubTotal.Amount + adjustmentTotal) * taxRate);

                                if (globalPricingPolicy.ShouldRoundPriceCalc)
                                {
                                    tax.Amount = decimal.Round(
                                        tax.Amount,
                                        globalPricingPolicy.RoundDigits,
                                        globalPricingPolicy.MidPointRoundUp ? MidpointRounding.AwayFromZero : MidpointRounding.ToEven);
                                }

                                line.Adjustments.Add(new CartLineLevelAwardedAdjustment
                                {
                                    Name = TaxConstants.TaxAdjustmentName,

                                    DisplayName         = $"{taxRate * 100}% Vat Tax",
                                    Adjustment          = tax,
                                    AdjustmentType      = context.GetPolicy <KnownCartAdjustmentTypesPolicy>().Tax,
                                    AwardingBlock       = this.Name,
                                    IsTaxable           = false,
                                    IncludeInGrandTotal = true
                                });
                            }
                        }
                    }
                }
            }
            return(arg);
        }
Пример #19
0
        public override async Task <EntityView> Run(EntityView entityView, CommercePipelineExecutionContext context)
        {
            Contract.Requires(entityView != null);
            Contract.Requires(context != null);
            Condition.Requires(entityView).IsNotNull($"{this.Name}: The argument cannot be null");

            if (entityView != null && entityView.Name != "VatTaxDashboard")
            {
                return(entityView);
            }
            var pluginPolicy = context != null?context.GetPolicy <PluginPolicy>() : null;

            if (entityView != null)
            {
                var newEntityViewTable = entityView;
                entityView.UiHint = "Table";
                entityView.Icon   = "cubes";
                entityView.ItemId = string.Empty;

                var sampleDashboardEntities = await _commerceCommander.Command <ListCommander>().GetListItems <VatTaxEntity>(context.CommerceContext, CommerceEntity.ListName <VatTaxEntity>(), 0, 99).ConfigureAwait(false);

                foreach (var sampleDashboardEntity in sampleDashboardEntities)
                {
                    newEntityViewTable.ChildViews.Add(
                        new EntityView
                    {
                        ItemId     = sampleDashboardEntity.Id,
                        Icon       = "cubes",
                        Properties = new List <ViewProperty>
                        {
                            new ViewProperty {
                                Name = "TaxTag", RawValue = sampleDashboardEntity.TaxTag
                            },
                            new ViewProperty {
                                Name = "CountryCode", RawValue = sampleDashboardEntity.CountryCode
                            },
                            new ViewProperty {
                                Name = "TaxPct", RawValue = sampleDashboardEntity.TaxPct
                            }
                        }
                    });
                }
            }
            return(entityView);
        }
Пример #20
0
        /// <summary>
        /// The run.
        /// </summary>
        /// <param name="arg">
        /// The argument.
        /// </param>
        /// <param name="context">
        /// The context.
        /// </param>
        /// <returns>
        /// The <see cref="bool"/>.
        /// </returns>
        public override async Task <string> Run(string arg, CommercePipelineExecutionContext context)
        {
            var artifactSet = "GiftCards.TestGiftCards-1.0";

            // Check if this environment has subscribed to this Artifact Set
            if (!context.GetPolicy <EnvironmentInitializationPolicy>().InitialArtifactSets.Contains(artifactSet))
            {
                return(arg);
            }

            context.Logger.LogInformation($"{this.Name}.InitializingArtifactSet: ArtifactSet={artifactSet}");

            // Add stock gift cards for testing
            await this._persistEntityPipeline.Run(
                new PersistEntityArgument(
                    new GiftCard
            {
                Id = $"{CommerceEntity.IdPrefix<GiftCard>()}GC1000000",
                Name = "Test Gift Card ($1,000,000)",
                Balance = new Money("USD", 1000000M),
                ActivationDate = DateTimeOffset.UtcNow,
                Customer = new EntityReference {
                    EntityTarget = "DefaultCustomer"
                },
                OriginalAmount = new Money("USD", 1000000M),
                GiftCardCode = "GC1000000",
                Components = new List <Component>
                {
                    new ListMembershipsComponent {
                        Memberships = new List <string> {
                            CommerceEntity.ListName <Entitlement>(), CommerceEntity.ListName <GiftCard>()
                        }
                    }
                }
            }),
                context);

            await this._persistEntityPipeline.Run(
                new PersistEntityArgument(
                    new EntityIndex
            {
                Id = $"{EntityIndex.IndexPrefix<GiftCard>("Id")}GC1000000",
                IndexKey = "GC1000000",
                EntityId = $"{CommerceEntity.IdPrefix<GiftCard>()}GC1000000"
            }),
                context);

            await this._persistEntityPipeline.Run(
                new PersistEntityArgument(
                    new GiftCard
            {
                Id = $"{CommerceEntity.IdPrefix<GiftCard>()}GC100B",
                Name = "Test Gift Card ($100,000,000,000,000)",
                Balance = new Money("USD", 100000000000000M),
                ActivationDate = DateTimeOffset.UtcNow,
                Customer = new EntityReference {
                    EntityTarget = "DefaultCustomer"
                },
                OriginalAmount = new Money("USD", 100000000000000M),
                GiftCardCode = "GC100B",
                Components = new List <Component>
                {
                    new ListMembershipsComponent {
                        Memberships = new List <string> {
                            CommerceEntity.ListName <Entitlement>(), CommerceEntity.ListName <GiftCard>()
                        }
                    }
                }
            }),
                context);

            await this._persistEntityPipeline.Run(
                new PersistEntityArgument(
                    new EntityIndex
            {
                Id = $"{EntityIndex.IndexPrefix<GiftCard>("Id")}GC100B",
                IndexKey = "GC100B",
                EntityId = $"{CommerceEntity.IdPrefix<GiftCard>()}GC100B"
            }),
                context);

            await this._persistEntityPipeline.Run(
                new PersistEntityArgument(
                    new GiftCard
            {
                Id = $"{CommerceEntity.IdPrefix<GiftCard>()}GC100",
                Name = "Test Gift Card ($100)",
                Balance = new Money("USD", 100M),
                ActivationDate = DateTimeOffset.UtcNow,
                Customer = new EntityReference {
                    EntityTarget = "DefaultCustomer"
                },
                OriginalAmount = new Money("USD", 100M),
                GiftCardCode = "GC100",
                Components = new List <Component>
                {
                    new ListMembershipsComponent {
                        Memberships = new List <string> {
                            CommerceEntity.ListName <Entitlement>(), CommerceEntity.ListName <GiftCard>()
                        }
                    }
                }
            }),
                context);

            await this._persistEntityPipeline.Run(
                new PersistEntityArgument(
                    new EntityIndex
            {
                Id = $"{EntityIndex.IndexPrefix<GiftCard>("Id")}GC100",
                IndexKey = "GC100",
                EntityId = $"{CommerceEntity.IdPrefix<GiftCard>()}GC100"
            }),
                context);

            return(arg);
        }
Пример #21
0
        public override async Task <EntityView> Run(EntityView entityView, CommercePipelineExecutionContext context)
        {
            Condition.Requires(entityView).IsNotNull($"{this.Name}: The argument cannot be null");

            if (entityView.Name != "MyDashboard")
            {
                return(entityView);
            }

            var pluginPolicy = context.GetPolicy <PluginPolicy>();

            entityView.UiHint      = "Flat";
            entityView.Icon        = pluginPolicy.Icon;
            entityView.DisplayName = "My Dashboard";

            entityView.Properties.Add(
                new ViewProperty
            {
                Name       = "ViewProperty1",
                IsHidden   = false,
                IsReadOnly = true,
                RawValue   = "ValueString"
            });

            entityView.Properties.Add(
                new ViewProperty
            {
                Name         = "HtmlProperty",
                IsHidden     = false,
                IsReadOnly   = true,
                OriginalType = "Html",
                UiType       = "Html",
                RawValue     = "<b>ValueString</b>"
            });

            entityView.Properties.Add(
                new ViewProperty
            {
                Name         = "TableSample",
                IsHidden     = false,
                IsReadOnly   = true,
                OriginalType = "Html",
                UiType       = "Html",
                RawValue     = "<table><tr><td style='color: red;width:100%'>tablecell1</td><td>tablecell2</td></tr><tr><td>tablecell1b</td><td>tablecell2b</td></tr></table>"
            });

            entityView.Properties.Add(
                new ViewProperty
            {
                Name         = "DivSample",
                IsHidden     = false,
                IsReadOnly   = true,
                OriginalType = "Html",
                UiType       = "Html",
                RawValue     = "<div style='color: red;'>In Div</div><div style='color: blue;'>In Div2</div>"
            });

            entityView.Properties.Add(
                new ViewProperty
            {
                Name         = "ImageProperty",
                IsHidden     = false,
                IsReadOnly   = true,
                OriginalType = "Html",
                UiType       = "Html",
                RawValue     = "<img alt='This is the alternate' height=100 width=100 src='http://sxa.storefront.com/-/media/Images/Habitat/6042177_01.ashx?h=625&w=770' style=''/>"
            });

            var newEntityViewTable = new EntityView
            {
                Name   = "Example Table View",
                UiHint = "Table",
                Icon   = pluginPolicy.Icon,
                ItemId = string.Empty,
            };

            entityView.ChildViews.Add(newEntityViewTable);

            var sampleDashboardEntities = await this._commerceCommander.Command <ListCommander>()
                                          .GetListItems <SampleDashboardEntity>(context.CommerceContext,
                                                                                CommerceEntity.ListName <SampleDashboardEntity>(), 0, 99);

            foreach (var sampleDashboardEntity in sampleDashboardEntities)
            {
                newEntityViewTable.ChildViews.Add(
                    new EntityView
                {
                    ItemId     = sampleDashboardEntity.Id,
                    Icon       = pluginPolicy.Icon,
                    Properties = new List <ViewProperty> {
                        new ViewProperty {
                            Name = "ItemId", RawValue = sampleDashboardEntity.Id, UiType = "EntityLink"
                        },
                        new ViewProperty {
                            Name = "Name", RawValue = sampleDashboardEntity.Name
                        },
                        new ViewProperty {
                            Name = "DisplayName", RawValue = sampleDashboardEntity.DisplayName, OriginalType = "Html", UiType = "Html"
                        }
                    }
                });
            }

            return(entityView);
        }
Пример #22
0
        /// <summary>
        /// /
        /// </summary>
        /// <param name="context"></param>
        /// <param name="findEntitiesInListCommand"></param>
        /// <returns></returns>
        private static string GenerateNewCustomerNumber(CommercePipelineExecutionContext context, FindEntitiesInListCommand findEntitiesInListCommand)
        {
            // get all existing customers.
            var customers = (IEnumerable <Customer>)findEntitiesInListCommand.Process <Customer>(context.CommerceContext, CommerceEntity.ListName <Customer>(), 0, int.MaxValue).Result.Items;

            // Total existing customers
            var customerCount = customers.Count();

            if (!customers.Any())
            {
                return("customer1");
            }

            // use the info you have to generate an appropriate customer number. You may also use the data you have to call an external system.
            // in this instance we will just return the number of existing customers incremented by 1
            // Return customer count and increment by 1 as the new customer number.

            var nextOrderNumber = customerCount + 1;

            return("customer" + nextOrderNumber.ToString());
        }
Пример #23
0
        /// <summary>
        /// The run.
        /// </summary>
        /// <param name="arg">
        /// The argument.
        /// </param>
        /// <param name="context">
        /// The context.
        /// </param>
        /// <returns>
        /// The <see cref="bool"/>.
        /// </returns>
        public override async Task <string> Run(string arg, CommercePipelineExecutionContext context)
        {
            var artifactSet = "Environment.Habitat.SellableItems-1.0";

            // Check if this environment has subscribed to this Artifact Set
            if (!context.GetPolicy <EnvironmentInitializationPolicy>()
                .InitialArtifactSets.Contains(artifactSet))
            {
                return(arg);
            }

            context.Logger.LogInformation($"{this.Name}.InitializingArtifactSet: ArtifactSet={artifactSet}");


            // DEFAULT SUBSCRIPTION SELLABLE ITEM TEMPLATE
            var itemId     = $"{CommerceEntity.IdPrefix<SellableItem>()}Subscription";
            var findResult = await this._findEntityPipeline.Run(new FindEntityArgument(typeof(SellableItem), itemId, false), context.CommerceContext.GetPipelineContextOptions());

            if (findResult == null)
            {
                var subscriptionSellableItem = new SellableItem
                {
                    Id       = itemId,
                    Name     = "Default Subscription",
                    Policies = new List <Policy>
                    {
                        new AvailabilityAlwaysPolicy()
                    },
                    Components = new List <Component>
                    {
                        new ListMembershipsComponent {
                            Memberships = new List <string> {
                                CommerceEntity.ListName <SellableItem>()
                            }
                        }
                    }
                };
                await this._persistEntityPipeline.Run(new PersistEntityArgument(subscriptionSellableItem), context);
            }

            // DEFAULT INSTALLATION SELLABLE ITEM TEMPLATE
            itemId     = $"{CommerceEntity.IdPrefix<SellableItem>()}Installation";
            findResult = await this._findEntityPipeline.Run(new FindEntityArgument(typeof(SellableItem), itemId, false), context.CommerceContext.GetPipelineContextOptions());

            if (findResult == null)
            {
                var installationSellableItem = new SellableItem
                {
                    Id       = itemId,
                    Name     = "Default Installation",
                    Policies = new List <Policy>
                    {
                        new AvailabilityAlwaysPolicy()
                    },
                    Components = new List <Component>
                    {
                        new ListMembershipsComponent {
                            Memberships = new List <string> {
                                CommerceEntity.ListName <SellableItem>()
                            }
                        }
                    }
                };
                await this._persistEntityPipeline.Run(new PersistEntityArgument(installationSellableItem), context);
            }

            // DEFAULT WARRANTY SELLABLE ITEM TEMPLATE
            itemId     = $"{CommerceEntity.IdPrefix<SellableItem>()}Warranty";
            findResult = await this._findEntityPipeline.Run(new FindEntityArgument(typeof(SellableItem), itemId, false), context.CommerceContext.GetPipelineContextOptions());

            if (findResult == null)
            {
                var warrantySellableItem = new SellableItem
                {
                    Id       = itemId,
                    Name     = "Default Warranty",
                    Policies = new List <Policy>
                    {
                        new AvailabilityAlwaysPolicy()
                    },
                    Components = new List <Component>
                    {
                        new ListMembershipsComponent {
                            Memberships = new List <string> {
                                CommerceEntity.ListName <SellableItem>()
                            }
                        }
                    }
                };
                await this._persistEntityPipeline.Run(new PersistEntityArgument(warrantySellableItem), context);
            }

            return(arg);
        }
 protected override bool IsSupportedEntity(CommerceEntity entity)
 {
     return(entity is SellableItem);
 }
Пример #25
0
        /// <summary>
        /// Runs the specified argument.
        /// </summary>
        /// <param name="arg">The argument.</param>
        /// <param name="context">The context.</param>
        /// <returns></returns>
        public override async Task <CommerceEnvironment> Run(MigrateEnvironmentArgument arg, CommercePipelineExecutionContext context)
        {
            Condition.Requires(arg).IsNotNull($"{this.Name}: the argument cannot be null.");

            context.Logger.LogInformation($"{this.Name} - Run IEntityMigrationPipeline:{arg.SourceEnvironment.Name}");

            context.CommerceContext.AddUniqueObjectByType(arg);
            context.CommerceContext.Environment = arg.SourceEnvironment;

            CommerceEnvironment environment;

            try
            {
                environment = await this._entityMigrationPipeline.Run(
                    new FindEntityArgument(typeof(CommerceEnvironment),
                                           arg.SourceEnvironment.Id)
                    { ShouldCreate = false },
                    context).ConfigureAwait(false) as CommerceEnvironment;

                if (environment == null)
                {
                    context.Abort(
                        await context.CommerceContext.AddMessage(
                            context.GetPolicy <KnownResultCodes>().Error,
                            "EntityNotFound",
                            new object[] { arg.SourceEnvironment.ArtifactStoreId, arg.SourceEnvironment.Id },
                            $"Source environment ArtifactStoreId={arg.SourceEnvironment.ArtifactStoreId}, Id={arg.SourceEnvironment.Id} was not found.").ConfigureAwait(false),
                        context);
                    return(null);
                }

                // update ArtifactStoreId to get lists
                arg.SourceEnvironment.ArtifactStoreId = environment.ArtifactStoreId;
                environment.ArtifactStoreId           = arg.NewArtifactStoreId;
                environment.Name        = arg.NewEnvironmentName;
                environment.Id          = $"{CommerceEntity.IdPrefix<CommerceEnvironment>()}{arg.NewEnvironmentName}";
                environment.IsPersisted = false;
                environment.Version     = 1;

                var sqlPoliciesCollection = context.CommerceContext?.GetObjects <List <KeyValuePair <string, EntityStoreSqlPolicy> > >()?.FirstOrDefault();
                if (sqlPoliciesCollection != null)
                {
                    var sourceGlobal = sqlPoliciesCollection.FirstOrDefault(p =>
                                                                            p.Key.Equals("SourceGlobal", StringComparison.OrdinalIgnoreCase)).Value;
                    var sqlPolicy = new EntityStoreSqlPolicy
                    {
                        Server            = sourceGlobal.Server,
                        Database          = environment.GetPolicy <EntityStoreSqlPolicy>().Database,
                        TrustedConnection = sourceGlobal.TrustedConnection,
                        ConnectTimeout    = 120000,
                        CleanEnvironmentCommandTimeout = 120000,
                        UserName             = sourceGlobal.UserName,
                        Password             = sourceGlobal.Password,
                        AdditionalParameters = sourceGlobal.AdditionalParameters
                    };
                    sqlPoliciesCollection.Add(
                        new KeyValuePair <string, EntityStoreSqlPolicy>("SourceShared", sqlPolicy));
                }

                context.CommerceContext.AddUniqueObjectByType(arg);
            }
            catch (Exception ex)
            {
                await context.CommerceContext.AddMessage(
                    context.GetPolicy <KnownResultCodes>().Error,
                    this.Name,
                    new object[] { ex },
                    $"{this.Name}.Exception: {ex.Message}").ConfigureAwait(false);

                context.CommerceContext.Environment = context.CommerceContext.GlobalEnvironment;
                context.CommerceContext.LogException($"{this.Name}. Exception when getting {arg.SourceEnvironment.Name}", ex);
                return(arg.SourceEnvironment);
            }

            context.CommerceContext.Environment = context.CommerceContext.GlobalEnvironment;
            return(environment);
        }
Пример #26
0
        public static IComponentMapper GetItemVariationComponentMapper(this Mappings mappings, CommerceEntity targetEntity, Component parentComponent, ImportEntityArgument importEntityArgument, object sourceComponent, CommerceCommander commerceCommander, CommercePipelineExecutionContext context)
        {
            var mapperType = mappings
                             .ItemVariationMappings
                             .FirstOrDefault();

            if (mapperType != null)
            {
                var t = Type.GetType(mapperType.FullTypeName);

                if (t != null)
                {
                    if (Activator.CreateInstance(t, importEntityArgument.SourceEntity, sourceComponent, targetEntity, parentComponent,
                                                 commerceCommander, context) is IComponentMapper mapper)
                    {
                        return(mapper);
                    }
                }
            }

            return(null);
        }
Пример #27
0
        public override async Task <Order> Run(ConvertGuestOrderToMemberOrderArgument arg, CommercePipelineExecutionContext context)
        {
            Condition.Requires(arg).IsNotNull("The arg can not be null");
            Condition.Requires(arg.OrderId).IsNotNull("The order id can not be null");
            Condition.Requires(arg.CustomerId).IsNotNull("The customer id can not be null");
            Condition.Requires(arg.CustomerEmail).IsNotNull("The customer email can not be null");


            var order = await this._commerceCommander.Command <GetOrderCommand>().Process(context.CommerceContext, arg.OrderId);

            if (order == null)
            {
                return(null);
            }

            if (!order.HasComponent <ContactComponent>())
            {
                order.Components.Add(new ContactComponent());
            }

            var contactComponent = order.GetComponent <ContactComponent>();

            if (contactComponent.IsRegistered == false)
            {
                contactComponent.CustomerId   = arg.CustomerId;
                contactComponent.ShopperId    = arg.CustomerId;
                contactComponent.Email        = arg.CustomerEmail;
                contactComponent.IsRegistered = true;
            }
            order.SetComponent(contactComponent);

            var policy = context.GetPolicy <KnownOrderListsPolicy>();
            var membershipsComponent = order.GetComponent <ListMembershipsComponent>();

            membershipsComponent.Memberships.Remove(policy.AnonymousOrders);
            membershipsComponent.Memberships.Add(policy.AuthenticatedOrders);
            membershipsComponent.Memberships.Add(string.Format(policy.CustomerOrders, $"{CommerceEntity.IdPrefix<Customer>()}{arg.CustomerId}"));
            order.SetComponent(membershipsComponent);

            await this._commerceCommander.Pipeline <IRemoveListEntitiesPipeline>().Run(new ListEntitiesArgument(new List <string>()
            {
                order.Id
            }, policy.AnonymousOrders), context);

            await this._commerceCommander.Pipeline <IAddListEntitiesPipeline>().Run(new ListEntitiesArgument(new List <string>()
            {
                order.Id
            }, policy.AuthenticatedOrders), context);

            await this._commerceCommander.Pipeline <IAddListEntitiesPipeline>().Run(new ListEntitiesArgument(new List <string>()
            {
                order.Id
            }, string.Format(policy.CustomerOrders, $"{CommerceEntity.IdPrefix<Customer>()}{arg.CustomerId}")), context);

            await this._commerceCommander.Pipeline <IPersistEntityPipeline>().Run(new PersistEntityArgument(order), context);

            return(order);
        }
Пример #28
0
        public static IComponentLocalizationMapper GetComponentChildComponentLocalizationMapper(this Mappings mappings, CommerceEntity targetEntity, Component component, ILanguageEntity languageEntity, object sourceVariant, CommerceCommander commerceCommander, CommercePipelineExecutionContext context)
        {
            var metadataPolicy = component.GetComponentMetadataPolicy();
            var mapperType     = mappings
                                 .ItemVariationComponentMappings
                                 .FirstOrDefault(
                x => (metadataPolicy != null && !string.IsNullOrEmpty(metadataPolicy.MapperKey) && x.Key.Equals(metadataPolicy.MapperKey, StringComparison.OrdinalIgnoreCase)) ||
                x.Type.Equals(component.GetType().FullName, StringComparison.OrdinalIgnoreCase));

            if (mapperType != null)
            {
                var t = Type.GetType(mapperType.LocalizationFullTypeName ?? mapperType.FullTypeName);

                if (t != null)
                {
                    if (Activator.CreateInstance(t, languageEntity.GetEntity(), sourceVariant, targetEntity, component,
                                                 commerceCommander, context) is IComponentLocalizationMapper mapper)
                    {
                        return(mapper);
                    }
                }
            }

            return(null);
        }
        /// <summary>
        /// The run.
        /// </summary>
        /// <param name="arg">
        /// The argument.
        /// </param>
        /// <param name="context">
        /// The context.
        /// </param>
        /// <returns>
        /// The <see cref="bool"/>.
        /// </returns>
        public override async Task <string> Run(string arg, CommercePipelineExecutionContext context)
        {
            var artifactSet = "Environment.Regions-1.0";

            //// Check if this environment has subscribed to this Artifact Set
            if (!context.GetPolicy <EnvironmentInitializationPolicy>()
                .InitialArtifactSets.Contains(artifactSet))
            {
                return(arg);
            }

            context.Logger.LogInformation($"{this.Name}.InitializingArtifactSet: ArtifactSet={artifactSet}");

            await this._persistEntityPipeline.Run(
                new PersistEntityArgument(
                    new Country(new List <Component>
            {
                new ListMembershipsComponent {
                    Memberships = new List <string> {
                        "Countries"
                    }
                }
            })
            {
                Id = $"{CommerceEntity.IdPrefix<Country>()}USA",
                Name = "United States",
                IsoCode2 = "US",
                IsoCode3 = "USA",
                AddressFormat = "1"
            }),
                context).ConfigureAwait(false);;

            await this._persistEntityPipeline.Run(
                new PersistEntityArgument(
                    new Country(new List <Component>
            {
                new ListMembershipsComponent {
                    Memberships = new List <string> {
                        "Countries"
                    }
                }
            })
            {
                Id = $"{CommerceEntity.IdPrefix<Country>()}CAN",
                Name = "Canada",
                IsoCode2 = "CA",
                IsoCode3 = "CAN",
                AddressFormat = "1"
            }),
                context).ConfigureAwait(false);

            await this._persistEntityPipeline.Run(
                new PersistEntityArgument(
                    new Country(new List <Component>
            {
                new ListMembershipsComponent {
                    Memberships = new List <string> {
                        "Countries"
                    }
                }
            })
            {
                Id = $"{CommerceEntity.IdPrefix<Country>()}DNK",
                Name = "Denmark",
                IsoCode2 = "DK",
                IsoCode3 = "DNK",
                AddressFormat = "1"
            }),
                context).ConfigureAwait(false);

            return(arg);
        }
 static public void SetRuntimePipelineConfig(CommerceEntity model, ICreateOrderPipelinesConfig createOrderPipelinesConfig)
 {
     if (model == null) throw new ArgumentNullException("model");
     if (createOrderPipelinesConfig == null) throw new ArgumentNullException("createOrderPipelinesConfig");
     model.SetPropertyValue(ModelKey, createOrderPipelinesConfig);
 }
 public EntityViewConditionsArgument(CommerceEntity entity, string viewName, string action)
 {
     Entity   = entity;
     ViewName = viewName;
     Action   = action;
 }