Example #1
0
        protected virtual ILineItem CreateLineItem(
            IPurchaseOrder purchaseOrder,
            IShipment shipment,
            SaleViewModel kachingSale,
            SaleLineItemViewModel kachingLineItem)
        {
            ILineItem lineItem = _orderGroupFactory.CreateLineItem(
                kachingLineItem.VariantId.DesanitizeKey() ?? kachingLineItem.Id.DesanitizeKey(),
                purchaseOrder);

            decimal quantity = kachingLineItem.UnitCount ?? kachingLineItem.Quantity;

            lineItem.Quantity    = quantity;
            lineItem.PlacedPrice = kachingLineItem.RetailPrice / quantity;

            // Get the specific discount amount of this line item (discount that were applied directly to the line item).
            decimal lineItemDiscount =
                kachingLineItem.Discounts?
                .Where(d => !(d.Discount?.Application.Basket ?? false))
                .Sum(d => d.Amount) ?? 0;

            // Get the amount of the order level discount that this line item contributes
            // (the order level discount are spread out on all line items).
            decimal orderLevelDiscount =
                kachingLineItem.Discounts?
                .Where(d => d.Discount?.Application.Basket ?? false)
                .Sum(d => d.Amount) ?? 0;

            lineItem.SetEntryDiscountValue(lineItemDiscount);
            lineItem.SetOrderDiscountValue(orderLevelDiscount);

            return(lineItem);
        }
        public ActionResult AddToCart(ShirtVariation currentContent, decimal Quantity, string Monogram)
        {
            // ToDo: (lab D1) add a LineItem to the Cart
            var cart     = _orderRepository.LoadOrCreateCart <ICart>(PrincipalInfo.CurrentPrincipal.GetContactId(), "Default");
            var cartItem = cart.GetAllLineItems().SingleOrDefault(item => item.Code == currentContent.Code);

            if (cartItem == null)
            {
                cartItem          = _orderGroupFactory.CreateLineItem(currentContent.Code, cart);
                cartItem.Quantity = Quantity;
                cart.AddLineItem(cartItem);
            }
            else
            {
                cartItem.Quantity += Quantity;
            }

            var validLineItem = _lineItemValidator.Validate(cartItem, cart.MarketId, (item, issue) => { });

            if (validLineItem)
            {
                cartItem.Properties["Monogram"] = Monogram;
                _orderRepository.Save(cart);
            }

            // if we want to redirect
            ContentReference cartRef  = _contentLoader.Get <StartPage>(ContentReference.StartPage).Settings.cartPage;
            CartPage         cartPage = _contentLoader.Get <CartPage>(cartRef);
            var    name         = cartPage.Name;
            var    lang         = ContentLanguage.PreferredCulture;
            string passingValue = cart.Name;

            // go to the cart page, if needed
            return(RedirectToAction("Index", lang + "/" + name, new { passedAlong = passingValue }));
        }
        public bool AddToCart(ICart cart, string code, int quantity, out string warningMessage)
        {
            warningMessage = string.Empty;

            var lineItem = cart.GetAllLineItems().FirstOrDefault(x => x.Code == code);

            if (lineItem == null)
            {
                lineItem          = _orderGroupFactory.CreateLineItem(code, cart);
                lineItem.Quantity = quantity;
                cart.AddLineItem(lineItem, _orderGroupFactory);
            }
            else
            {
                var shipment = cart.GetFirstShipment();
                cart.UpdateLineItemQuantity(shipment, lineItem, lineItem.Quantity + quantity);
            }

            var validationIssues = ValidateCart(cart);

            foreach (var validationIssue in validationIssues)
            {
                warningMessage += String.Format("Line Item with code {0} ", lineItem.Code);
                warningMessage  = validationIssue.Value.Aggregate(warningMessage, (current, issue) => current + String.Format("{0}, ", issue));
                warningMessage  = warningMessage.Substring(0, warningMessage.Length - 2);
            }

            if (validationIssues.HasItemBeenRemoved(lineItem))
            {
                return(false);
            }

            return(GetFirstLineItem(cart, code) != null);
        }
        public void RecreateLineItemsBasedOnShipments(ICart cart, IEnumerable <CartItemViewModel> cartItems, IEnumerable <AddressModel> addresses)
        {
            var form  = cart.GetFirstForm();
            var items = cartItems
                        .GroupBy(x => new { x.AddressId, x.Code, x.IsGift })
                        .Select(x => new
            {
                Code      = x.Key.Code,
                AddressId = x.Key.AddressId,
                Quantity  = x.Count(),
                IsGift    = x.Key.IsGift
            });

            foreach (var shipment in form.Shipments)
            {
                shipment.LineItems.Clear();
            }

            form.Shipments.Clear();

            foreach (var address in addresses)
            {
                IShipment shipment = _orderGroupFactory.CreateShipment(cart);
                form.Shipments.Add(shipment);
                shipment.ShippingAddress = _addressBookService.ConvertToAddress(cart, address);

                foreach (var item in items.Where(x => x.AddressId == address.AddressId))
                {
                    var lineItem = _orderGroupFactory.CreateLineItem(item.Code, cart);
                    lineItem.IsGift   = item.IsGift;
                    lineItem.Quantity = item.Quantity;
                    shipment.LineItems.Add(lineItem);
                }
            }

            ValidateCart(cart);
        }
