ICoupon GetCoupon(Commerce.Data.SqlRepository.Coupon coupon) {

            ICoupon result = null;
            switch (coupon.CouponTypeID) {

                //PercentOffOrder
                case 1:
                    result = new PercentOffOrderCoupon(coupon.PercentOff);
                    break;
                //PercentOffItem
                case 2:
                    result = new PercentOffItemCoupon(coupon.PercentOff, 
                        GetSplitArray(coupon.AppliesToProductCodes));
                    break;
                //AmountOffOrder
                case 3:
                    result = new AmountOffOrderCoupon(coupon.AmountOff);
                    break;
                //AmountOffItem
                case 4:
                    result = new AmountOffItemCoupon(coupon.AmountOff, 
                        GetSplitArray(coupon.AppliesToProductCodes));
                    break;

            }

            return result;
        }
        /// <summary>
        /// Processes the specified arguments.
        /// </summary>
        /// <param name="args">The arguments.</param>
        public override void Process(Commerce.Pipelines.ServicePipelineArgs args)
        {
            Assert.ArgumentNotNull(args, "args");
            Assert.ArgumentCondition(args.Request is GetAvailableRegionsRequest, "args.Request", "args.Request is GetAvailableRegionsRequest");
            Assert.ArgumentCondition(args.Result is GetAvailableRegionsResult, "args.Result", "args.Result is GetAvailableRegionsResult");

            var request = (GetAvailableRegionsRequest)args.Request;
            var result = (GetAvailableRegionsResult)args.Result;

            var regions = new Dictionary<string, string>();

            //// The country guid is passed into the coutry code.
            //// Item countryItem = Sitecore.Context.Database.GetItem(Sitecore.Data.ID.Parse(request.CountryCode));

            Item countryAndRegionItem = this.GetCountryAndRegionItem();
            string countryAndRegionPath = countryAndRegionItem.Paths.FullPath;
            string query = string.Format(CultureInfo.InvariantCulture, "fast:{0}//*[@{1} = '{2}']", countryAndRegionPath, CommerceServerStorefrontConstants.KnownFieldNames.CountryCode, request.CountryCode);
            Item foundCountry = countryAndRegionItem.Database.SelectSingleItem(query);
            if (foundCountry != null)
            {
                foreach (Item region in foundCountry.GetChildren())
                {
                    regions.Add(region.ID.ToGuid().ToString(), region[CommerceServerStorefrontConstants.KnownFieldNames.RegionName]);
                }
            }

            result.AvailableRegions = regions;
        }
        /// <summary>
        /// Translates the addresses.
        /// </summary>
        /// <param name="collection">The collection.</param>
        /// <param name="cart">The cart.</param>
        protected override void TranslateAddresses(CommerceServer.Core.Runtime.Orders.OrderAddressCollection collection, Commerce.Entities.Carts.Cart cart)
        {
            List<Party> partyList = new List<Party>();

            foreach (OrderAddress commerceAddress in collection)
            {
                int partyType = (commerceAddress[CommerceServerStorefrontConstants.KnowWeaklyTypesProperties.PartyType] == null) ? 1 : Convert.ToInt32(commerceAddress[CommerceServerStorefrontConstants.KnowWeaklyTypesProperties.PartyType], CultureInfo.InvariantCulture);

                Party party = null;

                switch (partyType)
                {
                    default:
                    case 1:
                        party = this.EntityFactory.Create<Commerce.Connect.CommerceServer.Orders.Models.CommerceParty>("Party");
                        this.TranslateAddress(commerceAddress, party as Sitecore.Commerce.Connect.CommerceServer.Orders.Models.CommerceParty);
                        break;

                    case 2:
                        party = this.EntityFactory.Create<RefSFModels.EmailParty>("EmailParty");
                        this.TranslateAddress(commerceAddress, party as RefSFModels.EmailParty);
                        break;
                }

                partyList.Add(party);
            }

            cart.Parties = partyList.AsReadOnly();
        }
        /// <summary>
        /// Initializes this object based on the data contained in the provided cart.
        /// </summary>
        /// <param name="cart">The cart used to initialize this object.</param>
        public override void Initialize(Commerce.Entities.Carts.Cart cart)
        {
            base.Initialize(cart);

            CommerceCart commerceCart = cart as CommerceCart;
            if (commerceCart == null)
            {
                return;
            }

            if (commerceCart.OrderForms.Count > 0)
            {
                foreach (var promoCode in (commerceCart.OrderForms[0].PromoCodes ?? Enumerable.Empty<String>()))
                {
                    this.PromoCodes.Add(promoCode);
                }
            }

            decimal totalSavings = 0;
            foreach (var lineitem in cart.Lines)
            {
                totalSavings += ((CommerceTotal)lineitem.Total).LineItemDiscountAmount;
            }

            this.Discount = totalSavings.ToCurrency(StorefrontConstants.Settings.DefaultCurrencyCode);
        }
Exemplo n.º 5
0
        public IActionResult Post([FromBody] ModelCommerceCreate Comer)
        {
            if (ModelState.IsValid)
            {
                if (context.BusinessModels.Count(x => x.Id == Comer.Id_Model) > 0)
                {
                    var com = new Commerce();
                    com.Alias     = Comer.Alias;
                    com.Address   = Comer.Address;
                    com.Latitude  = Comer.Latitude;
                    com.Longitude = Comer.Longitude;
                    com.Phone     = Comer.Phone;

                    context.Commerce.Add(com);
                    context.SaveChanges();

                    var modelcomer = new BussinessCommerce();
                    modelcomer.Commerce = com.Id;
                    modelcomer.Bussines = Comer.Id_Model;
                    context.BussinessCommerce.Add(modelcomer);
                    context.SaveChanges();
                }
                else
                {
                    return(BadRequest("No existe el modelo."));
                }

                return(Ok());
            }

            return(BadRequest(ModelState));
        }
    public void Process(MenuStack stack)
    {
        bool enabled = User.get_IsSignedInPSN() && !Commerce.IsBusy();

        this.menu.Update();
        if (this.menu.AddItem("Store", enabled))
        {
            stack.PushMenu(this.store.GetMenu());
        }
        if (this.menu.AddItem("In Game Store", true))
        {
            stack.PushMenu(this.inGameStore.GetMenu());
        }
        if (this.menu.AddItem("Downloads", true))
        {
            Commerce.DisplayDownloadList();
        }
        if (this.menu.AddItem("Entitlements", true))
        {
            stack.PushMenu(this.entitlements.GetMenu());
        }
        if (this.menu.AddItem("Find Installed Content", true))
        {
            this.EnumerateDRMContent();
        }
        if (this.menu.AddBackIndex("Back", true))
        {
            stack.PopMenu();
        }
    }
        /// <summary>
        /// Processes the specified arguments.
        /// </summary>
        /// <param name="args">The arguments.</param>
        public override void Process(Commerce.Pipelines.ServicePipelineArgs args)
        {
            Assert.ArgumentNotNull(args, "args");
            Assert.ArgumentCondition(args.Request is GetShippingOptionsRequest, "args.Request", "args.Request is GetShippingOptionsRequest");
            Assert.ArgumentCondition(args.Result is GetShippingOptionsResult, "args.Result", "args.Result is GetShippingOptionsResult");

            var request = (GetShippingOptionsRequest)args.Request;
            var result = (GetShippingOptionsResult)args.Result;

            List<ShippingOption> availableShippingOptionList = new List<ShippingOption>();
            List<ShippingOption> allShippingOptionList = new List<ShippingOption>();

            foreach (Item shippingOptionItem in this.GetShippingOptionsItem().GetChildren())
            {
                ShippingOption option = this.EntityFactory.Create<ShippingOption>("ShippingOption");

                this.TranslateToShippingOption(shippingOptionItem, option);

                bool add = option.ShippingOptionType == Models.ShippingOptionType.ElectronicDelivery && !CartCanBeEmailed(request.Cart as CommerceCart) ? false :
                           option.ShippingOptionType == Models.ShippingOptionType.DeliverItemsIndividually && request.Cart.Lines.Count <= 1 ? false : true;

                if (add)
                {
                    availableShippingOptionList.Add(option);
                }

                allShippingOptionList.Add(option);
            }

            result.ShippingOptions = new System.Collections.ObjectModel.ReadOnlyCollection<ShippingOption>(availableShippingOptionList);
            result.LineShippingPreferences = this.GetLineShippingOptions(request.Cart as CommerceCart, allShippingOptionList).AsReadOnly();
        }
