Beispiel #1
0
        /// <summary>
        /// Instantiates a basket
        /// </summary>
        /// <param name="merchelloContext">The merchello context</param>
        /// <param name="customer">The customer associated with the basket</param>
        /// <returns>The <see cref="IBasket"/></returns>
        internal static IBasket GetBasket(IMerchelloContext merchelloContext, ICustomerBase customer)
        {
            Mandate.ParameterNotNull(merchelloContext, "merchelloContext");
            Mandate.ParameterNotNull(customer, "customer");

            var cacheKey = MakeCacheKey(customer);

            var basket = (IBasket)merchelloContext.Cache.RuntimeCache.GetCacheItem(cacheKey);

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

            var customerItemCache = merchelloContext.Services.ItemCacheService.GetItemCacheWithKey(customer, ItemCacheType.Basket);

            basket = new Basket(customerItemCache, customer);

            if (basket.Validate())
            {
                merchelloContext.Cache.RuntimeCache.GetCacheItem(cacheKey, () => basket);
            }

            return(basket);
        }
        /// <summary>
        /// Creates an anonymous customer
        /// </summary>
        private void CreateAnonymousCustomer()
        {
            var customer = _customerService.CreateAnonymousCustomerWithKey();

            CurrentCustomer = customer;
            CacheCustomer(customer);
        }
        public void Init()
        {
            _destination = new Address()
            {
                Name        = "Mindfly Web Design Studio",
                Address1    = "114 W. Magnolia St.  Suite 504",
                Locality    = "Bellingham",
                Region      = "WA",
                PostalCode  = "98225",
                CountryCode = "US"
            };

            PreTestDataWorker.DeleteAllItemCaches();
            PreTestDataWorker.DeleteAllInvoices();
            _customer = PreTestDataWorker.MakeExistingAnonymousCustomer();
            _basket   = Basket.GetBasket(MerchelloContext, _customer);

            for (var i = 0; i < ProductCount; i++)
            {
                _basket.AddItem(PreTestDataWorker.MakeExistingProduct(true, WeightPerProduct, PricePerProduct));
            }

            Basket.Save(MerchelloContext, _basket);

            _shipCountry = ShipCountryService.GetShipCountryByCountryCode(Catalog.Key, "US");
        }
        /// <summary>
        /// Gets the checkout <see cref="IItemCache"/> for the <see cref="ICustomerBase"/>
        /// </summary>
        /// <param name="merchelloContext">
        /// The <see cref="IMerchelloContext"/>
        /// </param>
        /// <param name="customer">
        /// The customer associated with the checkout
        /// </param>
        /// <param name="versionKey">
        /// The version key for this <see cref="SalePreparationBase"/>
        /// </param>
        /// <returns>
        /// The <see cref="IItemCache"/> associated with the customer checkout
        /// </returns>
        protected static IItemCache GetItemCache(IMerchelloContext merchelloContext, ICustomerBase customer, Guid versionKey)
        {
            var runtimeCache = merchelloContext.Cache.RuntimeCache;

            var cacheKey  = MakeCacheKey(customer, versionKey);
            var itemCache = runtimeCache.GetCacheItem(cacheKey) as IItemCache;

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

            itemCache = merchelloContext.Services.ItemCacheService.GetItemCacheWithKey(customer, ItemCacheType.Checkout, versionKey);

            // this is probably an invalid version of the checkout
            if (!itemCache.VersionKey.Equals(versionKey))
            {
                var oldCacheKey = MakeCacheKey(customer, itemCache.VersionKey);
                runtimeCache.ClearCacheItem(oldCacheKey);
                Reset(merchelloContext, customer);

                // delete the old version
                merchelloContext.Services.ItemCacheService.Delete(itemCache);
                return(GetItemCache(merchelloContext, customer, versionKey));
            }

            runtimeCache.InsertCacheItem(cacheKey, () => itemCache);

            return(itemCache);
        }
Beispiel #5
0
        /// <summary>
        /// Tries to apply the discount line item reward
        /// </summary>
        /// <param name="validate">
        /// The <see cref="ILineItemContainer"/> to validate against
        /// </param>
        /// <param name="customer">
        /// The customer.
        /// </param>
        /// <returns>
        /// The <see cref="Attempt{ILinetItem}"/>.
        /// </returns>
        public override Attempt <ILineItem> TryAward(ILineItemContainer validate, ICustomerBase customer)
        {
            var shippingLineItems = validate.ShippingLineItems();
            var audits            = shippingLineItems.Select(item =>
                                                             new CouponRewardAdjustmentAudit()
            {
                RelatesToSku = item.Sku,
                Log          = new[]
                {
                    new DataModifierLog()
                    {
                        PropertyName  = "Price",
                        OriginalValue = item.Price,
                        ModifiedValue = 0M
                    }
                }
            }).ToList();

            // Get the item template
            var discountLineItem = CreateTemplateDiscountLineItem(audits);
            var discount         = validate.ShippingLineItems().Sum(x => x.TotalPrice);

            discountLineItem.Price = discount;

            return(Attempt <ILineItem> .Succeed(discountLineItem));
        }
        /// <summary>
        /// Tries to apply the discount line item reward
        /// </summary>
        /// <param name="validate">
        /// The <see cref="ILineItemContainer"/> to validate against
        /// </param>
        /// <param name="customer">
        /// The customer.
        /// </param>
        /// <returns>
        /// The <see cref="Attempt{ILinetItem}"/>.
        /// </returns>
        public override Attempt<ILineItem> TryAward(ILineItemContainer validate, ICustomerBase customer)
        {
            if (!IsConfigured) return Attempt<ILineItem>.Fail(new OfferRedemptionException("The coupon reward is not configured."));
            if (MerchelloContext.Current == null) return Attempt<ILineItem>.Fail(new OfferRedemptionException("The MerchelloContext was null"));

            // apply to the entire collection excluding previously added discounts
            var qualifying =
                Extensions.CreateNewItemCacheLineItemContainer(validate.Items.Where(x => x.LineItemType != LineItemType.Discount));

            var visitor = new CouponDiscountLineItemRewardVisitor(Amount, AdjustmentType);
            qualifying.Items.Accept(visitor);

            var qualifyingTotal = visitor.QualifyingTotal;


            var discount = this.AdjustmentType == Adjustment.Flat
                                    ? this.Amount > qualifyingTotal ? qualifyingTotal : this.Amount
                                    : qualifyingTotal * (this.Amount / 100);

            // Get the item template
            var discountLineItem = CreateTemplateDiscountLineItem(visitor.Audits);
            discountLineItem.ExtendedData.SetValue(Core.Constants.ExtendedDataKeys.CouponAdjustedProductPreTaxTotal, visitor.AdjustedProductPreTaxTotal.ToString(CultureInfo.InvariantCulture));
            discountLineItem.ExtendedData.SetValue(Core.Constants.ExtendedDataKeys.CouponAdjustedProductTaxTotal, visitor.AdjustedTaxTotal.ToString(CultureInfo.InvariantCulture));
            discountLineItem.Price = discount;

            return Attempt<ILineItem>.Succeed(discountLineItem);
        }
        /// <summary>
        /// Validates the constraint against the <see cref="ILineItemContainer"/>
        /// </summary>
        /// <param name="value">
        /// The value to object to which the constraint is to be applied.
        /// </param>
        /// <param name="customer">
        /// The <see cref="ICustomerBase"/>.
        /// </param>
        /// <returns>
        /// The <see cref="Attempt{ILineItemContainer}"/> indicating whether or not the constraint can be enforced.
        /// </returns>
        public override Attempt<ILineItemContainer> TryApply(ILineItemContainer value, ICustomerBase customer)
        {
            var visitor = new MaximumQuantityConstraintVisitor(MaximumQuantity);
            value.Items.Accept(visitor);

            return this.Success(this.CreateNewLineContainer(visitor.ModifiedItems));
        }