Example #5
0
        public ILineItem AddItemToCart(string code, int quantity)
        {
            var lineItem = LineItemByCode(code);

            if (lineItem == null)
            {
                lineItem          = _orderGroupFactory.CreateLineItem(code, ShoppingCart);
                lineItem.Quantity = quantity;
                ShoppingCart.AddLineItem(lineItem);
            }
            else
            {
                var shipment = ShoppingCart.GetFirstShipment();
                ShoppingCart.UpdateLineItemQuantity(shipment, lineItem, lineItem.Quantity + quantity);
            }

            return(lineItem);
        }
        public PurchaseOrderModel QuickBuyOrder(QuickBuyModel model, Guid customerId)
        {
            var cart = _orderRepository.LoadOrCreateCart <Cart>(customerId, Constants.Order.Cartname.Quickbuy);
            var item = _orderGroupFactory.CreateLineItem(model.Sku, cart);

            item.Quantity = 1;


            cart.GetFirstShipment().LineItems.Add(item);
            cart.GetFirstShipment().ShippingAddress = CreateAddress(model, cart, "Shipping");

            if (!string.IsNullOrEmpty(model.CouponCode))
            {
                cart.GetFirstForm().CouponCodes.Add(model.CouponCode);
            }

            cart.ValidateOrRemoveLineItems(ProcessValidationIssue);
            cart.UpdatePlacedPriceOrRemoveLineItems(ProcessValidationIssue);
            cart.UpdateInventoryOrRemoveLineItems(ProcessValidationIssue);
            _promotionEngine.Run(cart);


            cart.GetFirstForm().Payments.Add(CreateQuickBuyPayment(model, cart));
            cart.GetFirstForm().Payments.FirstOrDefault().BillingAddress = CreateAddress(model, cart, "Billing");

            cart.ProcessPayments();

            cart.OrderNumberMethod = cart1 => GetInvoiceNumber();

            var orderRef = _orderRepository.SaveAsPurchaseOrder(cart);

            var order = _orderRepository.Load <PurchaseOrder>(orderRef.OrderGroupId);

            order[Constants.Metadata.PurchaseOrder.Frequency]      = model.Frequency.ToString();
            order[Constants.Metadata.PurchaseOrder.LatestDelivery] = DateTime.Now.AddDays(5);

            OrderStatusManager.CompleteOrderShipment(order.GetFirstShipment() as Shipment);

            _orderRepository.Save(order);

            return(MapToModel(order));
        }
Example #7
0
        public ActionResult UpdateCart(int PurchaseQuantity, string itemCode)
        {
            var itemRef = _referenceConverter.GetContentLink(itemCode);
            var itemVar = _contentLoader.Get <DefaultVariation>(itemRef);

            var cart     = _orderRepository.LoadOrCreateCart <ICart>(CustomerContext.Current.CurrentContactId, "Default");
            var lineItem = cart.GetAllLineItems().FirstOrDefault(x => x.Code == itemCode);

            if (lineItem == null)
            {
                lineItem             = _orderGroupFactory.CreateLineItem(itemCode, cart);
                lineItem.Quantity    = PurchaseQuantity;
                lineItem.PlacedPrice = itemVar.GetDefaultPrice().UnitPrice;
                if (itemVar.RequireSpecialShipping)
                {
                    IShipment specialShip = _orderGroupFactory.CreateShipment(cart);
                    specialShip.ShippingMethodId = GetShipMethodByParam(itemCode);
                    specialShip.ShippingAddress  = GetOrderAddress(cart);
                    cart.AddShipment(specialShip);
                    cart.AddLineItem(specialShip, lineItem);
                }
                else
                {
                    var ship = cart.GetFirstShipment();
                    ship.ShippingAddress = GetOrderAddress(cart);

                    cart.AddLineItem(lineItem);
                }
            }
            else
            {
                var shipment = cart.GetFirstForm().Shipments.
                               Where(s => s.LineItems.Contains(lineItem) == true).FirstOrDefault();

                cart.UpdateLineItemQuantity(shipment, lineItem, PurchaseQuantity);
            }

            _orderRepository.Save(cart);

            return(RedirectToAction("Index"));
        }