Exemplo n.º 8
0
        public void TestMethod1()
        {
            Mock<IBillingProcessor> mockBilling = new Mock<IBillingProcessor>();

            Mock<ICustomer> mockCustomer = new Mock<ICustomer>();

            Mock<INotifier> mockNotifier = new Mock<INotifier>();

            Mock<ILogger> mockLogger = new Mock<ILogger>();

            mockBilling.Setup(obj => obj.ProcessPayment(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<double>()));

            mockCustomer.Setup(obj => obj.UpdateCustomerOrder(It.IsAny<string>(), It.IsAny<string>()));

            mockNotifier.Setup(obj => obj.SendReceipt(It.IsAny<OrderInfo>()));

            mockLogger.Setup(obj => obj.Log(It.IsAny<string>()));

            Commerce commerce = new Commerce(mockBilling.Object,
                                             mockCustomer.Object,
                                             mockNotifier.Object,
                                             mockLogger.Object);

            commerce.ProcessOrder(new OrderInfo());

            Assert.IsTrue(1 == 1); // this test just asserts that ProcessOrder can be called without error
        }
Exemplo n.º 9
0
        public async Task <IActionResult> Index()
        {
            var client = new HttpClient();

            var user = new Consumer();
            HttpResponseMessage res1 = await client.GetAsync($"{ACCOUNT_SERVICE_API_BASE}/consumers/5");

            if (res1.IsSuccessStatusCode)
            {
                var result = res1.Content.ReadAsStringAsync().Result;
                user = JsonConvert.DeserializeObject <Consumer>(result);
            }

            var products             = new List <Product>();
            HttpResponseMessage res2 = await client.GetAsync($"{INVENTORY_SERVICE_API_BASE}/products");

            if (res2.IsSuccessStatusCode)
            {
                var result = res2.Content.ReadAsStringAsync().Result;
                products = JsonConvert.DeserializeObject <List <Product> >(result);
            }

            var commerce = new Commerce()
            {
                User     = user,
                Products = products
            };

            return(View(commerce));
        }
        public Commerce.Data.Address VerifyAddress(Commerce.Data.Address address) {

            if (address.City == "Fail Town")
                throw new InvalidOperationException("Throw condition");
            
            return address;
        }
Exemplo n.º 11
0
        public ActionResult Get()
        {
            var userid  = ObtenerIDUser();
            var qrCodes = context.QrCode.Where(x => x.IdUser == userid && (x.Consumed == false || x.Valued == false)).ToList();

            //return Ok(new { results = qrCodes });
            var ListQR = new List <ModelQrDiscount>();
            var obj    = new ModelQrDiscount();
            var objD   = new Discounts();
            var objC   = new Commerce();

            foreach (QrCode Cont in qrCodes)
            {
                obj            = new ModelQrDiscount();
                objD           = context.Discounts.FirstOrDefault(x => x.Id == Cont.IdDiscount);
                objC           = context.Commerce.FirstOrDefault(x => x.Id == (context.CommerceDiscounts.FirstOrDefault(y => y.DiscountsID == objD.Id).CommerceID));
                obj.IdDiscount = Cont.IdDiscount;
                obj.IdCommerce = Cont.IdCommerce;
                obj.qrId       = Cont.Id;
                //obj.IdCommerce = objC.Id;
                obj.CommerceName        = context.BusinessModels.FirstOrDefault(x => x.Id == context.BussinessCommerce.FirstOrDefault(y => y.Commerce == Cont.IdCommerce).Bussines).Name;
                obj.CommerceAddres      = objC.Address;
                obj.Discount_value      = objD.Discount_value;
                obj.Discount_Type       = objD.Discount_Type;
                obj.InterestDescription = context.Interests.FirstOrDefault(x => x.Id == context.DiscountsInterests.FirstOrDefault(y => y.DiscountsID == objD.Id).InterestsId).Name;;
                obj.CommerceImage       = context.BusinessModels.FirstOrDefault(x => x.Id == context.BussinessCommerce.FirstOrDefault(y => y.Commerce == Cont.IdCommerce).Bussines).Image;
                obj.Consumed            = Cont.Consumed;
                ListQR.Add(obj);
            }

            return(Ok(new { results = ListQR }));


            //return context.Commerce.ToList();
        }
 private void OnGotProductInfo(Messages.PluginMessage msg)
 {
     OnScreenLog.Add("Got Detailed Product Info");
     Commerce.CommerceProductInfoDetailed detailedProductInfo = Commerce.GetDetailedProductInfo();
     OnScreenLog.Add("Product: " + detailedProductInfo.productName + " - " + detailedProductInfo.price);
     OnScreenLog.Add("Long desc: " + detailedProductInfo.longDescription);
 }
    public void Process(MenuStack stack)
    {
        bool enabled = User.IsSignedInPSN && sessionCreated && !Commerce.IsBusy();

        menu.Update();
        if (menu.AddItem("Category Info", enabled))
        {
            SonyNpCommerce.ErrorHandler(Commerce.RequestCategoryInfo(string.Empty));
        }
        if (menu.AddItem("Product List", enabled))
        {
            SonyNpCommerce.ErrorHandler(Commerce.RequestProductList(testCategoryID));
        }
        if (menu.AddItem("Product Info", enabled))
        {
            SonyNpCommerce.ErrorHandler(Commerce.RequestDetailedProductInfo(testProductID));
        }
        if (menu.AddItem("Browse Product", enabled))
        {
            SonyNpCommerce.ErrorHandler(Commerce.BrowseProduct(testProductID));
        }
        if (menu.AddItem("Checkout", enabled))
        {
            Commerce.GetProductList();
            SonyNpCommerce.ErrorHandler(Commerce.Checkout(testProductSkuIDs));
        }
        if (menu.AddItem("Redeem Voucher", enabled))
        {
            SonyNpCommerce.ErrorHandler(Commerce.VoucherInput());
        }
        if (menu.AddBackIndex("Back"))
        {
            stack.PopMenu();
        }
    }
Exemplo n.º 14
0
 private void OnGotEntitlementList(Messages.PluginMessage msg)
 {
     Commerce.CommerceEntitlement[] entitlementList = Commerce.GetEntitlementList();
     OnScreenLog.Add("Got Entitlement List, ");
     if (entitlementList.Length > 0)
     {
         Commerce.CommerceEntitlement[] array = entitlementList;
         for (int i = 0; i < array.Length; i++)
         {
             Commerce.CommerceEntitlement commerceEntitlement = array[i];
             OnScreenLog.Add(string.Concat(new object[]
             {
                 " ",
                 commerceEntitlement.get_id(),
                 " rc: ",
                 commerceEntitlement.remainingCount,
                 " cc: ",
                 commerceEntitlement.consumedCount,
                 " type: ",
                 commerceEntitlement.type
             }));
         }
     }
     else
     {
         OnScreenLog.Add("You do not have any entitlements.");
     }
 }
Exemplo n.º 15
0
    public void Process(MenuStack stack)
    {
        bool enabled = User.IsSignedInPSN && !Commerce.IsBusy();

        menu.Update();
        if (menu.AddItem("Store", enabled))
        {
            stack.PushMenu(store.GetMenu());
        }
        if (menu.AddItem("In Game Store"))
        {
            stack.PushMenu(inGameStore.GetMenu());
        }
        if (menu.AddItem("Downloads"))
        {
            Commerce.DisplayDownloadList();
        }
        if (menu.AddItem("Entitlements"))
        {
            stack.PushMenu(entitlements.GetMenu());
        }
        if (menu.AddItem("Find Installed Content"))
        {
            EnumerateDRMContent();
        }
        if (menu.AddBackIndex("Back"))
        {
            stack.PopMenu();
        }
    }
