Beispiel #1
0
 //Create a new cart for the logged user.
 public CartService(CartHelper cartHelper)
 {
     _cartHelper = cartHelper;
     if (cartHelper == null)
     {
         var user = SecurityContext.Current.CurrentUserId;
          _cartHelper = new CartHelper(Cart.DefaultName, user);
     }
 }
        public ShoppingCart GetCart()
        {
            CartHelper ch = new CartHelper(Cart.DefaultName);

            var items = ch.LineItems.Select(lineItem => new LineItem() {Name = lineItem.DisplayName}).ToList();

            return new ShoppingCart()
            {
                Items = items,
                Items2 = ch.LineItems
            };
        }
        public DibsPaymentProcessingResult ProcessPaymentResult(DibsPaymentResult result, IIdentity identity)
        {
            var cartHelper = new CartHelper(Cart.DefaultName);
            if (cartHelper.Cart.OrderForms.Count == 0)
                return null;
            var cart = cartHelper.Cart;
            var payment = cart.OrderForms[0].Payments[0] as DibsPayment;
            if (payment != null)
            {
                payment.CardNumberMasked = result.CardNumberMasked;
                payment.CartTypeName = result.CardTypeName;
                payment.TransactionID = result.Transaction;
                payment.TransactionType = TransactionType.Authorization.ToString();
                payment.Status = result.Status;
                cartHelper.Cart.Status = DIBSPaymentGateway.PaymentCompleted;
            }
            else
            {
                throw new Exception("Not a DIBS Payment");
            }

            var orderNumber = cartHelper.Cart.GeneratePredictableOrderNumber();

            Log.Debug("Order placed - order number: " + orderNumber);

            cartHelper.Cart.OrderNumberMethod = CartExtensions.GeneratePredictableOrderNumber;

            var results = OrderGroupWorkflowManager.RunWorkflow(cartHelper.Cart, OrderGroupWorkflowManager.CartCheckOutWorkflowName);
            var message = string.Join(", ", OrderGroupWorkflowManager.GetWarningsFromWorkflowResult(results));

            if (message.Length == 0)
            {
                cartHelper.Cart.SaveAsPurchaseOrder();
                cartHelper.Cart.Delete();
                cartHelper.Cart.AcceptChanges();
            }

            var order = _orderService.GetOrderByTrackingNumber(orderNumber);

            // Must be run after order is complete,
            // This will release the order for shipment and
            // send the order receipt by email
            _paymentCompleteHandler.ProcessCompletedPayment(order, identity);

            return new DibsPaymentProcessingResult(order, message);
        }
        private Money CalculateShippingCostSubTotal(IEnumerable<Shipment> shipments, CartHelper cartHelper)
        {
            var retVal = new Money(0, cartHelper.Cart.BillingCurrency);
            foreach (Shipment shipment in shipments)
            {
                if (cartHelper.FindAddressByName(shipment.ShippingAddressId) == null)
                    continue;

                var methods = ShippingManager.GetShippingMethods(CurrentPage.LanguageID);

                var shippingMethod = methods.ShippingMethod.FirstOrDefault(c => c.ShippingMethodId.Equals(shipment.ShippingMethodId));
                if (shippingMethod == null)
                    continue;

                var shipmentRateMoney = SampleStoreHelper.GetShippingCost(shippingMethod, shipment, cartHelper.Cart.BillingCurrency);
                retVal += shipmentRateMoney;
            }

            return retVal;
        }
        private CartActionResult AddToCart(string name, LineItem lineItem)
        {
            CartHelper ch = new CartHelper(name);
            string messages = string.Empty;

            if (lineItem.Quantity < 1)
            {
                lineItem.Quantity = 1;
            }

            // Need entry for adding to cart
            var entry = CatalogContext.Current.GetCatalogEntry(lineItem.Code);
            ch.AddEntry(entry, lineItem.Quantity, false, new CartHelper[] { });

            // Need content for easier access to more information
            ContentReference itemLink = _referenceConverter.GetContentLink(entry.CatalogEntryId,
                CatalogContentType.CatalogEntry, 0);
            EntryContentBase entryContent = _contentLoader.Get<EntryContentBase>(itemLink);

            // Populate line item with as much as we can find
            if (string.IsNullOrEmpty(lineItem.ImageUrl))
            {
                lineItem.ImageUrl = entryContent.GetDefaultImage();
            }

            if (string.IsNullOrEmpty(lineItem.ArticleNumber))
            {
                lineItem.ArticleNumber = entry.ID;
            }

            lineItem.Name = TryGetDisplayName(entry);
            //lineItem.IsInventoryAllocated = true; // Will this be enough?

            AddCustomProperties(lineItem, ch.Cart);

            messages = RunWorkflowAndReturnFormattedMessage(ch.Cart, OrderGroupWorkflowManager.CartValidateWorkflowName);
            ch.Cart.AcceptChanges();

            // TODO: Always returns success, if we get warnings, we need to show them
            return new CartActionResult() { Success = true, Message = messages };
        }
        public ActionResult Index()
        {
            var receiptPage = _contentRepository.Get <ReceiptPage>(_siteConfiguration.GetSettings().ReceiptPage);

            var cartHelper = new CartHelper(Cart.DefaultName);

            if (cartHelper.IsEmpty && !PageEditing.PageIsInEditMode)
            {
                return(View("Error/_EmptyCartError"));
            }

            string         message        = "";
            OrderViewModel orderViewModel = null;

            if (cartHelper.Cart.OrderForms.Count > 0)
            {
                var orderNumber = cartHelper.Cart.GeneratePredictableOrderNumber();

                _log.Debug("Order placed - order number: " + orderNumber);

                cartHelper.Cart.OrderNumberMethod = CartExtensions.GeneratePredictableOrderNumber;

                System.Diagnostics.Trace.WriteLine("Running Workflow: " + OrderGroupWorkflowManager.CartCheckOutWorkflowName);
                var results = OrderGroupWorkflowManager.RunWorkflow(cartHelper.Cart, OrderGroupWorkflowManager.CartCheckOutWorkflowName);
                message = string.Join(", ", OrderGroupWorkflowManager.GetWarningsFromWorkflowResult(results));

                if (message.Length == 0)
                {
                    var purchaseOrder = cartHelper.Cart.SaveAsPurchaseOrder();
                    cartHelper.Cart.Delete();
                    cartHelper.Cart.AcceptChanges();

                    // Track successfull order
                    //var trackingData = _trackingDataFactory.CreateOrderTrackingData(purchaseOrder, HttpContext);
                    //_trackingService.Send(trackingData, HttpContext, RetrieveRecommendationMode.Disabled);
                    _recommendationService.TrackOrder(purchaseOrder, HttpContext, CurrentPage);
                }

                System.Diagnostics.Trace.WriteLine("Loading Order: " + orderNumber);
                var order = _orderService.GetOrderByTrackingNumber(orderNumber);

                // Must be run after order is complete,
                // This might release the order for shipment and
                // send the order receipt by email
                System.Diagnostics.Trace.WriteLine(string.Format("Process Completed Payment: {0} (User: {1})", orderNumber, User.Identity.Name));
                _paymentCompleteHandler.ProcessCompletedPayment(order, User.Identity);

                orderViewModel = new OrderViewModel(_currentMarket.GetCurrentMarket().DefaultCurrency.Format, order);
            }

            ReceiptViewModel model = new ReceiptViewModel(receiptPage);

            model.CheckoutMessage = message;
            model.Order           = orderViewModel;

            // Track successfull order in Google Analytics
            TrackAfterPayment(model);

            _metricsLoggingService.Count("Purchase", "Purchase Success");
            _metricsLoggingService.Count("Payment", "Generic");

            return(View("ReceiptPage", model));
        }
        public CartActionResult RemoveFromCart(string name, LineItem product)
        {
            CartHelper ch = new CartHelper(name);
            var item = ch.Cart.OrderForms[0].LineItems.FindItemByCatalogEntryId(product.Code);
            ch.Cart.OrderForms[0].LineItems.Remove(item);
            ch.Cart.AcceptChanges();

            string messages = RunWorkflowAndReturnFormattedMessage(ch.Cart, OrderGroupWorkflowManager.CartValidateWorkflowName);

            return new CartActionResult() { Success = true, Message = messages };
        }
 public void UpdateShipping(string name)
 {
     var cart = new CartHelper(name).Cart;
     cart.OrderForms[0].SetShipmentLineItemQuantity();
     cart.AcceptChanges();
 }
 public StoreProductController(ApplicationDbContext context)
 {
     _context = context;
     helper   = new CartHelper();
 }
        public List<LineItem> GetItems(string cart, string language)
        {
            CartHelper ch = new CartHelper(cart);
            List<LineItem> items = new List<LineItem>();
            if (ch.LineItems != null)
            {
                foreach (Mediachase.Commerce.Orders.LineItem lineItem in ch.LineItems)
                {
                    var item = new LineItem(lineItem, language);
                    item.UpdateData(lineItem);
                    items.Add(item);
                }
            }

            return items;
        }
        public ActionResult Index(CheckoutPage currentPage, CheckoutViewModel model, PaymentSelection paymentSelection, int[] SelectedCategories)
        {
            model.PaymentSelection    = paymentSelection;
            model.AvailableCategories = GetAvailableCategories();
            model.SelectedCategories  = SelectedCategories;

            bool requireSSN = _paymentRegistry.PaymentMethodRequiresSocialSecurityNumber(paymentSelection);

            // validate input!
            ValidateFields(model, requireSSN);

            CartHelper ch = new CartHelper(Cart.DefaultName);

            // Verify that we actually have the items we're about to sell
            ConfirmStocks(ch.LineItems);

            if (ModelState.IsValid)
            {
                var    billingAddress  = model.BillingAddress.ToOrderAddress(Constants.Order.BillingAddressName);
                var    shippingAddress = model.ShippingAddress.ToOrderAddress(Constants.Order.ShippingAddressName);
                string username        = model.Email.Trim();
                billingAddress.Email = username;
                billingAddress.DaytimePhoneNumber = model.Phone;

                HandleUserCreation(model, billingAddress, shippingAddress, username);

                if (ModelState.IsValid)
                {
                    // Checkout:

                    ch.Cart.OrderAddresses.Add(billingAddress);
                    ch.Cart.OrderAddresses.Add(shippingAddress);

                    AddShipping(ch.Cart, shippingAddress);

                    ch.Cart.OrderForms[0][Constants.Metadata.OrderForm.CustomerClub] = model.MemberClub;
                    if (model.SelectedCategories != null)
                    {
                        ch.Cart.OrderForms[0][Constants.Metadata.OrderForm.SelectedCategories] = string.Join(",", model.SelectedCategories);
                    }
                    OrderGroupWorkflowManager.RunWorkflow(ch.Cart, OrderGroupWorkflowManager.CartPrepareWorkflowName);

                    AddPayment(ch.Cart, paymentSelection.SelectedPayment.ToString(), billingAddress);

                    ch.Cart.AcceptChanges();

                    var url = _paymentRegistry.GetPaymentMethodPageUrl(model.PaymentSelection.SelectedPayment.ToString());

                    if (url != null)
                    {
                        return(Redirect(url));
                    }
                }
            }

            Guid?selectedPayment = model.PaymentSelection.SelectedPayment;

            model.PaymentSelection = GetPaymentInfo();
            if (selectedPayment.HasValue)
            {
                model.PaymentSelection.SelectedPayment = selectedPayment.Value;
            }
            model.TermsArticle = currentPage.TermsArticle;

            return(View(model));
        }
