Example #1
0
 public decimal GetShippingTax(CartModel cart)
 {
     UKCourierShippingCalculation calculation = GetBestAvailableCalculation(cart);
     return calculation == null
         ? decimal.Zero
         : calculation.Tax(TaxRatePercentage);
 }
Example #2
0
        public CheckCodeResult CheckCode(CartModel cart, string discountCode)
        {
            DateTime now = CurrentRequestData.Now;
            var code = discountCode.Trim();
            var discounts = _session.QueryOver<Discount>()
                .Where(
                    discount =>
                        (discount.Code == code && discount.RequiresCode) &&
                        (discount.ValidFrom == null || discount.ValidFrom <= now) &&
                        (discount.ValidUntil == null || discount.ValidUntil >= now))
                .Cacheable().List();

            if (!discounts.Any())
            {
                return new CheckCodeResult
                {
                    Message = _stringResourceProvider.GetValue("The code you entered is not valid.")
                };
            }

            var checkLimitationsResults = discounts.Select(
                discount =>
                    _cartDiscountApplicationService.CheckLimitations(discount, cart)).ToList();
            if (checkLimitationsResults.All(result => result.Status == CheckLimitationsResultStatus.NeverValid))
            {
                return new CheckCodeResult
                {
                    Message = checkLimitationsResults.First().FormattedMessage
                };
            }
            return new CheckCodeResult { Success = true };
        }
 public IEnumerable<GoogleBaseCalculationInfo> GetCheapestCalculationsForEachCountry(CartModel cart)
 {
     IList<Country> countries = _session.QueryOver<Country>().Cacheable().List();
     HashSet<IShippingMethod> shippingMethods = _shippingMethodUIService.GetEnabledMethods();
     foreach (Country country in countries)
     {
         cart.ShippingAddress = new Address
         {
             CountryCode = country.ISOTwoLetterCode
         };
         HashSet<IShippingMethod> availableMethods =
             shippingMethods.FindAll(method => method.CanPotentiallyBeUsed(cart));
         if (availableMethods.Any())
         {
             IShippingMethod shippingMethod =
                 availableMethods.OrderBy(method => method.GetShippingTotal(cart)).First();
             yield return new GoogleBaseCalculationInfo
             {
                 CountryCode = country.ISOTwoLetterCode,
                 Price = shippingMethod.GetShippingTotal(cart),
                 ShippingMethodName = shippingMethod.DisplayName
             };
         }
     }
 }
Example #4
0
        public CartModel Build(Cart sessionCart)
        {
            var u = AccountAdminModelBuilder.BuildOneUser(WebSecurity.CurrentUserName);
            var model = new CartModel();
            model.cart = sessionCart;
            foreach (var cartItem in sessionCart.listSku)
            {
                var sku = dataService.GetSkuById(cartItem.idSku);
                if (u != null && u.Discount > 0)
                {
                    sku.priceAct = sku.priceAct - ((sku.priceAct/100)*u.Discount);
                }
                sku.smalPhoto.path = string.Format("{0}/{1}", imagesPath.GetImagesPath(), sku.smalPhoto.path);
                    model.listSku.Add(sku);
            }

            foreach (var cartItem in model.cart.listSku)
            {
                var tmpSku = model.listSku.First(i => i.id == cartItem.idSku);
                cartItem.priceAct = tmpSku.priceAct;
            }

            model.menu = BuildMenu();
            model.listState = dataService.ListCartState();
            return model;
        }
Example #5
0
 public bool CanPotentiallyBeUsed(CartModel cart)
 {
     if (cart == null || cart.Items.Any(item => !item.IsAbleToUseShippingMethod(this)))
         return false;
     var calculation = GetBestAvailableCalculation(cart);
     return calculation != null;
 }
    protected void Page_Load(object sender, EventArgs e)
    {
        List<Cart> carts = (List<Cart>)Application["ShoppingCart"];

        string clientName = Application["clientName"].ToString();
        int clientId = Convert.ToInt32(Application["clientId"]);
        DateTime date = DateTime.Now;
        double totalAmount = Convert.ToDouble(Application["totalAmount"]);

        //Create new record in database
        OrderModel orderModel = new OrderModel();
        Order order = new Order
        {
            ClientID = clientId,
            OrderDate = date,
            Status = "Waitting",
            TotalAmount = totalAmount,
        };
        string id = orderModel.InsertOrder(order);

        //Fill page
        lblName.Text = clientName;
        lblDate.Text = date.ToString();
        lblStatus.Text = "Waitting";
        lblAmount.Text = "$ " + totalAmount.ToString();
        lblNumber.Text = id;

        CartModel cartModel = new CartModel();
        cartModel.MarkOrderAsPaid(carts);
        Application["ShoppingCart"] = null;
    }
    protected void btnAdd_Click(object sender, EventArgs e)
    {
        if (!string.IsNullOrWhiteSpace(Request.QueryString["id"]))
        {
            string clientId = Context.User.Identity.GetUserId();
            if (clientId != null)
            {

                int id = Convert.ToInt32(Request.QueryString["id"]);
                int amount = Convert.ToInt32(ddlAmount.SelectedValue);

                Cart cart = new Cart
                {
                    Amount = amount,
                    ClientID = clientId,
                    DatePurchased = DateTime.Now,
                    IsInCart = true,
                    ProductID = id
                };

                CartModel model = new CartModel();
                lblResult.Text = model.InsertCart(cart);
            }
            else
            {
                lblResult.Text = "Please log in to order items";
            }
        }
    }
Example #8
0
    protected void btnAdd_Click(object sender, EventArgs e)
    {
        if (!string.IsNullOrWhiteSpace(Request.QueryString["id"]))
        {
            //get the id of the current logged in user
            string clientId = Context.User.Identity.GetUserId();

            //implement a check to make sure only logged in user can order a product
            if (clientId != null)
            {
                int id = Convert.ToInt32(Request.QueryString["id"]);
                int amount = Convert.ToInt32(ddlAmount.SelectedValue);

                Cart cart = new Cart
                {
                    Amount = amount,
                    ClientID = clientId,
                    DatePurchased = DateTime.Now,
                    IsInCart = true,
                    ProductID = id
                };

                CartModel cartModel = new CartModel();
                lblResult.Text = cartModel.InsertCart(cart);
                Response.Redirect("~/Index.aspx");
            }
            else
            {
                lblResult.Text = "Please log in to order items";
            }
        }
    }
Example #9
0
 public decimal GetShippingTotal(CartModel cart)
 {
     CountryBasedShippingCalculation calculation = GetBestAvailableCalculation(cart);
     return calculation == null
         ? decimal.Zero
         : calculation.Amount(TaxRatePercentage);
 }
Example #10
0
 public PayPalCartManager(ICartManager cartManager, IShippingMethodUIService shippingMethodUiService,
     CartModel cart)
 {
     _cartManager = cartManager;
     _shippingMethodUiService = shippingMethodUiService;
     _cart = cart;
 }
