Ejemplo n.º 1
0
 public BasketComponent(UserManager <ApplicationUser> userManager, SignInManager <ApplicationUser> signInManager, IInventory context, IBasket basket)
 {
     _context       = context;
     _basket        = basket;
     _userManager   = userManager;
     _signInManager = signInManager;
 }
Ejemplo n.º 2
0
 private IEnumerable <IProduct> TakeEBooksThisAuthor(IBasket basket, string author, int count)
 {
     return(basket.GetProducts()
            .Where(product => IsEBookThisAuthor(product, author))
            .OrderBy(product => product.Price)
            .Take(count));
 }
Ejemplo n.º 3
0
        public void Can_Remove_An_Existing_Item_From_A_Basket()
        {
            //// Arrange
            var product1 = PreTestDataWorker.MakeExistingProduct();
            var product2 = PreTestDataWorker.MakeExistingProduct();
            var product3 = PreTestDataWorker.MakeExistingProduct();

            _basket.AddItem(product1);
            _basket.AddItem(product2);
            _basket.AddItem(product3);
            Basket.Save(MerchelloContext.Current, _basket);
            Assert.IsTrue(3 == _basket.Items.Count);

            //// Act
            _basket.RemoveItem(product2.Sku);
            Basket.Save(MerchelloContext.Current, _basket);
            _basket = Basket.GetBasket(MerchelloContext.Current, _customer);

            var price = _basket.TotalBasketPrice;

            Console.WriteLine(price);

            //// Assert
            Assert.IsTrue(2 == _basket.Items.Count);
        }
Ejemplo n.º 4
0
        public Purchase ConvertBasketToSale(HttpContextBase context, IUserInfo user, IBasket basket, decimal taxRate, string saleCodePrefix)
        {
            UserStatus status = UserStatus.None;

            // if we have a user that has not yet been created, create them
            if (!_securityService.Exists(user.Identity.Name))
            {
                status = _securityService.CreateUser(user);

                if (status != UserStatus.Success)
                {
                    throw new SecurityException($"Unable to create user for sale: {_securityService.StatusMessage(status)}");
                }
            }

            // save it to the datasource so it can be used in the sale
            SaveBasket(user, basket);

            // create sale
            SaleFlags  flags = (basket.Delivery.DeliveryType == DeliveryType.Address ? SaleFlags.Delivery : SaleFlags.CollectionOnly) | SaleFlags.Created;
            SaleEntity sale  = _productDataProvider.CreateAndReturnSale(user.GetUniqueId <Guid>(), flags, taxRate, string.Concat(saleCodePrefix, GenerateSaleCode()), null);

            ClearBasket(context, user, emptyDatasource: false); // clear the basket (leave the basket intact in the datasource - this binds the sale)

            Purchase purchase = _checkoutProvider.CreateSale(sale);

            purchase.UserStatus = status;

            return(purchase);
        }
		public IElectronicPayment CreatePayment(IBasket order, ITextTranslator translator) {
			
			IElectronicPayment payment = new ElectronicPayment();
			PopulatePayment(payment, order, translator);

			return payment;
		}
 /// <summary>
 /// Create Basket For User.
 /// </summary>
 /// <param name='operations'>
 /// The operations group for this extension method.
 /// </param>
 /// <param name='userGuid'>
 /// The users unique identifier.
 /// </param>
 /// <param name='cancellationToken'>
 /// The cancellation token.
 /// </param>
 public static async Task <Guid?> PostBasketAsyncAsync(this IBasket operations, Guid userGuid, CancellationToken cancellationToken = default(CancellationToken))
 {
     using (var _result = await operations.PostBasketAsyncWithHttpMessagesAsync(userGuid, null, cancellationToken).ConfigureAwait(false))
     {
         return(_result.Body);
     }
 }
		public void PopulatePayment(IElectronicPayment payment, IBasket order, ITextTranslator translator) {

			BasketDecorator basket = new BasketDecorator(order);

			payment.LocalRequestReference = basket.OrderHeader.OrderHeaderID.ToString();
			payment.Description = string.Format(translator.GetText("web_store_purchase{0}"), payment.LocalRequestReference);
			payment.PaymentAmount = basket.GrandTotal;
			payment.PaymentDate = DateTime.Now;

            IUserDetails userDetails = (order.UserDetails != null) ? new UserDecorator(order.UserDetails) : order.AltUserDetails;

            //payment.UserInfo.UserDetails. = userDetails.FirstName + " " + userDetails.LastName; -- Is this needed?
            if(payment.UserInfo.UserDetails == null){
                payment.UserInfo.UserDetails = userDetails;
            }

			IAddress invoiceAddress = basket.OrderHeader.InvoiceAddress; 

			payment.UserInfo.UserAddress = invoiceAddress;

			if (invoiceAddress.AddressLine3 != null && invoiceAddress.AddressLine3.Length > 0) {
				payment.UserInfo.UserAddress.AddressLine2 = invoiceAddress.AddressLine2 + ", " + invoiceAddress.AddressLine3;
			} else {
				payment.UserInfo.UserAddress.AddressLine2 = invoiceAddress.AddressLine2;
			}

			payment.UserInfo.UserAddress.City = invoiceAddress.City;
			payment.UserInfo.UserAddress.Region = invoiceAddress.Region;
			payment.UserInfo.UserAddress.Postcode = invoiceAddress.Postcode;
			
			ITextTranslator ccTrans = TranslatorUtils.GetTextTranslator(typeof(CountryCode), translator.CultureCode);
			payment.UserInfo.UserAddress.CountryCode = invoiceAddress.CountryCode;
		}