Beispiel #12
0
 public void DeleteCart(int productID)
 {
     CartHelper.DeleteCart(productID);
 }
        public Cart Get()
        {
            CartHelper helper = new CartHelper(Cart.DefaultName);

            return(helper.Cart);
        }
        private void GetOrderProductsInfo(string cartItemIds, long?regionId)
        {
            ShippingAddressInfo shippingAddressInfo = new ShippingAddressInfo();

            shippingAddressInfo = (!regionId.HasValue ? ServiceHelper.Create <IShippingAddressService>().GetDefaultUserShippingAddressByUserId(base.CurrentUser.Id) : ServiceHelper.Create <IShippingAddressService>().GetUserShippingAddress(regionId.Value));
            int cityId = 0;

            if (shippingAddressInfo != null)
            {
                cityId = Instance <IRegionService> .Create.GetCityId(shippingAddressInfo.RegionIdPath);
            }
            CartHelper cartHelper = new CartHelper();
            IEnumerable <ShoppingCartItem> cartItems = null;

            if (!string.IsNullOrWhiteSpace(cartItemIds))
            {
                char[]             chrArray = new char[] { ',' };
                IEnumerable <long> nums     =
                    from t in cartItemIds.Split(chrArray)
                    select long.Parse(t);

                cartItems = ServiceHelper.Create <ICartService>().GetCartItems(nums);
            }
            else
            {
                cartItems = cartHelper.GetCart(base.CurrentUser.Id).Items;
            }
            IProductService      productService = ServiceHelper.Create <IProductService>();
            IShopService         shopService    = ServiceHelper.Create <IShopService>();
            List <CartItemModel> list           = cartItems.Select <ShoppingCartItem, CartItemModel>((ShoppingCartItem item) =>
            {
                ProductInfo product = productService.GetProduct(item.ProductId);
                SKUInfo sku         = productService.GetSku(item.SkuId);
                return(new CartItemModel()
                {
                    skuId = item.SkuId,
                    id = product.Id,
                    imgUrl = product.GetImage(ProductInfo.ImageSize.Size_50, 1),
                    name = product.ProductName,
                    price = sku.SalePrice,
                    shopId = product.ShopId,
                    count = item.Quantity,
                    productCode = product.ProductCode
                });
            }).ToList();
            IEnumerable <IGrouping <long, CartItemModel> > groupings =
                from a in list
                group a by a.shopId;
            List <ShopCartItemModel> shopCartItemModels = new List <ShopCartItemModel>();

            foreach (IGrouping <long, CartItemModel> nums1 in groupings)
            {
                IEnumerable <long> nums2 =
                    from r in nums1
                    select r.id;
                IEnumerable <int> nums3 =
                    from r in nums1
                    select r.count;
                ShopCartItemModel shopCartItemModel = new ShopCartItemModel()
                {
                    shopId = nums1.Key,

                    Freight = (cityId <= 0 ? new decimal(0) : ServiceHelper.Create <IProductService>().GetFreight(nums2, nums3, cityId)),
                };

                shopCartItemModel.CartItemModels = (
                    from a in list
                    where a.shopId == shopCartItemModel.shopId
                    select a).ToList();
                shopCartItemModel.ShopName    = shopService.GetShop(shopCartItemModel.shopId, false).ShopName;
                shopCartItemModel.UserCoupons = ServiceHelper.Create <ICouponService>().GetUserCoupon(shopCartItemModel.shopId, base.CurrentUser.Id, nums1.Sum <CartItemModel>((CartItemModel a) => a.price * a.count));
                shopCartItemModel.UserBonus   = ServiceHelper.Create <IShopBonusService>().GetDetailToUse(shopCartItemModel.shopId, base.CurrentUser.Id, nums1.Sum <CartItemModel>((CartItemModel a) => a.price * a.count));

                shopCartItemModels.Add(shopCartItemModel);
            }
            ViewBag.products         = shopCartItemModels;
            base.ViewBag.totalAmount = list.Sum <CartItemModel>((CartItemModel item) => item.price * item.count);
            base.ViewBag.Freight     = shopCartItemModels.Sum <ShopCartItemModel>((ShopCartItemModel a) => a.Freight);
            dynamic viewBag = base.ViewBag;
            dynamic obj     = ViewBag.totalAmount;

            viewBag.orderAmount = obj + ViewBag.Freight;
        }
        //Exercise (E2) Do CheckOut
        public ActionResult CheckOut(CheckOutViewModel model)
        {
            // ToDo: declare a variable for CartHelper
            CartHelper ch = new CartHelper(Cart.DefaultName);

            int orderAddressId = 0;

            // ToDo: Addresses (an If-Else)
            if (CustomerContext.Current.CurrentContact == null)
            {
                // Anonymous... one way of "doing it"... for example, if no other address exist
                orderAddressId = ch.Cart.OrderAddresses.Add(
                    new OrderAddress
                {
                    CountryCode        = "SWE",
                    CountryName        = "Sweden",
                    Name               = "SomeCustomerAddress",
                    DaytimePhoneNumber = "123456",
                    FirstName          = "John",
                    LastName           = "Smith",
                    Email              = "*****@*****.**",
                });
            }
            else
            {
                // Logged in
                if (CustomerContext.Current.CurrentContact.PreferredShippingAddress == null)
                {
                    // no pref. address set... so we set one for the contact
                    CustomerAddress newCustAddress =
                        CustomerAddress.CreateForApplication(AppContext.Current.ApplicationId);
                    newCustAddress.AddressType        = CustomerAddressTypeEnum.Shipping; // mandatory
                    newCustAddress.ContactId          = CustomerContext.Current.CurrentContact.PrimaryKeyId;
                    newCustAddress.CountryCode        = "SWE";
                    newCustAddress.CountryName        = "Sweden";
                    newCustAddress.Name               = "new customer address"; // mandatory
                    newCustAddress.DaytimePhoneNumber = "123456";
                    newCustAddress.FirstName          = CustomerContext.Current.CurrentContact.FirstName;
                    newCustAddress.LastName           = CustomerContext.Current.CurrentContact.LastName;
                    newCustAddress.Email              = "*****@*****.**";

                    // note: Line1 & City is what is shown in CM at a few places... not the Name
                    CustomerContext.Current.CurrentContact.AddContactAddress(newCustAddress);
                    CustomerContext.Current.CurrentContact.SaveChanges();

                    // ... needs to be in this order
                    CustomerContext.Current.CurrentContact.PreferredShippingAddress = newCustAddress;
                    CustomerContext.Current.CurrentContact.SaveChanges(); // need this ...again

                    // then, for the cart
                    orderAddressId = ch.Cart.OrderAddresses.Add(new OrderAddress(newCustAddress));
                }
                else
                {
                    // there is a preferred address set (and, a fourth alternative exists... do later )
                    OrderAddress orderAddress =
                        new OrderAddress(CustomerContext.Current.CurrentContact.PreferredShippingAddress);

                    // then, for the cart
                    orderAddressId = ch.Cart.OrderAddresses.Add(orderAddress);
                }
            }

            // Depending how it was created...
            OrderAddress address = ch.FindAddressById(orderAddressId.ToString());

            // ToDo: Define Shipping
            ShippingMethodDto.ShippingMethodRow theShip =
                ShippingManager.GetShippingMethod(model.SelectedShipId).ShippingMethod.First();

            int shippingId = ch.Cart.OrderForms[0].Shipments.Add(
                new Shipment
            {                                          // ...removing anything?
                ShippingAddressId      = address.Name, // note: use no custom prefixes
                ShippingMethodId       = theShip.ShippingMethodId,
                ShippingMethodName     = theShip.Name,
                ShipmentTotal          = theShip.BasePrice,
                ShipmentTrackingNumber = "My tracking number",
            });

            // get the Shipping ... check to see if the Shipping knows about the LineItem
            Shipment firstOrderShipment = ch.Cart.OrderForms[0].Shipments.FirstOrDefault();

            // First (and only) OrderForm
            LineItemCollection lineItems = ch.Cart.OrderForms[0].LineItems;

            // ...basic now... one OrderForm - one Shipping
            foreach (LineItem lineItem in lineItems)
            {
                int index = lineItems.IndexOf(lineItem);
                if ((firstOrderShipment != null) && (index != -1))
                {
                    firstOrderShipment.AddLineItemIndex(index, lineItem.Quantity);
                }
            }


            // Execute the "Shipping & Taxes - WF" (CartPrepare) ... and take care of the return object
            WorkflowResults resultPrepare     = ch.Cart.RunWorkflow(OrderGroupWorkflowManager.CartPrepareWorkflowName);
            List <string>   wfMessagesPrepare = new List <string>(OrderGroupWorkflowManager.GetWarningsFromWorkflowResult(resultPrepare));


            // ToDo: Define Shipping
            PaymentMethodDto.PaymentMethodRow thePay = PaymentManager.GetPaymentMethod(model.SelectedPayId).PaymentMethod.First();
            Payment firstOrderPayment = ch.Cart.OrderForms[0].Payments.AddNew(typeof(OtherPayment));

            // ... need both below
            firstOrderPayment.Amount            = firstOrderShipment.SubTotal + firstOrderShipment.ShipmentTotal; // will change...
            firstOrderPayment.BillingAddressId  = address.Name;
            firstOrderPayment.PaymentMethodId   = thePay.PaymentMethodId;
            firstOrderPayment.PaymentMethodName = thePay.Name;
            // ch.Cart.CustomerName = "John Smith"; // ... this line overwrites what´s in there, if logged in


            // Execute the "Payment activation - WF" (CartCheckout) ... and take care of the return object
            // ...activates the gateway (same for shipping)
            WorkflowResults resultCheckout     = ch.Cart.RunWorkflow(OrderGroupWorkflowManager.CartCheckOutWorkflowName, false);
            List <string>   wfMessagesCheckout = new List <string>(OrderGroupWorkflowManager.GetWarningsFromWorkflowResult(resultCheckout));
            //ch.RunWorkflow("CartValidate") ... can see this (or variations)

            string        trackingNumber = String.Empty;
            PurchaseOrder purchaseOrder  = null;

            // Add a transaction scope and convert the cart to PO
            using (var scope = new Mediachase.Data.Provider.TransactionScope())
            {
                purchaseOrder = ch.Cart.SaveAsPurchaseOrder();
                ch.Cart.Delete();
                ch.Cart.AcceptChanges();
                trackingNumber = purchaseOrder.TrackingNumber;
                scope.Complete();
            }

            // Housekeeping below (Shipping release, OrderNotes and save the order)
            OrderStatusManager.ReleaseOrderShipment(purchaseOrder.OrderForms[0].Shipments[0]);

            OrderNotesManager.AddNoteToPurchaseOrder(purchaseOrder, DateTime.UtcNow.ToShortDateString() + " released for shipping", OrderNoteTypes.System, CustomerContext.Current.CurrentContactId);

            purchaseOrder.ExpirationDate = DateTime.UtcNow.AddDays(30);
            purchaseOrder.Status         = OrderStatus.InProgress.ToString();

            purchaseOrder.AcceptChanges(); // need this here, else no "order-note" persisted


            // Final steps, navigate to the order confirmation page
            StartPage        home = _contentLoader.Service.Get <StartPage>(ContentReference.StartPage);
            ContentReference orderPageReference = home.Settings.orderPage;

            string passingValue = trackingNumber;

            return(RedirectToAction("Index", new { node = orderPageReference, passedAlong = passingValue }));
        }