Example #11
0
 public DoExpressCheckoutPaymentReq GetDoExpressCheckoutRequest(CartModel cart)
 {
     // populate payment details
     var paymentDetails = new PaymentDetailsType
         {
             OrderTotal = cart.TotalToPay.GetAmountType(),
             ShippingTotal = cart.ShippingTotal.GetAmountType(),
             ItemTotal = _payPalOrderService.GetItemTotal(cart),
             TaxTotal = cart.ItemTax.GetAmountType(),
             Custom = cart.CartGuid.ToString(),
             ButtonSource = "Thought_Cart_MrCMS",
             InvoiceID = cart.CartGuid.ToString(),
             PaymentDetailsItem = _payPalOrderService.GetPaymentDetailsItems(cart)
         };
     // build the request
     return new DoExpressCheckoutPaymentReq
     {
         DoExpressCheckoutPaymentRequest = new DoExpressCheckoutPaymentRequestType
         {
             DoExpressCheckoutPaymentRequestDetails = new DoExpressCheckoutPaymentRequestDetailsType
             {
                 Token = cart.PayPalExpressToken,
                 PayerID = cart.PayPalExpressPayerId,
                 PaymentAction = _payPalExpressCheckoutSettings.PaymentAction,
                 PaymentDetails = new List<PaymentDetailsType> { paymentDetails }
             }
         }
     };
 }
Example #12
0
 public CartDiscountService(ICartDiscountCodeService cartDiscountCodeService,
     IGetValidDiscounts getValidDiscounts, CartModel cart)
 {
     _cartDiscountCodeService = cartDiscountCodeService;
     _getValidDiscounts = getValidDiscounts;
     _cart = cart;
 }
 public HashSet<CartItem> Get(CartItemBasedDiscountApplication application, CartModel cart)
 {
     var cartItems = new HashSet<CartItem>();
     cartItems.AddRange(_getCartItemsBySKUList.GetCartItems(cart, application.SKUs));
     cartItems.AddRange(_getCartItemsByCategoryIdList.GetCartItems(cart, application.CategoryIds));
     return cartItems;
 }
Example #14
0
    protected void Page_Load(object sender, EventArgs e)
    {
        //return the identity of the currently logged in user
        var user = Context.User.Identity;

        //to check if the user is logged in
        if(user.IsAuthenticated)
        {
            //to retrieve the name of the current user
            litStatus.Text = Context.User.Identity.Name;

            lnkLogin.Visible = false;
            lnkRegister.Visible = false;

            lnkLogut.Visible = true;
            litStatus.Visible = true;

            CartModel model = new CartModel();
            string userId = HttpContext.Current.User.Identity.GetUserId();
            litStatus.Text = string.Format("{0} ({1})", Context.User.Identity.Name,
                model.GetAmountOfOrders(userId));

        }
        else
        {
            lnkLogin.Visible = true;
            lnkRegister.Visible = true;

            lnkLogut.Visible = false;
            litStatus.Visible = false;

        }
    }
        public CheckLimitationsResult CheckLimitations(Discount discount, CartModel cart)
        {
            var limitations = _session.QueryOver<DiscountLimitation>()
                .Where(limitation => limitation.Discount.Id == discount.Id)
                .Cacheable()
                .List();

            var results = new CheckLimitationsResult[limitations.Count];
            for (var i = 0; i < limitations.Count; i++)
            {
                var limitation = limitations[i];
                var fullName = limitation.GetType().FullName;
                if (LimitationCheckerTypes.ContainsKey(fullName))
                {
                    var checker = _kernel.Get(LimitationCheckerTypes[fullName]) as DiscountLimitationChecker;
                    if (checker != null)
                    {
                        results[i] = checker.CheckLimitations(limitation, cart);
                        continue;
                    }
                }
                results[i] = CheckLimitationsResult.CurrentlyInvalid("Limitation cannot be checked");
            }
            return CheckLimitationsResult.Combine(results);
        }
Example #16
0
        public List<PaymentDetailsItemType> GetPaymentDetailsItems(CartModel cart)
        {
            var paymentDetailsItemTypes = cart.Items.Select(item => new PaymentDetailsItemType
            {
                Name = item.Name,
                Amount = item.UnitPricePreTax.GetAmountType(),
                ItemCategory = item.RequiresShipping ? ItemCategoryType.PHYSICAL : ItemCategoryType.DIGITAL,
                Quantity = item.Quantity,
                Tax = item.UnitTax.GetAmountType(),
            }).ToList();
            var applications = (from discountInfo in cart.Discounts
                                let info = _cartDiscountApplicationService.ApplyDiscount(discountInfo, cart)
                                select new { info, discountInfo }).ToHashSet();
            paymentDetailsItemTypes.AddRange(from application in applications

                                             where application.info.OrderTotalDiscount > 0
                                             select new PaymentDetailsItemType
                                             {
                                                 Name = "Order Total Discount - " + application.discountInfo.Discount.Name,
                                                 Amount = (-application.info.OrderTotalDiscount).GetAmountType(),
                                                 ItemCategory = ItemCategoryType.PHYSICAL,
                                                 Quantity = 1,
                                                 Tax = 0m.GetAmountType()
                                             });

            paymentDetailsItemTypes.AddRange(from application in applications
                                             where application.info.ShippingDiscount > 0
                                             select new PaymentDetailsItemType
                                             {
                                                 Name = "Shipping Discount - " + application.discountInfo.Discount.Name,
                                                 Amount = (-application.info.ShippingDiscount).GetAmountType(),
                                                 ItemCategory = ItemCategoryType.PHYSICAL,
                                                 Quantity = 1,
                                                 Tax = 0m.GetAmountType()
                                             });

            paymentDetailsItemTypes.AddRange(from giftCard in cart.AppliedGiftCards
                                             where giftCard.AvailableAmount > 0
                                             select new PaymentDetailsItemType
                                             {
                                                 Name = "Gift Card - " + giftCard.Code,
                                                 Amount = (-giftCard.AvailableAmount).GetAmountType(),
                                                 ItemCategory = ItemCategoryType.PHYSICAL,
                                                 Quantity = 1,
                                                 Tax = 0m.GetAmountType()
                                             });

            if (cart.AppliedRewardPointsAmount > 0)
                paymentDetailsItemTypes.Add(new PaymentDetailsItemType
                {
                    Name = string.Format("Reward Points ({0})", cart.AppliedRewardPoints),
                    Amount = (-cart.AppliedRewardPointsAmount).GetAmountType(),
                    ItemCategory = ItemCategoryType.PHYSICAL,
                    Quantity = 1,
                    Tax = 0m.GetAmountType()
                });

            return paymentDetailsItemTypes;
        }