Beispiel #8
0
 public Simulations(ILogger logger, IWarehouse warehouse, ICustomerBase customerBase, IShop shop)
 {
     this.logger  = logger;
     Warehouse    = warehouse;
     CustomerBase = customerBase;
     Shop         = shop;
 }
Beispiel #9
0
        /// <summary>
        /// Provides an assertion that the customer cookie is associated with the correct customer Umbraco member relation.
        /// </summary>
        /// <param name="customer">
        /// The customer.
        /// </param>
        /// <remarks>
        /// http://issues.merchello.com/youtrack/issue/M-454
        /// </remarks>
        private void EnsureIsLoggedInCustomer(ICustomerBase customer)
        {
            if (_cache.RequestCache.GetCacheItem(CacheKeys.EnsureIsLoggedInCustomerValidated(customer.Key)) != null)
            {
                return;
            }

            var memberId  = _membershipHelper.GetCurrentMemberId();
            var dataValue = ContextData.Values.FirstOrDefault(x => x.Key == UmbracoMemberIdDataKey);

            // If the dataValues do not contain the umbraco member id reinitialize
            if (!string.IsNullOrEmpty(dataValue.Value))
            {
                // Assert are equal
                if (!dataValue.Value.Equals(memberId.ToString(CultureInfo.InvariantCulture)))
                {
                    this.Reinitialize(customer);
                }
                return;
            }

            if (dataValue.Value != memberId.ToString(CultureInfo.InvariantCulture))
            {
                this.Reinitialize(customer);
            }
        }
        /// <summary>
        /// Tries to apply the discount line item reward
        /// </summary>
        /// <param name="validate">
        /// The <see cref="ILineItemContainer"/> to validate against
        /// </param>
        /// <param name="customer">
        /// The customer.
        /// </param>
        /// <returns>
        /// The <see cref="Attempt{ILinetItem}"/>.
        /// </returns>
        public override Attempt<ILineItem> TryAward(ILineItemContainer validate, ICustomerBase customer)
        {
            var shippingLineItems = validate.ShippingLineItems();
            var audits = shippingLineItems.Select(item =>
                new CouponRewardAdjustmentAudit()
                    {
                        RelatesToSku = item.Sku,
                        Log = new[]
                                  {
                                      new DataModifierLog()
                                          {
                                              PropertyName = "Price",
                                              OriginalValue = item.Price,
                                              ModifiedValue = 0M
                                          }
                                  }
                    }).ToList();

            // Get the item template
            var discountLineItem = CreateTemplateDiscountLineItem(audits);
            var discount = validate.ShippingLineItems().Sum(x => x.TotalPrice);
            discountLineItem.Price = discount;

            return Attempt<ILineItem>.Succeed(discountLineItem);
        }
        /// <summary>
        /// The caches the customer.
        /// </summary>
        /// <param name="customer">
        /// The customer.
        /// </param>
        private void CacheCustomer(ICustomerBase customer)
        {
            // set/reset the cookie
            var cookie = new HttpCookie(CustomerCookieName)
            {
                Value = this.ContextData.ToJson()
            };

            // Ensure a session cookie for Anonymous customers
            if (customer.IsAnonymous)
            {
                if (_anonCookieExpireDays <= 0)
                {
                    cookie.Expires = DateTime.MinValue;
                }
                else
                {
                    var expires = DateTime.Now.AddDays(_anonCookieExpireDays);
                    cookie.Expires = expires;
                }
            }

            this._umbracoContext.HttpContext.Response.Cookies.Add(cookie);

            this._cache.RequestCache.GetCacheItem(CustomerCookieName, () => this.ContextData);
            this._cache.RuntimeCache.GetCacheItem(CacheKeys.CustomerCacheKey(customer.Key), () => customer, TimeSpan.FromMinutes(20), true);
        }
 /// <summary>
 /// Updates the context data.
 /// </summary>
 /// <param name="converted">
 /// The converted.
 /// </param>
 /// <param name="ctxValues">
 /// The context values.
 /// </param>
 private static void UpdateContextData(ICustomerBase converted, IEnumerable <KeyValuePair <string, string> > ctxValues)
 {
     foreach (var value in ctxValues)
     {
         converted.ExtendedData.SetValue(value.Key, value.Value);
     }
 }
Beispiel #13
0
 public Buyer(ILogger logger, ICustomerBase customerBase, IWarehouse warehouse, IShop shop)
 {
     this.logger  = logger;
     CustomerBase = customerBase;
     Warehouse    = warehouse;
     Shop         = shop;
 }