Exemplo n.º 16
0
        protected override object DoExecute(Commerce.CMSIntegration.DataSources.CommerceDataSourceContext context, ParsedGenericCommerceDataSourceSettings settings)
        {
            var userId = context.HttpContext.GetVisitorUniqueId();

            var top = settings.Top.GetValueOrDefault(4);
            ISet<string> toIgnoreItems;

            var engine = GetRecommendationEngine(context, settings, out toIgnoreItems);

            var items = engine.Recommend(userId, top, toIgnoreItems);
            var itemIds = items.Select(it => Convert.ToInt32(it.ItemId)).ToArray();

            var reasonItemIds = new List<int>();
            foreach (var item in items)
            {
                var reasonId = item.GetBestReasonItemId();
                if (reasonId > 0)
                {
                    reasonItemIds.Add(reasonId);
                }
            }

            var products = context.Site.Commerce()
                                  .Products.Query().ByIds(itemIds)
                                  .Include(p => p.Brand)
                                  .Include(p => p.Images)
                                  .Include(p => p.Variants)
                                  .ToList();

            var reasons = context.Site.Commerce()
                                 .Products.Query().ByIds(reasonItemIds.ToArray())
                                 .ToList();

            var result = new List<ProductRecommendation>();

            foreach (var item in items)
            {
                var productId = Convert.ToInt32(item.ItemId);
                var product = products.Find(p => p.Id == productId);
                if (product != null)
                {
                    var recommendation = new ProductRecommendation
                    {
                        Product = product,
                        Weight = item.Weight
                    };

                    var reasonId = item.GetBestReasonItemId();
                    if (reasonId > 0)
                    {
                        recommendation.Reason = reasons.Find(p => p.Id == reasonId);
                    }

                    result.Add(recommendation);
                }
            }

            return result;
        }
Exemplo n.º 17
0
        public ActionResult Index()
        {
            var list = Commerce.GetItemModel(1, "", out TotalPage, 0, 10, true).ToList();

            ViewBag.items = list;
            ViewBag.id    = 0;
            return(View());
        }
Exemplo n.º 18
0
        public ActionResult GetModel(int id = 0, int type = 0)
        {
            var list = Commerce.GetItemModel(1, "", out TotalPage, type, 10, true).ToList();

            ViewBag.items = list;
            ViewBag.id    = id;
            return(View());
        }
        /// <summary>
        /// Initializes this object based on the data contained in the provided cart.
        /// </summary>
        /// <param name="cart">The cart used to initialize this object.</param>
        public override void Initialize(Commerce.Entities.Carts.Cart cart)
        {
            base.Initialize(cart);

            foreach (var adjustment in (cart.Adjustments ?? Enumerable.Empty<CartAdjustment>()))
            {
                this.PromoCodes.Add(adjustment.Description);
            }
        }
        /// <summary>
        /// Executes the business logic of the TriggerPageEevent processor.
        /// </summary>
        /// <param name="args">The arguments.</param>
        public override void Process(Commerce.Pipelines.ServicePipelineArgs args)
        {
            if (Sitecore.Context.Site.DisplayMode != DisplayMode.Normal)
            {
                return;
            }

            base.Process(args);
        }
 public void Initialize()
 {
     this.menu         = new MenuLayout(this, 450, 34);
     this.store        = new SonyNpCommerceStore();
     this.inGameStore  = new SonyNpCommerceInGameStore();
     this.entitlements = new SonyNpCommerceEntitlements();
     Commerce.add_OnError(new Messages.EventHandler(this.OnCommerceError));
     Commerce.add_OnDownloadListStarted(new Messages.EventHandler(this.OnSomeEvent));
     Commerce.add_OnDownloadListFinished(new Messages.EventHandler(this.OnSomeEvent));
 }
Exemplo n.º 22
0
        /// <summary>
        /// Processes the specified arguments.
        /// </summary>
        /// <param name="args">The arguments.</param>
        public override void Process(Commerce.Pipelines.ServicePipelineArgs args)
        {
            Assert.ArgumentNotNull(args, "args");
            Assert.ArgumentNotNull(args.Request, "args.request");
            Assert.ArgumentCondition(args.Request is GetProductBulkPricesRequest, "args.Request", "args.Request is GetProductBulkPricesRequest");
            Assert.ArgumentCondition(args.Result is GetProductBulkPricesResult, "args.Result", "args.Result is GetProductBulkPricesResult");

            GetProductBulkPricesRequest request = (GetProductBulkPricesRequest)args.Request;
            GetProductBulkPricesResult result = (GetProductBulkPricesResult)args.Result;

            Assert.ArgumentNotNull(request.ProductCatalogName, "request.ProductCatalogName");
            Assert.ArgumentNotNull(request.ProductIds, "request.ProductIds");
            Assert.ArgumentNotNull(request.PriceType, "request.PriceType");

            ICatalogRepository catalogRepository = CommerceTypeLoader.CreateInstance<ICatalogRepository>();
            bool isList = Array.FindIndex(request.PriceTypeIds as string[], t => t.IndexOf("List", StringComparison.OrdinalIgnoreCase) >= 0) > -1;
            bool isAdjusted = Array.FindIndex(request.PriceTypeIds as string[], t => t.IndexOf("Adjusted", StringComparison.OrdinalIgnoreCase) >= 0) > -1;

            var uniqueIds = request.ProductIds.ToList().Distinct();
            foreach (var requestedProductId in uniqueIds)
            {
                try
                {
                    var product = catalogRepository.GetProductReadOnly(request.ProductCatalogName, requestedProductId);
                    Dictionary<string, Price> prices = new Dictionary<string, Price>();

                    // BasePrice is a List price and ListPrice is Adjusted price
                    if (isList)
                    {
                        if (product.HasProperty("BasePrice") && product["BasePrice"] != null)
                        {
                            prices.Add("List", new Price { PriceType = "List", Amount = (product["BasePrice"] as decimal?).Value });
                        }
                        else
                        {
                            // No base price is defined, the List price is set to the actual ListPrice define in the catalog
                            prices.Add("List", new Price { PriceType = "List", Amount = product.ListPrice });
                        }
                    }

                    if (isAdjusted && !product.IsListPriceNull())
                    {
                        prices.Add("Adjusted", new Price { PriceType = "Adjusted", Amount = product.ListPrice });
                    }

                    result.Prices.Add(requestedProductId, prices);
                }
                catch (CommerceServer.Core.EntityDoesNotExistException e)
                {
                    result.Success = false;
                    result.SystemMessages.Add(new SystemMessage { Message = e.Message });
                    continue;
                }
            }
        }
 public void Initialize()
 {
     this.menu = new MenuLayout(this, 450, 34);
     Commerce.add_OnSessionCreated(new Messages.EventHandler(this.OnSessionCreated));
     Commerce.add_OnSessionAborted(new Messages.EventHandler(this.OnSomeEvent));
     Commerce.add_OnGotCategoryInfo(new Messages.EventHandler(this.OnGotCategoryInfo));
     Commerce.add_OnGotProductList(new Messages.EventHandler(this.OnGotProductList));
     Commerce.add_OnGotProductInfo(new Messages.EventHandler(this.OnGotProductInfo));
     Commerce.add_OnCheckoutStarted(new Messages.EventHandler(this.OnSomeEvent));
     Commerce.add_OnCheckoutFinished(new Messages.EventHandler(this.OnSomeEvent));
 }