Ejemplo n.º 8
0
        public void Init()
        {
            PreTestDataWorker.DeleteAllItemCaches();

            _customer = PreTestDataWorker.MakeExistingAnonymousCustomer();
            _basket   = Basket.GetBasket(MerchelloContext.Current, _customer);
        }
Ejemplo n.º 9
0
        public IReceipt ApplyTaxes(IBasket basket)
        {
            var receipt        = new Receipt();
            var totalWithTaxes = 0d;

            foreach (var product in basket.Products)
            {
                var taxes = ProductCategoryTaxLiabilities
                            .Where(taxLiability =>
                                   product
                                   .Categories
                                   .Any(category => taxLiability.Category.Description == category.Description))
                            .SelectMany(liability => liability.Taxes) ?? new ITax[] { };

                var totalTaxRate = 1 + taxes.Aggregate(0f, (soFar, currentTax) => soFar + currentTax.Rate);

                totalWithTaxes        += totalTaxRate * product.Price;
                receipt.ProductSummary = receipt
                                         .ProductSummary
                                         .Concat(new[] { $"1 {product.Description}: £{(product.Price * totalTaxRate).ToString("0.00")}" })
                                         .ToArray();
            }

            var taxesOnly = (float)totalWithTaxes - basket.Products.Sum(product => product.Price);

            receipt.SaleTaxesDescription = $"Sale Taxes: £{Round(taxesOnly).ToString("0.00")}";
            receipt.TotalDescription     = $"Total: £{Math.Round(totalWithTaxes, 2).ToString("0.00")}";
            return(receipt);
        }
Ejemplo n.º 10
0
 public BasketPresenter(IBasketView view, ProductService productService,
                        IBasket basket)
 {
     _productService = productService;
     _view           = view;
     _basket         = basket;
 }
        public String RenderBasketOnceResolved(IBasket basket)
        {
            var resolver = new RenderBasket_IBasketResolver(this);

            basket.Accept(resolver);
            return(resolver.Result);
        }
        public ProcessStatusMessage Process(IBasket basket) {

            basket.GrandTotal = new Money(basket.SubTotal);
            basket.GrandTotal.Add(basket.TaxPrice);

            return new ProcessStatusMessage(ProcessStatus.Success);
        }
Ejemplo n.º 13
0
 public ProductDetailPresenter(IProductDetailView view, ProductService productService, IBasket basket, IPageNavigator pageNavigator)
 {
     _view = view;
     _productService = productService;
     _basket = basket;
     _pageNavigator = pageNavigator;
 }
Ejemplo n.º 14
0
        public static RegionBasket TryAsRegionBasket(this IBasket basket)
        {
            var resolver = new TryAs_IBasketResolver();

            basket.Accept(resolver);
            return(resolver.RegionBasketOpt);
        }