Beispiel #16
0
 public void CreateEmptyCart()
 {
     _helper = new CartHelper(Cart.DefaultName);
     _helper.Cart.AcceptChanges();
 }
Beispiel #17
0
 public CartNav(ApplicationDbContext context)
 {
     _context = context;
     helper   = new CartHelper();
 }
Beispiel #18
0
 private void LoadCart()
 {
     dgwCart.DataSource = CartHelper.Converter(_cart);
 }
        public IActionResult Checkout()
        {
            List <VideoGame> games = CartHelper.GetGames(_httpAccessor);

            return(View(games));
        }
Beispiel #20
0
        private void GetOrderProductsInfo(string cartItemIds)
        {
            CartHelper cartHelper = new CartHelper();
            IEnumerable <ShoppingCartItem> cartItems = null;

            if (!string.IsNullOrWhiteSpace(cartItemIds))
            {
                char[]             chrArray = new char[] { ',' };
                IEnumerable <long> nums     =
                    from t in cartItemIds.Split(chrArray)
                    select long.Parse(t);

                cartItems = ServiceHelper.Create <ICartService>().GetCartItems(nums);
            }
            else
            {
                cartItems = cartHelper.GetCart(base.CurrentUser.Id).Items;
            }
            int cityId = 0;
            ShippingAddressInfo defaultUserShippingAddressByUserId = ServiceHelper.Create <IShippingAddressService>().GetDefaultUserShippingAddressByUserId(base.CurrentUser.Id);

            if (defaultUserShippingAddressByUserId != null)
            {
                cityId = Instance <IRegionService> .Create.GetCityId(defaultUserShippingAddressByUserId.RegionIdPath);
            }
            IProductService      productService = ServiceHelper.Create <IProductService>();
            IShopService         shopService    = ServiceHelper.Create <IShopService>();
            List <CartItemModel> list           = cartItems.Select <ShoppingCartItem, CartItemModel>((ShoppingCartItem item) => {
                ProductInfo product = productService.GetProduct(item.ProductId);
                SKUInfo sku         = productService.GetSku(item.SkuId);
                return(new CartItemModel()
                {
                    skuId = item.SkuId,
                    id = product.Id,
                    imgUrl = product.GetImage(ProductInfo.ImageSize.Size_100, 1),
                    name = product.ProductName,
                    price = sku.SalePrice,
                    shopId = product.ShopId,
                    count = item.Quantity
                });
            }).ToList();
            IEnumerable <IGrouping <long, CartItemModel> > groupings =
                from a in list
                group a by a.shopId;
            List <ShopCartItemModel> shopCartItemModels = new List <ShopCartItemModel>();

            foreach (IGrouping <long, CartItemModel> nums1 in groupings)
            {
                IEnumerable <long> nums2 =
                    from r in nums1
                    select r.id;
                IEnumerable <int> nums3 =
                    from r in nums1
                    select r.count;
                ShopCartItemModel shopCartItemModel = new ShopCartItemModel()
                {
                    shopId = nums1.Key
                };
                if (ServiceHelper.Create <IVShopService>().GetVShopByShopId(shopCartItemModel.shopId) != null)
                {
                    shopCartItemModel.vshopId = ServiceHelper.Create <IVShopService>().GetVShopByShopId(shopCartItemModel.shopId).Id;
                }
                else
                {
                    shopCartItemModel.vshopId = 0;
                }
                shopCartItemModel.CartItemModels = (
                    from a in list
                    where a.shopId == shopCartItemModel.shopId
                    select a).ToList();
                shopCartItemModel.ShopName = shopService.GetShop(shopCartItemModel.shopId, false).ShopName;
                if (cityId > 0)
                {
                    shopCartItemModel.Freight = ServiceHelper.Create <IProductService>().GetFreight(nums2, nums3, cityId);
                }
                List <ShopBonusReceiveInfo> detailToUse = ServiceHelper.Create <IShopBonusService>().GetDetailToUse(shopCartItemModel.shopId, base.CurrentUser.Id, nums1.Sum <CartItemModel>((CartItemModel a) => a.price * a.count));
                List <CouponRecordInfo>     userCoupon  = ServiceHelper.Create <ICouponService>().GetUserCoupon(shopCartItemModel.shopId, base.CurrentUser.Id, nums1.Sum <CartItemModel>((CartItemModel a) => a.price * a.count));
                if (detailToUse.Count() > 0 && userCoupon.Count() > 0)
                {
                    ShopBonusReceiveInfo shopBonusReceiveInfo = detailToUse.FirstOrDefault();
                    CouponRecordInfo     couponRecordInfo     = userCoupon.FirstOrDefault();
                    decimal?price = shopBonusReceiveInfo.Price;
                    decimal num   = couponRecordInfo.ChemCloud_Coupon.Price;
                    if ((price.GetValueOrDefault() <= num ? true : !price.HasValue))
                    {
                        shopCartItemModel.Coupon = new CouponModel()
                        {
                            CouponName  = couponRecordInfo.ChemCloud_Coupon.CouponName,
                            CouponId    = couponRecordInfo.Id,
                            CouponPrice = couponRecordInfo.ChemCloud_Coupon.Price,
                            Type        = 0
                        };
                    }
                    else
                    {
                        shopCartItemModel.Coupon = new CouponModel()
                        {
                            CouponName  = shopBonusReceiveInfo.ChemCloud_ShopBonusGrant.ChemCloud_ShopBonus.Name,
                            CouponId    = shopBonusReceiveInfo.Id,
                            CouponPrice = shopBonusReceiveInfo.Price.Value,
                            Type        = 1
                        };
                    }
                }
                else if (detailToUse.Count() <= 0 && userCoupon.Count() <= 0)
                {
                    shopCartItemModel.Coupon = null;
                }
                else if (detailToUse.Count() <= 0 && userCoupon.Count() > 0)
                {
                    CouponRecordInfo couponRecordInfo1 = userCoupon.FirstOrDefault();
                    shopCartItemModel.Coupon = new CouponModel()
                    {
                        CouponName  = couponRecordInfo1.ChemCloud_Coupon.CouponName,
                        CouponId    = couponRecordInfo1.Id,
                        CouponPrice = couponRecordInfo1.ChemCloud_Coupon.Price,
                        Type        = 0
                    };
                }
                else if (detailToUse.Count() > 0 && userCoupon.Count() <= 0)
                {
                    ShopBonusReceiveInfo shopBonusReceiveInfo1 = detailToUse.FirstOrDefault();
                    shopCartItemModel.Coupon = new CouponModel()
                    {
                        CouponName  = shopBonusReceiveInfo1.ChemCloud_ShopBonusGrant.ChemCloud_ShopBonus.Name,
                        CouponId    = shopBonusReceiveInfo1.Id,
                        CouponPrice = shopBonusReceiveInfo1.Price.Value,
                        Type        = 1
                    };
                }
                decimal num1        = shopCartItemModel.CartItemModels.Sum <CartItemModel>((CartItemModel d) => d.price * d.count);
                decimal num2        = num1 - (shopCartItemModel.Coupon == null ? new decimal(0) : shopCartItemModel.Coupon.CouponPrice);
                decimal freeFreight = shopService.GetShop(shopCartItemModel.shopId, false).FreeFreight;
                shopCartItemModel.isFreeFreight = false;
                if (freeFreight > new decimal(0))
                {
                    shopCartItemModel.shopFreeFreight = freeFreight;
                    if (num2 >= freeFreight)
                    {
                        shopCartItemModel.Freight       = new decimal(0);
                        shopCartItemModel.isFreeFreight = true;
                    }
                }
                shopCartItemModels.Add(shopCartItemModel);
            }
            decimal num3 = (
                from a in shopCartItemModels
                where a.Coupon != null
                select a).Sum <ShopCartItemModel>((ShopCartItemModel b) => b.Coupon.CouponPrice);

            ViewBag.products         = shopCartItemModels;
            base.ViewBag.totalAmount = list.Sum <CartItemModel>((CartItemModel item) => item.price * item.count);
            base.ViewBag.Freight     = shopCartItemModels.Sum <ShopCartItemModel>((ShopCartItemModel a) => a.Freight);
            dynamic viewBag = base.ViewBag;
            dynamic obj     = ViewBag.totalAmount;

            viewBag.orderAmount = obj + ViewBag.Freight - num3;
            IMemberIntegralService memberIntegralService = ServiceHelper.Create <IMemberIntegralService>();
            MemberIntegral         memberIntegral        = memberIntegralService.GetMemberIntegral(base.CurrentUser.Id);
            int num4 = (memberIntegral == null ? 0 : memberIntegral.AvailableIntegrals);

            ViewBag.userIntegrals      = num4;
            ViewBag.integralPerMoney   = 0;
            ViewBag.memberIntegralInfo = memberIntegral;
            MemberIntegralExchangeRules integralChangeRule = memberIntegralService.GetIntegralChangeRule();
            decimal num5     = new decimal(0);
            decimal num6     = new decimal(0);
            decimal viewBag1 = (decimal)ViewBag.totalAmount;

            if (integralChangeRule == null || integralChangeRule.IntegralPerMoney <= 0)
            {
                num5 = new decimal(0);
                num6 = new decimal(0);
            }
            else
            {
                if (((viewBag1 - num3) - Math.Round((decimal)num4 / integralChangeRule.IntegralPerMoney, 2)) <= new decimal(0))
                {
                    num5 = Math.Round(viewBag1 - num3, 2);
                    num6 = Math.Round((viewBag1 - num3) * integralChangeRule.IntegralPerMoney);
                }
                else
                {
                    num5 = Math.Round((decimal)num4 / integralChangeRule.IntegralPerMoney, 2);
                    num6 = num4;
                }
                if (num5 <= new decimal(0))
                {
                    num5 = new decimal(0);
                    num6 = new decimal(0);
                }
            }
            ViewBag.integralPerMoney = num5;
            ViewBag.userIntegrals    = num6;
        }
 public CartService()
 {
     _helper = new CartHelper(Cart.DefaultName, PrincipalInfo.CurrentPrincipal.GetContactId());
 }