Beispiel #14
0
        /// <summary>
        /// Creates a basket for a consumer with a given type
        /// </summary>
        /// <param name="customer">
        /// The customer.
        /// </param>
        /// <param name="itemCacheType">
        /// The item Cache Type.
        /// </param>
        /// <param name="versionKey">
        /// The version Key.
        /// </param>
        /// <returns>
        /// The <see cref="IItemCache"/>.
        /// </returns>
        public IItemCache GetItemCacheWithKey(ICustomerBase customer, ItemCacheType itemCacheType, Guid versionKey)
        {
            Mandate.ParameterCondition(Guid.Empty != versionKey, "versionKey");

            // determine if the consumer already has a item cache of this type, if so return it.
            var itemCache = GetItemCacheByCustomer(customer, itemCacheType);
            if (itemCache != null) return itemCache;

            itemCache = new ItemCache(customer.Key, itemCacheType)
            {
                VersionKey = versionKey
            };

            if (Creating.IsRaisedEventCancelled(new Events.NewEventArgs<IItemCache>(itemCache), this))
            {
                // registry.WasCancelled = true;
                return itemCache;
            }

            itemCache.EntityKey = customer.Key;

            using (new WriteLock(Locker))
            {
                var uow = _uowProvider.GetUnitOfWork();
                using (var repository = _repositoryFactory.CreateItemCacheRepository(uow))
                {
                    repository.AddOrUpdate(itemCache);
                    uow.Commit();
                }
            }

            Created.RaiseEvent(new Events.NewEventArgs<IItemCache>(itemCache), this);

            return itemCache;
        }
Beispiel #15
0
        /// <summary>
        /// Instantiates a wish list
        /// </summary>
        /// <param name="merchelloContext">The merchello context</param>
        /// <param name="customer">The customer associated with the wish list</param>
        /// <returns>The <see cref="IWishList"/></returns>
        internal static IWishList GetWishList(IMerchelloContext merchelloContext, ICustomerBase customer)
        {
            Mandate.ParameterNotNull(merchelloContext, "merchelloContext");
            Mandate.ParameterNotNull(customer, "customer");

            var cacheKey = MakeCacheKey(customer);

            var wishlist = (IWishList)merchelloContext.Cache.RuntimeCache.GetCacheItem(cacheKey);

            if (wishlist != null && wishlist.Validate())
            {
                return(wishlist);
            }

            var customerItemCache = merchelloContext.Services.ItemCacheService.GetItemCacheWithKey(customer, ItemCacheType.Wishlist);

            wishlist = new WishList(customerItemCache, customer);

            if (wishlist.Validate())
            {
                merchelloContext.Cache.RuntimeCache.GetCacheItem(cacheKey, () => wishlist, TimeSpan.FromHours(2));
            }

            return(wishlist);
        }
Beispiel #16
0
        public void Init()
        {
            PreTestDataWorker.DeleteAllItemCaches();

            _customer = PreTestDataWorker.MakeExistingAnonymousCustomer();
            _basket   = Basket.GetBasket(MerchelloContext.Current, _customer);
        }
        /// <summary>
        ///  Inserts an address record in the merchBasket table and returns an <see cref="IItemCache"/> object representation
        /// </summary>
        public IItemCache MakeExistingItemCache(ICustomerBase customer, ItemCacheType itemCacheType)
        {
            var itemCache = MockCustomerItemCacheDataMaker.ConsumerItemCacheForInserting(customer, itemCacheType);

            ItemCacheService.Save(itemCache);
            return(itemCache);
        }
Beispiel #18
0
        /// <summary>
        /// Try to apply the award
        /// </summary>
        /// <param name="validatedAgainst">
        /// The validated against.
        /// </param>
        /// <param name="customer">
        /// The customer.
        /// </param>
        /// <returns>
        /// The <see cref="Attempt"/>.
        /// </returns>
        public Attempt <object> TryAward(object validatedAgainst, ICustomerBase customer)
        {
            if (!this.IsInitialized)
            {
                return(Attempt <object> .Fail(new OfferRedemptionException("Offer processor not initialized.")));
            }

            try
            {
                var reward    = _reward as OfferRewardComponentBase <TConstraint, TAward>;
                var converted = validatedAgainst.TryConvertTo <TConstraint>();
                if (converted.Success)
                {
                    if (reward == null)
                    {
                        return(Attempt <object> .Fail(new NullReferenceException("Converted reward was null")));
                    }

                    var rewardAttempt = reward.TryAward(converted.Result, customer);

                    return(!rewardAttempt.Success ?
                           Attempt <object> .Fail(rewardAttempt.Result, rewardAttempt.Exception) :
                           Attempt <object> .Succeed(rewardAttempt.Result));
                }

                LogHelper.Error(typeof(OfferProcessorBase <TConstraint, TAward>), "Failed to convert validation object", converted.Exception);
                throw converted.Exception;
            }
            catch (Exception ex)
            {
                LogHelper.Error(typeof(OfferProcessorBase <TConstraint, TAward>), "Failed to convert reward type", ex);
                throw;
            }
        }
Beispiel #19
0
        /// <summary>
        /// Applies the constraints
        /// </summary>
        /// <param name="validatedAgainst">
        /// The constrain by.
        /// </param>
        /// <param name="customer">
        /// The customer.
        /// </param>
        /// <returns>
        /// The <see cref="Attempt"/>.
        /// </returns>
        public Attempt <object> TryApplyConstraints(object validatedAgainst, ICustomerBase customer)
        {
            if (!this.IsInitialized)
            {
                return(Attempt <object> .Fail(new OfferRedemptionException("Offer processor not initialized.")));
            }

            var convert = validatedAgainst.TryConvertTo <TConstraint>();

            if (!convert.Success)
            {
                var invalid =
                    new InvalidOperationException(
                        "validatedAgainst parameter could not be converted to type " + typeof(TConstraint).FullName);
                return(Attempt <object> .Fail(invalid));
            }

            if (TaskHandlers.Any())
            {
                TaskHandlers.Clear();
            }
            this.BuildConstraintChain(this._constraints.Select(x => this.ConvertConstraintToTask(x, customer)));

            var attempt = TaskHandlers.Any()
                              ? TaskHandlers.First().Execute(convert.Result)
                              : Attempt <TConstraint> .Succeed(convert.Result); // there were no constraints

            // convert bask to an object
            return(attempt.Success
                       ? Attempt <object> .Succeed(attempt.Result)
                       : Attempt <object> .Fail(attempt.Result, attempt.Exception));
        }
        public virtual void FixtureSetup()
        {
            // Sets Umbraco SqlSytax and ensure database is setup
            DbPreTestDataWorker = new DbPreTestDataWorker();
            DbPreTestDataWorker.ValidateDatabaseSetup();
            DbPreTestDataWorker.DeleteAllAnonymousCustomers();

            // Merchello CoreBootStrap
            var bootManager = new WebBootManager();
            bootManager.Initialize();

            if(MerchelloContext.Current == null) Assert.Ignore("MerchelloContext.Current is null");

            CurrentCustomer = DbPreTestDataWorker.MakeExistingAnonymousCustomer();

            // Product saves

            ProductService.Created += ProductServiceCreated;
            ProductService.Saved += ProductServiceSaved;
            ProductService.Deleted += ProductServiceDeleted;
            ProductVariantService.Created += ProductVariantServiceCreated;
            ProductVariantService.Saved += ProductVariantServiceSaved;
            ProductVariantService.Deleted += ProductVariantServiceDeleted;

            // BasketCheckout
               // ItemCacheService.Saved += BasketItemCacheSaved;
        }