Ejemplo n.º 15
0
        public static CountryBasket TryAsCountryBasket(this IBasket basket)
        {
            var resolver = new TryAs_IBasketResolver();

            basket.Accept(resolver);
            return(resolver.CountryBasketOpt);
        }
        public override float CancelDiscount(IBasket basket)
        {
            var discountedItemCount = basket.Items.FirstOrDefault(i => i.Id == ProductId)?.ProductsCount;

            if (discountedItemCount == null)
            {
                throw new ArgumentException($"{Name}.Item with id: {ProductId} was not found.");
            }

            var existingItem = basket.Items.FirstOrDefault(i => i.Id == _bonusProduct.Id);

            if (existingItem == null)
            {
                throw new ArgumentException($"{Name}.Item with id: {_bonusProduct.Id} was not found.");
            }

            if (existingItem.ProductsCount > discountedItemCount)
            {
                existingItem.ProductsCount -= discountedItemCount.Value;
            }
            else
            {
                basket.RemoveBonusProduct(_bonusProduct.Id, discountedItemCount.Value);
            }

            return(basket.GrandTotalPrice);
        }
Ejemplo n.º 17
0
 private void EnsureOperationAllowed(Operations operation, IBasket basket, IVisit visit)
 {
     if (!IsOperationAllowed(User, operation, basket, visit))
     {
         throw new UnauthorizedAccessException($"User is not allowed to perform '{operation}'");
     }
 }
Ejemplo n.º 18
0
        public static BasketWhitoutCheckOutId ClearBasket(IProduct _product, IBasket _basket, ResolveFieldContext <object> context)
        {
            string checkoutId = context.GetArgument <string>("checkoutId");
            Basket basket     = _basket.ClearBasket(checkoutId);

            return(ConvertBasketToBasketWithProductObjects.BasketConverter(_product, basket));
        }
Ejemplo n.º 19
0
 public BasketController(SignInManager <ApplicationUser> signInManager, UserManager <ApplicationUser> userManager, IBasket basket, IInventory context)
 {
     _context       = context;
     _basket        = basket;
     _signInManager = signInManager;
     _userManager   = userManager;
 }
		public BasketDecorator(IBasket basket) {
            if (basket != null) {
                _basket = basket;
            } else {
                throw new ArgumentException("Null child basket supplied to BasketDecorator");
            }
		}
Ejemplo n.º 21
0
        /// <inheritdoc />
        public decimal CalculateBasketPrice(IBasket basket)
        {
            IList <IOffer> offerList = new List <IOffer>();

            foreach (var basketItem in basket.Items)
            {
                // offer 1 Buy 2 Butter and get a Bread at 50% off
                if (basketItem.Id == 1 || basketItem.Id == 3)
                {
                    ApplyOffer(basketItem, offerList, 1);
                }
                // offer 2 Buy 3 Milk and get the 4th milk for free
                else if (basketItem.Id == 2)
                {
                    ApplyOffer(basketItem, offerList, 2);
                }
            }

            foreach (var offer in offerList)
            {
                offer.CheckOfferConditions();
            }

            Rebalance(basket, offerList);

            decimal fullPrices = basket.Items.Sum(i => i.Price);

            decimal offerPrices = offerList.Sum(l => l.OfferPrice);

            return(fullPrices + offerPrices);
        }
Ejemplo n.º 22
0
 public AdminController(UserManager <ApplicationUser> userManager, IInventory inventory, IOrder order, IBasket basket)
 {
     _userManager = userManager;
     _inventory   = inventory;
     _order       = order;
     _basket      = basket;
 }