Beispiel #22
0
        public ActionResult Index(CheckoutPage currentPage, CheckoutViewModel model, PaymentInfo paymentInfo, int[] SelectedCategories)
        {
            model.PaymentInfo         = paymentInfo;
            model.AvailableCategories = GetAvailableCategories();
            model.SelectedCategories  = SelectedCategories;

            bool requireSSN = paymentInfo.SelectedPayment == new Guid("8dca4a96-a5bb-4e85-82a4-2754f04c2117") ||
                              paymentInfo.SelectedPayment == new Guid("c2ea88f8-c702-4331-819e-0e77e7ac5450");

            // validate input!
            ValidateFields(model, requireSSN);

            CartHelper ch = new CartHelper(Cart.DefaultName);

            // Verify that we actually have the items we're about to sell
            ConfirmStocks(ch.LineItems);

            if (ModelState.IsValid)
            {
                var    billingAddress  = model.BillingAddress.ToOrderAddress(Constants.Order.BillingAddressName);
                var    shippingAddress = model.ShippingAddress.ToOrderAddress(Constants.Order.ShippingAddressName);
                string username        = model.Email.Trim();
                billingAddress.Email = username;
                billingAddress.DaytimePhoneNumber = model.Phone;

                HandleUserCreation(model, billingAddress, shippingAddress, username);

                if (ModelState.IsValid)
                {
                    // Checkout:

                    ch.Cart.OrderAddresses.Add(billingAddress);
                    ch.Cart.OrderAddresses.Add(shippingAddress);

                    AddShipping(ch.Cart, shippingAddress);

                    ch.Cart.OrderForms[0][Constants.Metadata.OrderForm.CustomerClub] = model.MemberClub;
                    if (model.SelectedCategories != null)
                    {
                        ch.Cart.OrderForms[0][Constants.Metadata.OrderForm.SelectedCategories] = string.Join(",", model.SelectedCategories);
                    }
                    OrderGroupWorkflowManager.RunWorkflow(ch.Cart, OrderGroupWorkflowManager.CartPrepareWorkflowName);

                    AddPayment(ch.Cart, paymentInfo.SelectedPayment.ToString(), billingAddress);

                    ch.Cart.AcceptChanges();

                    // TODO: This assume the different payment pages are direct children of the start page
                    // and could break the payment if we move the pages.
                    BasePaymentPage page      = null;
                    var             startPage = _contentRepository.Get <HomePage>(ContentReference.StartPage);
                    foreach (var p in _contentRepository.GetChildren <BasePaymentPage>(startPage.Settings.PaymentContainerPage))
                    {
                        if (p.PaymentMethod.Equals(model.PaymentInfo.SelectedPayment.ToString()))
                        {
                            page = p;
                            break;
                        }
                    }

                    var resolver = ServiceLocator.Current.GetInstance <UrlResolver>();

                    if (page != null)
                    {
                        var url = resolver.GetUrl(page.ContentLink);
                        return(Redirect(url));
                    }
                }
            }

            Guid?selectedPayment = model.PaymentInfo.SelectedPayment;

            model.PaymentInfo = GetPaymentInfo();
            if (selectedPayment.HasValue)
            {
                model.PaymentInfo.SelectedPayment = selectedPayment.Value;
            }
            model.TermsArticle = currentPage.TermsArticle;

            return(View(model));
        }