Example #17
0
 public bool CanBeUsed(CartModel cart)
 {
     if (!CanPotentiallyBeUsed(cart))
         return false;
     if (cart.ShippingAddress == null)
         return false;
     return cart.ShippingAddress.CountryCode == "GB";
 }
        public void IfShippingMethodIsSetShouldBeValueOfItsShippingPercentage()
        {
            var shippingMethod = A.Fake<IShippingMethod>();
            var cartModel = new CartModel {ShippingMethod = shippingMethod};
            A.CallTo(() => shippingMethod.TaxRatePercentage).Returns(12.3m);

            cartModel.ShippingTaxPercentage.Should().Be(12.3m);
        }
 public PaypointRequestService(SECVPN secvpn, CartModel cartModel, IPaypointRequestHelper paypointHelper, PaypointSettings paypointSettings, IPaypoint3DSecureHelper paypoint3DSecureHelper)
 {
     _secvpn = secvpn;
     _cartModel = cartModel;
     _paypointHelper = paypointHelper;
     _paypointSettings = paypointSettings;
     _paypoint3DSecureHelper = paypoint3DSecureHelper;
 }
 public BraintreePaymentService(BraintreeSettings braintreeSettings, CartModel cartModel, 
     IOrderPlacementService orderPlacementService, ILogAdminService logAdminService)
 {
     _braintreeSettings = braintreeSettings;
     _cartModel = cartModel;
     _orderPlacementService = orderPlacementService;
     _logAdminService = logAdminService;
 }
 public SetShippingMethodService(CartModel cart, IShippingMethodUIService shippingMethodUIService,
     ICartManager cartManager, IUniquePageService uniquePageService)
 {
     _cart = cart;
     _shippingMethodUIService = shippingMethodUIService;
     _cartManager = cartManager;
     _uniquePageService = uniquePageService;
 }
Example #22
0
        public void IfShippingMethodIsNotNullShouldBeTheValueOfItsGetShippingTotalMethod()
        {
            var shippingMethod = A.Fake<IShippingMethod>();
            var cartModel = new CartModel {ShippingMethod = shippingMethod};
            A.CallTo(() => shippingMethod.GetShippingTotal(cartModel)).Returns(1.23m);

            cartModel.ShippingTotal.Should().Be(1.23m);
        }
        public void CartModel_DiscountAmount_ShouldBe0IfDiscountIsNull()
        {
            var cartModel = new CartModel();

            var discountAmount = cartModel.DiscountAmount;

            discountAmount.Should().Be(0);
        }
Example #24
0
 public bool CanBeUsed(CartModel cart)
 {
     if (!CanPotentiallyBeUsed(cart))
         return false;
     if (cart.ShippingAddress == null)
         return false;
     return GetBestAvailableCalculation(cart) != null;
 }
 public PaymentNotRequiredUIService(IUniquePageService uniquePageService, CartModel cartModel,
     IStringResourceProvider stringResourceProvider, IOrderPlacementService orderPlacementService)
 {
     _uniquePageService = uniquePageService;
     _cartModel = cartModel;
     _stringResourceProvider = stringResourceProvider;
     _orderPlacementService = orderPlacementService;
 }
Example #26
0
 private IShippingMethod GetShippingMethod(CartModel cart, Guid userGuid)
 {
     var type = _cartSessionManager.GetSessionValue<string>(CartManager.CurrentShippingMethodTypeKey, userGuid);
     IShippingMethod shippingMethod = _shippingMethodUIService.GetMethodByTypeName(type);
     if (shippingMethod != null)
         return shippingMethod.CanBeUsed(cart) ? shippingMethod : null;
     return null;
 }
 public ProductAddedToCartUIService(IUniquePageService uniquePageService, CartModel cart,
     IRelatedProductsService relatedProductsService, IPeopleWhoBoughtThisService peopleWhoBoughtThisService)
 {
     _uniquePageService = uniquePageService;
     _cart = cart;
     _relatedProductsService = relatedProductsService;
     _peopleWhoBoughtThisService = peopleWhoBoughtThisService;
 }
Example #28
0
 public bool CanUse(CartModel cart)
 {
     var anythingToPay = cart.AnythingToPay();
     if (anythingToPay)
     {
         return StandardCanUseLogic(cart);
     }
     return IsPaymentNotRequired;
 }
Example #29
0
        public CartModel Assign(CartModel cart, Guid userGuid)
        {
            cart.UseRewardPoints = _cartSessionManager.GetSessionValue<bool>(UseRewardPoints, userGuid);
            cart.AvailablePoints = _getUserRewardPointsBalance.GetBalance(cart.User);
            cart.AvailablePointsValue = _getUserRewardPointsBalance.GetBalanceValue(cart.User);
            cart.RewardPointsExchangeRate = _getUserRewardPointsBalance.GetExchangeRate();

            return cart;
        }
Example #30
0
        public void ShouldBeZeroIfNoGiftCardsAreApplied()
        {
            var cartModel = new CartModel
            {
                AppliedGiftCards = new List<GiftCard>()
            };

            cartModel.GiftCardAmount.Should().Be(0m);
        }
Example #31
0
        public IActionResult GetCartDetails(int tid)
        {
            CartModel model = new CartModel(_db);

            return(Ok(model.GetCartDetails(tid, HttpContext.Session.GetString(SessionVars.User))));
        }