Exemplo n.º 24
0
        public IActionResult Put([FromBody] Commerce comer, int id)
        {
            if (comer.Id != id)
            {
                return(BadRequest());
            }

            context.Entry(comer).State = EntityState.Modified;
            context.SaveChanges();
            return(Ok());
        }
 private void OnGotProductList(Messages.PluginMessage msg)
 {
     OnScreenLog.Add("Got Product List");
     Commerce.CommerceProductInfo[] productList = Commerce.GetProductList();
     Commerce.CommerceProductInfo[] array       = productList;
     for (int i = 0; i < array.Length; i++)
     {
         Commerce.CommerceProductInfo commerceProductInfo = array[i];
         OnScreenLog.Add("Product: " + commerceProductInfo.productName + " - " + commerceProductInfo.price);
     }
 }
 /// <summary>
 /// Gets the page event text.
 /// </summary>
 /// <param name="args">The arguments.</param>
 /// <returns>
 /// The page event text.
 /// </returns>
 protected override string GetPageEventText(Commerce.Pipelines.ServicePipelineArgs args)
 {
     var request = args.Request as SearchInitiatedRequest;
     if (request != null)
     {
         return string.Format(CultureInfo.InvariantCulture, "{0} ({1} results)", request.SearchTerm, request.NumberOfHits);
     }
     else
     {
         return base.GetPageEventText(args);
     }
 }
Exemplo n.º 27
0
        public ActionResult GetLeader(int id = 0)
        {
            base.pageSize = 12;
            var list = Commerce.GetItemModel(1, "", out TotalPage, 0, base.pageSize, true).ToList();

            ViewBag.list = list;
            var lists = Commerce.GetItemModel(1, "", out TotalPage, 2, base.pageSize, true).ToList();

            SetViewBagPage();
            ViewBag.items = lists;
            ViewBag.id    = id;
            return(View());
        }
Exemplo n.º 28
0
        /// <summary>
        /// Processes the specified arguments.
        /// </summary>
        /// <param name="args">The arguments.</param>
        public override void Process(Commerce.Pipelines.ServicePipelineArgs args)
        {
            base.Process(args);

            var cartContext = CartPipelineContext.Get(args.Request.RequestContext);
            Assert.IsNotNullOrEmpty(cartContext.UserId, "cartContext.UserId");
            Assert.IsNotNullOrEmpty(cartContext.ShopName, "cartContext.ShopName");

            if (cartContext.HasBasketErrors && !args.Result.Success)
            {
                args.Result.Success = true;
            }
        }
    public void Process(MenuStack stack)
    {
        bool enabled = User.get_IsSignedInPSN() && !Commerce.IsBusy();

        this.menu.Update();
        if (this.menu.AddItem("Browse Category", enabled))
        {
            SonyNpCommerce.ErrorHandler(Commerce.BrowseCategory(string.Empty));
        }
        if (this.menu.AddBackIndex("Back", true))
        {
            stack.PopMenu();
        }
    }
Exemplo n.º 30
0
        public ActionResult AjaxGetLeader(int pageIndex)
        {
            base.pageSize = 12;
            var lists = Commerce.GetItemModel(pageIndex, "", out TotalPage, 2, base.pageSize, true).ToList();

            if (lists.Count > 0)
            {
                return(WriteSuccess("", lists));
            }
            else
            {
                return(WriteError(""));
            }
        }
Exemplo n.º 31
0
 public static ErrorCode ErrorHandler(ErrorCode errorCode = ErrorCode.NP_ERR_FAILED)
 {
     if (errorCode != 0)
     {
         ResultCode result = default(ResultCode);
         Commerce.GetLastError(out result);
         if (result.lastError != 0)
         {
             OnScreenLog.Add("Error: " + result.className + ": " + result.lastError + ", sce error 0x" + result.lastErrorSCE.ToString("X8"));
             return(result.lastError);
         }
     }
     return(errorCode);
 }
Exemplo n.º 32
0
        public void Commerce_Constructor_Test()
        {
            // Arrange
            var mockBilling  = new Mock <IBillingProcessor>();
            var mockCustomer = new Mock <ICustomerProcessor>();
            var mockNotifer  = new Mock <INotifier>();
            var mockLogger   = new Mock <ILogger>();

            // Act
            var commerce = new Commerce(mockBilling.Object, mockCustomer.Object, mockNotifer.Object, mockLogger.Object);

            // Assert
            Assert.IsNotNull(commerce);
        }
        /// <summary>
        /// Gets the page event data.
        /// </summary>
        /// <param name="args">The arguments.</param>
        /// <returns>
        /// The page event data.
        /// </returns>
        protected override Dictionary<string, object> GetPageEventData(Commerce.Pipelines.ServicePipelineArgs args)
        {
            Assert.ArgumentNotNull(args, "args");

            var data = base.GetPageEventData(args) ?? new Dictionary<string, object>();
            var request = args.Request as SearchInitiatedRequest;
            if (request != null)
            {
                data.Add(StorefrontConstants.PageEventDataNames.ShopName, request.ShopName);
                data.Add(StorefrontConstants.PageEventDataNames.SearchTerm, request.SearchTerm ?? string.Empty);
                data.Add(StorefrontConstants.PageEventDataNames.NumberOfHits, request.NumberOfHits);
            }

            return data;
        }
Exemplo n.º 34
0
        // GET: /Home/
        public ActionResult Index()
        {
            HomeViewModel model = new HomeViewModel();

            model.FSHistoryList    = FSHistorySer.GetItemModel(1, out TotalPage, "", 10, 0, true).ToList();
            model.ImageList        = siteService.GetItems(1, 5, 0, true).ToList();
            model.NewList          = news.NewPageList(1, 1, "", out TotalPage, 10, true);
            model.NewListType      = news.NewPageList(1, 3, "", out TotalPage, 10, true);
            model.vipUserImageList = Commerce.GetItemModel(1, "", out TotalPage, 2, 1000, true).ToList();
            model.MemberTellList   = memberSer.GetMemberMsgByPage(1, pageSize, out TotalPage, 1, false);
            model.MemberNewsList   = memberSer.GetMemberMsgByPage(1, pageSize, out TotalPage, 2, false);
            model.MemberZhaoList   = memberSer.GetMemberMsgByPage(1, pageSize, out TotalPage, 3, false);
            ViewBag.ModelList      = model;
            return(View());
        }
Exemplo n.º 35
0
        public async Task <IActionResult> OnGetAsync(int?id)
        {
            if (id == null)
            {
                return(NotFound());
            }

            Commerce = await _context.Commerces.FirstOrDefaultAsync(m => m.Id == id);

            if (Commerce == null)
            {
                return(NotFound());
            }
            return(Page());
        }
Exemplo n.º 36
0
        /// <summary>
        /// Processes the specified arguments.
        /// </summary>
        /// <param name="args">The arguments.</param>
        public override void Process(Commerce.Pipelines.ServicePipelineArgs args)
        {
            Assert.ArgumentNotNull(args, "args");
            Assert.ArgumentCondition(args.Request is CommerceGetPaymentMethodsRequest, "args.Request", "args.Request is CommerceGetPaymentMethodsRequest");
            Assert.ArgumentCondition(args.Result is GetPaymentMethodsResult, "args.Result", "args.Result is GetPaymentMethodsResult");

            var request = (CommerceGetPaymentMethodsRequest)args.Request;
            var result = (GetPaymentMethodsResult)args.Result;

            if (request.PaymentOption.PaymentOptionType == null)
            {
                base.Process(args);
                return;
            }

            Item paymentOptionsItem = this.GetPaymentOptionsItem();

            string query = string.Format(CultureInfo.InvariantCulture, "fast:{0}//*[@{1} = '{2}']", paymentOptionsItem.Paths.FullPath, CommerceServerStorefrontConstants.KnownFieldNames.PaymentOptionValue, request.PaymentOption.PaymentOptionType.Value);
            Item foundOption = paymentOptionsItem.Database.SelectSingleItem(query);
            if (foundOption != null)
            {
                string paymentMethodsIds = foundOption[CommerceServerStorefrontConstants.KnownFieldNames.CommerceServerPaymentMethods];
                if (!string.IsNullOrWhiteSpace(paymentMethodsIds))
                {
                    base.Process(args);
                    if (result.Success)
                    {
                        List<PaymentMethod> currentList = new List<PaymentMethod>(result.PaymentMethods);
                        List<PaymentMethod> returnList = new List<PaymentMethod>();

                        string[] ids = paymentMethodsIds.Split('|');
                        foreach (string id in ids)
                        {
                            string trimmedId = id.Trim();

                            var found2 = currentList.Find(o => o.ExternalId.Equals(trimmedId, StringComparison.OrdinalIgnoreCase));
                            PaymentMethod found = currentList.Find(o => o.ExternalId.Equals(trimmedId, StringComparison.OrdinalIgnoreCase));
                            if (found != null)
                            {
                                returnList.Add(found);
                            }
                        }

                        result.PaymentMethods = new System.Collections.ObjectModel.ReadOnlyCollection<PaymentMethod>(returnList);
                    }
                }
            }
        }
        ShippingMethod GetOrderShippingMethod(Commerce.Data.SqlRepository.ShippingMethod method, SqlRepository.Order order) {

            ShippingMethod result = null;
            Decimal orderWeight = order.OrderItems.Sum(x => x.Product.WeightInPounds);
            if (method != null) {
                result = new ShippingMethod();
                result.ID = method.ShippingMethodID;
                result.Carrier = method.Carrier;
                result.EstimatedDelivery = method.EstimatedDelivery;
                result.RatePerPound = method.RatePerPound;
                result.ServiceName = method.ServiceName;
                result.Cost = method.BaseRate + (method.RatePerPound * orderWeight);
            }

            return result;
        }