Beispiel #23
0
        protected void Page_Load(object sender, EventArgs e)
        {
            Response.ContentType = "text/json";
            Encoding encoding = new UTF8Encoding();

            Response.ContentEncoding = encoding;

            try
            {
                LoadParams();

                if (
                    method != "AddProductToCart_Catalog" &&
                    method != "AddProductToCart_Details" &&
                    method != "UpdateCart" &&
                    method != "RemoveFromCart" &&
                    method != "ChangeAttributes"
                    )
                {
                    Response.Write(StringHelper.ToJsonString(new
                    {
                        success = false,
                        message = "No method found with the " + method
                    }));
                    return;
                }

                if (method == "UpdateCart")
                {
                    Response.Write(CartHelper.UpdateCart(postParams));
                    return;
                }
                else if (method == "RemoveFromCart")
                {
                    Guid itemGuid = Guid.Empty;
                    if (postParams.Get("itemguid") != null)
                    {
                        Guid.TryParse(postParams.Get("itemguid"), out itemGuid);
                    }

                    Response.Write(CartHelper.RemoveFromCart(itemGuid));
                    return;
                }

                int     productId = -1;
                Product product   = null;
                //productId = WebUtils.ParseInt32FromQueryString("ProductId", productId);
                if (postParams.Get("productid") != null)
                {
                    int.TryParse(postParams.Get("productid"), out productId);
                }

                SiteSettings siteSettings = CacheHelper.GetCurrentSiteSettings();
                if (siteSettings != null && siteSettings.SiteId > 0)
                {
                    product = new Product(siteSettings.SiteId, productId);
                }

                if (
                    product == null ||
                    product.ProductId <= 0 ||
                    !product.IsPublished ||
                    product.IsDeleted
                    )
                {
                    Response.Write(StringHelper.ToJsonString(new
                    {
                        success = false,
                        message = "No product found with the specified ID"
                    }));
                    return;
                }

                switch (method)
                {
                case "AddProductToCart_Catalog":
                    int quantity = 1;
                    if (postParams.Get("qty") != null)
                    {
                        int.TryParse(postParams.Get("qty"), out quantity);
                    }
                    Response.Write(CartHelper.AddProductToCart_Catalog(product, ShoppingCartTypeEnum.ShoppingCart, quantity));
                    break;

                case "AddProductToCart_Details":
                    Response.Write(CartHelper.AddProductToCart_Details(product, ShoppingCartTypeEnum.ShoppingCart, postParams));
                    break;

                case "ChangeAttributes":
                    Response.Write(ChangeAttributes(product, postParams));
                    break;
                }
            }
            catch (Exception ex)
            {
                log.Error(ex);

                Response.Write(StringHelper.ToJsonString(new
                {
                    success = false,
                    message = "Failed to process from the server. Please refresh the page and try one more time."
                }));
            }
        }
Beispiel #24
0
 public CartController(AppDbContext db)
 {
     _cartHelper = new CartHelper();
     _db         = db;
 }
Beispiel #25
0
        public object GetUpdateToCart(string openId, string SkuID, int Quantity, int GiftID = 0)
        {
            //验证用户
            CheckUserLogin();
            var  cartHelper  = new CartHelper();
            long userId      = CurrentUser != null ? CurrentUser.Id : 0;
            var  skus        = cartHelper.GetCart(userId);
            var  oldQuantity = GetCartProductQuantity(skus, skuId: SkuID);

            oldQuantity = oldQuantity + Quantity;

            long productId = 0;
            var  skuItem   = skus.Items.FirstOrDefault(i => i.SkuId == SkuID);

            if (null == skuItem)
            {
                var sku = ProductManagerApplication.GetSKU(SkuID);
                if (null == sku)
                {
                    return(Json(ErrorResult <dynamic>("错误的参数:SkuId")));
                }
                productId = sku.ProductId;
            }
            else
            {
                productId = skuItem.ProductId;
            }
            var ladderPrice = 0m;
            var product     = ProductManagerApplication.GetProduct(productId);

            if (product != null)
            {
                if (product.MaxBuyCount > 0 && oldQuantity > product.MaxBuyCount && !product.IsOpenLadder)
                {
                    cartHelper.UpdateCartItem(SkuID, product.MaxBuyCount, userId);
                    return(Json(ErrorResult <dynamic>(string.Format("每个ID限购{0}件", product.MaxBuyCount), new { stock = product.MaxBuyCount })));
                }
            }


            SKUInfo skuinfo = OrderApplication.GetSkuByID(SkuID);

            if (skuinfo.Stock < oldQuantity)
            {
                cartHelper.UpdateCartItem(SkuID, Convert.ToInt32(skuinfo.Stock), userId);
                return(Json(ErrorResult <dynamic>("库存不足", new { stock = skuinfo.Stock })));
            }

            cartHelper.UpdateCartItem(SkuID, oldQuantity, userId);
            //调用查询购物车数据

            #region 阶梯价--张宇枫
            var isOpenLadder = product.IsOpenLadder;
            if (isOpenLadder)
            {
                var shop = ShopApplication.GetShop(product.ShopId);
                var groupCartByProduct = cartHelper.GetCart(userId).Items.Where(item => item.ShopBranchId == 0).GroupBy(i => i.ProductId).ToList();
                //var groupCartByProduct = skus.Items.Where(item => item.ShopBranchId == 0).Select(c =>
                //{
                //    var cItem = new Mall.Entities.ShoppingCartItem();
                //    var skuInfo = ServiceProvider.Instance<IProductService>.Create.GetSku(c.SkuId);
                //    if (skuInfo != null)
                //        cItem = c;
                //    return cItem;
                //}).GroupBy(i => i.ProductId).ToList();

                var quantity =
                    groupCartByProduct.Where(i => i.Key == productId)
                    .ToList()
                    .Sum(cartitem => cartitem.Sum(i => i.Quantity));
                ladderPrice = ProductManagerApplication.GetProductLadderPrice(productId, quantity);
                if (shop.IsSelf)
                {
                    ladderPrice = CurrentUser.MemberDiscount * ladderPrice;
                }
            }
            #endregion
            return(Json(new { Price = ladderPrice.ToString("F2"), ProductId = productId, IsOpenLadder = isOpenLadder ? 1 : 0 }));
        }
 public decimal GetTax(string name)
 {
     var cart = new CartHelper(name).Cart;
     var tax = cart.TaxTotal;
     // TODO: Get tax percent from somewhere
     if (tax == 0)
     {
         tax = 0.25m * cart.Total;
     }
     return tax;
 }
Beispiel #27
0
        public IActionResult PaymentInfo(string orderGuid, bool error = false)
        {
            Order order = null;
            Cart  cart  = null;

            //if order guid is set, we need to make sure that order is new
            if (!orderGuid.IsNullEmptyOrWhiteSpace())
            {
                order = _orderService.GetByGuid(orderGuid);
                if (order == null || order.PaymentStatus != PaymentStatus.Pending)
                {
                    return(RedirectToRoute(RouteNames.Home));
                }
            }
            else
            {
                //we don't have orderGuid, so it's a fresh checkout
                if (!CanCheckout(out cart))
                {
                    return(RedirectToRoute(RouteNames.Home));
                }

                //is payment required
                if (!CartHelper.IsPaymentRequired(cart))
                {
                    return(RedirectToRoute(RouteNames.CheckoutConfirm));
                }
            }

            //do we have addresses?
            if (cart != null && (cart.BillingAddressId == 0 || cart.ShippingAddressId == 0 && CartHelper.IsShippingRequired(cart)))
            {
                return(RedirectToRoute(RouteNames.CheckoutAddress));
            }

            //find available payment methods
            var paymentHandlers = _pluginAccountant.GetActivePlugins(typeof(IPaymentHandlerPlugin));

            if (!paymentHandlers.Any())
            {
                //redirect to confirm page...payment must be handled offline
                cart.PaymentMethodName = ApplicationConfig.UnavailableMethodName;
                _cartService.Update(cart);
                return(RedirectToRoute(RouteNames.CheckoutConfirm));
            }

            if ((cart != null && CartHelper.IsSubscriptionCart(cart)) || (order != null && OrderHelper.IsSubscription(order)))
            {
                //filter by payment methods which support subscription
                paymentHandlers = paymentHandlers
                                  .Where(x => x.LoadPluginInstance <IPaymentHandlerPlugin>().SupportsSubscriptions).ToList();
            }
            var paymentModels = paymentHandlers.Select(x =>
            {
                var pluginHandlerInstance = x.LoadPluginInstance <IPaymentHandlerPlugin>();
                var model = new PaymentMethodModel()
                {
                    SystemName   = x.SystemName,
                    Description  = x.Description,
                    FriendlyName = x.Name,
                    Url          = Url.RouteUrl(pluginHandlerInstance.PaymentHandlerComponentRouteName)
                };
                try
                {
                    model.Fee = order == null
                            ? pluginHandlerInstance.GetPaymentHandlerFee(cart)
                            : pluginHandlerInstance.GetPaymentHandlerFee(order);
                }
                catch (Exception ex)
                {
                    _logger.Log <CheckoutController>(LogLevel.Error, ex.Message, ex);
                    //do nothing
                }
                return(model);
            })
                                .ToList();

            //get if there are store credits available
            GetAvailableStoreCredits(out var availableStoreCredits, out var availableStoreCreditAmount, ApplicationEngine.CurrentCurrency, cart);

            //if order guid is set, it means a payment transaction has failed in previous attempt
            //we can use this identifier to skip confirmation page for subsequent attempt
            //this will be same as retry payment from a failed order page
            return(R.Success.With("paymentMethods", paymentModels)
                   .With("error", error)
                   .With("availableStoreCredits", availableStoreCredits)
                   .With("availableStoreCreditAmount", availableStoreCreditAmount)
                   .With("orderGuid", orderGuid).Result);
        }
        public CartActionResult UpdateCart(string name, LineItem product)
        {
            CartHelper ch = new CartHelper(name);
            string messages = string.Empty;

            var item = ch.LineItems.FirstOrDefault(i => i.Code == product.Code);

            if (item != null)
            {
                item.Quantity = product.Quantity > 0 ? product.Quantity : 0;

                messages = RunWorkflowAndReturnFormattedMessage(ch.Cart, OrderGroupWorkflowManager.CartValidateWorkflowName);

                ch.Cart.AcceptChanges();
            }

            // TODO: Should we always return success? What if the messages indicate otherwise?
            return new CartActionResult() { Success = true, Message = messages };
        }