Example #32
0
        public virtual bool CreateCart(CartModel cart)
        {
            var result = _CartDAC.CreateCart(cart);

            return(result);
        }
        public override CartModel MapResult(GetCartResult serviceResult, HttpRequestMessage request)
        {
            CustomerOrder cart        = serviceResult.Cart;
            CartModel     destination = this.ObjectToObjectMapper.Map <GetCartResult, CartModel>(serviceResult);

            this.ObjectToObjectMapper.Map <CustomerOrder, CartModel>(cart, destination);
            if (cart.ShipVia != null)
            {
                this.ObjectToObjectMapper.Map <Carrier, CarrierDto>(cart.ShipVia.Carrier, destination.Carrier);
            }
            destination.SalespersonName      = cart.Salesperson?.Name ?? string.Empty;
            destination.InitiatedByUserName  = cart.InitiatedByUserProfile?.UserName ?? string.Empty;
            destination.OrderSubTotal        = serviceResult.OrderSubTotal;
            destination.OrderSubTotalDisplay = this.CurrencyFormatProvider.GetString(destination.OrderSubTotal, (ICurrency)cart.Currency);
            destination.OrderSubTotalWithOutProductDiscounts        = serviceResult.OrderSubTotalWithOutProductDiscounts;
            destination.OrderSubTotalWithOutProductDiscountsDisplay = this.CurrencyFormatProvider.GetString(destination.OrderSubTotalWithOutProductDiscounts, (ICurrency)cart.Currency);
            destination.OrderGrandTotal            = serviceResult.OrderGrandTotal;
            destination.OrderGrandTotalDisplay     = this.CurrencyFormatProvider.GetString(destination.OrderGrandTotal, (ICurrency)cart.Currency);
            destination.ShippingAndHandling        = serviceResult.ShippingAndHandling;
            destination.ShippingAndHandlingDisplay = this.CurrencyFormatProvider.GetString(destination.ShippingAndHandling, (ICurrency)cart.Currency);
            destination.TotalTax        = serviceResult.TotalTax;
            destination.TotalTaxDisplay = this.CurrencyFormatProvider.GetString(destination.TotalTax, (ICurrency)cart.Currency);
            destination.TypeDisplay     = this.TranslationLocalizer.TranslateLabel(cart.Type);
            destination.StatusDisplay   = this.TranslationLocalizer.TranslateLabel(cart.Status);
            destination.CurrencySymbol  = serviceResult.CurrencySymbol;
            CartModel      cartModel1             = destination;
            DateTimeOffset?requestedDeliveryDate1 = serviceResult.RequestedDeliveryDate;

            DateTimeOffset valueOrDefault;
            string         str;

            if (!requestedDeliveryDate1.HasValue)
            {
                str = (string)null;
            }
            else
            {
                valueOrDefault = requestedDeliveryDate1.GetValueOrDefault();
                str            = valueOrDefault.ToString();
            }
            cartModel1.RequestedDeliveryDate = str;
            CartModel      cartModel2             = destination;
            DateTimeOffset?requestedDeliveryDate2 = serviceResult.RequestedDeliveryDate;

            DateTime?nullable;

            if (!requestedDeliveryDate2.HasValue)
            {
                nullable = new DateTime?();
            }
            else
            {
                valueOrDefault = requestedDeliveryDate2.GetValueOrDefault();
                nullable       = new DateTime?(valueOrDefault.Date);
            }
            cartModel2.RequestedDeliveryDateDisplay = nullable;
            if (cart.Status.EqualsIgnoreCase("Cart"))
            {
                destination.Id = this.RouteDataProvider.GetRouteValue(request, "cartid");
            }
            if (serviceResult.GetBillToResult != null)
            {
                destination.BillTo = this.GetBillToMapper.MapResult(serviceResult.GetBillToResult, request);
                if (serviceResult.Properties.ContainsKey("IsNewUser") && destination.BillTo != null)
                {
                    destination.BillTo.FirstName   = serviceResult.Cart.BTFirstName;
                    destination.BillTo.LastName    = serviceResult.Cart.BTLastName;
                    destination.BillTo.CompanyName = serviceResult.Cart.BTCompanyName;
                    destination.BillTo.Address1    = serviceResult.Cart.BTAddress1;
                    destination.BillTo.Address2    = serviceResult.Cart.BTAddress2;
                    destination.BillTo.City        = serviceResult.Cart.BTCity;
                    destination.BillTo.PostalCode  = serviceResult.Cart.BTPostalCode;
                    destination.BillTo.Phone       = serviceResult.Cart.BTPhone;
                    destination.BillTo.Email       = serviceResult.Cart.BTEmail;
                    if (!string.IsNullOrEmpty(serviceResult.Cart.BTCountry))
                    {
                        var country = SiteContext.Current.Website.Countries.Where(c => c.Name.Equals(serviceResult.Cart.BTCountry)).FirstOrDefault(); //TODO - Obsoleted Website -> WebsiteDTO
                        if (country != null && !string.IsNullOrEmpty(serviceResult.Cart.BTState))
                        {
                            destination.BillTo.Country = GetCountryMapper.MapResult(new GetCountryResult()
                            {
                                Country = country
                            }, request);
                            var state = country.States.Where(s => s.Name.Equals(serviceResult.Cart.BTState)).FirstOrDefault();
                            if (state != null)
                            {
                                destination.BillTo.State = GetStateMapper.MapResult(new GetStateResult()
                                {
                                    State = state
                                }, request);
                            }
                        }
                    }
                }
            }
            if (serviceResult.GetShipToResult != null)
            {
                destination.ShipTo      = this.GetShipToMapper.MapResult(serviceResult.GetShipToResult, request);
                destination.ShipToLabel = serviceResult.GetShipToResult.Label;
                if (serviceResult.Properties.ContainsKey("IsNewUser") && destination.ShipTo != null)
                {
                    destination.ShipTo.FirstName   = serviceResult.Cart.STFirstName;
                    destination.ShipTo.LastName    = serviceResult.Cart.STLastName;
                    destination.ShipTo.CompanyName = serviceResult.Cart.STCompanyName;
                    destination.ShipTo.Address1    = serviceResult.Cart.STAddress1;
                    destination.ShipTo.Address2    = serviceResult.Cart.STAddress2;
                    destination.ShipTo.City        = serviceResult.Cart.STCity;
                    destination.ShipTo.PostalCode  = serviceResult.Cart.STPostalCode;
                    destination.ShipTo.Phone       = serviceResult.Cart.STPhone;
                    if (!string.IsNullOrEmpty(serviceResult.Cart.STCountry))
                    {
                        var country = SiteContext.Current.Website.Countries.Where(c => c.Name.Equals(serviceResult.Cart.STCountry)).FirstOrDefault();
                        if (country != null && !string.IsNullOrEmpty(serviceResult.Cart.STState))
                        {
                            destination.ShipTo.Country = GetCountryMapper.MapResult(new GetCountryResult()
                            {
                                Country = country
                            }, request);
                            var state = country.States.Where(s => s.Name.Equals(serviceResult.Cart.STState)).FirstOrDefault();
                            if (state != null)
                            {
                                destination.ShipTo.State = GetStateMapper.MapResult(new GetStateResult()
                                {
                                    State = state
                                }, request);
                            }
                        }
                    }
                }
            }
            //Below code was removed in 4.2
            //foreach (CustomerOrderTaxDto customerOrderTax in (IEnumerable<CustomerOrderTaxDto>)destination.CustomerOrderTaxes)
            //{
            //    customerOrderTax.TaxCode = this.TranslationLocalizer.TranslateLabel(customerOrderTax.TaxCode);
            //    customerOrderTax.TaxDescription = this.TranslationLocalizer.TranslateLabel(customerOrderTax.TaxDescription);
            //    customerOrderTax.TaxAmountDisplay = this.CurrencyFormatProvider.GetString(customerOrderTax.TaxAmount, (ICurrency)cart.Currency);
            //}
            destination.Uri = this.UrlHelper.Link("CartV1", (object)new
            {
                cartid = destination.Id
            }, request);
            destination.CartLinesUri = this.UrlHelper.Link("CartLinesV1", (object)new
            {
                cartid = destination.Id
            }, request);
            CartLineCollectionModel lineCollectionModel = this.GetCartLineCollectionMapper.MapResult(new GetCartLineCollectionResult()
            {
                GetCartResult      = serviceResult,
                GetCartLineResults = serviceResult.CartLineResults
            }, request);

            if (lineCollectionModel != null)
            {
                destination.CartLines = lineCollectionModel.CartLines;
            }
            if (destination.Status.EqualsIgnoreCase("SubscriptionOrder"))
            {
                CartModel_Brasseler cartModel_Brasseler = new CartModel_Brasseler();

                var cartModel = AutoMapper.Mapper.DynamicMap <CartModel_Brasseler>(destination);
                cartModel.CartSubscriptionDto = new CartSubscriptionDto();

                var subscriptionBrasseler = this.UnitOfWork.GetRepository <SubscriptionBrasseler>().GetTable().Where(x => x.CustomerOrderId.ToString().ToUpper() == destination.Id.ToUpper()).FirstOrDefault();

                if (subscriptionBrasseler != null)
                {
                    cartModel.CartSubscriptionDto.CustomerOrderId   = subscriptionBrasseler.CustomerOrderId;
                    cartModel.CartSubscriptionDto.Frequency         = subscriptionBrasseler.Frequency;
                    cartModel.CartSubscriptionDto.NextDelieveryDate = subscriptionBrasseler.NextDelieveryDate;
                    cartModel.CartSubscriptionDto.DeActivationDate  = subscriptionBrasseler.DeActivationDate;
                    cartModel.CartSubscriptionDto.ActivationDate    = subscriptionBrasseler.ActivationDate;
                    cartModel.CartSubscriptionDto.PaymentMethod     = subscriptionBrasseler.PaymentMethod;
                    return(cartModel);
                }
            }

            destination.Messages = (ICollection <string>)serviceResult.Messages.Select <ResultMessage, string>((Func <ResultMessage, string>)(m => m.Message)).ToList <string>();
            destination.CreditCardBillingAddress = serviceResult.CreditCardBillingAddress;
            return(destination);
        }
        public override CheckLimitationsResult CheckLimitations(SingleUsagePerCustomer limitation, CartModel cart, IList <Discount> allDiscounts)
        {
            var user = _getCurrentUser.Get();

            if (user == null)
            {
                return(CheckLimitationsResult.NeverValid(_stringResourceProvider.GetValue("This discount requires an account.")));
            }

            var discountId = limitation.Discount.Id;
            var anyUsages  =
                _session.Query <DiscountUsage>()
                .Where(usage => usage.Discount.Id == discountId && usage.Order.User.Id == user.Id)
                .Cacheable()
                .Any();

            return(anyUsages
                ? CheckLimitationsResult.NeverValid(_stringResourceProvider.GetValue("This discount has already been used."))
                : CheckLimitationsResult.Successful(Enumerable.Empty <CartItemData>()));
        }