Exemplo n.º 38
0
        public ActionResult LeaderModel(int id)
        {
            var list = Commerce.GetItemModel(1, "", out TotalPage, 0, 10, true).OrderByDescending(c => c.Nid).ToList();

            ViewBag.list = list;
            if (id > 0)
            {
                var model = Commerce.QueryWhere(c => c.id == id).First();
                ViewBag.Model = model;
            }
            else
            {
                ViewBag.Model = null;
            }
            return(View());
        }
Exemplo n.º 39
0
        public void CommerceOrder_ReturnsTrue_WhenPlacingOrder()
        {
            //    string expectedValue = "Jon";
            //    User user = new User(expectedValue, new UserChangedNotifier());
            //    subject.NotifyUsernameChanged(user);
            //    string actualValue = subject.GetUsername();
            //    Assert.Equal(expectedValue, actualValue);


            //    IUserChangedNotifier userChanged = new UserChangedNotifier();
            //    mockIUserChangedNotifier.Setup(e => e.NotifyUsernameChanged(It.IsAny<User>()));
            //    Assert.True(subject.NotifyUsernameChanged(user));
            Commerce commerce = new Commerce(mockIBillingProcess.Object, mockICustomer.Object, mockITransactionNotifier.Object, mockILogger.Object);

            //commerce.ProcessOrder(new OrderInfo());
            Assert.True(1 == 1);
        }
Exemplo n.º 40
0
        /// <summary>
        /// Processes the specified arguments.
        /// </summary>
        /// <param name="args">The arguments.</param>
        public override void Process(Commerce.Pipelines.ServicePipelineArgs args)
        {
            Assert.ArgumentNotNull(args, "args");
            Assert.ArgumentCondition(args.Request is AddPartiesRequest, "args.Request", "args.Request is AddPartiesRequest");
            Assert.ArgumentCondition(args.Result is AddPartiesResult, "args.Result", "args.Result is AddPartiesResult");

            var request = (AddPartiesRequest)args.Request;
            var result = (AddPartiesResult)args.Result;
            Assert.ArgumentNotNull(request.Parties, "request.Parties");
            Assert.ArgumentNotNull(request.CommerceCustomer, "request.CommerceCustomer");

            Profile customerProfile = null;
            var response = this.GetCommerceUserProfile(request.CommerceCustomer.ExternalId, ref customerProfile);
            if (!response.Success)
            {
                result.Success = false;
                response.SystemMessages.ToList().ForEach(m => result.SystemMessages.Add(m));
                return;
            }

            List<Party> partiesAdded = new List<Party>();

            foreach (Party party in request.Parties)
            {
                if (party == null)
                {
                    continue;
                }

                Party newParty = null;

                if (party is RefSFModels.CommerceParty)
                {
                    newParty = this.ProcessCommerceParty(result, customerProfile, party as RefSFModels.CommerceParty);
                }
                else
                {
                    newParty = this.ProcessCustomParty(result, customerProfile, party);
                }

                if (newParty != null)
                {
                    partiesAdded.Add(newParty);
                }
            }
        }
Exemplo n.º 41
0
        public async Task <IActionResult> OnPostAsync(int?id)
        {
            if (id == null)
            {
                return(NotFound());
            }

            Commerce = await _context.Commerces.FindAsync(id);

            if (Commerce != null)
            {
                _context.Commerces.Remove(Commerce);
                await _context.SaveChangesAsync();
            }

            return(RedirectToPage("./Index"));
        }
        /// <summary>
        /// Processes the specified arguments.
        /// </summary>
        /// <param name="args">The arguments.</param>
        public override void Process(Commerce.Pipelines.ServicePipelineArgs args)
        {
            Assert.ArgumentNotNull(args, "args");
            Assert.ArgumentNotNull(args.Request, "args.request");
            Assert.ArgumentCondition(args.Request is GetProductBulkPricesRequest, "args.Request", "args.Request is GetProductBulkPricesRequest");
            Assert.ArgumentCondition(args.Result is Sitecore.Commerce.Services.Prices.GetProductBulkPricesResult, "args.Result", "args.Result is GetProductBulkPricesResult");

            GetProductBulkPricesRequest request = (GetProductBulkPricesRequest)args.Request;
            Sitecore.Commerce.Services.Prices.GetProductBulkPricesResult result = (Sitecore.Commerce.Services.Prices.GetProductBulkPricesResult)args.Result;

            Assert.ArgumentNotNull(request.ProductCatalogName, "request.ProductCatalogName");
            Assert.ArgumentNotNull(request.ProductIds, "request.ProductIds");
            Assert.ArgumentNotNull(request.PriceType, "request.PriceType");

            var uniqueIds = request.ProductIds.ToList().Distinct();
            foreach (var requestedProductId in uniqueIds)
            {
                var productDocument = this.GetProductFromIndex(request.ProductCatalogName, requestedProductId);
                if (productDocument != null)
                {
                    decimal? listPrice = string.IsNullOrWhiteSpace(productDocument.SafeGetFieldValue("listprice")) ? (decimal?)null : Convert.ToDecimal(productDocument["listprice"], CultureInfo.InvariantCulture);
                    decimal? adjustedPrice = string.IsNullOrWhiteSpace(productDocument.SafeGetFieldValue("adjustedprice")) ? (decimal?)null : Convert.ToDecimal(productDocument["adjustedprice"], CultureInfo.InvariantCulture);

                    ExtendedCommercePrice extendedPrice = this.EntityFactory.Create<ExtendedCommercePrice>("Price");

                    if (adjustedPrice.HasValue)
                    {
                        extendedPrice.ListPrice = adjustedPrice.Value;
                    }
                    else
                    {
                        // No base price is defined, the List price is set to the actual ListPrice define in the catalog
                        extendedPrice.ListPrice = listPrice.Value;
                    }

                    // The product list price is the Connect "Adjusted" price.
                    if (listPrice.HasValue)
                    {
                        extendedPrice.Amount = listPrice.Value;
                    }

                    result.Prices.Add(requestedProductId, extendedPrice);
                }
            }
        }
        public void Implement()
        {
            Console.WriteLine("\nLearning Dependency Injection Pattern\n");
            // First Implementation (without using DI)
            Commerce commerce = new Commerce();
            Order    o        = new Order("Subash", "12245", "GWP", new Product("Dell"));

            commerce.ProcessOrder(o);


            // Second implementation of DI (using Constructor Injection)
            Product product = new Product("Dell");
            Order   order   = new Order("Subash", "12345", "GWP", product);

            CommerceRepoDI_CtorInjection.BillingProcessor  billingProcessor  = new CommerceRepoDI_CtorInjection.BillingProcessor(order.CreditCard, order.CustomerName);
            CommerceRepoDI_CtorInjection.CustomerProcessor customerProcessor = new CommerceRepoDI_CtorInjection.CustomerProcessor(order.CustomerName, product);
            CommerceRepoDI_CtorInjection.Notifier          notifier          = new CommerceRepoDI_CtorInjection.Notifier(order);

            CommerceRepoDI_CtorInjection.Commerce commerceDI = new CommerceRepoDI_CtorInjection.Commerce(billingProcessor, customerProcessor, notifier);
            commerceDI.ProcessOrder();


            // Third implementation of DI (using DI Container eg. Autofactory ) concept R&R (Registry and Resolver)
            ContainerBuilder builder = new ContainerBuilder();

            //Register commerce class and it now doesn't have any interface association
            builder.RegisterType <CommerceRepoDI_Interface.Commerce>();
            //Register Notifier class and attach to INotifier
            builder.RegisterType <CommerceRepoDI_Interface.Notifier>().As <CommerceRepoDI_Interface.Interfaces.INotifier>();
            builder.RegisterType <CommerceRepoDI_Interface.BillingProcessor>().As <CommerceRepoDI_Interface.Interfaces.IBillingProcessor>();
            builder.RegisterType <CommerceRepoDI_Interface.CustomerProcessor>().As <CommerceRepoDI_Interface.Interfaces.ICustomerProcessor>();
            container = builder.Build();

            Product product1 = new Product("Dell");
            Order   order1   = new Order("Subash", "12345", "GWP", product1);

            CommerceRepoDI_Interface.Commerce commerce1 = container.Resolve <CommerceRepoDI_Interface.Commerce>();
            commerce1.ProcessOrder(order1);
            //CommerceRepoDI_Interface.BillingProcessor billingProcessor1 = container.Resolve<CommerceRepoDI_Interface.BillingProcessor(order1.CreditCard, order1.CustomerName);
            //CommerceRepoDI_Interface.CustomerProcessor customerProcessor1 = new CommerceRepoDI_Interface.CustomerProcessor(order1.CustomerName, product1);
            //CommerceRepoDI_Interface.Notifier notifier1 = new CommerceRepoDI_Interface.Notifier(order1);

            //CommerceRepoDI_Interface.Commerce commerceDI1 = new CommerceRepoDI_Interface.Commerce(billingProcessor1, customerProcessor1, notifier1);
            //commerceDI.ProcessOrder();
        }