Beispiel #29
0
        public IActionResult ConfirmSave()
        {
            if (!CanCheckout(out Cart cart))
            {
                return(R.Fail.With("error", T("An error occurred while checking out")).Result);
            }
            var shippingRequired = CartHelper.IsShippingRequired(cart);

            if (cart.BillingAddressId == 0 || cart.ShippingAddressId == 0 && shippingRequired)
            {
                return(R.Fail.With("error", T("The address details were not provided")).Result);
            }

            if (cart.ShippingMethodName.IsNullEmptyOrWhiteSpace() && shippingRequired)
            {
                return(R.Fail.With("error", T("The shipping details were not provided.")).Result);
            }

            if (CartHelper.IsPaymentRequired(cart) && cart.PaymentMethodName.IsNullEmptyOrWhiteSpace() && !cart.UseStoreCredits)
            {
                return(R.Fail.With("error", T("The payment method was not provided")).Result);
            }

            if (shippingRequired)
            {
                //validate shipping method
                var shippingHandler = PluginHelper.GetShipmentHandler(cart.ShippingMethodName);
                if (shippingHandler == null || !shippingHandler.IsMethodAvailable(cart))
                {
                    return(R.Fail.With("error", T("Shipping method unavailable")).Result);
                }
            }


            var currentUser = ApplicationEngine.CurrentUser;
            var order       = new Order()
            {
                PaymentMethodName         = cart.PaymentMethodName,
                PaymentMethodDisplayName  = cart.PaymentMethodDisplayName,
                ShippingMethodName        = cart.ShippingMethodName,
                ShippingMethodDisplayName = cart.ShippingMethodDisplayName,
                SelectedShippingOption    = cart.SelectedShippingOption,
                CreatedOn         = DateTime.UtcNow,
                DiscountId        = cart.DiscountCouponId,
                Guid              = Guid.NewGuid().ToString(),
                UserId            = cart.UserId,
                PaymentStatus     = PaymentStatus.Pending,
                OrderStatus       = OrderStatus.New,
                DiscountCoupon    = cart.DiscountCoupon?.CouponCode,
                Discount          = cart.Discount + cart.CartItems.Sum(x => x.Discount),
                PaymentMethodFee  = cart.PaymentMethodFee,
                ShippingMethodFee = cart.ShippingFee,
                Tax            = cart.CartItems.Sum(x => x.Tax),
                UserIpAddress  = WebHelper.GetClientIpAddress(),
                CurrencyCode   = ApplicationEngine.BaseCurrency.IsoCode,
                Subtotal       = cart.FinalAmount - cart.CartItems.Sum(x => x.Tax),
                ExchangeRate   = ApplicationEngine.BaseCurrency.ExchangeRate,
                DisableReturns = cart.CartItems.All(x => !x.Product.AllowReturns),
                User           = currentUser,
                IsSubscription = CartHelper.IsSubscriptionCart(cart)
            };

            order.OrderTotal = order.Subtotal + order.Tax + (order.PaymentMethodFee ?? 0) + (order.ShippingMethodFee ?? 0) - order.Discount;
            //load the addresses
            var addressIds = new List <int>()
            {
                cart.BillingAddressId, cart.ShippingAddressId
            };
            var addresses       = _addressService.Get(x => addressIds.Contains(x.Id)).ToList();
            var billingAddress  = addresses.First(x => x.Id == cart.BillingAddressId);
            var shippingAddress = addresses.FirstOrDefault(x => x.Id == cart.ShippingAddressId);

            order.BillingAddressSerialized  = _dataSerializer.Serialize(billingAddress);
            order.ShippingAddressSerialized =
                shippingAddress == null ? null : _dataSerializer.Serialize(shippingAddress);

            //get all the products
            var distinctProductIds = cart.CartItems.Select(x => x.ProductId).ToList();
            var products           = _productService.Get(x => distinctProductIds.Contains(x.Id)).ToList();

            order.OrderItems = new List <OrderItem>();
            foreach (var cartItem in cart.CartItems)
            {
                var orderItem = new OrderItem()
                {
                    AttributeJson    = cartItem.AttributeJson,
                    OrderId          = order.Id,
                    Price            = cartItem.Price,
                    ProductId        = cartItem.ProductId,
                    Quantity         = cartItem.Quantity,
                    Tax              = cartItem.Tax,
                    TaxPercent       = cartItem.TaxPercent,
                    TaxName          = cartItem.TaxName,
                    ProductVariantId = cartItem.ProductVariantId,
                    IsDownloadable   = cartItem.IsDownloadable,
                    Product          = products.First(x => x.Id == cartItem.ProductId),
                };
                orderItem.SubscriptionCycle = orderItem.Product.SubscriptionCycle;
                orderItem.CycleCount        = orderItem.Product.CycleCount;
                orderItem.TrialDays         = orderItem.Product.TrialDays;
                order.OrderItems.Add(orderItem);
            }
            var creditAmount = 0m;

            if (cart.UseStoreCredits)
            {
                GetAvailableStoreCredits(out var credits, out creditAmount, ApplicationEngine.BaseCurrency, cart);
                if (credits > 0 && _affiliateSettings.MinimumStoreCreditsToAllowPurchases <= credits)
                {
                    order.UsedStoreCredits  = true;
                    order.StoreCredits      = credits;
                    order.StoreCreditAmount = creditAmount;
                }
            }

            //insert complete order
            _orderAccountant.InsertCompleteOrder(order);

            //process payment
            var paymentMethodData = cart.PaymentMethodData.IsNullEmptyOrWhiteSpace()
                ? null
                : _dataSerializer.DeserializeAs <Dictionary <string, object> >(
                _cryptographyService.Decrypt(cart.PaymentMethodData));

            CustomResponse response = null;

            if (cart.PaymentMethodName != ApplicationConfig.UnavailableMethodName && !ProcessPayment(order, creditAmount, paymentMethodData, out response))
            {
                return(response.With("orderGuid", order.Guid).Result);
            }

            //clear the user's cart
            _cartService.ClearCart(currentUser.Id);

            if (currentUser.IsVisitor())
            {
                //if current user is visitor, change the email to billing address and change it to registered user
                currentUser.Email = billingAddress.Email;
                _userService.Update(currentUser);

                var roleId = _roleService.Get(x => x.SystemName == SystemRoleNames.Registered).First().Id;
                //assign registered role to the user
                _roleService.SetUserRoles(currentUser.Id, new[] { roleId });

                ApplicationEngine.SignIn(currentUser.Email, null, false);
            }

            response = response ?? R.Success;
            return(response.With("orderGuid", order.Guid).Result);
        }
        public CartActionResult ValidateCart(string name)
        {
            CartHelper ch = new CartHelper(name);
            CartActionResult actionResult = new CartActionResult()
            {
                Success = false,
                Message = ""
            };

            if (ch.IsEmpty == false)
            {
                var cart = ch.Cart;

                actionResult.Message = RunWorkflowAndReturnFormattedMessage(cart, OrderGroupWorkflowManager.CartValidateWorkflowName);
                cart.AcceptChanges();
                actionResult.Success = true;
            }
            return actionResult;
        }
Beispiel #31
0
 private void GetAvailableStoreCredits(out decimal availableStoreCredits, out decimal availableStoreCreditAmount, Currency targetCurrency, Cart cart)
 {
     availableStoreCredits      = 0;
     availableStoreCreditAmount = 0;
     //check if store credits can be used
     if (_affiliateSettings.AllowStoreCreditsForPurchases && (cart == null || !CartHelper.IsSubscriptionCart(cart)))
     {
         availableStoreCredits = _storeCreditService.GetBalance(CurrentUser.Id);
         if (availableStoreCredits < _affiliateSettings.MinimumStoreCreditsToAllowPurchases)
         {
             availableStoreCredits = 0;
         }
         availableStoreCreditAmount = _priceAccountant.ConvertCurrency(
             availableStoreCredits * _affiliateSettings.StoreCreditsExchangeRate, targetCurrency);
     }
 }
        /// <summary>
        /// Process the order
        /// </summary>
        protected void wzdCheckOut_FinishButtonClick(object sender, WizardNavigationEventArgs e)
        {
            using (var context = new PetShopDataContext())
            {
                var profile = context.Profile.GetProfile(User.Identity.Name);
                if (profile.ShoppingCart.Count > 0)
                {
                    // display ordered items
                    CartListOrdered.Bind(profile.ShoppingCart);

                    // display total and credit card information
                    ltlTotalComplete.Text      = ltlTotal.Text;
                    ltlCreditCardComplete.Text = ltlCreditCard.Text;

                    #region Create Order

                    var order = new Order();

                    order.UserId              = profile.UniqueID.ToString();
                    order.OrderDate           = DateTime.Now;
                    order.CreditCard          = GetCreditCard();
                    order.Courier             = order.CreditCard.CardType;
                    order.TotalPrice          = CartHelper.GetTotal(profile.ShoppingCart);
                    order.AuthorizationNumber = 0;
                    order.Locale              = "en-us";

                    #region Shipping Information

                    order.ShipAddr1       = billingForm.Address.Address1;
                    order.ShipAddr2       = billingForm.Address.Address2;
                    order.ShipCity        = billingForm.Address.City;
                    order.ShipState       = billingForm.Address.State;
                    order.ShipZip         = billingForm.Address.Zip;
                    order.ShipCountry     = billingForm.Address.Country;
                    order.ShipToFirstName = billingForm.Address.FirstName;
                    order.ShipToLastName  = billingForm.Address.LastName;

                    #endregion

                    #region Billing Information

                    order.BillAddr1       = shippingForm.Address.Address1;
                    order.BillAddr2       = shippingForm.Address.Address2;
                    order.BillCity        = shippingForm.Address.City;
                    order.BillState       = shippingForm.Address.State;
                    order.BillZip         = shippingForm.Address.Zip;
                    order.BillCountry     = shippingForm.Address.Country;
                    order.BillToFirstName = shippingForm.Address.FirstName;
                    order.BillToLastName  = shippingForm.Address.LastName;

                    #endregion
                    context.Order.InsertOnSubmit(order);
                    context.SubmitChanges();

                    #endregion

                    int itemsOnBackOrder = 0;
                    //Decrement and check the Inventory.
                    foreach (Cart cart in profile.ShoppingCart)
                    {
                        var inventory = context.Inventory.GetByKey(cart.ItemId);

                        if (cart.Quantity > inventory.Qty)
                        {
                            itemsOnBackOrder += cart.Quantity - inventory.Qty;
                        }

                        inventory.Qty -= cart.Quantity;
                        context.SubmitChanges();
                    }

                    if (itemsOnBackOrder > 0)
                    {
                        ItemsOnBackOrder.Text = string.Format("<br /><p style=\"color:red;\"><b>Backorder ALERT:</b> {0} items are on backorder.</p>", itemsOnBackOrder);
                    }

                    CartHelper.SaveOrderLineItems(profile.ShoppingCart, order.OrderId);

                    // destroy cart
                    CartHelper.ClearCart(profile.ShoppingCart);
                }
                else
                {
                    lblMsg.Text =
                        "<p><br>Can not process the order. Your cart is empty.</p><p class=SignUpLabel><a class=linkNewUser href=Default.aspx>Continue shopping</a></p>";
                    wzdCheckOut.Visible = false;
                }
            }
        }