Ejemplo n.º 23
0
        private Core.SecurityModel DeserializeAdditionalSecurity(
            IBasket basket,
            Aims.Data.Server.SecurityModel securityModel,
            TopDown.Core.ManagingTargetingTypes.TargetingTypeGroup targetingTypeGroup,
            TopDown.Core.ManagingBenchmarks.BenchmarkRepository benchmarkRepository
            )
        {
            var baseExpression       = this.modelBuilder.CreateBaseExpression();
            var benchmarkExpression  = this.modelBuilder.CreateBenchmarkExpression();
            var baseActiveExpression = this.modelBuilder.CreateBaseActiveExpression(baseExpression, benchmarkExpression);
            var result = new Core.SecurityModel(
                this.deserializer.DeserializeSecurity(securityModel),
                baseExpression,
                benchmarkExpression,
                targetingTypeGroup.GetBgaPortfolios().Select(bgaPortfolio => new Core.PortfolioTargetModel(
                                                                 bgaPortfolio,
                                                                 this.modelBuilder.CreatePortfolioTargetExpression(bgaPortfolio.Name))
                                                             ).ToList(),
                baseActiveExpression
                );

            if (!String.IsNullOrWhiteSpace(targetingTypeGroup.BenchmarkIdOpt))
            {
                this.benchmarkInitializer.InitializeSecurity(basket, targetingTypeGroup.BenchmarkIdOpt, result, benchmarkRepository);
            }
            return(result);
        }
        /// <summary>
        /// Creates a <see cref="ICheckoutShipRateQuoteModel"/>.
        /// </summary>
        /// <param name="basket">
        /// The <see cref="IBasket"/>.
        /// </param>
        /// <param name="destination">
        /// The destination <see cref="IAddress"/>.
        /// </param>
        /// <param name="tryGetCached">
        /// A value to indicate whether or not to get checked shipping provider quotes.
        /// </param>
        /// <returns>
        /// The modified <see cref="ICheckoutShipRateQuoteModel"/>.
        /// </returns>
        public TShipRateQuoteModel Create(IBasket basket, IAddress destination, bool tryGetCached = true)
        {
            var shipment = basket.PackageBasket(destination).FirstOrDefault();

            var quotes = (shipment != null
                            ? _gatewayContext.Shipping.GetShipRateQuotesForShipment(shipment, tryGetCached).OrderBy(x => x.Rate)
                            : Enumerable.Empty <IShipmentRateQuote>()).ToArray();

            var shipMethodKey = quotes.Any() ? quotes.First().ShipMethod.Key : Guid.Empty;

            var selectItems = quotes.Select(x => new SelectListItem
            {
                Value = x.ShipMethod.Key.ToString(),
                Text  = string.Format("{0} ({1})", x.ShipMethod.Name, x.Rate.AsFormattedCurrency())
            });

            var model = new TShipRateQuoteModel
            {
                ShipMethodKey  = shipMethodKey,
                ShippingQuotes = selectItems,
                ProviderQuotes = quotes
            };

            return(OnCreate(model, basket, destination));
        }
Ejemplo n.º 25
0
        private IBasket AddToBasket(IProduct product)
        {
            var basket = HttpContext.Session.GetObjectFromJson <Basket>("Basket");

            if (basket == null)
            {
                basket = new Basket();
            }

            var basketItem = basket.BasketItems.Where(x => x.Product == product).FirstOrDefault();

            if (basketItem == null)
            {
                basket.BasketItems.Add(new BasketItem()
                {
                    Product      = (Product)product,
                    ProductCount = 1
                });
            }
            else
            {
                basketItem.ProductCount++;
            }
            basket.BasketCount++;
            basket.BasketTotalPrice += product.UnitPrice;

            HttpContext.Session.SetObjectAsJson("Basket", basket);

            return(basket);
        }
Ejemplo n.º 26
0
        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");
        }
Ejemplo n.º 27
0
        public void ThenTheErrorMessageShouldBe(string expectedErrorMessage)
        {
            IBasket basket             = (IBasket)_context["Basket"];
            string  actualErrorMessage = basket.ErrorMessage;

            Assert.IsTrue(expectedErrorMessage == actualErrorMessage);
        }
Ejemplo n.º 28
0
        protected Decimal?TryGetTotalByBasketOnceResolved(IBasket basket, String benchmarkId, BenchmarkRepository benchmarkRepository)
        {
            var resolver = new TryGetTotalByBasket_IBasketResolver(this, benchmarkRepository, benchmarkId);

            basket.Accept(resolver);
            return(resolver.Result);
        }
Ejemplo n.º 29
0
        public void ThenTheTotalPriceShouldBe(Decimal expectedTotalPrice)
        {
            IBasket basket           = (IBasket)_context["Basket"];
            decimal actualTotalPrice = basket.TotalPrice;

            Assert.AreEqual(expectedTotalPrice, actualTotalPrice);
        }
Ejemplo n.º 30
0
        public void ThenThereShouldBeNoErrorMessage()
        {
            IBasket basket             = (IBasket)_context["Basket"];
            string  actualErrorMessage = basket.ErrorMessage;

            Assert.IsTrue(String.IsNullOrEmpty(actualErrorMessage));
        }