Exemplo n.º 44
0
        public void dataset_test()
        {
            var c = new Commerce
            {
                Random = new Randomizer(54321)
            };

            c.Product().Should().Be("Shirt");
            Randomizer.Seed = new Random(7331);
            c.Product().Should().Be("Soap");

            Randomizer.Seed = new Random(1337);
            c.Random        = new Randomizer(54321);

            c.Product().Should().Be("Shirt");
            Randomizer.Seed = new Random(3173);
            c.Product().Should().Be("Soap");
        }
        /// <summary>
        /// Processes the specified arguments.
        /// </summary>
        /// <param name="args">The arguments.</param>
        public override void Process(Commerce.Pipelines.ServicePipelineArgs args)
        {
            Assert.ArgumentNotNull(args, "args");
            Assert.ArgumentCondition(args.Request is GetAvailableCountriesRequest, "args.Request", "args.Request is GetAvailableCountriesRequest");
            Assert.ArgumentCondition(args.Result is GetAvailableCountriesResult, "args.Result", "args.Result is GetAvailableCountriesResult");

            var request = (GetAvailableCountriesRequest)args.Request;
            var result = (GetAvailableCountriesResult)args.Result;

            var countryDictionary = new Dictionary<string, string>();

            foreach (Item country in this.GetCountryAndRegionItem().GetChildren())
            {
                countryDictionary.Add(country[CommerceServerStorefrontConstants.KnownFieldNames.CountryCode], country[CommerceServerStorefrontConstants.KnownFieldNames.CountryName]);
            }

            result.AvailableCountries = countryDictionary;
        }
Exemplo n.º 46
0
        /// <summary>
        /// Processes the specified arguments.
        /// </summary>
        /// <param name="args">The arguments.</param>
        public override void Process(Commerce.Pipelines.ServicePipelineArgs args)
        {
            base.Process(args);

            GetUserRequest request = (GetUserRequest)args.Request;
            GetUserResult result = (GetUserResult)args.Result;

            if (result.CommerceUser == null)
            {
                return;
            }

            // if we found a user, add some addition info
            var userProfile = GetUserProfile(result.CommerceUser.UserName);
            Assert.IsNotNull(userProfile, "profile");

            UpdateCustomer(result.CommerceUser, userProfile);
        }
Exemplo n.º 47
0
        static WordFunctions()
        {
            var commerce = new Commerce();
            var company  = new Company();
            var address  = new Address();
            var finance  = new Finance();
            var hacker   = new Hacker();
            var name     = new Name();

            Functions.Add(() => commerce.Department());
            Functions.Add(() => commerce.ProductName());
            Functions.Add(() => commerce.ProductAdjective());
            Functions.Add(() => commerce.ProductMaterial());
            Functions.Add(() => commerce.ProductName());
            Functions.Add(() => commerce.Color());

            Functions.Add(() => company.CatchPhraseAdjective());
            Functions.Add(() => company.CatchPhraseDescriptor());
            Functions.Add(() => company.CatchPhraseNoun());
            Functions.Add(() => company.BsAdjective());
            Functions.Add(() => company.BsBuzz());
            Functions.Add(() => company.BsNoun());

            Functions.Add(() => address.StreetSuffix());
            Functions.Add(() => address.County());
            Functions.Add(() => address.Country());
            Functions.Add(() => address.State());

            Functions.Add(() => address.StreetSuffix());

            Functions.Add(() => finance.AccountName());
            Functions.Add(() => finance.TransactionType());
            Functions.Add(() => finance.Currency().Description);

            Functions.Add(() => hacker.Noun());
            Functions.Add(() => hacker.Verb());
            Functions.Add(() => hacker.Adjective());
            Functions.Add(() => hacker.IngVerb());
            Functions.Add(() => hacker.Abbreviation());

            Functions.Add(() => name.JobDescriptor());
            Functions.Add(() => name.JobArea());
            Functions.Add(() => name.JobType());
        }
Exemplo n.º 48
0
        public async Task <IActionResult> Seed()
        {
            _logger.LogInformation("Start seeding database");
            var categoriesName = new Commerce().Categories(20).Distinct().ToList();

            var categoryFaker = new Faker <Category>()
                                .RuleFor(s => s.Name, s =>
            {
                var c = s.PickRandom(categoriesName);
                categoriesName.Remove(c);
                return(c);
            });

            var productFaker = new Faker <Product>()
                               .RuleFor(s => s.Name, s => s.Commerce.Product())
                               .RuleFor(s => s.Description, s => s.Lorem.Paragraph())
                               .RuleFor(s => s.ImageUri, s => s.Image.PicsumUrl())
                               .RuleFor(s => s.SellQuantity, s => 90)
                               .RuleFor(s => s.StockQuantity, s => 100)
                               .RuleFor(s => s.CartMaxQuantity, s => 10)
                               .RuleFor(s => s.Price, s => decimal.Parse(s.Commerce.Price()));

            var categories = categoryFaker.Generate(5);

            foreach (var category in categories)
            {
                var products = productFaker.Generate(Randomizer.Seed.Next(50, 200));
                foreach (var product in products)
                {
                    category.Products.Add(new ProductCategory
                    {
                        Product = product
                    });
                }
            }

            await _context.Set <Category>().AddRangeAsync(categories);

            await _context.SaveChangesAsync();

            _logger.LogInformation("Seeding database successful");

            return(Ok());
        }