Beispiel #21
0
        private void EnsureIsLoggedInCustomer(ICustomerBase customer, string membershipId)
        {
            if (this._cache.RequestCache.GetCacheItem(CacheKeys.EnsureIsLoggedInCustomerValidated(customer.Key)) != null)
            {
                return;
            }

            var dataValue = this.ContextData.Values.FirstOrDefault(x => x.Key == UmbracoMemberIdDataKey);

            // If the dataValues do not contain the umbraco member id reinitialize
            if (!string.IsNullOrEmpty(dataValue.Value))
            {
                // Assert are equal
                if (!dataValue.Value.Equals(membershipId))
                {
                    this.Reinitialize(customer);
                }
                return;
            }

            if (dataValue.Value != membershipId)
            {
                this.Reinitialize(customer);
            }
        }
Beispiel #22
0
 public static IItemCache ConsumerItemCacheForInserting(ICustomerBase customer, ItemCacheType itemCacheType)
 {
     return(new ItemCache(customer.EntityKey, itemCacheType)
     {
         EntityKey = customer.EntityKey
     });
 }
 public static IItemCache ConsumerItemCacheForInserting(ICustomerBase customer, ItemCacheType itemCacheType)
 {
     return new ItemCache(customer.EntityKey, itemCacheType)
     {
         EntityKey = customer.EntityKey
     };
 }
Beispiel #24
0
        public OfferConstraintChainTask(OfferConstraintComponentBase <T> component, ICustomerBase customer)
        {
            Mandate.ParameterNotNull(component, "component");
            Mandate.ParameterNotNull(customer, "customer");

            _component = component;
            _customer  = customer;
        }
        /// <summary>
        /// Overrides the creation of the <see cref="ICustomerProfile"/>.
        /// </summary>
        /// <param name="model">
        /// The <see cref="NewMemberModel"/>.
        /// </param>
        /// <param name="customer">
        /// The <see cref="CustomerBase"/>.
        /// </param>
        /// <returns>
        /// The modified <see cref="NewMemberModel"/>.
        /// </returns>
        protected override TModel OnCreate(TModel model, ICustomerBase customer)
        {
            model.MemberTypeAlias = "merchelloCustomer";
            model.PersistLogin    = true;
            model.ViewData        = new StoreViewData();

            return(base.OnCreate(model, customer));
        }
Beispiel #26
0
        /// <summary>
        /// Initializes a new instance of the <see cref="CheckoutEventArgs{T}"/> class.
        /// </summary>
        /// <param name="customer">
        /// The customer.
        /// </param>
        /// <param name="item">
        /// The item.
        /// </param>
        public CheckoutEventArgs(ICustomerBase customer, T item)
            : base(item, true)
        {
            Mandate.ParameterNotNull(customer, "customer");
            Mandate.ParameterNotNull(item, "item");

            this.Customer = customer;
        }
Beispiel #27
0
        /// <summary>
        /// Gets the Braintree server token.
        /// </summary>
        /// <param name="customer">
        /// The current customer.
        /// </param>
        /// <returns>
        /// The Braintree server token
        /// </returns>
        protected string GetBraintreeToken(ICustomerBase customer)
        {
            var token = customer.IsAnonymous ?
                        this._braintreeApiService.Customer.GenerateClientRequestToken() :
                        this._braintreeApiService.Customer.GenerateClientRequestToken((ICustomer)customer);

            return(token);
        }
Beispiel #28
0
        private string CreateQuery(ICustomerBase customer)
        {
            if (customer == null)
            {
                return(string.Empty);
            }

            var query = new StringBuilder();

            if (customer.CustomerId > 0)
            {
                query.Append($"WHERE CustomerId={customer.CustomerId}");
            }

            if (!string.IsNullOrEmpty(customer.FirstName))
            {
                if (query.Length == 0)
                {
                    query.Append("WHERE ");
                }
                else
                {
                    query.Append(" AND ");
                }

                query.Append($"FirstName LIKE N'%{customer.FirstName}%'");
            }

            if (!string.IsNullOrEmpty(customer.LastName))
            {
                if (query.Length == 0)
                {
                    query.Append("WHERE ");
                }
                else
                {
                    query.Append(" AND ");
                }

                query.Append($"LastName LIKE N'%{customer.LastName}%'");
            }

            if (!string.IsNullOrEmpty(customer.Email))
            {
                if (query.Length == 0)
                {
                    query.Append("WHERE ");
                }
                else
                {
                    query.Append(" AND ");
                }

                query.Append($"Email LIKE '%{customer.Email}%'");
            }

            return(query.ToString());
        }
        /// <summary>
        /// Returns a collection of item caches for the consumer
        /// </summary>
        /// <param name="customer">
        /// The customer.
        /// </param>
        /// <returns>
        /// The <see cref="IEnumerable{IItemCache}"/>.
        /// </returns>
        public IEnumerable <IItemCache> GetItemCacheByCustomer(ICustomerBase customer)
        {
            using (var repository = RepositoryFactory.CreateItemCacheRepository(UowProvider.GetUnitOfWork()))
            {
                var query = Query <IItemCache> .Builder.Where(x => x.EntityKey == customer.Key);

                return(repository.GetByQuery(query));
            }
        }
        /// <summary>
        /// Returns the customer item cache of a given type. This method will not create an item cache if the cache does not exist.
        /// </summary>
        /// <param name="customer">
        /// The customer.
        /// </param>
        /// <param name="itemCacheTfKey">
        /// The item Cache type field Key.
        /// </param>
        /// <returns>
        /// The <see cref="IItemCache"/>.
        /// </returns>
        public IItemCache GetItemCacheByCustomer(ICustomerBase customer, Guid itemCacheTfKey)
        {
            using (var repository = RepositoryFactory.CreateItemCacheRepository(UowProvider.GetUnitOfWork()))
            {
                var query = Query <IItemCache> .Builder.Where(x => x.EntityKey == customer.Key && x.ItemCacheTfKey == itemCacheTfKey);

                return(repository.GetByQuery(query).FirstOrDefault());
            }
        }