Ejemplo n.º 31
0
        public Register(IBasket basket, IDisplay display, IScanner scanner)
        {
            logger = LoggerFactory.GetLogger();

            this.basket = basket;
            this.display = display;
            this.scanner = scanner;

            basket.OnAdd += display.AddProduct;
            basket.AddSuccess += scanner.FlashLed;
            basket.AddFail += scanner.FlashLed;
            basket.OnUpdate += display.UpdateProduct;
            basket.OnRemove += display.RemoveProduct;
            basket.OnUpdateTotalCost += display.UpdateTotalCost;
            basket.OnUpdateProductCount += display.UpdateProductCount;

            display.OnStartScan += scanner.Start;
            display.OnStopScan += scanner.Stop;
            display.OnClear += basket.Clear;

            scanner.OnRead += new OnReadHandler(scanner_OnRead);

            logger.Write("Register", LogLevel.INFO, "Register initialized");

            display.Display();
        }
Ejemplo n.º 32
0
        public void GivenIHaveAddedTheFollowingItemsToMyBasket(Table table)
        {
            List <Product> products = table.CreateSet <Product>().ToList();
            IBasket        basket   = (IBasket)_context["Basket"];

            basket.AddItemsToBasket(products);
        }
		public virtual void BindOrder(IBasket order) {

			if (ctlUserView != null) {
                if (order.UserDetails != null) {
                    ctlUserView.BindUserDetails(order.UserDetails);
                } else {
                    ctlUserView.BindUserDetails(order.AltUserDetails);
                }
			}

			if (ctlAddressView != null) {
                
                bool showAddress = false;
                
                if (order.OrderHeader.InvoiceAddress != null) {
					ctlAddressView.BindInvoiceAddress(order.OrderHeader.InvoiceAddress);
                    showAddress = true;
				}
				if (order.OrderHeader.DeliveryAddress != null) {
					ctlAddressView.BindDeliveryAddress(order.OrderHeader.DeliveryAddress);
                    showAddress = true;
				}

                ctlAddressView.Visible = showAddress;
			}

			if (ctlOrderView != null) {
				ctlOrderView.BindOrder(order);
			}
		}
        protected virtual void RenderBasket(IBasket basket) {
            try {

                if (basket != null) {

                    BasketDecorator decoratedBasket = new BasketDecorator(basket);
                    litBasketTotal.Text = HtmlFormatUtils.FormatMoney(decoratedBasket.StandardItemPrice);
                    ArrayList standardItems = decoratedBasket.GetStandardItems();

                    if (standardItems.Count > 0) {

                        int itemCounter = 0;

                        for (int i = 0; i < standardItems.Count; i++) {
                            itemCounter += ((IBasketLine)standardItems[i]).Quantity;
                        }

                        ItemCount = itemCounter;
                    }
                }

            } catch (System.Threading.ThreadAbortException) {
            } catch (Exception ex) {
                LogManager.GetLogger(GetType()).Error(ex);
            }
        }
Ejemplo n.º 35
0
        public QueryShop(IProduct _product, IBasket _basket)
        {
            Field <ListGraphType <ProductType> >("allProducts", arguments: new QueryArguments(
                                                     new QueryArgument <AllProductsInputType> {
                Name = "ordering"
            }
                                                     ),
                                                 resolve: context => GetAllProductsQuery.GetAllProducts(_product, context)
                                                 );

            Field <ProductType>("product",
                                arguments: new QueryArguments(
                                    new QueryArgument <IntGraphType> {
                Name = "id"
            }
                                    ),
                                resolve: context => GetProductByIdQuery.GetProductById(_product, context)
                                );

            Field <BasketWithProductObjectsType>("basket",
                                                 arguments: new QueryArguments(
                                                     new QueryArgument <StringGraphType> {
                Name = "checkoutId"
            }
                                                     ),
                                                 resolve: context => GetBasketByCheckoutIdQuery.GetBasketByCheckoutId(_product, _basket, context)
                                                 );
        }
Ejemplo n.º 36
0
        public void AddProductWhenNullShouldThrowException()
        {
            webshop = new MyWebshop(basket = new Basket());
            Product p = null;

            Assert.Throws <IncorrectProductException>(() => webshop.Basket.AddProduct(p, 2), "Product can not be null");
        }
Ejemplo n.º 37
0
        public BasketManagerTests()
        {
            var dataHelper = new DataHelper();

            _basket   = dataHelper.GetBasketManager();
            _products = dataHelper.GetProducts();
        }