Example #35
0
        /// <summary>
        /// 获取购物车列表
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        private string List(HttpContext context)
        {
            try
            {
                var sourceData = bllMall.GetShoppingCartList(currentUserInfo.UserID, true);
                //for (int i = 0; i < sourceData.Count; i++)
                //{
                //    if (bllMall.GetCount<ZentCloud.BLLJIMP.Model.WXMallProductInfo>(string.Format(" PID='{0}' And (IsDelete=1 Or IsOnSale='0')", sourceData[i].ProductId)) > 0)
                //    {
                //        sourceData.RemoveAt(i);//删除或下架的不显示
                //    }

                //}

                //TODO: 改造下,价格和积分再次拉取商品信息表数据
                List <BLLJIMP.Model.WXMallProductInfo> productList = new List <BLLJIMP.Model.WXMallProductInfo>();

                List <CartModel> resultDataList = new List <CartModel>();
                foreach (var item in sourceData)
                {
                    int isInvalid  = 0;
                    var productSku = bllMall.GetProductSku(item.SkuId);
                    if (productSku == null)
                    {
                        isInvalid = 1;
                        //continue;
                    }
                    BLLJIMP.Model.WXMallProductInfo product = productList.SingleOrDefault(p => p.PID == item.ProductId.ToString());

                    if (product == null)
                    {
                        product = bllMall.GetProduct(item.ProductId);
                        if (product == null)
                        {
                            continue;
                        }
                        productList.Add(product);
                    }
                    if (product.IsDelete == 1 || product.IsOnSale == "0")
                    {
                        isInvalid = 1;
                    }
                    //dynamic resultDataItem = new
                    //{
                    //    cart_id = item.CartId,
                    //    sku_id = item.SkuId,
                    //    product_id = item.ProductId,
                    //    title = item.Title,
                    //    properties = item.SkuPropertiesName,
                    //    img_url = bllMall.GetImgUrl(item.ImgUrl),
                    //    quote_price = product.PreviousPrice,
                    //    price = product.Score > 0? product.Price : bllMall.GetSkuPrice(productSku),
                    //    score = product.Score,
                    //    is_cashpay_only = product.IsCashPayOnly,
                    //    total_fee = item.TotalFee,
                    //    discount_fee = item.DiscountFee,
                    //    count = item.Count,
                    //    freight_terms = item.FreightTerms,
                    //    freight = item.Freight,
                    //    max_count = productSku.Stock,
                    //    product_tags = item.Tags,
                    //    is_no_express = product.IsNoExpress,
                    //    supplier_name=bllMall.GetSuppLierByUserId(product.SupplierUserId,bllMall.WebsiteOwner).Company,
                    //    is_invalid = isInvalid
                    //};

                    CartModel model = new CartModel();
                    model.cart_id         = item.CartId;
                    model.sku_id          = item.SkuId;
                    model.product_id      = item.ProductId;
                    model.title           = item.Title;
                    model.properties      = item.SkuPropertiesName;
                    model.img_url         = bllMall.GetImgUrl(item.ImgUrl);
                    model.quote_price     = product.PreviousPrice;
                    model.price           = product.Score > 0? product.Price : item.Price;
                    model.score           = product.Score;
                    model.is_cashpay_only = product.IsCashPayOnly;
                    model.total_fee       = item.TotalFee;
                    model.discount_fee    = item.DiscountFee;
                    model.count           = item.Count;
                    model.freight_terms   = item.FreightTerms;
                    model.freight         = item.Freight;
                    model.max_count       = productSku.Stock;
                    model.product_tags    = item.Tags;
                    model.is_no_express   = product.IsNoExpress;
                    model.supplier_id     = item.SupplierId;
                    //model.supplier_name=bllMall.GetSuppLierByUserId(product.SupplierUserId,bllMall.WebsiteOwner).Company;
                    model.supplier_name = item.SupplierName;
                    model.is_invalid    = isInvalid;
                    model.store_address = item.StoreAddress;
                    resultDataList.Add(model);
                }
                resultDataList = resultDataList.OrderBy(p => p.is_invalid).ToList();
                var data = new
                {
                    totalcount = resultDataList.Count(),
                    list       = resultDataList,//列表
                };

                return(ZentCloud.Common.JSONHelper.ObjectToJson(data));
            }
            catch (Exception ex)
            {
                return(ex.ToString());
            }
        }
Example #36
0
 public ActionResult PartialViewCartCheckOut(CartModel cart)
 {
     return(View("_PartialViewCartCheckOut", cart.CartItems));
 }