Beispiel #33
0
        // Optional lab in Mod. D - create a WishList and inspection in CM + config -alteration
        public void AddToWishList(FashionVariation currentContent)
        {
            CartHelper wishList = new CartHelper(CartHelper.WishListName); // note the arg.

            wishList.AddEntry(currentContent.LoadEntry());
        }
Beispiel #34
0
        // GET: Carts/Add/5
        public IActionResult Add(int id, int quantity = 1, bool isDigital = false, bool goToCart = true)
        {
            if (!UserHelper.IsLoggedIn(this))
            {
                return(UserHelper.RequireLogin(this));
            }

            List <CartItem> cart       = CartHelper.getCartFromSession(this);
            var             qtyInStock = _context.Game.Find(id).GameQty;

            if (cart.Any(c => c.Game.GameId == id))
            {
                // Add quantity by one if the game exists in the cart
                var item = cart.Where(c => c.Game.GameId == id).First();
                item.Quantity = item.Quantity + quantity;
                if (!isDigital && qtyInStock < item.Quantity)
                {
                    HttpContext.Session.SetString("modalTitle", "Error!");
                    HttpContext.Session.SetString("modalMessage", $"There are only {qtyInStock} item(s) in stock.");
                    return(RedirectToAction("Index"));
                }
                if (item.Quantity <= 0)
                {
                    cart.Remove(item);
                }
            }
            else
            {
                if (!isDigital && qtyInStock < quantity)
                {
                    HttpContext.Session.SetString("modalTitle", "Error!");
                    HttpContext.Session.SetString("modalMessage", "Does not have enough of this game in stock.");
                    return(RedirectToAction("Index"));
                }

                // Add the game to the cart
                var item = new CartItem()
                {
                    Game = _context.Game.Find(id), Quantity = quantity, IsDigital = isDigital
                };
                if (quantity > 0)
                {
                    cart.Add(item);
                }
            }

            var str = JsonConvert.SerializeObject(cart);

            HttpContext.Session.SetString(SESSION_CART, str);

            if (goToCart)
            {
                return(RedirectToAction("Index"));
            }
            else
            {
                HttpContext.Session.SetString("modalTitle", "Game Added");
                HttpContext.Session.SetString("modalMessage", "The game has been added to your cart.");
                return(RedirectToAction("Details", "Games", new { id = id }));
            }
        }
        /// <summary>
        /// Binds the billing address.
        /// </summary>
        private void BindBillingAddress()
        {
            CustomerProfile ci = ProfileContext.Current.Profile;

            if (ci == null || ci.Account == null || ci.Account.Addresses == null || ci.Account.Addresses.Count == 0)
            {
                tblAddresses.Visible = false;
                OrderAddress address = CartHelper.FindAddressByName(CartHelper.OrderForm.BillingAddressId);
                if (address != null)
                {
                    AddressNewModule1.AddressInfo = address;
                }
                else
                {
                    if (CartHelper.Cart.OrderAddresses.Count > 0)
                    {
                        AddressNewModule1.AddressInfo = CartHelper.Cart.OrderAddresses[0];
                    }
                }

                rbBillingNewAddress.Checked = true;
                return;
            }

            //bool bSearch = CurrentOrderInfo.BillingAddress!=null;
            //bool bFound = false;
            AddressesList.Items.Clear();

            if (ci.Account.Addresses.Count > 0)
            {
                AddressesList.DataSource = ci.Account.Addresses;
                AddressesList.DataBind();

                AddressViewModule.AddressInfo = StoreHelper.ConvertToOrderAddress(ci.Account.Addresses[0]);
                AddressViewModule.DataBind();

                CommonHelper.SelectListItem(AddressesList, Profile.PreferredBillingAddress);

                if (!rbBillingNewAddress.Checked)
                {
                    rbBillingAddress.Checked = true;
                }
            }
            else
            {
            }

            /*
             * foreach (AddressInfo info in ci.Addresses)
             * {
             *  string strAddress = MakeAddressString(info);
             *  AddressesList.Items.Add(new ListItem(strAddress, info.AddressId));
             *  if(bSearch && (info.AddressId == CurrentOrderInfo.BillingAddress.AddressId))
             *      bFound = true;
             * }
             * */

            /*
             * if (!bFound)
             * {
             *  if (CurrentOrderInfo.BillingAddress != null)
             *  {
             *      AddressNewModule1.AddressInfo = CurrentOrderInfo.BillingAddress;
             *  }
             *  else
             *  {
             *      // bind shipping address
             *      if (CurrentOrderInfo.Shipments != null && CurrentOrderInfo.Shipments.Length > 0 && CurrentOrderInfo.Shipments[0].Details.DeliveryAddress != null)
             *      {
             *          // need to set AddressId to 0 to avoid replacing corresponding address' fields if new address' fields will be changed
             *          AddressInfo ai = CurrentOrderInfo.Shipments[0].Details.DeliveryAddress;
             *          ai.AddressId = "0";
             *          AddressNewModule1.AddressInfo = ai;
             *      }
             *  }
             *
             *  rbBillingNewAddress.Checked = true;
             *
             *  // Bind view address
             *  if (ci != null && ci.Addresses != null && ci.Addresses.Length != 0)
             *  {
             *      AddressViewModule.AddressInfo = ci.Addresses[0];
             *      AddressViewModule.DataBind();
             *  }
             * }
             * else
             * {
             *  if (BillingAddress != null && !String.IsNullOrEmpty(BillingAddress.AddressId))
             *  {
             *      CommonHelper.SelectListItem(AddressesList, BillingAddress.AddressId);
             *      AddressViewModule.AddressInfo = BillingAddress;
             *      AddressViewModule.DataBind();
             *  }
             *  else
             *  {
             *      CommonHelper.SelectListItem(AddressesList, AddressesList.Items[0].Value);
             *      AddressViewModule.AddressInfo = ci.Addresses[0];
             *      AddressViewModule.DataBind();
             *  }
             *  rbBillingAddress.Checked = true;
             * }
             * */
        }
    /// <summary>
    /// Handles the Command event of the WishListLink control.
    /// </summary>
    /// <param name="sender">The source of the event.</param>
    /// <param name="e">The <see cref="System.Web.UI.WebControls.CommandEventArgs"/> instance containing the event data.</param>
    public void WishlistLink_Command(object sender, CommandEventArgs e)
    {
        Entry variation = null;
        Entry product   = null;
        int   productId;

        if (String.Compare(e.CommandName, "AddToWishList") == 0)
        {
            string arg = e.CommandArgument as string;
            if (String.IsNullOrEmpty(arg))
            {
                Response.Redirect(Request.RawUrl);
                return;
            }

            CartHelper helper = new CartHelper(CartHelper.WishListName);

            bool alreadyExists = false;
            productId = Int32.Parse(arg);

            // Check if item exists
            foreach (LineItem item in helper.LineItems)
            {
                if (item.CatalogEntryId.Equals(productId))
                {
                    alreadyExists = true;
                    Response.Redirect(Request.RawUrl);
                    return;
                }
            }

            if (_ProductsToCompare != null && _ProductsToCompare.Length > 0)
            {
                foreach (Entry productTemp in _ProductsToCompare)
                {
                    if (productTemp.CatalogEntryId == productId)
                    {
                        product = productTemp;

                        if (product.EntryType.Equals("Variation") || product.EntryType.Equals("Package"))
                        {
                            variation = product;
                        }
                        else if (product.Entries.Entry != null && product.Entries.Entry.Length > 0)
                        {
                            variation = product.Entries.Entry[0];
                            break;
                        }
                    }
                }

                // if variation is found, add it to cart and redirect to product view page
                if (variation != null)
                {
                    if (!alreadyExists)
                    {
                        helper.AddEntry(variation);
                    }

                    Response.Redirect(Request.RawUrl);
                }
            }
            else
            {
                Response.Redirect(Request.RawUrl);
                return;
            }
        }
    }