Example #8
0
        private void GetTaxInfo(DemoMarketsViewModel viewModel)
        {
            ICart cart = _orderRepository.LoadOrCreateCart <ICart>(CustomerContext.Current.CurrentContactId, "BogusCart");

            IOrderAddress bogusAddress = _orderGroupFactory.CreateOrderAddress(cart);

            bogusAddress.CountryCode = viewModel.SelectedMarket.Countries.FirstOrDefault();
            bogusAddress.City        = "Stockholm";

            ILineItem lineItem = _orderGroupFactory.CreateLineItem(viewModel.Shirt.Code, cart);

            lineItem.Quantity      = 1;
            lineItem.PlacedPrice   = viewModel.Shirt.GetDefaultPrice().UnitPrice;
            lineItem.TaxCategoryId = viewModel.Shirt.TaxCategoryId;
            cart.AddLineItem(lineItem);

            viewModel.TaxAmount = _taxCalculator.GetSalesTax(lineItem, viewModel.SelectedMarket,
                                                             bogusAddress, new Money(lineItem.PlacedPrice, viewModel.SelectedMarket.DefaultCurrency));

            viewModel.TaxAmountOldSchool = GetTaxOldSchool(viewModel, bogusAddress);
        }
Example #9
0
        private ILineItem GetOrAdjustLineItem(ICart cart, string code, decimal quantity, string monogram)
        {
            var item = cart.GetAllLineItems()
                       .FirstOrDefault(x => x.Code.Equals(code, StringComparison.OrdinalIgnoreCase));

            if (item != null)
            {
                item.Quantity += quantity;
            }
            else
            {
                item          = _orderGroupFactory.CreateLineItem(code, cart);
                item.Quantity = quantity;

                if (_lineItemValidator.Validate(item, cart.Market, (i, issue) => { }))
                {
                    cart.AddLineItem(item);
                }
            }

            item.Properties["Monogram"] = monogram;
            return(item);
        }
        public ActionResult Index(ShirtVariation currentContent)
        {
            IsOnLine = CheckIfOnLine.IsInternetAvailable; // Need to know... for Find
            CheckWarehouses(currentContent);              // WH-info on the Page

            var startPage = _contentLoader.Get <StartPage>(ContentReference.StartPage);
            var cartUrl   = _urlResolver.GetUrl(startPage.Settings.cartPage, currentContent.Language.Name);
            var wUrl      = _urlResolver.GetUrl(startPage.Settings.cartPage, currentContent.Language.Name);

            PricingService pSrvs = new PricingService(
                _priceService, _currentMarket, _priceDetailService);

            // used elsewere
            //currentContent.GetCustomerPrices() // works with the R/O-pricingLoader, would miss the custom SaleTypes
            //currentContent.GetPrices() // this one also uses the R/O-Loader ... unusable

            #region Newpromotions

            // New promotions
            decimal savedMoney        = 0;
            string  rewardDescription = String.Empty;
            //IEnumerable<RewardDescription> rewards;

            // get prices incl. "BasePrice"
            //IPriceValue salePrice = BestPricingCalculatorEver.GetSalePrice(currentContent.ContentLink);//
            IPriceValue salePrice = _myPriceCalculator.GetSalePrice(currentContent, 1);
            // the below does the second "Evaluate"
            var descr = _promotionEngine.Evaluate(currentContent.ContentLink).ToList();
            if (descr.Count == 0) // No promos
            {
                var d = new RewardDescription(
                    FulfillmentStatus.NotFulfilled, null, null, 0, 0, RewardType.None, "No promo");
                descr.Add(d);
                rewardDescription = descr.First().Description; // ...just to show
            }
            else
            {
                foreach (var item in descr)
                {
                    rewardDescription += item.Description;
                }
            }

            // previous way
            if (descr.Count() >= 1)
            {
                savedMoney = descr.First().Percentage *salePrice.UnitPrice.Amount / 100;
                //rewardDescription = descr.First().Description;
                Session["SavedMoney"] = savedMoney;
            }
            else
            {
                savedMoney = 0;
                //rewardDescription = "No discount";
            }

            // ...this goes to PriceCalc-discount
            var promoPrice = salePrice.UnitPrice.Amount - savedMoney;

            #endregion

            #region just checking on promos
            //List<RewardDescription> rewards = new List<RewardDescription>();
            //rewards = _promotionEngine.Evaluate(currentContent.ContentLink).ToList();
            //IEnumerable<DiscountedEntry> entries = _promotionEngine.GetDiscountPrices(currentContent.ContentLink, _currentMarket.GetCurrentMarket());
            #endregion

            #region FindStuff


            // new Find-Stuff - need to check this out...
            // FindQueries Qs = new FindQueries();
            // Qs.NewExtensionMethods(currentContent);
            // Qs.SDKExamples(currentContent.ContentLink);
            #endregion

            #region Checking some for routing and http-ctx

            /*
             * var str = currentContent.GetOriginalType().Name; // not for redirect
             * var x = ServiceLocator.Current.GetInstance<TemplateResolver>();
             *
             * RequestContext requestContext = new RequestContext(base.HttpContext, base.RouteData);
             * var parentStack = requestContext.HttpContext.Items[ContentContext.ContentContextKey] as
             * Stack<ContentContext.ContentPropertiesStack>;
             *
             * string controller = requestContext.GetController();
             * var t = x.Resolve(requestContext.HttpContext, new CartPage(), TemplateTypeCategories.MvcController); // could use .Name
             */
            #endregion

            #region LookingAround (incl. new and old Promo-engine)

            //LoadingExamples(currentContent);
            //CheckPrices(currentContent);

            // Have to fake a cart... but it looks good
            //string rewardDescription = String.Empty;

            //decimal savedMoney = CheckBetaPromotions(currentContent, out rewardDescription);

            //var theProxy = currentContent.GetType();
            //var yourClass = currentContent.GetOriginalType();

            //StoreHelper.GetDiscountPrice(currentContent.LoadEntry());
            //StoreHelper.GetSalePrice(currentContent.LoadEntry()

            #endregion

            #region Relations, parent - child, etc.

            CheckOnRelations(currentContent);

            #endregion

            #region RoCe - check this

            // quick-fix - nothing back
            ICart     dummyCart = _orderRepository.LoadOrCreateCart <ICart>(new Guid(), "DummyCart");
            ILineItem lineItem  = _orderGroupFactory.CreateLineItem(currentContent.Code, dummyCart);
            var       c2        = _lineItemCalculator.GetExtendedPrice(lineItem, _currentMarket.GetCurrentMarket().DefaultCurrency);
            var       check     = _lineItemCalculator.GetDiscountedPrice(
                lineItem, _currentMarket.GetCurrentMarket().DefaultCurrency).Amount;

            // Should check the BasePrice here (new way)
            // BestPricingCalc is the old way
            // should override the LI-calculator

            #endregion

            //_currentMarket.GetCurrentMarket().DefaultCurrency.Format(cu)
            //Currency.SetFormat(_currentMarket.GetCurrentMarket().DefaultCurrency.Format.CurrencySymbol);
            string thePriceString = string.Empty;

            if (currentContent.GetDefaultPrice().UnitPrice.Amount == 0)
            {
                thePriceString = "no default price";
            }
            else
            {
                thePriceString = currentContent.GetDefaultPrice().UnitPrice.ToString();
            }

            var model = new ShirtVariationViewModel
            {
                MainBody = currentContent.MainBody,

                // Pricing
                priceString = thePriceString,
                //theRightPriceToPlace = GetThePriceToPlace(currentContent), // tiered pricing...old, not in use
                CustomerPricingPrice = GetCustomerPricingPrice(currentContent),
                //discountPrice = CustomStoreHelper.GetDiscountPrice(currentContent.LoadEntry(CatalogEntryResponseGroup.ResponseGroup.Nodes)),
                discountPriceNew = _lineItemCalculator.GetDiscountedPrice(lineItem, _currentMarket.GetCurrentMarket().DefaultCurrency).Amount,

                image            = GetDefaultAsset((IAssetContainer)currentContent),
                CanBeMonogrammed = currentContent.CanBeMonogrammed,
                ProductArea      = currentContent.ProductArea,
                CartUrl          = cartUrl, // new stuff - not yet in course
                WishlistUrl      = wUrl,    // new stuff - not yet in course

                // Added for Adv. below
                //labPrice = BestPricingCalculatorEver.GetDiscountPrice(currentContent, 1, promoPrice), // , "Fashion", "Shirts"
                labPrice          = _myPriceCalculator.CheckDiscountPrice(currentContent, 1, promoPrice),
                overridePrices    = pSrvs.GetPrices(currentContent.Code),
                PromoString       = rewardDescription, // in #region LookingAround
                betaDiscountPrice = savedMoney,        // in #region LookingAround

                // warehouse info (Lists get filled up in the entrance of "Index-method")
                generalWarehouseInfo  = this.generalWarehouseInfo,
                specificWarehouseInfo = this.specificWarehouseInfo, // Fills up "Specific-List"
                localMarketWarehouses = GetLocalMarketWarehouses(),
                entryCode             = currentContent.Code,

                //Markets
                currentMarket = GetCurrentMarket(),
                marketOwner   = GetMarketOwner(),

                // Associations
                //Associations = GetAssociatedEntries(currentContent), // IEnumerable<ContentReference> // Remove when Aggregation is done
                //AssociationMetaData = GetAssociationMetaData(currentContent), // string // Remove when Aggregation is done
                AssocAggregated = GetAggregatedAssocciations(currentContent), // Dictionary<string, ContentReference> // The final thing

                // Searchendizing ... need to be OnLine to use
                BoughtThisBoughtThat = GetOtherEntries(currentContent.Code),

                // Taxes
                Tax          = GetTaxOldSchool(currentContent),
                TaxString    = GetTaxStrings(currentContent),
                TaxNewSchool = GetTaxNewSchool(currentContent),

                // info about the variation
                VariationAvailability = currentContent.IsAvailableInCurrentMarket(),
                VariationInfo         = "Info: " + CollectInfo()
            };

            return(View(model));
        }