Example #37
0
        public ActionResult OrderNow(CartModel cart1)
        {
            WEBEntities1   db   = new WEBEntities1();
            HoaDon         HD   = new HoaDon();
            ThongTinHoaDon TTHD = new ThongTinHoaDon();
            String         b;

            b = Session["LogedMaND"].ToString();

            long a;

            a = Convert.ToInt64(b);

            HD.NgayLap = DateTime.Now;
            HD.MaND    = a;
            HD.DiaChi  = cart1.DiaChi;

            String a1;
            String a2;
            String a3;
            String aMaHD = "0";

            a1 = HD.NgayLap.ToString();
            a2 = HD.MaND.ToString();
            a3 = HD.DiaChi.ToString();


            string studentName;

            if (ModelState.IsValid)
            {
                db.HoaDons.Add(HD);
                db.SaveChanges();

                //using (var ctx = new WEBEntities1())
                //{
                //    //Get student name of string type
                //    studentName = ctx.Database.SqlQuery<string>("Select MaHD from HoaDon where MaND = "+a2+",NgayLap ='"+a1+"'").FirstOrDefault<string>();
                // }
                HoaDon a5;
                using (var ctx = new WEBEntities1())
                {
                    List <HoaDon> listHD = (from hd in db.HoaDons select hd).ToList <HoaDon>();
                    a5 = listHD.Last();
                }

                foreach (Item item in (List <Item>)Session["cart"])
                {
                    TTHD.MaSP    = item.Sanpham.MaSP;
                    TTHD.SoLuong = item.Quantity;
                    TTHD.Gia     = item.Sanpham.Gia;
                    TTHD.MaHD    = a5.MaHD;
                    if (ModelState.IsValid)
                    {
                        db.ThongTinHoaDons.Add(TTHD);
                        db.SaveChanges();
                    }
                }

                return(RedirectToAction("Index", "Home"));
            }
            else
            {
                return(View("Fail", "User"));
            }
        }
 public userController()
 {
     context   = new RachnaDBContext();
     _mcartmdl = new CartModel();
 }
Example #39
0
        public static void ChangeOrderStatus(DataBaseContext db, CarVendor.Web.Models.Order ROrder, string status)
        {
            Order order    = db.Orders.Where(c => c.Id == ROrder.id).FirstOrDefault();
            var   exchange = db.Conversions.Where(cc => cc.FromCurrency.Name == ROrder.currency).OrderByDescending(o => o.CreationDate).Select(s => s.Value).FirstOrDefault();

            switch (ROrder.currency)
            {
            case "USD":
                if (order.Currency == "USD" && order.TotalAmount == (decimal)ROrder.amount)
                {
                    order.Status = status;
                }
                else
                {
                    order.Status = "Different Amount";
                }

                break;

            case "EUR":
                if (order.Currency == "EUR" && order.TotalAmount == (decimal)ROrder.amount)
                {
                    order.Status = status;
                }
                else
                {
                    order.Status = "Different Amount";
                }
                break;

            default:
                if (order.Currency == "EGP" && order.TotalAmount == (decimal)ROrder.amount)
                {
                    order.Status = status;
                }
                else
                {
                    order.Status = "Different Amount";
                }
                break;
            }

            db.SaveChanges();
            CartModel customer_cart = new CartModel();

            customer_cart.Order     = order;
            customer_cart.CartItems = order.OrderItems.Select(s => new CartItemModel
            {
                Brand    = s.Car.Brand.Name,
                CarName  = s.Car.Name,
                Category = new CategoryModel {
                    Text = s.Category
                },
                Color = new ColorModel {
                    Text = s.Color
                },
                Price    = s.TotalPrice,
                Quantity = s.Quantity
            }).ToList();

            customer_cart.CustomerInfo = db.Users.Where(s => s.Id == order.UserId).Select(u => new CustomerInfoModel
            {
                Individually    = u.Individually,
                FName           = u.FName,
                MName           = u.MName,
                LName           = u.LName,
                Phone           = u.Phone,
                DeliveryAddress = u.UserAddresses.Where(a => a.User.Id == order.UserId).FirstOrDefault().Address.DeliveryAddress,
                MainAddress     = u.UserAddresses.Where(a => a.User.Id == order.UserId).FirstOrDefault().Address.MainAddress

                                  //DeliveryAddress=u.UserAddresses,
            }).FirstOrDefault();

            // TODO: Send Mail Here
            EmailTemplate Email     = new EmailTemplate();
            string        path      = @"~/Common/OrderDetailsEmailTemplate.html";
            var           emailHtml = Email.ReadTemplateEmail(customer_cart, path);
            var           Emails    = db.Mails.Select(s => s.mail).ToList();

            try
            {
                Emails.Add(order.User.Email);
                GmailSender.SendEmail("*****@*****.**", "Serious!1", Emails, "Order", emailHtml, null);
            }
            catch (Exception ex)
            {
                throw new Exception("error", ex);
            }
        }
 public ActionResult AddProductToCart(CartModel model)
 {
     CartHelper.Source.AddItemToCart(model);
     return(PartialView("PublicSite/MiniCart", CartHelper.Source.GetCartItems()));
 }
Example #41
0
 protected IEnumerable <CartItem> GetItems(T application, CheckLimitationsResult checkLimitationsResult, CartModel cart)
 {
     if (application.CartItemsFromLimitations)
     {
         return(checkLimitationsResult.CartItems);
     }
     return(_getCartItemBasedApplicationProducts.Get(application, cart));
 }
Example #42
0
        protected override void OnCreate(Bundle savedInstanceState)
        {
            myEmail = Intent.GetStringExtra("email");
            base.OnCreate(savedInstanceState);
            // Create your application here
            SetContentView(Resource.Layout.ItemDesc);
            myDB = Realm.GetInstance(config);

            imgItem     = FindViewById <ImageView>(Resource.Id.imgItem);
            txtItemName = FindViewById <TextView>(Resource.Id.txtItemName);
            txtPrice    = FindViewById <TextView>(Resource.Id.txtPrice);
            txtDesc     = FindViewById <TextView>(Resource.Id.txtDesc);
            edtQty      = FindViewById <EditText>(Resource.Id.edtQty);
            edtAdd      = FindViewById <EditText>(Resource.Id.edtAdd);
            btnAddCart  = FindViewById <Button>(Resource.Id.btnAddToCart);
            if (myEmail == "admin")
            {
                btnAddCart.Visibility = ViewStates.Invisible;
                edtQty.Visibility     = ViewStates.Invisible;
                edtAdd.Visibility     = ViewStates.Invisible;
            }
            int itemId     = Convert.ToInt32(Intent.GetStringExtra("itemId"));
            var itemDetail = from a in myDB.All <ItemModel>() where (a.id == itemId) select a;

            int imgRes;


            foreach (var item in itemDetail)
            {
                itemId           = item.id;
                hotelId          = item.hotelId;
                txtItemName.Text = item.itemName;
                txtDesc.Text     = item.description;
                txtPrice.Text    = "$" + item.price.ToString();
                imgRes           = (int)typeof(Resource.Drawable).GetField(item.itemImg).GetValue(null);
                imgItem.SetImageResource(imgRes);
            }


            btnAddCart.Click += delegate
            {
                if (edtQty.Text == "")
                {
                    msg = "Please enter Quantity";
                    Alert(msg);
                }
                else
                {
                    CartModel objCartModel = new CartModel();
                    int       count        = myDB.All <CartModel>().Count();
                    //increatement index
                    int nextID = count + 1;

                    //insert new value
                    objCartModel.id      = nextID;
                    objCartModel.itemId  = itemId;
                    objCartModel.qty     = Convert.ToInt32(edtQty.Text);
                    objCartModel.hotelId = hotelId;
                    objCartModel.userId  = myEmail;

                    myDB.Write(() =>
                    {
                        myDB.Add(objCartModel);
                    });
                    Toast.MakeText(this, "" + "Added to Cart Successfully", ToastLength.Short).Show();
                    Intent CartIntent = new Intent(this, typeof(CartView));
                    CartIntent.PutExtra("email", myEmail);
                    StartActivity(CartIntent);
                }
            };
        }