Ejemplo n.º 38
0
        public string GetCheck(IBasket basket)
        {
            List <int> listTotals    = new List <int>();
            string     text          = "";
            int        countDiscount = 0;
            int        countTotal    = 0;

            foreach (var productsBasket in basket.GetProducts())
            {
                countDiscount = 0;
                if (_promotions.DiscountExists(productsBasket))
                {
                    foreach (var discount in _promotions.GetDiscounts())
                    {
                        foreach (var productsDiscount in discount.GetProducts())
                        {
                            if (productsBasket.GetName() == productsDiscount.GetName())
                            {
                                countDiscount++;
                            }
                        }
                    }
                }
                else
                {
                    text += GetStringProduct(productsBasket);
                }
            }

            return(text);
        }
        public void Save(IBasket basket) {

            Basket b = basket as Basket;

            if (b != null) {
                _commonDao.SaveOrUpdateObject(b);
            }
        }
Ejemplo n.º 40
0
        /// <summary>
        /// Initializes a new instance of the <see cref="BasketConversionBase"/> class.
        /// </summary>
        /// <param name="anonymousBasket">
        /// The anonymousBasket.
        /// </param>
        /// <param name="customerBasket">
        /// The customerBasket.
        /// </param>
        internal BasketConversionBase(IBasket anonymousBasket, IBasket customerBasket)
        {
            Mandate.ParameterNotNull(anonymousBasket, "anonymousBasket");
            Mandate.ParameterNotNull(customerBasket, "customerBasket");

            AnonymousBasket = anonymousBasket;
            CustomerBasket = customerBasket;
        }
 public void SetCurrentBasket(IStoreContext context, IBasket basket) {
     if (basket != null) {
         context.CurrentBasket = basket;
         context.BasketID = basket.BasketID;
     } else {
         context.BasketID = StoreContext.ID_NULL;
         context.IsBasketEmpty = true;
     }
 }
Ejemplo n.º 42
0
		/// <summary>
		/// Gets the payment providers for the given basket 
		/// </summary>
		/// <param name="order">the order to match the payment providers with</param>
		/// <param name="useZone">if set to <c>true</c> [use zone].</param>
		/// <param name="storeAlias">The store alias.</param>
		/// <param name="currencyCode">The currency code.</param>
		/// <returns></returns>
		public static IEnumerable<IBillingProvider> GetPaymentProvidersForOrder(IBasket order, bool useZone = true,
			string storeAlias = null, string currencyCode = null)
		{
			var orderInfo = Basket.GetOrderInfoFromOrderBasket(order);
			var localization = StoreHelper.GetLocalizationOrCurrent(storeAlias, currencyCode);
			return
				PaymentProviderHelper.GetBillingProvidersForOrder(orderInfo, useZone, storeAlias, currencyCode)
					.Select(s => new BillingFulfillmentAdaptor(s, orderInfo.PricesAreIncludingVAT, localization));
		}
Ejemplo n.º 43
0
        /// <summary>
        /// Refreshes the runtime cache
        /// </summary>
        /// <param name="merchelloContext">The merchello context</param>
        /// <param name="basket">The <see cref="IBasket"/></param>
        public static void Refresh(IMerchelloContext merchelloContext, IBasket basket)
        {
            var cacheKey = MakeCacheKey(basket.Customer);
            merchelloContext.Cache.RuntimeCache.ClearCacheItem(cacheKey);

            var customerItemCache = merchelloContext.Services.ItemCacheService.GetItemCacheWithKey(basket.Customer, ItemCacheType.Basket);
            basket = new Basket(customerItemCache, basket.Customer);
            merchelloContext.Cache.RuntimeCache.GetCacheItem(cacheKey, () => basket);
        }
		public Money CalculatePriceReduction(IBasket basket) {

			//Spent a lot?
			if (basket.SubTotal.Amount > PromotionBase.AuxData) {
				return AllowedDiscount(GenericPromotion.CalculateDefaultPriceReduction(basket.SubTotal, 1, PromotionBase), basket);
			}

			//No?
			return new Money(basket.CurrencyCode, 0);
		}
		public void BindOrder(IBasket order) {

            ECommerceModule mod = Module as ECommerceModule;

			Order = new BasketDecorator(order);
			Header = order.OrderHeader;

			rptBasketLines.DataSource = Order.GetStandardItems();
			rptBasketLines.DataBind();
		}