Exemplo n.º 49
0
        static void Commerce2(OrderInfo orderInfo)
        {
            try
            {
                Ninject.IKernel kernel               = new StandardKernel(new DI());
                var             _OrderInfo           = kernel.Get <OrderInfo>();
                var             _BillingProcess      = kernel.Get <BillingProcess>();
                var             _Customer            = kernel.Get <Customer>();
                var             _TransactionNotifier = kernel.Get <TransactionNotifier>();
                var             _Logger              = kernel.Get <Logger>();

                Commerce commerce = new Commerce(_BillingProcess, _Customer, _TransactionNotifier, _Logger);
                commerce.ProcessOrder(orderInfo);
            }
            catch (Exception e)
            {
                Console.WriteLine($"main: exception=[{e.Message}]");
            }
        }
        /// <summary>
        /// Processes the specified arguments.
        /// </summary>
        /// <param name="args">The arguments.</param>
        public override void Process(Commerce.Pipelines.ServicePipelineArgs args)
        {
            Assert.ArgumentNotNull(args, "args");
            Assert.ArgumentNotNull(args.Request, "args.request");
            Assert.ArgumentNotNull(args.Result, "args.result");
            Assert.ArgumentCondition(args.Request is TranslateEntityToCommerceAddressProfileRequest, "args.Request ", "args.Request is TranslateEntityToCommerceAddressProfileRequest");

            var request = (TranslateEntityToCommerceAddressProfileRequest)args.Request;
            Assert.ArgumentNotNull(request.SourceParty, "request.SourceParty");
            Assert.ArgumentNotNull(request.DestinationProfile, "request.DestinationProfile");

            if (request.SourceParty is RefSFModels.CommerceParty)
            {
                this.TranslateCommerceCustomerParty(request.SourceParty as RefSFModels.CommerceParty, request.DestinationProfile);
            }
            else
            {
                this.TranslateCustomParty(request.SourceParty, request.DestinationProfile);
            }
        }
        public void Save(Commerce.Data.UserEvent userEvent)
        {


            using (DB db = new DB())
            {
                //make sure there's a user
                int userCount = (from u in db.Users
                                 where u.UserName == userEvent.UserName
                                 select u).Count();

                //if not, need to add one
                if (userCount == 0)
                {
                    Commerce.Data.SqlRepository.User newUser = new Commerce.Data.SqlRepository.User();
                    newUser.UserName = userEvent.UserName;
                    newUser.CreatedOn = DateTime.Now;
                    newUser.ModifiedOn = DateTime.Now;
                    db.Users.InsertOnSubmit(newUser);
                }

                //there is no updating of user events - it's always an insert
                Commerce.Data.SqlRepository.UserEvent newEvent = new Commerce.Data.SqlRepository.UserEvent();

                //some left/right
                newEvent.IP = userEvent.IP;
                newEvent.UserName = userEvent.UserName;
                newEvent.ProductID = userEvent.ProductID;
                newEvent.CategoryID = userEvent.CategoryID;
                newEvent.EventDate = DateTime.Now;
                if (userEvent.OrderID != Guid.Empty)
                    newEvent.OrderID = userEvent.OrderID;
                else
                    newEvent.OrderID = null;
                newEvent.UserBehaviorID = (int)userEvent.Behavior;

                db.UserEvents.InsertOnSubmit(newEvent);
                db.SubmitChanges();
            }
        }
Exemplo n.º 52
0
        /// <summary>
        /// Processes the specified arguments.
        /// </summary>
        /// <param name="args">The arguments.</param>
        public override void Process(Commerce.Pipelines.ServicePipelineArgs args)
        {
            Assert.ArgumentNotNull(args, "args");
            Assert.ArgumentCondition(args.Request is GetPaymentOptionsRequest, "args.Request", "args.Request is GetPaymentOptionsRequest");
            Assert.ArgumentCondition(args.Result is GetPaymentOptionsResult, "args.Result", "args.Result is GetPaymentOptionsResult");

            var request = (GetPaymentOptionsRequest)args.Request;
            var result = (GetPaymentOptionsResult)args.Result;

            List<PaymentOption> paymentOptionList = new List<PaymentOption>();

            foreach (Item paymentOptionItem in this.GetPaymentOptionsItem().GetChildren())
            {
                PaymentOption option = this.EntityFactory.Create<PaymentOption>("PaymentOption");

                this.TranslateToPaymentOption(paymentOptionItem, option, result);

                paymentOptionList.Add(option);
            }

            result.PaymentOptions = new System.Collections.ObjectModel.ReadOnlyCollection<PaymentOption>(paymentOptionList);
        }
 public Commerce.Data.Transaction Capture(Commerce.Data.Order order)
 {
     throw new InvalidOperationException("Capture failed");
 }
Exemplo n.º 54
0
        /// <summary>
        /// Processes the specified arguments.
        /// </summary>
        /// <param name="args">The arguments.</param>
        public override void Process(Commerce.Pipelines.ServicePipelineArgs args)
        {
            Assert.ArgumentNotNull(args, "args");
            Assert.ArgumentCondition(args.Request is RemovePartiesRequest, "args.Request", "args.Request is RemovePartiesRequest");
            Assert.ArgumentCondition(args.Result is CustomerResult, "args.Result", "args.Result is CustomerResult");

            var request = (RemovePartiesRequest)args.Request;
            var result = (CustomerResult)args.Result;

            Profile customerProfile = null;
            var response = this.GetCommerceUserProfile(request.CommerceCustomer.ExternalId, ref customerProfile);
            if (!response.Success)
            {
                result.Success = false;
                response.SystemMessages.ToList().ForEach(m => result.SystemMessages.Add(m));
                return;
            }

            string preferredAddress = customerProfile["GeneralInfo.preferred_address"].Value as string;

            var profileValue = customerProfile["GeneralInfo.address_list"].Value as object[];
            if (profileValue != null)
            {
                var e = profileValue.Select(i => i.ToString());
                var addressList = new ProfilePropertyListCollection<string>(e);

                foreach (var partyToRemove in request.Parties)
                {
                    var foundId = addressList.Where(x => x.Equals(partyToRemove.ExternalId, StringComparison.OrdinalIgnoreCase)).FirstOrDefault();
                    if (foundId != null)
                    {
                        response = this.DeleteAddressCommerceProfile(foundId);
                        if (!response.Success)
                        {
                            result.Success = false;
                            response.SystemMessages.ToList().ForEach(m => result.SystemMessages.Add(m));
                            return;
                        }

                        addressList.Remove(foundId);

                        if (addressList.Count() == 0)
                        {
                            customerProfile["GeneralInfo.address_list"].Value = System.DBNull.Value;
                        }
                        else
                        {
                            customerProfile["GeneralInfo.address_list"].Value = addressList.Cast<object>().ToArray();
                        }

                        // Preffered address check. If the address being deleted was the preferred address we must clear it from the customer profile.
                        if (!string.IsNullOrWhiteSpace(preferredAddress) && preferredAddress.Equals(partyToRemove.ExternalId, StringComparison.OrdinalIgnoreCase))
                        {
                            customerProfile["GeneralInfo.preferred_address"].Value = System.DBNull.Value;
                        }

                        customerProfile.Update();
                    }
                }
            }
        }
Exemplo n.º 55
0
 public void Send(Commerce.Data.Mailer mailer)
 {
     _logger.Info("Didn't send an email to "+mailer.ToEmailAddress);
 }