Example #43
0
 public override CheckLimitationsResult CheckLimitations(CartHasAtLeastXItems limitation, CartModel cart, IList <Discount> allDiscounts)
 {
     return(cart.ItemQuantity >= limitation.NumberOfItems
         ? CheckLimitationsResult.Successful(Enumerable.Empty <CartItemData>())
         : CheckLimitationsResult.CurrentlyInvalid(
                string.Format(
                    _stringResourceProvider.GetValue("You need at least {0} items to apply this discount"),
                    limitation.NumberOfItems)));
 }
Example #44
0
        public IActionResult GetCarts()
        {
            CartModel model = new CartModel(_db);

            return(Ok(model.GetAll(HttpContext.Session.GetString(SessionVars.User))));
        }
        public CartModel Create(CartModel cart)
        {
            _context.Cart.Add(cart);

            return(cart);
        }
Example #46
0
 public async Task <int> UpdateCartModel(CartModel newCartModel)
 {
     return(await this._cartRepo.UpdateCartModel(newCartModel));
 }
Example #47
0
 public ActionResult Index(CartModel model)
 {
     this.cartService.DeleteFromCart(model);
     return(RedirectToAction("Index"));
 }
 public GetExistingAddressOptions(IGetCurrentUser getCurrentUser, CartModel cart, IBelongToUserLookupService belongToUserLookupService)
 {
     _getCurrentUser            = getCurrentUser;
     _cart                      = cart;
     _belongToUserLookupService = belongToUserLookupService;
 }
 public PaymentNotRequiredController(CartModel cartModel, IPaymentNotRequiredUIService paymentNotRequiredUIService, IUniquePageService uniquePageService)
 {
     _cartModel = cartModel;
     _paymentNotRequiredUIService = paymentNotRequiredUIService;
     _uniquePageService           = uniquePageService;
 }
Example #50
0
        /// <summary>
        /// 修改购物车中套装数量
        /// </summary>
        public ActionResult ChangeSuitCount()
        {
            //当商城不允许游客使用购物车时
            if (WorkContext.ShopConfig.IsGuestSC == 0 && WorkContext.Uid < 1)
            {
                return(AjaxResult("nologin", "请先登录"));
            }

            int    pmId     = WebHelper.GetQueryInt("pmId");                                      //套装id
            int    buyCount = WebHelper.GetQueryInt("buyCount");                                  //购买数量
            string selectedCartItemKeyList = WebHelper.GetQueryString("selectedCartItemKeyList"); //选中的购物车项键列表

            //购物车商品列表
            List <OrderProductInfo> orderProductList = Carts.GetCartProductList(WorkContext.Uid, WorkContext.Sid);
            //套装商品列表
            List <OrderProductInfo> suitOrderProductList = Carts.GetSuitOrderProductList(pmId, orderProductList, true);

            if (suitOrderProductList.Count > 0) //当套装已经存在
            {
                if (buyCount < 1)               //当购买数量小于1时,删除此套装
                {
                    Carts.DeleteCartSuit(ref orderProductList, pmId);
                }
                else
                {
                    OrderProductInfo orderProductInfo = suitOrderProductList.Find(x => x.Type == 3);
                    int oldBuyCount = orderProductInfo.RealCount / orderProductInfo.ExtCode2;
                    if (buyCount != oldBuyCount)
                    {
                        Carts.AddExistSuitToCart(ref orderProductList, suitOrderProductList, buyCount);
                    }
                }
            }

            //商品数量
            int pCount = Carts.SumOrderProductCount(orderProductList);
            //购物车信息
            CartInfo cartInfo = Carts.TidyOrderProductList(StringHelper.SplitString(selectedCartItemKeyList), orderProductList);

            //商品总数量
            int totalCount = Carts.SumOrderProductCount(cartInfo.SelectedOrderProductList);
            //商品合计
            decimal productAmount = Carts.SumOrderProductAmount(cartInfo.SelectedOrderProductList);
            //满减折扣
            int fullCut = Carts.SumFullCut(cartInfo);
            //订单合计
            decimal orderAmount = productAmount - fullCut;

            CartModel model = new CartModel
            {
                TotalCount    = totalCount,
                ProductAmount = productAmount,
                FullCut       = fullCut,
                OrderAmount   = orderAmount,
                CartInfo      = cartInfo
            };

            //将购物车中商品数量写入cookie
            Carts.SetCartProductCountCookie(pCount);

            return(View("ajaxindex", model));
        }
 private void HandleMessage(CartModel cartModel)
 {
     //TODO: afwerking RabbitMessage - CreateOrder
     Console.WriteLine("Order nog verwerken en opslaan in de database.");
 }