Example #11
0
        public ActionResult AddToCart(ShirtVariation currentContent, decimal Quantity, string Monogram)
        {
            // LoadOrCreateCart - in EPiServer.Commerce.Order.IOrderRepositoryExtensions
            var cart = _orderRepository.LoadOrCreateCart <ICart>(
                PrincipalInfo.CurrentPrincipal.GetContactId(), "Default");

            //cart.  // ...have a look at all the extension methods

            string code = currentContent.Code;

            // Manually checking - could have a look at the InventoryRecord - properties
            // ...could be part of an optional lab in Fund
            IWarehouse      wh  = _whRep.GetDefaultWarehouse();
            InventoryRecord rec = _invService.Get(code, wh.Code);


            // ... can get: Sequence contains more than one matching element...
            // ...when we have two different lineitems for the same SKU
            // Use when the cart is empty/one LI for SKU with Qty --> no crash
            var lineItem = cart.GetAllLineItems().SingleOrDefault(x => x.Code == code);

            //currentContent.IsAvailableInCurrentMarket();

            // Below works for the same SKU on different LineItems... Changing back for the Fund
            //var lineItem = cart.GetAllLineItems().First(x => x.Code == code); // Changed to this for multiple LI with the same code - crash if no cart

            // ECF 12 changes - market.MarketId
            IMarket market = _currentMarket.GetCurrentMarket();

            if (lineItem == null)
            {
                lineItem          = _orderFactory.CreateLineItem(code, cart);
                lineItem.Quantity = Quantity; // gets this as an argument for the method

                // ECF 12 changes - market.MarketId
                _placedPriceProcessor.UpdatePlacedPrice
                    (lineItem, GetContact(), market.MarketId, cart.Currency,
                    (lineItemToValidate, validation) => { }); // does not take care of the messages here

                cart.AddLineItem(lineItem);
            }
            else
            {
                // Qty increases ... no new LineItem ...
                // original for Fund.
                lineItem.Quantity += Quantity; // need an update
                // maybe do price validation here too
            }

            // Validations
            var validationIssues = new Dictionary <ILineItem, ValidationIssue>();

            // ECF 12 changes - market.MarketId
            // RoCe - This needs to be updated to get the message out + Lab-steps added...
            var validLineItem = _lineItemValidator.Validate(lineItem, market.MarketId, (item, issue) => { });

            cart.ValidateOrRemoveLineItems((item, issue) => validationIssues.Add(item, issue), _lineItemValidator);
            //var someIssue = validationIssues.First().Value;

            if (validLineItem) // We're happy
            {
                // If MDP - error when adding, may need to reset IIS as the model has changed
                //    when adding/removing the MetaField in CM
                lineItem.Properties["Monogram"] = Monogram;

                _orderRepository.Save(cart);
            }

            ContentReference cartRef     = _contentLoader.Get <StartPage>(ContentReference.StartPage).Settings.CartPage;
            ContentReference cartPageRef = EPiServer.Web.SiteDefinition.Current.StartPage;
            CartPage         cartPage    = _contentLoader.Get <CartPage>(cartRef);
            var name = cartPage.Name;
            var lang = ContentLanguage.PreferredCulture;

            string passingValue = cart.Name; // if something is needed

            //return RedirectToAction("Index", new { node = theRef, passedAlong = passingValue }); // Doesn't work
            return(RedirectToAction("Index", lang + "/" + name, new { passedAlong = passingValue })); // Works
        }