Beispiel #37
0
 public CartService(CartHelper cartHelper)
 {
     _cartHelper = cartHelper;
 }
Beispiel #38
0
 public void UpdateCart(int productID, int quantity)
 {
     CartHelper.UpdateCart(productID, quantity);
 }
        /// <summary>
        /// Gets all shipping methods.
        /// </summary>
        /// <param name="cart">The cart.</param>
        /// <param name="methodIds">The method ids.</param>
        /// <returns>shipping method model</returns>
        public static ShippingMethodModel[] GetShippingMethods(this CartHelper cart, List <string> methodIds = null)
        {
            var list = new List <ShippingMethodModel>();

            methodIds = methodIds ?? new List <string>();
            IEnumerable <ShippingMethod> shippingMethods;

            if (methodIds.Any())
            {
                shippingMethods = cart.ShippingClient.GetAllShippingMethods().Where(so => methodIds.Contains(so.ShippingMethodId));
            }
            else
            {
                var options = cart.ShippingClient.GetAllShippingOptions();
                shippingMethods = options.SelectMany(o => o.ShippingMethods.Where(m => m.IsActive));
            }

            var address = cart.FindAddressByName("Shipping") ?? cart.FindAddressByName("Billing");

            foreach (var method in shippingMethods.Where(m => m.IsActive &&
                                                         (string.IsNullOrEmpty(m.Currency) || m.Currency.Equals(UserHelper.CustomerSession.Currency, StringComparison.OrdinalIgnoreCase))))
            {
                var model = new ShippingMethodModel(method, cart.Cart);

                //Filter by shipping method jurisdiction
                var jurisdictionRelations = method.ShippingMethodJurisdictionGroups.SelectMany(g => g.JurisdictionGroup.JurisdictionRelations).ToArray();

                if (jurisdictionRelations.Any())
                {
                    var jurisdictionFound = false;

                    if (address != null)
                    {
                        jurisdictionFound = jurisdictionRelations.Any(j => j.Jurisdiction.CheckAllFieldsMatch(
                                                                          address.CountryCode,
                                                                          address.StateProvince,
                                                                          address.PostalCode,
                                                                          address.RegionName, "", "",
                                                                          address.City));
                    }

                    if (!jurisdictionFound)
                    {
                        continue;
                    }
                }

                if (!string.IsNullOrWhiteSpace(method.RestrictJurisdictionGroups))
                {
                    var jurisdictionFound = false;
                    if (address != null)
                    {
                        var ids           = method.RestrictJurisdictionGroups.Split(new[] { ';', ',' }, StringSplitOptions.RemoveEmptyEntries);
                        var jurisdictions = cart.OrderRepository.JurisdictionGroups.Where(x => ids.Contains(x.JurisdictionGroupId))
                                            .SelectMany(x => x.JurisdictionRelations).Select(x => x.Jurisdiction).ToArray();

                        jurisdictionFound = jurisdictions.Any(j => j.CheckAllFieldsMatch(address.CountryCode, address.StateProvince,
                                                                                         address.PostalCode, address.RegionName, "", "", address.City));
                    }

                    //If found any match in restrcitions cannot use this shipping method
                    if (jurisdictionFound)
                    {
                        continue;
                    }
                }

                methodIds.Add(method.ShippingMethodId);
                list.Add(model);
            }

            var rates = GetAllShippingRates(cart, methodIds.ToArray(), cart.LineItems);

            if (rates != null)
            {
                foreach (var sm in list)
                {
                    sm.Rate = (from r in rates where r.Id == sm.Id select r).SingleOrDefault();
                }
            }

            return(list.ToArray());
        }
Beispiel #40
0
 public void AddCart(int productID, int quantity)
 {
     CartHelper.AddCart(productID, quantity);
 }
 internal Money CalculateShippingCostSubTotal(Shipment shipment, CartHelper cartHelper)
 {
     return CalculateShippingCostSubTotal(new List<Shipment>(1) { shipment }, cartHelper);
 }
Beispiel #42
0
 public ActionResult Break()
 {
     CartHelper.SetBreak();
     return(View());
 }
Beispiel #43
0
 public PromotionCD()
 {
     cartHelper = new CartHelper();
 }
Beispiel #44
0
 public CartService()
 {
     _cartHelper = new CartHelper(Cart.DefaultName, SecurityContext.Current.CurrentUserId);
 }
        public CartActionResult AddDiscountCode(string name, string code)
        {
            CartHelper ch = new CartHelper(name);
            string messages = string.Empty;
            bool success = true;

            var localizationService = ServiceLocator.Current.GetInstance<LocalizationService>();

            var discounts = GetAllDiscounts(ch.Cart);
            if (discounts.Exists(x => x.DiscountCode == code))
            {
                if (!string.IsNullOrEmpty(messages))
                {
                    messages += "  ";
                }
                messages += localizationService.GetString("/common/cart/coupon_codes/error_already_used");
            }
            else
            {

                MarketingContext.Current.AddCouponToMarketingContext(code);

                if (!ch.IsEmpty)
                {
                    messages += ValidateCart(name).Message;

                    // check if coupon was applied
                    discounts = GetAllDiscounts(ch.Cart);

                    if (discounts.Count == 0 || !discounts.Exists(x => x.DiscountCode == code))
                    {
                        success = false;
                        if (!string.IsNullOrEmpty(messages))
                        {
                            messages += "  ";
                        }

                        messages += localizationService.GetString("/common/cart/coupon_codes/error_invalid");
                    }

                }
            }
            return new CartActionResult() { Success = success, Message = messages };
        }
 /// <summary>
 /// Sums the shipping COSTS of a Cart without the discounts applied.
 /// </summary>
 /// <param name="shipments"></param>
 /// <returns></returns>
 internal Money CalculateShippingCostSubTotal(ShipmentCollection shipments, CartHelper cartHelper)
 {
     return CalculateShippingCostSubTotal(shipments.Cast<Shipment>(), cartHelper);
 }
 public CartActionResult EmptyCart(string name)
 {
     CartHelper ch = new CartHelper(name);
     ch.Delete();
     ch.Cart.AcceptChanges();
     return new CartActionResult() { Success = true };
 }
 public List<DiscountItem> GetAllDiscountCodes(string name)
 {
     var cart = new CartHelper(name).Cart;
     var discounts = GetAllDiscounts(cart);
     return discounts.Where(x => !string.IsNullOrEmpty(x.DiscountCode)).Select(x => new DiscountItem(x)).ToList();
 }
Beispiel #49
0
        public JsonResult UpdateCartItem(string skuId, int count)
        {
            //TODO:FG 购物车改造 购物车数量变更
            long userId     = CurrentUser != null ? CurrentUser.Id : 0;
            var  cartHelper = new CartHelper();
            var  skucart    = cartHelper.GetCart(userId).Items.FirstOrDefault(d => d.SkuId == skuId);
            bool isadd      = true;

            if (skucart != null)
            {
                if (skucart.Quantity > count)
                {
                    isadd = false;
                }
            }

            Entities.SKUInfo skuinfo = OrderApplication.GetSkuByID(skuId);
            if (skuinfo.Stock < count && isadd)
            {
                return(Json(new { success = false, msg = "库存不足", stock = skuinfo.Stock }));
            }

            var product = ProductManagerApplication.GetProduct(skuinfo.ProductId);

            if (product != null)
            {
                if (product.MaxBuyCount > 0 && count > product.MaxBuyCount && !product.IsOpenLadder)
                {
                    return(Json(new { success = false, msg = string.Format("每个ID限购{0}件", product.MaxBuyCount), stock = product.MaxBuyCount }));
                }
            }

            cartHelper.UpdateCartItem(skuId, count, userId);

            #region 购物车修改数量阶梯价变动--张宇枫
            //获取产品详情
            var price = 0m;
            if (product.IsOpenLadder)
            {
                var shop = ShopApplication.GetShop(product.ShopId);

                var groupCartByProduct = cartHelper.GetCart(userId).Items.Where(item => item.ShopBranchId == 0).Select(c =>
                {
                    var cItem   = new Mall.Entities.ShoppingCartItem();
                    var skuInfo = _iProductService.GetSku(c.SkuId);
                    if (skuInfo != null)
                    {
                        cItem = c;
                    }
                    return(cItem);
                }).GroupBy(i => i.ProductId).ToList();
                var quantity = groupCartByProduct.Where(i => i.Key == product.Id).ToList().Sum(cartitem => cartitem.Sum(i => i.Quantity));

                decimal discount = 1M;
                if (CurrentUser != null)
                {
                    discount = CurrentUser.MemberDiscount;
                }
                price = ProductManagerApplication.GetProductLadderPrice(product.Id, quantity);
                if (shop.IsSelf)
                {
                    price = price * discount;
                }
            }

            #endregion

            return(SuccessResult <dynamic>(data: new { saleprice = price.ToString("F2"), productid = product.Id, isOpenLadder = product.IsOpenLadder }));
        }