Beispiel #31
0
        internal Basket(IItemCache itemCache, ICustomerBase customer)
        {
            Mandate.ParameterNotNull(itemCache, "ItemCache");
            Mandate.ParameterCondition(itemCache.ItemCacheType == ItemCacheType.Basket, "itemCache");
            Mandate.ParameterNotNull(customer, "customer");

            _customer = customer;
            _itemCache = itemCache;
        }
Beispiel #32
0
        internal Basket(IItemCache itemCache, ICustomerBase customer)
        {
            Mandate.ParameterNotNull(itemCache, "ItemCache");
            Mandate.ParameterCondition(itemCache.ItemCacheType == ItemCacheType.Basket, "itemCache");
            Mandate.ParameterNotNull(customer, "customer");

            _customer  = customer;
            _itemCache = itemCache;
        }
Beispiel #33
0
        public IEnumerable <IShipmentRateQuote> GetShippingMethods(BackofficeAddItemModel model)
        {
            _customer   = MerchelloContext.Services.CustomerService.GetAnyByKey(new Guid(model.CustomerKey));
            _backoffice = _customer.Backoffice();

            var shipment = _backoffice.PackageBackoffice(model.ShippingAddress.ToAddress()).FirstOrDefault();

            return(shipment.ShipmentRateQuotes());
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="CustomerItemCacheBase"/> class.
        /// </summary>
        /// <param name="itemCache">
        /// The item cache.
        /// </param>
        /// <param name="customer">
        /// The customer.
        /// </param>
        protected CustomerItemCacheBase(IItemCache itemCache, ICustomerBase customer)
        {
            Mandate.ParameterNotNull(itemCache, "ItemCache");
            Mandate.ParameterNotNull(customer, "customer");
            _customer = customer;
            _itemCache = itemCache;
            EnableDataModifiers = true;

            this.Initialize();
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="CustomerItemCacheBase"/> class.
        /// </summary>
        /// <param name="itemCache">
        /// The item cache.
        /// </param>
        /// <param name="customer">
        /// The customer.
        /// </param>
        protected CustomerItemCacheBase(IItemCache itemCache, ICustomerBase customer)
        {
            Mandate.ParameterNotNull(itemCache, "ItemCache");
            Mandate.ParameterNotNull(customer, "customer");
            _customer           = customer;
            _itemCache          = itemCache;
            EnableDataModifiers = true;

            this.Initialize();
        }
Beispiel #36
0
        /// <summary>
        /// Initializes the <see cref="MerchelloControllerBase"/>
        /// </summary>
        private void Initialize()
        {
            var customerContext = new CustomerContext(UmbracoContext);

            _currentCustomer = customerContext.CurrentCustomer;

            _home = new Lazy <IPublishedContent>(GetHomePage);

            _basket = _currentCustomer.Basket();
        }
Beispiel #37
0
        /// <summary>
        /// Initializes a new instance of the <see cref="BasketLineItemFactory"/> class.
        /// </summary>
        /// <param name="umbraco">
        /// The umbraco.
        /// </param>
        /// <param name="currentCustomer">
        /// The current Customer.
        /// </param>
        /// <param name="currency">
        /// The currency.
        /// </param>
        public BasketLineItemFactory(UmbracoHelper umbraco, ICustomerBase currentCustomer, ICurrency currency)
        {
            Mandate.ParameterNotNull(umbraco, "umbraco");
            Mandate.ParameterNotNull(currency, "currency");
            Mandate.ParameterNotNull(currentCustomer, "currentCustomer");

            this._umbraco         = umbraco;
            this._currency        = currency;
            this._currentCustomer = currentCustomer;
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="BasketLineItemFactory"/> class.
        /// </summary>
        /// <param name="umbraco">
        /// The umbraco.
        /// </param>
        /// <param name="currentCustomer">
        /// The current Customer.
        /// </param>
        /// <param name="currency">
        /// The currency.
        /// </param>
        public BasketLineItemFactory(UmbracoHelper umbraco, ICustomerBase currentCustomer, ICurrency currency)
        {
            Mandate.ParameterNotNull(umbraco, "umbraco");
            Mandate.ParameterNotNull(currency, "currency");
            Mandate.ParameterNotNull(currentCustomer, "currentCustomer");

            this._umbraco = umbraco;
            this._currency = currency;
            this._currentCustomer = currentCustomer;
        }
        /// <summary>
        /// Tries to apply the discount line item reward
        /// </summary>
        /// <param name="validate">
        /// The <see cref="ILineItemContainer"/> to validate against
        /// </param>
        /// <param name="customer">
        /// The customer.
        /// </param>
        /// <returns>
        /// The <see cref="Attempt{ILinetItem}"/>.
        /// </returns>
        public override Attempt<ILineItem> TryAward(ILineItemContainer validate, ICustomerBase customer)
        {
            // Get the item template
            var discountLineItem = CreateTemplateDiscountLineItem();

            var discount = validate.ShippingLineItems().Sum(x => x.TotalPrice);

            discountLineItem.Price = discount;

            return Attempt<ILineItem>.Succeed(discountLineItem);
        }
        /// <summary>
        /// The try apply.
        /// </summary>
        /// <param name="value">
        /// The value.
        /// </param>
        /// <param name="customer">
        /// The customer.
        /// </param>
        /// <returns>
        /// The <see cref="Attempt"/>.
        /// </returns>
        public override Attempt<ILineItemContainer> TryApply(ILineItemContainer value, ICustomerBase customer)
        {
            if (MerchelloContext.Current != null)
            {
                if (!MerchelloContext.Current.Gateways.Taxation.ProductPricingEnabled) return this.Success(value);
                var vistor = new ExcludeTaxesInProductPricesVisitor();
                value.Items.Accept(vistor);
                return this.Success(value);
            }

            return Attempt<ILineItemContainer>.Fail(new NullReferenceException("MerchelloContext was null"));
        }
Beispiel #41
0
        /// <summary>
        /// Initializes a new instance of the <see cref="SalePreparationBase"/> class.
        /// </summary>
        /// <param name="merchelloContext">
        /// The merchello context.
        /// </param>
        /// <param name="itemCache">
        /// The item cache.
        /// </param>
        /// <param name="customer">
        /// The customer.
        /// </param>
        internal SalePreparationBase(IMerchelloContext merchelloContext, IItemCache itemCache, ICustomerBase customer)
        {
            Mandate.ParameterNotNull(merchelloContext, "merchelloContext");
            Mandate.ParameterNotNull(itemCache, "ItemCache");
            Mandate.ParameterCondition(itemCache.ItemCacheType == ItemCacheType.Checkout, "itemCache");
            Mandate.ParameterNotNull(customer, "customer");

            _merchelloContext = merchelloContext;
            _customer = customer;
            _itemCache = itemCache;
            ApplyTaxesToInvoice = true;
        }
Beispiel #42
0
        /// <summary>
        /// The ensure customer creation and convert basket.
        /// </summary>
        /// <param name="customer">
        /// The customer.
        /// </param>
        protected override void EnsureCustomerCreationAndConvertBasket(ICustomerBase customer)
        {
            if (!customer.IsAnonymous) return;

            var memberId = Convert.ToInt32(this.MembershipProviderKey(customer.Key));
            var member = _memberService.GetById(memberId);

            if (MerchelloConfiguration.Current.CustomerMemberTypes.Any(x => x == member.ContentTypeAlias))
            {
                base.EnsureCustomerCreationAndConvertBasket(customer);
            }
        }
Beispiel #43
0
        private void CacheCustomer(ICustomerBase customer)
        {
            // set/reset the cookie
            // TODO decide how we want to deal with cookie persistence options
            var cookie = new HttpCookie(ConsumerCookieKey)
            {
                Value = EncryptionHelper.Encrypt(customer.EntityKey.ToString())
            };
            _umbracoContext.HttpContext.Response.Cookies.Add(cookie);

            _cache.RequestCache.GetCacheItem(ConsumerCookieKey, () => customer.EntityKey);
            _cache.RuntimeCache.GetCacheItem(CacheKeys.CostumerCacheKey(customer.EntityKey), () => customer, TimeSpan.FromMinutes(5), true);
        }
Beispiel #44
0
        /// <summary>
        /// Initializes a new instance of the <see cref="CheckoutContext"/> class.
        /// </summary>
        /// <param name="customer">
        /// The <see cref="ICustomerBase"/> associated with this checkout.
        /// </param>
        /// <param name="itemCache">
        /// The temporary <see cref="IItemCache"/> of the basket <see cref="IItemCache"/> to be used in the
        /// checkout process.
        /// </param>
        /// <param name="merchelloContext">
        /// The <see cref="IMerchelloContext"/>.
        /// </param>
        /// <param name="settings">
        /// The version change settings.
        /// </param>
        public CheckoutContext(ICustomerBase customer, IItemCache itemCache, IMerchelloContext merchelloContext, ICheckoutContextSettings settings)
        {
            Mandate.ParameterNotNull(customer, "customer");
            Mandate.ParameterNotNull(itemCache, "itemCache");
            Mandate.ParameterNotNull(merchelloContext, "merchelloContext");
            Mandate.ParameterNotNull(settings, "settings");

            this.MerchelloContext = merchelloContext;
            this.ItemCache = itemCache;
            this.Customer = customer;
            this.Cache = merchelloContext.Cache.RuntimeCache;
            this.ApplyTaxesToInvoice = true;
            this.Settings = settings;
            this.RaiseCustomerEvents = false;
        }
        protected MerchelloSurfaceContoller(IMerchelloContext merchelloContext)
        {
            if (merchelloContext == null)
            {
                var ex = new ArgumentNullException("merchelloContext");
                LogHelper.Error<MerchelloSurfaceContoller>("The MerchelloContext was null upon instantiating the CartController.", ex);
                throw ex;
            }

            _merchelloContext = merchelloContext;

            var customerContext = new CustomerContext(UmbracoContext); // UmbracoContext is from SurfaceController
            _currentCustomer = customerContext.CurrentCustomer;

            _basket = _currentCustomer.Basket();
        }
        /// <summary>
        /// Validates the constraint against the <see cref="ILineItemContainer"/>
        /// </summary>
        /// <param name="value">
        /// The value to object to which the constraint is to be applied.
        /// </param>
        /// <param name="customer">
        /// The <see cref="ICustomerBase"/>.
        /// </param>
        /// <returns>
        /// The <see cref="Attempt{ILineItemContainer}"/> indicating whether or not the constraint can be enforced.
        /// </returns>
        public override Attempt<ILineItemContainer> TryApply(ILineItemContainer value, ICustomerBase customer)
        {
            if (customer.IsAnonymous) return Attempt<ILineItemContainer>.Fail(new OfferRedemptionException("Cannot be applied by anonymous customers."));

            if (MerchelloContext.Current != null)
            {
                var offerRedeemedService = ((ServiceContext)MerchelloContext.Current.Services).OfferRedeemedService;
                var offerSettingsKey = this.OfferComponentDefinition.OfferSettingsKey;
                var remptions = offerRedeemedService.GetByOfferSettingsKeyAndCustomerKey(offerSettingsKey, customer.Key);

                return remptions.Any()
                           ? this.Fail(value, "Customer has already redeemed this offer.")
                           : this.Success(value);

            }

            return Attempt<ILineItemContainer>.Fail(new NullReferenceException("MerchelloContext was null"));
        }
        /// <summary>
        /// Validates the constraint against the <see cref="ILineItemContainer"/>
        /// </summary>
        /// <param name="value">
        /// The value to object to which the constraint is to be applied.
        /// </param>
        /// <param name="customer">
        /// The <see cref="ICustomerBase"/>.
        /// </param>
        /// <returns>
        /// The <see cref="Attempt{ILineItemContainer}"/> indicating whether or not the constraint can be enforced.
        /// </returns>
        public override Attempt<ILineItemContainer> TryApply(ILineItemContainer value, ICustomerBase customer)
        {
            if (MaximumRedemptions == 0) return Attempt<ILineItemContainer>.Succeed(value);

            if (MerchelloContext.Current != null)
            {
                var offerRedeemedService = ((ServiceContext)MerchelloContext.Current.Services).OfferRedeemedService;
                var offerSettingsKey = this.OfferComponentDefinition.OfferSettingsKey;
                var remptionCount = offerRedeemedService.GetOfferRedeemedCount(offerSettingsKey);

                return remptionCount >= MaximumRedemptions
                           ? this.Fail(value, "Redemption count would exceed the maximum number of allowed")
                           : this.Success(value);

            }

            return this.Fail(value, "MerchelloContext was null");
        }
        public virtual void FixtureSetup()
        {
            //AutoMapperMappings.CreateMappings();

            // Umbraco Application
            var applicationMock = new Mock<UmbracoApplication>();

            // Sets Umbraco SqlSytax and ensure database is setup
            DbPreTestDataWorker = new DbPreTestDataWorker();
            DbPreTestDataWorker.ValidateDatabaseSetup();
            DbPreTestDataWorker.DeleteAllAnonymousCustomers();

            // Merchello CoreBootStrap
            var bootManager = new WebBootManager(DbPreTestDataWorker.TestLogger);
            bootManager.Initialize();

            if(MerchelloContext.Current == null) Assert.Ignore("MerchelloContext.Current is null");

            CurrentCustomer = DbPreTestDataWorker.MakeExistingAnonymousCustomer();

            // Product saves
            ProductService.Created += ProductServiceCreated;
            ProductService.Saved += ProductServiceSaved;
            ProductService.Deleted += ProductServiceDeleted;
            ProductVariantService.Created += ProductVariantServiceCreated;
            ProductVariantService.Saved += ProductVariantServiceSaved;
            ProductVariantService.Deleted += ProductVariantServiceDeleted;

            // BasketCheckout
               // ItemCacheService.Saved += BasketItemCacheSaved;

            SalePreparationBase.Finalizing += SalePreparationBaseOnFinalizing;

            EntityCollectionService.Created += EntityCollectionServiceOnCreated;
            EntityCollectionService.Deleted += EntityCollectionServiceOnDeleted;
        }
Beispiel #49
0
 /// <summary>
 /// The ensure customer and convert basket.
 /// </summary>
 /// <param name="customer">
 /// The customer.
 /// </param>
 protected virtual void EnsureCustomerCreationAndConvertBasket(ICustomerBase customer)
 {
     ConvertBasket(customer, this.GetMembershipProviderKey(), this.GetMembershipProviderUserName());
 }
        public void Init()
        {
            PreTestDataWorker.DeleteAllProducts();
            PreTestDataWorker.DeleteAllItemCaches();

            _customer = PreTestDataWorker.MakeExistingAnonymousCustomer();
            _basket = Basket.GetBasket(MerchelloContext.Current, _customer);

            for(var i = 0; i < ProductCount; i++) _basket.AddItem(PreTestDataWorker.MakeExistingProduct());
            _basket.AddItem(PreTestDataWorker.MakeExistingProduct(false));

            Basket.Save(MerchelloContext.Current, _basket);
        }
Beispiel #51
0
        private void EnsureIsLoggedInCustomer(ICustomerBase customer, string membershipId)
        {
            if (this._cache.RequestCache.GetCacheItem(CacheKeys.EnsureIsLoggedInCustomerValidated(customer.Key)) != null) return;

            var dataValue = this.ContextData.Values.FirstOrDefault(x => x.Key == UmbracoMemberIdDataKey);

            // If the dataValues do not contain the umbraco member id reinitialize
            if (!string.IsNullOrEmpty(dataValue.Value))
            {
                // Assert are equal
                if (!dataValue.Value.Equals(membershipId)) this.Reinitialize(customer);
                return;
            }

            if (dataValue.Value != membershipId) this.Reinitialize(customer);
        }
Beispiel #52
0
 /// <summary>
 /// Purges persisted checkout information
 /// </summary>
 /// <param name="merchelloContext">
 /// The merchello Context.
 /// </param>
 /// <param name="customer">
 /// The customer.
 /// </param>
 private static void Reset(IMerchelloContext merchelloContext, ICustomerBase customer)
 {
     customer.ExtendedData.RemoveValue(Core.Constants.ExtendedDataKeys.ShippingDestinationAddress);
     customer.ExtendedData.RemoveValue(Core.Constants.ExtendedDataKeys.BillingAddress);
     SaveCustomer(merchelloContext, customer);
 }
Beispiel #53
0
 /// <summary>
 /// Saves the current customer
 /// </summary>
 /// <param name="merchelloContext">
 /// The merchello Context.
 /// </param>
 /// <param name="customer">
 /// The customer.
 /// </param>
 private static void SaveCustomer(IMerchelloContext merchelloContext, ICustomerBase customer)
 {
     if (typeof(AnonymousCustomer) == customer.GetType())
     {
         merchelloContext.Services.CustomerService.Save(customer as AnonymousCustomer);
     }
     else
     {
         ((CustomerService)merchelloContext.Services.CustomerService).Save(customer as Customer);
     }
 }
Beispiel #54
0
        /// <summary>
        /// Gets the checkout <see cref="IItemCache"/> for the <see cref="ICustomerBase"/>
        /// </summary>
        /// <param name="merchelloContext">
        /// The <see cref="IMerchelloContext"/>
        /// </param>
        /// <param name="customer">
        /// The customer associated with the checkout
        /// </param>
        /// <param name="versionKey">
        /// The version key for this <see cref="SalePreparationBase"/>
        /// </param>
        /// <returns>
        /// The <see cref="IItemCache"/> associated with the customer checkout
        /// </returns>
        protected static IItemCache GetItemCache(IMerchelloContext merchelloContext, ICustomerBase customer, Guid versionKey)
        {
            var runtimeCache = merchelloContext.Cache.RuntimeCache;

            var cacheKey = MakeCacheKey(customer, versionKey);
            var itemCache = runtimeCache.GetCacheItem(cacheKey) as IItemCache;
            if (itemCache != null) return itemCache;

            itemCache = merchelloContext.Services.ItemCacheService.GetItemCacheWithKey(customer, ItemCacheType.Checkout, versionKey);

            // this is probably an invalid version of the checkout
            if (!itemCache.VersionKey.Equals(versionKey))
            {
                var oldCacheKey = MakeCacheKey(customer, itemCache.VersionKey);
                runtimeCache.ClearCacheItem(oldCacheKey);
                Reset(merchelloContext, customer);

                // delete the old version
                merchelloContext.Services.ItemCacheService.Delete(itemCache);
                return GetItemCache(merchelloContext, customer, versionKey);
            }

            runtimeCache.InsertCacheItem(cacheKey, () => itemCache);
            return itemCache;
        }
Beispiel #55
0
 /// <summary>
 /// Generates a unique cache key for runtime caching of the <see cref="SalePreparationBase"/>
 /// </summary>
 /// <param name="customer">The <see cref="ICustomerBase"/> for which to generate the cache key</param>
 /// <param name="versionKey">The version key</param>
 /// <returns>The unique CacheKey string</returns>
 /// <remarks>
 /// 
 /// CacheKey is assumed to be unique per customer and globally for CheckoutBase.  Therefore this will NOT be unique if 
 /// to different checkouts are happening for the same customer at the same time - we consider that an extreme edge case.
 /// 
 /// </remarks>
 private static string MakeCacheKey(ICustomerBase customer, Guid versionKey)
 {
     var itemCacheTfKey = EnumTypeFieldConverter.ItemItemCache.Checkout.TypeKey;
     return Cache.CacheKeys.ItemCacheCacheKey(customer.Key, itemCacheTfKey, versionKey);
 }
Beispiel #56
0
        /// <summary>
        /// Converts an anonymous customer's basket to a customer basket
        /// </summary>
        /// <param name="customer">
        /// The anonymous customer - <see cref="ICustomerBase"/>.
        /// </param>
        /// <param name="membershipId">
        /// The Membership Providers .
        /// </param>
        /// <param name="customerLoginName">
        /// The customer login name.
        /// </param>
        protected void ConvertBasket(ICustomerBase customer, string membershipId, string customerLoginName)
        {
            var anonymousBasket = Basket.GetBasket(this._merchelloContext, customer);

            customer = this.CustomerService.GetByLoginName(customerLoginName) ??
                            this.CustomerService.CreateCustomerWithKey(customerLoginName);

            this.ContextData.Key = customer.Key;
            this.ContextData.Values.Add(new KeyValuePair<string, string>(UmbracoMemberIdDataKey, membershipId));
            var customerBasket = Basket.GetBasket(this._merchelloContext, customer);

            //// convert the customer basket
            ConvertBasket(anonymousBasket, customerBasket);

            this.CacheCustomer(customer);
            this.CurrentCustomer = customer;
        }
Beispiel #57
0
        /// <summary>
        /// The caches the customer.
        /// </summary>
        /// <param name="customer">
        /// The customer.
        /// </param>
        private void CacheCustomer(ICustomerBase customer)
        {
            // set/reset the cookie
            // TODO decide how we want to deal with cookie persistence options
            var cookie = new HttpCookie(CustomerCookieName)
            {
                Value = this.ContextData.ToJson()
            };

            // Ensure a session cookie for Anonymous customers
            // TODO - on persisted authenticcation, we need to synch the cookie expiration
            if (customer.IsAnonymous) cookie.Expires = DateTime.MinValue;

            this._umbracoContext.HttpContext.Response.Cookies.Add(cookie);

            this._cache.RequestCache.GetCacheItem(CustomerCookieName, () => this.ContextData);
            this._cache.RuntimeCache.GetCacheItem(CacheKeys.CustomerCacheKey(customer.Key), () => customer, TimeSpan.FromMinutes(5), true);
        }
 /// <summary>
 /// Validates the constraint against the <see cref="ILineItemContainer"/>
 /// </summary>
 /// <param name="value">
 /// The value to object to which the constraint is to be applied.
 /// </param>
 /// <param name="customer">
 /// The <see cref="ICustomerBase"/>.
 /// </param>
 /// <returns>
 /// The <see cref="Attempt{ILineItemContainer}"/> indicating whether or not the constraint can be enforced.
 /// </returns>
 public override Attempt<ILineItemContainer> TryApply(ILineItemContainer value, ICustomerBase customer)
 {
     return !value.ContainsAnyCoupons()
                ? this.Success(value)
                : this.Fail(value, "One or more coupons have already been added.");
 }
Beispiel #59
0
        /// <summary>
        /// Reinitializes the customer context
        /// </summary>
        /// <param name="customer">
        /// The <see cref="CustomerBase"/>
        /// </param>
        /// <remarks>
        /// Sometimes useful to clear the various caches used internally in the customer context
        /// </remarks>
        public virtual void Reinitialize(ICustomerBase customer)
        {
            // customer has logged out, so we need to go back to an anonymous customer
            var cookie = this._umbracoContext.HttpContext.Request.Cookies[CustomerCookieName];

            if (cookie == null)
            {
                this.Initialize();
                return;
            }

            cookie.Expires = DateTime.Now.AddDays(-1);

            this._cache.RequestCache.ClearCacheItem(CustomerCookieName);
            this._cache.RuntimeCache.ClearCacheItem(CacheKeys.CustomerCacheKey(customer.Key));

            this.Initialize();
        }
 /// <summary>
 /// Validates the constraint against the <see cref="ILineItemContainer"/>
 /// </summary>
 /// <param name="value">
 /// The value to object to which the constraint is to be applied.
 /// </param>
 /// <param name="customer">
 /// The <see cref="ICustomerBase"/>.
 /// </param>
 /// <returns>
 /// The <see cref="Attempt{ILineItemContainer}"/> indicating whether or not the constraint can be enforced.
 /// </returns>
 public override Attempt<ILineItemContainer> TryApply(ILineItemContainer value, ICustomerBase customer)
 {
     return Attempt<ILineItemContainer>.Succeed(CreateNewLineContainer(value.Items.Where(x => x.LineItemType != LineItemType.Shipping)));
 }