Ejemplo n.º 46
0
 public void ProcessVoucher(IVoucher voucher, IBasket basket, IBasketVoucher basketVoucher)
 {
     if (voucher.MinSpend < basket.BasketTotal())
     {
         basketVoucher.Value = voucher.Value;
         basketVoucher.VoucherCode = voucher.VoucherCode;
         basketVoucher.VoucherDescription = voucher.VoucherDescription;
         basketVoucher.VoucherId = voucher.VoucherId;
         basket.AddBasketVoucher(basketVoucher);
     }  
 }
        public IBasketLine CreateBasketLine(IBasket basket) {

            Basket b = basket as Basket;

            if (b != null) {
                BasketItem item = new BasketItem();
                item.Basket = b;
                return item;
            }

            return null;
        }
        public ProcessStatusMessage Process(IBasket basket) {

            basket.SubTotal = new Money(basket.CurrencyCode, 0M);

            foreach (BasketItem line in basket.BasketItemList) {
                if (line.LinePrice != null) {
                    basket.SubTotal.Add(line.LinePrice);
                }
            }

            return new ProcessStatusMessage(ProcessStatus.Success);
        }
Ejemplo n.º 49
0
        private Database()
        {
            userEp =  new EndpointAddress("http://localhost:8733/WCFService/UserImp/");
            userProxy = ChannelFactory<IUser>.CreateChannel(new BasicHttpBinding(), userEp);

            orderEp =  new EndpointAddress("http://localhost:8733/WCFService/OrderImp/");
            orderProxy = ChannelFactory<IOrder>.CreateChannel(new BasicHttpBinding(), orderEp);

            productEp =  new EndpointAddress("http://localhost:8733/WCFService/ProductImp/");
            productProxy = ChannelFactory<IProduct>.CreateChannel(new BasicHttpBinding(), productEp);

            basketEp = new EndpointAddress("http://localhost:8733/WCFService/BasketImp/");
            basketProxy = ChannelFactory<IBasket>.CreateChannel(new BasicHttpBinding(), basketEp);
        }
        public ProcessStatusMessage Process(IBasket order) {

            foreach (BasketItem line in order.BasketItemList) {

                line.UnitPrice = new Money();
                line.UnitPrice.Amount = Igentics.Common.Util.RandomSingleton.Instance.Next((int) (100 * _minPrice), (int) (100 * _maxPrice));
                line.UnitPrice.Divide(100);

                line.LinePrice = new Money(line.UnitPrice);
                line.LinePrice.Multiply(line.Quantity);
                line.PricingStatus = PricingStatus.OK;
            }

            return new ProcessStatusMessage(ProcessStatus.Success);
        }
        public ProcessStatusMessage Process(IBasket order) {

            if (order.SubTotal != null) {

                foreach (BandedCharge charge in _chargeList) {

                    decimal bandBoundary = charge.Boundary;
                    if (order.SubTotal.Amount > bandBoundary) {
                        order.DeliveryCharge = new Money(charge.Charge);
                    }
                }
            }

            return new ProcessStatusMessage(ProcessStatus.Success);
        }
Ejemplo n.º 52
0
        internal static BasketSalePreparation GetBasketCheckoutPreparation(IMerchelloContext merchelloContext, IBasket basket)
        {
            var customer = basket.Customer;
            var itemCache = GetItemCache(merchelloContext, customer, basket.VersionKey);

            if (!itemCache.Items.Any())
            {
                // this is either a new preparation or a reset due to version
                foreach (var item in basket.Items)
                {
                    // convert to a LineItem of the same type for use in the CheckoutPrepartion collection
                    itemCache.AddItem(item.AsLineItemOf<ItemCacheLineItem>());
                }
            }
            return new BasketSalePreparation(merchelloContext, itemCache, customer);
        }