Example #52
0
        /// <summary>
        /// 添加满赠到购物车
        /// </summary>
        public ActionResult AddFullSend()
        {
            //当商城不允许游客使用购物车时
            if (WorkContext.ShopConfig.IsGuestSC == 0 && WorkContext.Uid < 1)
            {
                return(AjaxResult("nologin", "请先登录"));
            }

            int    pmId = WebHelper.GetQueryInt("pmId");                                          //满赠id
            int    pid  = WebHelper.GetQueryInt("pid");                                           //商品id
            string selectedCartItemKeyList = WebHelper.GetQueryString("selectedCartItemKeyList"); //选中的购物车项键列表

            //添加的商品
            PartProductInfo partProductInfo = Products.GetPartProductById(pid);

            if (partProductInfo == null)
            {
                return(AjaxResult("noproduct", "请选择商品"));
            }

            //商品库存
            int stockNumber = Products.GetProductStockNumberByPid(pid);

            if (stockNumber < 1)
            {
                return(AjaxResult("stockout", "商品库存不足"));
            }

            //满赠促销活动
            FullSendPromotionInfo fullSendPromotionInfo = Promotions.GetFullSendPromotionByPmIdAndTime(pmId, DateTime.Now);

            if (fullSendPromotionInfo == null)
            {
                return(AjaxResult("nopromotion", "满赠促销活动不存在或已经结束"));
            }

            //购物车商品列表
            List <OrderProductInfo> orderProductList = Carts.GetCartProductList(WorkContext.Uid, WorkContext.Sid);

            //满赠主商品列表
            List <OrderProductInfo> fullSendMainOrderProductList = Carts.GetFullSendMainOrderProductList(pmId, orderProductList);

            if (fullSendMainOrderProductList.Count < 1)
            {
                return(AjaxResult("nolimit", "不符合活动条件"));
            }
            decimal amount = Carts.SumOrderProductAmount(fullSendMainOrderProductList);

            if (fullSendPromotionInfo.LimitMoney > amount)
            {
                return(AjaxResult("nolimit", "不符合活动条件"));
            }

            if (!Promotions.IsExistFullSendProduct(pmId, pid, 1))
            {
                return(AjaxResult("nofullsendproduct", "此商品不是满赠商品"));
            }

            //赠送商品
            OrderProductInfo fullSendMinorOrderProductInfo = Carts.GetFullSendMinorOrderProduct(pmId, orderProductList);

            if (fullSendMinorOrderProductInfo != null)
            {
                if (fullSendMinorOrderProductInfo.Pid != pid)
                {
                    Carts.DeleteCartFullSend(ref orderProductList, fullSendMinorOrderProductInfo);
                }
                else
                {
                    return(AjaxResult("exist", "此商品已经添加"));
                }
            }

            //添加满赠商品
            Carts.AddFullSendToCart(ref orderProductList, partProductInfo, fullSendPromotionInfo, WorkContext.Sid, WorkContext.Uid, DateTime.Now);

            //商品数量
            int pCount = Carts.SumOrderProductCount(orderProductList);
            //购物车信息
            CartInfo cartInfo = Carts.TidyOrderProductList(StringHelper.SplitString(selectedCartItemKeyList), orderProductList);

            //商品总数量
            int totalCount = Carts.SumOrderProductCount(cartInfo.SelectedOrderProductList);
            //商品合计
            decimal productAmount = Carts.SumOrderProductAmount(cartInfo.SelectedOrderProductList);
            //满减折扣
            int fullCut = Carts.SumFullCut(cartInfo);
            //订单合计
            decimal orderAmount = productAmount - fullCut;

            CartModel model = new CartModel
            {
                TotalCount    = totalCount,
                ProductAmount = productAmount,
                FullCut       = fullCut,
                OrderAmount   = orderAmount,
                CartInfo      = cartInfo
            };

            //将购物车中商品数量写入cookie
            Carts.SetCartProductCountCookie(pCount);

            return(View("ajaxindex", model));
        }
Example #53
0
 public GetExistingAddressOptions(IGetCurrentUser getCurrentUser, CartModel cart, IUserService userService)
 {
     _getCurrentUser = getCurrentUser;
     _cart           = cart;
     _userService    = userService;
 }
Example #54
0
 public bool AddToCart(CartModel cartModel)
 {
     return(_cartRepository.AddCartItem(cartModel));
 }
 public ProductShippingCheckerBuilder WithCartModel(CartModel cartModel)
 {
     _cartModel = cartModel;
     return(this);
 }
Example #56
0
 public Task <int> AddCartModel(CartModel cartModel)
 {
     return(this._cartRepo.AddCartModel(cartModel));
 }
Example #57
0
        static void Main(string[] args)
        {
            //define business manager and repository
            var inventoryManager = new InventoryManager();
            var cartManager      = new CartManager();

            ConsoleKeyInfo keyPressed = default(ConsoleKeyInfo);

            do
            {
                WriteLine("1 - List Products");
                WriteLine("2 - Display Cart Items");
                WriteLine("3 - Add Item to Cart");
                WriteLine("4 - Place Order");
                WriteLine("Press Command.. Q to exit");

                keyPressed = ReadKey();
                WriteLine("");

                switch (keyPressed.Key)
                {
                case ConsoleKey.D1:
                    var products = inventoryManager.GetProducts();
                    foreach (var product in products)
                    {
                        WriteLine($"{product.Name} {product.Price}");
                    }
                    break;

                case ConsoleKey.D2:
                    WriteLine("Type your userid:");
                    string input  = ReadLine();
                    int    userid = int.Parse(input);
                    //call the business manager
                    var cart = cartManager.GetCart(userid);
                    if (cart != null)
                    {
                        WriteLine($"cart item for user {userid}");
                        foreach (var item in cart.Items)
                        {
                            WriteLine($"{item.Product.Name} {item.Product.Price}");
                        }
                    }
                    else
                    {
                        WriteLine($"No cart item for user {userid}. Please add item");
                    }
                    break;

                case ConsoleKey.D3:
                    WriteLine("Specify your user id");     //get userid
                    string id = ReadLine();
                    userid = int.Parse(id);
                    WriteLine("Specify your product id");
                    string productinput = ReadLine();
                    int    productid    = int.Parse(productinput);

                    //create cartitem object
                    CartModel cartmodel = new CartModel();
                    cartmodel.UserId = userid;
                    cartmodel.Items.Add(new ItemModel
                    {
                        ProductId = productid
                    });

                    bool result = cartManager.AddCartItem(cartmodel);
                    if (result)
                    {
                        WriteLine("item added to cart");
                    }
                    else
                    {
                        WriteLine("invalid data or error occurred");
                    }
                    break;
                }

                WriteLine(Environment.NewLine);
            } while (keyPressed.Key != ConsoleKey.Q);
        }
        public async Task <IActionResult> Put(CartModel cartModel)
        {
            await this.cartService.UpdateAsync(this.UserId, cartModel);

            return(Ok(new ApiResponse <CartModel>()));
        }
Example #59
0
        public override CheckLimitationsResult CheckLimitations(ShippingPostcodeStartsWith limitation, CartModel cart)
        {
            if (cart.ShippingAddress == null)
            {
                return
                    (CheckLimitationsResult.CurrentlyInvalid(_stringResourceProvider.GetValue("Shipping address is not yet set")));
            }
            var postcodes =
                (limitation.ShippingPostcode ?? string.Empty).Split(new[] { "," }, StringSplitOptions.RemoveEmptyEntries)
                .Select(s => s.Trim().ToUpper())
                .ToHashSet();
            var postcode = cart.ShippingAddress.FormattedPostcode();

            return(postcodes.Any(postcode.StartsWith)
                ? CheckLimitationsResult.Successful(Enumerable.Empty <CartItem>())
                : CheckLimitationsResult.CurrentlyInvalid(
                       _stringResourceProvider.GetValue("Shipping postcode is not valid for this discount")));
        }
Example #60
0
        public async Task <int> CreateCartAsync(CartDTO cart)
        {
            CartModel cartModel = _mapper.Map <CartModel>(cart);

            return(await _cartEFService.AddCartAsync(cartModel));
        }