示例#1
0
        public override async Task <Customer> Run(SOMEOBJECTWITHCUSTOMERDATA arg, CommercePipelineExecutionContext context)
        {
            var    propertiesPolicy = context.GetPolicy <CustomerPropertiesPolicy>();
            var    customer         = new Customer();
            string friendlyId       = Guid.NewGuid().ToString("N");

            customer.AccountNumber = friendlyId;
            customer.FriendlyId    = friendlyId;
            customer.Id            = $"{CommerceEntity.IdPrefix<Customer>()}{friendlyId}";

            customer.Email = arg.EmailAddress;



            //add customer to the entity index so that we can search later
            await this._persistEntityPipeline.Run(
                new PersistEntityArgument(
                    new EntityIndex
            {
                Id = $"{EntityIndex.IndexPrefix<Customer>("Id")}{customer.Id}",
                IndexKey = customer.Id,
                EntityId = customer.Id
            }),
                context);

            return(customer);
        }
示例#2
0
        public override async Task <RenameCustomerArgument> Run(RenameCustomerArgument arg, CommercePipelineExecutionContext context)
        {
            Condition.Requires(arg).IsNotNull($"{this.Name}: The argument can not be null");

            var oldCustomerIndexEntityId = $"{EntityIndex.IndexPrefix<Customer>("Id")}{arg.FromUsername}";
            var result = await Commander.DeleteEntity(context.CommerceContext, oldCustomerIndexEntityId);

            return(arg);
        }
示例#3
0
        /// <summary>
        /// Runs the specified argument.
        /// </summary>
        /// <param name="arg">The argument.</param>
        /// <param name="context">The context.</param>
        /// <returns>the Customer entity</returns>
        public override async Task <Customer> Run(Customer arg, CommercePipelineExecutionContext context)
        {
            Condition.Requires(arg).IsNotNull($"{this.Name} The customer can not be null");

            var upgradePolicy = context.CommerceContext.GetPolicy <CustomersUpgradePolicy>();

            arg.UserName = string.Concat(upgradePolicy?.CustomersDomain, "\\", arg.Email);

            await this._deleteEntityPipeline.Run(new DeleteEntityArgument($"{EntityIndex.IndexPrefix<Customer>("Id")}{arg.Email}"), context).ConfigureAwait(false);

            return(arg);
        }
        /// <summary>
        /// Runs the specified argument.
        /// </summary>
        /// <param name="arg">The argument.</param>
        /// <param name="context">The context.</param>
        /// <returns></returns>
        public override async Task <CommerceEntity> Run(CommerceEntity arg, CommercePipelineExecutionContext context)
        {
            if (arg == null)
            {
                return(arg);
            }

            if (!(arg is Order))
            {
                return(arg);
            }

            var migrationPolicy = context.CommerceContext?.GetPolicy <MigrationPolicy>();

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

                return(arg);
            }

            Guid id;

            if (!Guid.TryParse(arg.Id, out id))
            {
                context.Logger.LogInformation($"{this.Name} - Invalid Order Id:{arg.Id}");
                return(arg);
            }

            arg.Id = $"{CommerceEntity.IdPrefix<Order>()}{id:N}";

            var targetOrder = await _findEntityCommand.Process(context.CommerceContext, typeof(Order), arg.Id).ConfigureAwait(false);

            if (targetOrder != null)
            {
                arg.IsPersisted = true;
                arg.Version     = targetOrder.Version;
                return(arg);
            }

            if (arg.HasComponent <ContactComponent>())
            {
                var indexByCustomerId = new EntityIndex
                {
                    Id       = $"{EntityIndex.IndexPrefix<Order>("Id")}{arg.Id}",
                    IndexKey = arg.GetComponent <ContactComponent>()?.CustomerId,
                    EntityId = arg.Id
                };

                if (!migrationPolicy.ReviewOnly)
                {
                    await this._persistEntityPipeline.Run(new PersistEntityArgument(indexByCustomerId), context).ConfigureAwait(false);
                }
            }

            var order = (Order)arg;
            var indexByConfirmationId = new EntityIndex
            {
                Id       = $"{EntityIndex.IndexPrefix<Order>("Id")}{order?.OrderConfirmationId}",
                IndexKey = order?.OrderConfirmationId,
                EntityId = arg.Id
            };

            if (!migrationPolicy.ReviewOnly)
            {
                await this._persistEntityPipeline.Run(new PersistEntityArgument(indexByConfirmationId), context).ConfigureAwait(false);
            }

            return(arg);
        }
        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);
        }
        /// <summary>
        /// The execute.
        /// </summary>
        /// <param name="arg">The argument.</param>
        /// <param name="context">The context.</param>
        /// <returns>
        /// The data row for a customer<see cref="DataRow" />.
        /// </returns>
        public override async Task <DataRow> Run(DataRow arg, CommercePipelineExecutionContext context)
        {
            Condition.Requires(arg).IsNotNull($"{this.Name} The data row can not be null");

            var email = arg["u_email_address"] as string;

            // verify if customer exists
            var result = await this._findEntityPipeline.Run(new FindEntityArgument(typeof(EntityIndex), $"{EntityIndex.IndexPrefix<Customer>("Id")}{email}"), context).ConfigureAwait(false);

            if (result is EntityIndex customerIndex)
            {
                context.Abort(
                    await context.CommerceContext.AddMessage(
                        context.GetPolicy <KnownResultCodes>().Warning,
                        "CustomerAlreadyExists",
                        new object[] { email, customerIndex.EntityId },
                        $"Customer { email } already exists.").ConfigureAwait(false),
                    context);
                return(null);
            }

            return(arg);
        }
示例#7
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);
        }
        /// <summary>
        /// Runs the specified argument.
        /// </summary>
        /// <param name="arg">The argument.</param>
        /// <param name="context">The context.</param>
        /// <returns></returns>
        public override async Task <CommerceEntity> Run(CommerceEntity arg, CommercePipelineExecutionContext context)
        {
            if (arg == null)
            {
                return(arg);
            }

            if (!(arg is GiftCard))
            {
                return(arg);
            }

            var giftCard = arg as GiftCard;

            var migrationPolicy = context.CommerceContext?.GetPolicy <MigrationPolicy>();

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

                return(giftCard);
            }

            if (giftCard.Order != null)
            {
                var orderId = $"{CommerceEntity.IdPrefix<Order>()}{giftCard.Order.EntityTarget}";
                giftCard.Order = new EntityReference(orderId);
            }

            giftCard.SetComponent(new ListMembershipsComponent
            {
                Memberships = new List <string>
                {
                    $"{CommerceEntity.ListName<Entitlement>()}",
                    $"{CommerceEntity.ListName<GiftCard>()}"
                }
            });

            if (giftCard.IsPersisted)
            {
                return(giftCard);
            }

            var indexByGiftCardCode = new EntityIndex
            {
                Id       = $"{EntityIndex.IndexPrefix<GiftCard>("Id")}{giftCard.GiftCardCode}",
                IndexKey = giftCard.GiftCardCode,
                EntityId = giftCard.Id
            };

            if (!migrationPolicy.ReviewOnly)
            {
                await this._persistEntityPipeline.Run(new PersistEntityArgument(indexByGiftCardCode), context);
            }

            return(giftCard);
        }