Exemplo n.º 56
0
        public void SendOrderEmail(Commerce.Data.Order order, Commerce.Data.MailerType mailType)
        {
            //pull the mailer
            Mailer mailer = GetMailerForOrder(order, mailType);

            //no catches here - let bubble to caller
            Send(mailer);
        }
        /// <summary>
        /// Processes the specified arguments.
        /// </summary>
        /// <param name="args">The arguments.</param>
        public override void Process(Commerce.Pipelines.ServicePipelineArgs args)
        {
            Assert.ArgumentNotNull(args, "args");
            Assert.ArgumentNotNull(args.Request, "args.request");
            Assert.ArgumentCondition(args.Request is GetProductBulkPricesRequest, "args.Request", "args.Request is GetProductBulkPricesRequest");
            Assert.ArgumentCondition(args.Result is Sitecore.Commerce.Services.Prices.GetProductBulkPricesResult, "args.Result", "args.Result is GetProductBulkPricesResult");

            GetProductBulkPricesRequest request = (GetProductBulkPricesRequest)args.Request;
            Sitecore.Commerce.Services.Prices.GetProductBulkPricesResult result = (Sitecore.Commerce.Services.Prices.GetProductBulkPricesResult)args.Result;

            Assert.ArgumentNotNull(request.ProductCatalogName, "request.ProductCatalogName");
            Assert.ArgumentNotNull(request.ProductIds, "request.ProductIds");
            Assert.ArgumentNotNull(request.PriceType, "request.PriceType");

            ICatalogRepository catalogRepository = CommerceTypeLoader.CreateInstance<ICatalogRepository>();

            bool isList = request.PriceTypeIds.FirstOrDefault(x => x.Equals(PriceTypes.List, StringComparison.OrdinalIgnoreCase)) != null;
            bool isAdjusted = request.PriceTypeIds.FirstOrDefault(x => x.Equals(PriceTypes.Adjusted, StringComparison.OrdinalIgnoreCase)) != null;
            bool isLowestPriceVariantSpecified = request.PriceTypeIds.FirstOrDefault(x => x.Equals(PriceTypes.LowestPricedVariant, StringComparison.OrdinalIgnoreCase)) != null;
            bool isLowestPriceVariantListPriceSpecified = request.PriceTypeIds.FirstOrDefault(x => x.Equals(PriceTypes.LowestPricedVariantListPrice, StringComparison.OrdinalIgnoreCase)) != null;
            bool isHighestPriceVariantSpecified = request.PriceTypeIds.FirstOrDefault(x => x.Equals(PriceTypes.HighestPricedVariant, StringComparison.OrdinalIgnoreCase)) != null;

            var uniqueIds = request.ProductIds.ToList().Distinct();
            foreach (var requestedProductId in uniqueIds)
            {
                try
                {
                    var product = catalogRepository.GetProductReadOnly(request.ProductCatalogName, requestedProductId);

                    ExtendedCommercePrice extendedPrice = this.EntityFactory.Create<ExtendedCommercePrice>("Price");

                    // BasePrice is a List price and ListPrice is Adjusted price
                    if (isList)
                    {
                        if (product.HasProperty("BasePrice") && product["BasePrice"] != null)
                        {
                            extendedPrice.Amount = (product["BasePrice"] as decimal?).Value;
                        }
                        else
                        {
                            // No base price is defined, the List price is set to the actual ListPrice define in the catalog
                            extendedPrice.Amount = product.ListPrice;
                        }
                    }

                    if (isAdjusted && !product.IsListPriceNull())
                    {
                        extendedPrice.ListPrice = product.ListPrice;
                    }

                    if ((isLowestPriceVariantSpecified || isLowestPriceVariantListPriceSpecified || isHighestPriceVariantSpecified) && product is ProductFamily)
                    {
                        this.SetVariantPrices(product as ProductFamily, extendedPrice, isLowestPriceVariantSpecified, isLowestPriceVariantListPriceSpecified, isHighestPriceVariantSpecified);
                    }

                    result.Prices.Add(requestedProductId, extendedPrice);
                }
                catch (CommerceServer.Core.EntityDoesNotExistException e)
                {
                    result.Success = false;
                    result.SystemMessages.Add(new SystemMessage { Message = e.Message });
                    continue;
                }
            }
        }
 public Commerce.Data.Transaction Refund(Commerce.Data.Order order)
 {
     throw new InvalidOperationException("Refund failed");
 }
 public Commerce.Data.Transaction Authorize(Commerce.Data.Order order)
 {
     throw new InvalidOperationException("Authorization failed");
 }
        /// <summary>
        /// Processes the specified arguments.
        /// </summary>
        /// <param name="args">The arguments.</param>
        public override void Process(Commerce.Pipelines.ServicePipelineArgs args)
        {
            Assert.ArgumentNotNull(args, "args");
            Assert.ArgumentNotNull(args.Request, "args.request");
            Assert.ArgumentCondition(args.Request is GetProductBulkPricesRequest, "args.Request", "args.Request is GetProductBulkPricesRequest");
            Assert.ArgumentCondition(args.Result is Sitecore.Commerce.Services.Prices.GetProductBulkPricesResult, "args.Result", "args.Result is GetProductBulkPricesResult");

            GetProductBulkPricesRequest request = (GetProductBulkPricesRequest)args.Request;
            Sitecore.Commerce.Services.Prices.GetProductBulkPricesResult result = (Sitecore.Commerce.Services.Prices.GetProductBulkPricesResult)args.Result;

            Assert.ArgumentNotNull(request.ProductCatalogName, "request.ProductCatalogName");
            Assert.ArgumentNotNull(request.ProductIds, "request.ProductIds");
            Assert.ArgumentNotNull(request.PriceType, "request.PriceType");

            bool isList = request.PriceTypeIds.FirstOrDefault(x => x.Equals(PriceTypes.List, StringComparison.OrdinalIgnoreCase)) != null;
            bool isAdjusted = request.PriceTypeIds.FirstOrDefault(x => x.Equals(PriceTypes.Adjusted, StringComparison.OrdinalIgnoreCase)) != null;
            bool isLowestPriceVariantSpecified = request.PriceTypeIds.FirstOrDefault(x => x.Equals(PriceTypes.LowestPricedVariant, StringComparison.OrdinalIgnoreCase)) != null;
            bool isLowestPriceVariantListPriceSpecified = request.PriceTypeIds.FirstOrDefault(x => x.Equals(PriceTypes.LowestPricedVariantListPrice, StringComparison.OrdinalIgnoreCase)) != null;
            bool isHighestPriceVariantSpecified = request.PriceTypeIds.FirstOrDefault(x => x.Equals(PriceTypes.HighestPricedVariant, StringComparison.OrdinalIgnoreCase)) != null;

            var uniqueIds = request.ProductIds.ToList().Distinct();
            foreach (var requestedProductId in uniqueIds)
            {
                var productDocument = this.GetProductFromIndex(request.ProductCatalogName, requestedProductId);
                if (productDocument != null)
                {
                    decimal? listPrice = string.IsNullOrWhiteSpace(productDocument.SafeGetFieldValue("listprice")) ? (decimal?)null : Convert.ToDecimal(productDocument["listprice"], CultureInfo.InvariantCulture);
                    decimal? basePrice = string.IsNullOrWhiteSpace(productDocument.SafeGetFieldValue("baseprice")) ? (decimal?)null : Convert.ToDecimal(productDocument["baseprice"], CultureInfo.InvariantCulture);

                    ExtendedCommercePrice extendedPrice = this.EntityFactory.Create<ExtendedCommercePrice>("Price");

                    // The product base price is the Connect "List" price.
                    if (isList)
                    {
                        if (basePrice.HasValue)
                        {
                            extendedPrice.Amount = basePrice.Value;
                        }
                        else
                        {
                            // No base price is defined, the List price is set to the actual ListPrice define in the catalog
                            extendedPrice.Amount = listPrice.Value;
                        }
                    }

                    // The product list price is the Connect "Adjusted" price.
                    if (isAdjusted && listPrice.HasValue)
                    {
                        extendedPrice.ListPrice = listPrice.Value;
                    }

                    var variantInfoString = productDocument["VariantInfo"];
                    if ((isLowestPriceVariantSpecified || isLowestPriceVariantListPriceSpecified || isHighestPriceVariantSpecified) && !string.IsNullOrWhiteSpace(variantInfoString))
                    {
                        List<VariantIndexInfo> variantIndexInfoList = JsonConvert.DeserializeObject<List<VariantIndexInfo>>(variantInfoString);
                        this.SetVariantPricesFromProductVariants(productDocument, variantIndexInfoList, extendedPrice, isLowestPriceVariantSpecified, isLowestPriceVariantListPriceSpecified, isHighestPriceVariantSpecified);
                    }

                    result.Prices.Add(requestedProductId, extendedPrice);
                }
            }
        }