Ejemplo n.º 53
0
        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();
        }
		public void Process(IBasket basket) {

			basket.SubTotal.Amount = 0;

			foreach (IBasketLine line in basket.BasketItemList) {
				switch (line.ItemType) {
					case BasketItemType.CreditNote:
					case BasketItemType.Discount:
					case BasketItemType.Voucher:
					case BasketItemType.OtherCredit:
						basket.SubTotal.Subtract(line.LinePrice);
						break;
					default:
						basket.SubTotal.Add(line.LinePrice);
						break;
				}
			}
		}
        void IOrderProcessor.Process(IBasket order) {
            foreach (IBasketLine line in order.BasketItemList) {

                BasketItem item = line as BasketItem;

                if (item != null && item.ItemType == Cuyahoga.Modules.ECommerce.Util.Enums.BasketItemType.DeliveryCharge) {
                    if (item.LinePrice.Amount < _minimumDeliveryCharge) {
                        order.UpdateItem(item, "Minimum Delivery Charge", _minimumDeliveryCharge);
                    }

                    _hasDeliveryAttached = true;
                }
            }

            if (!_hasDeliveryAttached) {
                order.AddItem(Cuyahoga.Modules.ECommerce.Util.Enums.BasketItemType.DeliveryCharge, "Minimum Delivery Charge", _minimumDeliveryCharge);
            }
        }
        private void DisplayContents(IBasket basket) {

            Visible = true;

            if (basket != null) {

                BasketDecorator decorator = basket as BasketDecorator;

                if (decorator == null) {
                    decorator = new BasketDecorator(basket);
                }

                if (!decorator.IsEmpty) {
                    RenderBasket(CurrentBasket);
                    pnlDetails.Visible = true;
                }
            }

            pnlEmpty.Visible = !pnlDetails.Visible;
        }
        public ProcessStatusMessage Process(IBasket order) {

            if (order == null) return new ProcessStatusMessage(ProcessStatus.Error, "Null Order");

            foreach (BasketItem item in order.BasketItemList) {

                if (item.UnitPrice == null) continue;

                if (item.UnitPrice.CurrencyCode != order.CurrencyCode) {
                    item.UnitPrice = new Money(
                        order.CurrencyCode,
                        item.UnitPrice.Amount * GetExchangeRate(item.UnitPrice.CurrencyCode, order.CurrencyCode)
                        );
                    item.LinePrice = new Money(item.UnitPrice);
                    item.LinePrice.Multiply(item.Quantity);
                }
            }

            return new ProcessStatusMessage(ProcessStatus.Success);
        }
        public void Process(IBasket order) {

            foreach (IBasketLine line in order.BasketItemList) {

                BasketItem item = line as BasketItem;

                if (item != null && item.Status != PricingStatus.OK) {

                    decimal unitPrice = item.Product.BasePrice;

                    if (item.OptionList != null) {
                        foreach (BasketItemAttribute attribute in item.OptionList) {
                            unitPrice += attribute.OptionPrice;
                        }
                    }

                    item.UnitLinePrice = new Money(order.CurrencyCode, unitPrice);
                    item.Status = PricingStatus.OK;
                }
            }
        }
        public void Process(IBasket order) {

            order.TaxPrice = new Money(order.CurrencyCode, 0);

            foreach (IBasketLine line in order.BasketItemList) {

                line.TaxPrice.Amount = line.UnitLinePrice.Amount * VAT_RATE * line.Quantity;

                switch (line.ItemType) {
                    case BasketItemType.CreditNote:
                    case BasketItemType.Discount:
                    case BasketItemType.Voucher:
                    case BasketItemType.OtherCredit:
                        order.TaxPrice.Subtract(line.TaxPrice);
                        break;
                    default:
                        order.TaxPrice.Add(line.TaxPrice);
                        break;
                }
            }
        }
        public void Process(IBasket order) {

            BasketDecorator dec = order as BasketDecorator;
            if (dec == null) {
                dec = new BasketDecorator(order);
            }

            //Remove any existing delivery charge
            dec.RemoveItems(BasketItemType.DeliveryCharge);

            decimal totalWeight = 0;

            foreach (IBasketLine line in order.BasketItemList) {

                BasketItem item = line as BasketItem;

                if (item != null && item.Product != null) {
                    totalWeight += line.Quantity * GetProductWeight(item.Product.ProductID);
                }
            }

            string countryCode = "GB";
            if (order.OrderHeader != null && (order.OrderHeader.DeliveryAddress != null || order.OrderHeader.InvoiceAddress != null)) {
                if (order.OrderHeader.DeliveryAddress != null) {
                    countryCode = order.OrderHeader.DeliveryAddress.CountryCode;
                } else {
                    countryCode = order.OrderHeader.InvoiceAddress.CountryCode;
                }
            }

            decimal cost = GetDeliveryChargeByWeight(countryCode, totalWeight);

            if (cost > 0 && order.BasketItemList.Count > 0) {
                //Where does this magic item come from?
                // We should have a variable in order header / basket that stores Delivery Charges. Not bodging it as an item.
                order.AddItem(BasketItemType.DeliveryCharge, "Delivery Charge", cost);
            }
        }